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
lgpl-2.1
2f9ddd6a49a524cdd8635cbbebf68d99cc92fd71
0
ekiwi/jade-mirror,ekiwi/jade-mirror,ekiwi/jade-mirror,ekiwi/jade-mirror
/***************************************************************** JADE - Java Agent DEvelopment Framework is a framework to develop multi-agent systems in compliance with the FIPA specifications. Copyright (C) 2000 CSELT S.p.A. GNU Lesser General Public License 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, version 2.1 of the License. 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 jade.lang.acl; import java.io.Reader; import java.io.Writer; import java.io.Serializable; import java.io.IOException; import java.io.StringWriter; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import java.io.ObjectOutputStream; import java.io.ObjectInputStream; import java.lang.ClassNotFoundException; import java.util.Date; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.util.Properties; import java.util.Enumeration; import jade.core.AID; import jade.domain.FIPAAgentManagement.Envelope; import starlight.util.Base64; /** * The class ACLMessage implements an ACL message compliant to the <b>FIPA 97</b> specs. * All parameters are couples <em>keyword: value</em>. * All keywords are <code>private final String</code>. * All values can be set by using the methods <em>set</em> and can be read by using * the methods <em>get</em>. <p> * Notice that the <em>get</em> methods never * return null, rather they return an empty String. <p> * The methods <code> setContentObject() </code> and * <code> getContentObject() </code> allow to send * serialized Java objects over the content of an ACLMessage. * These method are not FIPA compliant so their usage is not encouraged. @author Fabio Bellifemine - CSELT @version $Date$ $Revision$ */ public class ACLMessage implements Cloneable, Serializable { /** constant identifying the FIPA performative **/ public static final int ACCEPT_PROPOSAL = 0; /** constant identifying the FIPA performative **/ public static final int AGREE = 1; /** constant identifying the FIPA performative **/ public static final int CANCEL = 2; /** constant identifying the FIPA performative **/ public static final int CFP = 3; /** constant identifying the FIPA performative **/ public static final int CONFIRM = 4; /** constant identifying the FIPA performative **/ public static final int DISCONFIRM = 5; /** constant identifying the FIPA performative **/ public static final int FAILURE = 6; /** constant identifying the FIPA performative **/ public static final int INFORM = 7; /** constant identifying the FIPA performative **/ public static final int INFORM_IF = 8; /** constant identifying the FIPA performative **/ public static final int INFORM_REF = 9; /** constant identifying the FIPA performative **/ public static final int NOT_UNDERSTOOD = 10; /** constant identifying the FIPA performative **/ public static final int PROPOSE = 11; /** constant identifying the FIPA performative **/ public static final int QUERY_IF = 12; /** constant identifying the FIPA performative **/ public static final int QUERY_REF = 13; /** constant identifying the FIPA performative **/ public static final int REFUSE = 14; /** constant identifying the FIPA performative **/ public static final int REJECT_PROPOSAL = 15; /** constant identifying the FIPA performative **/ public static final int REQUEST = 16; /** constant identifying the FIPA performative **/ public static final int REQUEST_WHEN = 17; /** constant identifying the FIPA performative **/ public static final int REQUEST_WHENEVER = 18; /** constant identifying the FIPA performative **/ public static final int SUBSCRIBE = 19; /** constant identifying the FIPA performative **/ public static final int PROXY = 20; /** constant identifying the FIPA performative **/ public static final int PROPAGATE = 21; /** constant identifying an unknown performative **/ public static final int UNKNOWN = -1; /** @serial */ private int performative; // keeps the performative type of this object private static List performatives = new ArrayList(22); static { // initialization of the Vector of performatives performatives.add("ACCEPT-PROPOSAL"); performatives.add("AGREE"); performatives.add("CANCEL"); performatives.add("CFP"); performatives.add("CONFIRM"); performatives.add("DISCONFIRM"); performatives.add("FAILURE"); performatives.add("INFORM"); performatives.add("INFORM-IF"); performatives.add("INFORM-REF"); performatives.add("NOT-UNDERSTOOD"); performatives.add("PROPOSE"); performatives.add("QUERY-IF"); performatives.add("QUERY-REF"); performatives.add("REFUSE"); performatives.add("REJECT-PROPOSAL"); performatives.add("REQUEST"); performatives.add("REQUEST-WHEN"); performatives.add("REQUEST-WHENEVER"); performatives.add("SUBSCRIBE"); performatives.add("PROXY"); performatives.add("PROPAGATE"); } private static final String SENDER = new String(" :sender "); private static final String RECEIVER = new String(" :receiver "); private static final String CONTENT = new String(" :content "); private static final String REPLY_WITH = new String(" :reply-with "); private static final String IN_REPLY_TO = new String(" :in-reply-to "); private static final String REPLY_TO = new String(" :reply-to "); private static final String LANGUAGE = new String(" :language "); private static final String ENCODING = new String(" :encoding "); private static final String ONTOLOGY = new String(" :ontology "); private static final String REPLY_BY = new String(" :reply-by "); private static final String PROTOCOL = new String(" :protocol "); private static final String CONVERSATION_ID = new String(" :conversation-id "); /** @serial */ private AID source = null; /** @serial */ private ArrayList dests = new ArrayList(); /** @serial */ private ArrayList reply_to = new ArrayList(); /** @serial */ private StringBuffer content = null; /** @serial */ private StringBuffer reply_with = null; /** @serial */ private StringBuffer in_reply_to = null; /** @serial */ private StringBuffer encoding = null; /** @serial */ private StringBuffer language = null; /** @serial */ private StringBuffer ontology = null; /** @serial */ private StringBuffer reply_by = null; /** @serial */ private long reply_byInMillisec; /** @serial */ private StringBuffer protocol = null; /** @serial */ private StringBuffer conversation_id = null; /** @serial */ private Properties userDefProps = new Properties(); private Envelope messageEnvelope; /** Returns the list of the communicative acts. */ public static List getAllPerformatives() { return performatives; } /** @deprecated Since every ACL Message must have a message type, you should use the new constructor which gets a message type as a parameter. To avoid problems, now this constructor silently sets the message type to <code>not-understood</code>. @see jade.lang.acl.ACLMessage#ACLMessage(String type) */ public ACLMessage() { performative = NOT_UNDERSTOOD; } /** @deprecated It increases the probability of error when the passed String does not belong to the set of performatives supported by FIPA. This constructor creates an ACL message object with the specified type. To avoid problems, the constructor <code>ACLMessage(int)</code> should be used instead. @param type The type of the communicative act represented by this message. @see jade.lang.acl.ACLMessage#ACLMessage(int type) */ public ACLMessage(String type) { performative = performatives.indexOf(type.toUpperCase()); } /** * This constructor creates an ACL message object with the specified * performative. If the passed integer does not correspond to any of * the known performatives, it silently initializes the message to * <code>not-understood</code>. **/ public ACLMessage(int perf) { performative = perf; } /** Writes the <code>:sender</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param source The new value for the slot. @see jade.lang.acl.ACLMessage#getSender() */ public void setSender(AID s) { if (s != null) source = (AID)s.clone(); else source = null; } /** Adds a value to <code>:receiver</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param r The value to add to the slot value set. */ public void addReceiver(AID r) { if(r != null) dests.add(r); } /** Removes a value from <code>:receiver</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param r The value to remove from the slot value set. @return true if the AID has been found and removed, false otherwise */ public boolean removeReceiver(AID r) { if (r != null) return dests.remove(r); else return false; } /** Removes all values from <code>:receiver</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> */ public void clearAllReceiver() { dests.clear(); } /** Adds a value to <code>:reply-to</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param dest The value to add to the slot value set. */ public void addReplyTo(AID dest) { if (dest != null) reply_to.add(dest); } /** Removes a value from <code>:reply_to</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param dest The value to remove from the slot value set. @return true if the AID has been found and removed, false otherwise */ public boolean removeReplyTo(AID dest) { if (dest != null) return reply_to.remove(dest); else return false; } /** Removes all values from <code>:reply_to</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> */ public void clearAllReplyTo() { reply_to.clear(); } /** * set the performative of this ACL message object to the passed constant. * Remind to * use the set of constants (i.e. <code> INFORM, REQUEST, ... </code>) * defined in this class */ public void setPerformative(int perf) { performative = perf; } /** * Writes the <code>:content</code> slot. <em><b>Warning:</b> no * checks are made to validate the slot value.</em> <p> * In order to transport serialized Java objects, * or arbitrary sequence of bytes (i.e. something different from * a Java <code>String</code>) over an ACL message, it is suggested to use * the method <code>ACLMessage.setContentObject()</code> instead. * @param content The new value for the slot. * @see jade.lang.acl.ACLMessage#getContent() * @see jade.lang.acl.ACLMessage#setContentObject(Serializable s) */ public void setContent(String content) { if (content != null) this.content = new StringBuffer(content); else this.content = null; } /** * This method sets the current content of this ACLmessage to * the passed sequence of bytes. * Base64 encoding is applied. <p> * This method should be used to write serialized Java objects over the * content of an ACL Message to override the limitations of the Strings. <p> * For example, to write Java objects into the content: <br> * <PRE> * ACLMessage msg; * ByteArrayOutputStream c = new ByteArrayOutputStream(); * ObjectOutputStream oos = new ObjectOutputStream(c); * oos.writeInt(1234); * oos.writeObject("Today"); * oos.writeObject(new Date()); * oos.flush(); * msg.setContentBase64(c.toByteArray()); * * </PRE> * * @see jade.lang.acl.ACLMessage#getContentBase64() * @see jade.lang.acl.ACLMessage#getContent() * @see java.io.ObjectOutputStream#writeObject(Object o) * @param bytes is the the sequence of bytes to be appended to the content of this message */ private void setContentBase64(byte[] bytes) { try { content = new StringBuffer().append(Base64.encode(bytes)); } catch(java.lang.NoClassDefFoundError jlncdfe) { System.err.println("\n\t===== E R R O R !!! =======\n"); System.err.println("Missing support for Base64 conversions"); System.err.println("Please refer to the documentation for details."); System.err.println("=============================================\n\n"); System.err.println(""); try { Thread.currentThread().sleep(3000); } catch(InterruptedException ie) { } content = null; } } /** * This method sets the content of this ACLMessage to a Java object. * It is not FIPA compliant so its usage is not encouraged. * For example:<br> * <PRE> * ACLMessage msg = new ACLMessage(ACLMessage.INFORM); * Date d = new Date(); * try{ * msg.setContentObject(d); * }catch(IOException e){} * </PRE> * * @param s the object that will be used to set the content of the ACLMessage. * @exception IOException if an I/O error occurs. */ public void setContentObject(Serializable s) throws IOException { ByteArrayOutputStream c = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(c); oos.writeObject(s); oos.flush(); setContentBase64(c.toByteArray()); } /** * This method returns the content of this ACLmessage * after decoding according to Base64. * For example to read Java objects from the content * (when they have been written by using the setContentBase64() method,: <br> * <PRE> * ACLMessage msg; * ObjectInputStream oin = new ObjectInputStream(new ByteArrayInputStream(msg.getContentBase64()));; * * int i = oin.readInt(); * String today = (String)oin.readObject(); * Date date = (Date)oin.readObject(); * * </PRE> * @see jade.lang.acl.ACLMessage#setContentBase64(byte[]) * @see jade.lang.acl.ACLMessage#getContent() * @see java.io.ObjectInputStream#readObject() */ private byte[] getContentBase64() { try { char[] cc = new char[content.length()]; content.getChars(0,content.length(),cc,0); return Base64.decode(cc); } catch(java.lang.StringIndexOutOfBoundsException e){ return new byte[0]; } catch(java.lang.NullPointerException e){ return new byte[0]; } catch(java.lang.NoClassDefFoundError jlncdfe) { System.err.println("\t\t===== E R R O R !!! =======\n"); System.err.println("Missing support for Base64 conversions"); System.err.println("Please refer to the documentation for details."); System.err.println("=============================================\n\n"); try { Thread.currentThread().sleep(3000); }catch(InterruptedException ie) { } return new byte[0]; } } /** * This method returns the content of this ACLMessage after decoding according to Base64. * It is not FIPA compliant so its usage is not encouraged. * For example to read Java objects from the content * (when they have been written by using the setContentOnbject() method): <br> * <PRE> * ACLMessage msg = blockingReceive(); * try{ * Date d = (Date)msg.getContentObject(); * }catch(UnreadableException e){} * </PRE> * * @return the object read from the content of this ACLMessage * @exception UnreadableException when an error occurs during the deconding. */ public Serializable getContentObject() throws UnreadableException { try{ ObjectInputStream oin = new ObjectInputStream(new ByteArrayInputStream(getContentBase64())); Serializable s = (Serializable)oin.readObject(); return s; } catch (java.lang.Error e) { throw new UnreadableException(e.getMessage()); } catch (IOException e1) { throw new UnreadableException(e1.getMessage()); } catch(ClassNotFoundException e2) { throw new UnreadableException(e2.getMessage()); } } /** Writes the <code>:reply-with</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param reply The new value for the slot. @see jade.lang.acl.ACLMessage#getReplyWith() */ public void setReplyWith(String reply) { if (reply != null) reply_with = new StringBuffer(reply); else reply_with = null; } /** Writes the <code>:in-reply-to</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param reply The new value for the slot. @see jade.lang.acl.ACLMessage#getInReplyTo() */ public void setInReplyTo(String reply) { if (reply != null) in_reply_to = new StringBuffer(reply); else in_reply_to = null; } /** Writes the <code>:encoding</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param str The new value for the slot. @see jade.lang.acl.ACLMessage#getEncoding() */ public void setEncoding(String str) { if (str != null) encoding = new StringBuffer(str); else encoding = null; } /** Writes the <code>:language</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param str The new value for the slot. @see jade.lang.acl.ACLMessage#getLanguage() */ public void setLanguage(String str) { if (str != null) language = new StringBuffer(str); else language = null; } /** Writes the <code>:ontology</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param str The new value for the slot. @see jade.lang.acl.ACLMessage#getOntology() */ public void setOntology(String str) { if (str != null) ontology = new StringBuffer(str); else ontology = null; } /** Writes the <code>:reply-by</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param str The new value for the slot, as ISO8601 time. @see jade.lang.acl.ACLMessage#getReplyBy() */ public void setReplyBy(String str) { if (str != null) { reply_by = new StringBuffer(str); try { reply_byInMillisec = ISO8601.toDate(str).getTime(); } catch (Exception e) { reply_byInMillisec = new Date().getTime(); // now } } else { reply_by = null; reply_byInMillisec = new Date().getTime(); } } /** Writes the <code>:reply-by</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param date The new value for the slot. @see jade.lang.acl.ACLMessage#getReplyByDate() */ public void setReplyByDate(Date date) { reply_byInMillisec = date.getTime(); reply_by = new StringBuffer(ISO8601.toString(date)); } /** Writes the <code>:protocol</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param str The new value for the slot. @see jade.lang.acl.ACLMessage#getProtocol() */ public void setProtocol( String str ) { if (str != null) protocol = new StringBuffer(str); else protocol = null; } /** Writes the <code>:conversation-id</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param str The new value for the slot. @see jade.lang.acl.ACLMessage#getConversationId() */ public void setConversationId( String str ) { if (str != null) conversation_id = new StringBuffer(str); else conversation_id = null; } /** Reads <code>:receiver</code> slot. @return An <code>Iterator</code> containing the Agent IDs of the receiver agents for this message. */ public Iterator getAllReceiver() { return dests.iterator(); } /** Reads <code>:reply_to</code> slot. @return An <code>Iterator</code> containing the Agent IDs of the reply_to agents for this message. */ public Iterator getAllReplyTo() { return reply_to.iterator(); } /** Reads <code>:sender</code> slot. @return The value of <code>:sender</code>slot. @see jade.lang.acl.ACLMessage#setSender(AID). */ public AID getSender() { if(source != null) return (AID)source.clone(); else return null; } /** Returns the string corresponding to the integer for the performative @return the string corresponding to the integer for the performative; "NOT-UNDERSTOOD" if the integer is out of range. */ public static String getPerformative(int perf){ try { return new String((String)performatives.get(perf)); } catch (Exception e) { return new String((String)performatives.get(NOT_UNDERSTOOD)); } } /** Returns the integer corresponding to the performative @returns the integer corresponding to the performative; -1 otherwise */ public static int getInteger(String perf) { return performatives.indexOf(perf.toUpperCase()); } /** * return the integer representing the performative of this object * @return an integer representing the performative of this object */ public int getPerformative() { return performative; } /** * Reads <code>:content</code> slot. <p> * It is sometimes useful to transport serialized Java objects, * or arbitrary sequence of bytes (i.e. something different from * a Java <code>String</code>) over an ACL message. See * getContentObject(). * @return The value of <code>:content</code> slot. * @see jade.lang.acl.ACLMessage#setContent(String) * @see jade.lang.acl.ACLMessage#getContentObject() * @see java.io.ObjectInputStream */ public String getContent() { if(content != null) return new String(content); else return null; } /** Reads <code>:reply-with</code> slot. @return The value of <code>:reply-with</code>slot. @see jade.lang.acl.ACLMessage#setReplyWith(String). */ public String getReplyWith() { if(reply_with != null) return new String(reply_with); else return null; } /** Reads <code>:reply-to</code> slot. @return The value of <code>:reply-to</code>slot. @see jade.lang.acl.ACLMessage#setInReplyTo(String). */ public String getInReplyTo() { if(in_reply_to != null) return new String(in_reply_to); else return null; } /** Reads <code>:encoding</code> slot. @return The value of <code>:encoding</code>slot. @see jade.lang.acl.ACLMessage#setEncoding(String). */ public String getEncoding() { if(encoding != null) return new String(encoding); else return null; } /** Reads <code>:language</code> slot. @return The value of <code>:language</code>slot. @see jade.lang.acl.ACLMessage#setLanguage(String). */ public String getLanguage() { if(language != null) return new String(language); else return null; } /** Reads <code>:ontology</code> slot. @return The value of <code>:ontology</code>slot. @see jade.lang.acl.ACLMessage#setOntology(String). */ public String getOntology() { if(ontology != null) return new String(ontology); else return null; } /** Reads <code>:reply-by</code> slot. @return The value of <code>:reply-by</code>slot, as a string. @see jade.lang.acl.ACLMessage#setReplyBy(String). */ public String getReplyBy() { if(reply_by != null) return new String(reply_by); else return null; } /** Reads <code>:reply-by</code> slot. @return The value of <code>:reply-by</code>slot, as a <code>Date</code> object. @see jade.lang.acl.ACLMessage#setReplyByDate(Date). */ public Date getReplyByDate() { if(reply_by != null) return new Date(reply_byInMillisec); else return null; } /** Reads <code>:protocol</code> slot. @return The value of <code>:protocol</code>slot. @see jade.lang.acl.ACLMessage#setProtocol(String). */ public String getProtocol() { if(protocol != null) return new String(protocol); else return null; } /** Reads <code>:conversation-id</code> slot. @return The value of <code>:conversation-id</code>slot. @see jade.lang.acl.ACLMessage#setConversationId(String). */ public String getConversationId() { if(conversation_id != null) return new String(conversation_id); else return null; } /** * Add a new user defined parameter to this ACLMessage. * Notice that according to the FIPA specifications, the keyword of a * user-defined parameter must start with the String ":X-". * If it does not, then this method adds the prefix silently! * @param key the property key. * @param value the property value **/ public void addUserDefinedParameter(String key, String value) { if (key.startsWith(":X-") || key.startsWith(":x-")) userDefProps.setProperty(key,value); else { System.err.println("WARNING: ACLMessage.addUserDefinedParameter. The key must start with :X-. Prefix has been silently added."); if (key.startsWith("X-") || key.startsWith("x-")) userDefProps.setProperty(":"+key,value); else userDefProps.setProperty(":X-"+key,value); } } /** * Searches for the user defined parameter with the specified key. * The method returns * <code>null</code> if the parameter is not found. * * @param key the parameter key. * @return the value in this ACLMessage with the specified key value. */ public String getUserDefinedParameter(String key){ return userDefProps.getProperty(key); } /** * get a clone of the data structure with all the user defined parameters **/ public Properties getAllUserDefinedParameters() { return (Properties)userDefProps.clone(); } /** * Removes the key and its corresponding value from the list of user * defined parameters in this ACLMessage. * @param key the key that needs to be removed @return true if the property has been found and removed, false otherwise */ public boolean removeUserDefinedParameter(String key) { return (userDefProps.remove(key) != null); } /** Attaches an envelope to this message. The envelope is used by the <b><it>ACC</it></b> for inter-platform messaging. @param e The <code>Envelope</code> object to attach to this message. @see jade.lang.acl#getEnvelope() @see jade.lang.acl#setDefaultEnvelope() */ public void setEnvelope(Envelope e) { messageEnvelope = e; } /** Writes the message envelope for this message, using the <code>:sender</code> and <code>:receiver</code> message slots to fill in the envelope. @see jade.lang.acl#setEnvelope(Envelope e) @see jade.lang.acl#getEnvelope() */ public void setDefaultEnvelope() { messageEnvelope = new Envelope(); messageEnvelope.setFrom(source); Iterator it = dests.iterator(); while(it.hasNext()) messageEnvelope.addTo((AID)it.next()); messageEnvelope.setAclRepresentation(StringACLCodec.NAME); messageEnvelope.setDate(new Date()); } /** Reads the envelope attached to this message, if any. @return The envelope for this message. @see jade.lang.acl#setEnvelope(Envelope e) @see jade.lang.acl#setDefaultEnvelope() */ public Envelope getEnvelope() { return messageEnvelope; } /** Writes an ACL message object on a stream as a character string. This method allows to write a string representation of an <code>ACLMessage</code> object onto a character stream. @param w A <code>Writer</code> object to write the message onto. */ public void toText(Writer w) { try { w.write("("); w.write(getPerformative(getPerformative()) + "\n"); if (source != null) { w.write(SENDER + " "); source.toText(w); w.write("\n"); } if (dests.size() > 0) { w.write(RECEIVER + " (set "); Iterator it = dests.iterator(); while(it.hasNext()) { ((AID)it.next()).toText(w); w.write(" "); } w.write(")\n"); } if (reply_to.size() > 0) { w.write(REPLY_TO + " (set \n"); Iterator it = reply_to.iterator(); while(it.hasNext()) { ((AID)it.next()).toText(w); w.write(" "); } w.write(")\n"); } if(content != null) if(content.length() > 0) w.write(CONTENT + " \"" + escape(content) + "\" \n"); if(reply_with != null) if(reply_with.length() > 0) w.write(REPLY_WITH + " " + reply_with + "\n"); if(in_reply_to != null) if(in_reply_to.length() > 0) w.write(IN_REPLY_TO + " " + in_reply_to + "\n"); if(encoding != null) if(encoding.length() > 0) w.write(ENCODING + " " + encoding + "\n"); if(language != null) if(language.length() > 0) w.write(LANGUAGE + " " + language + "\n"); if(ontology != null) if(ontology.length() > 0) w.write(ONTOLOGY + " " + ontology + "\n"); if(reply_by != null) if(reply_by.length() > 0) w.write(REPLY_BY + " " + reply_by + "\n"); if(protocol != null) if(protocol.length() > 0) w.write(PROTOCOL + " " + protocol + "\n"); if(conversation_id != null) if(conversation_id.length() > 0) w.write(CONVERSATION_ID + " " + conversation_id + "\n"); Enumeration e = userDefProps.propertyNames(); String tmp; while (e.hasMoreElements()) { tmp = (String)e.nextElement(); w.write(" " + tmp + " " + userDefProps.getProperty(tmp) + "\n"); } w.write(")"); w.flush(); } catch(IOException ioe) { ioe.printStackTrace(); } } /** Clone an <code>ACLMessage</code> object. @return A copy of this <code>ACLMessage</code> object. The copy must be casted back to <code>ACLMessage</code> type before being used. */ public synchronized Object clone() { ACLMessage result; try { result = (ACLMessage)super.clone(); result.dests = (ArrayList)dests.clone(); // Deep copy result.reply_to = (ArrayList)reply_to.clone(); // Deep copy } catch(CloneNotSupportedException cnse) { throw new InternalError(); // This should never happen } return result; } /** Convert an ACL message to its string representation. This method writes a representation of this <code>ACLMessage</code> into a character string. @return A <code>String</code> representing this message. */ public String toString(){ StringWriter text = new StringWriter(); toText(text); return text.toString(); } /** * Resets all the message slots. */ public void reset() { source = null; dests.clear(); reply_to.clear(); performative = NOT_UNDERSTOOD; content = null; reply_with = null; in_reply_to = null; encoding = null; language = null; ontology = null; reply_by = null; reply_byInMillisec = new Date().getTime(); protocol = null; conversation_id = null; userDefProps.clear(); } /** * create a new ACLMessage that is a reply to this message. * In particular, it sets the following parameters of the new message: * receiver, language, ontology, protocol, conversation-id, * in-reply-to, reply-with. * The programmer needs to set the communicative-act and the content. * Of course, if he wishes to do that, he can reset any of the fields. * @return the ACLMessage to send as a reply */ public ACLMessage createReply() { ACLMessage m = (ACLMessage)clone(); m.clearAllReceiver(); Iterator it = reply_to.iterator(); while (it.hasNext()) m.addReceiver((AID)it.next()); if (reply_to.isEmpty()) m.addReceiver(getSender()); m.clearAllReplyTo(); m.setLanguage(getLanguage()); m.setOntology(getOntology()); m.setProtocol(getProtocol()); m.setSender(null); m.setInReplyTo(getReplyWith()); if (source != null) m.setReplyWith(source.getName() + java.lang.System.currentTimeMillis()); else m.setReplyWith("X"+java.lang.System.currentTimeMillis()); m.setConversationId(getConversationId()); m.setReplyBy(null); m.setContent(null); m.setEncoding(null); //Set the Aclrepresentation of the reply message to the aclrepresentation of the sent message if (messageEnvelope != null) { String aclCodec= messageEnvelope.getAclRepresentation(); if (aclCodec != null) { m.setDefaultEnvelope(); m.getEnvelope().setAclRepresentation(aclCodec); } } else m.setEnvelope(null); return m; } private String escape(StringBuffer s) { // Make the stringBuffer a little larger than strictly // necessary in case we need to insert any additional // characters. (If our size estimate is wrong, the // StringBuffer will automatically grow as needed). StringBuffer result = new StringBuffer(s.length()+20); for( int i=0; i<s.length(); i++) if( s.charAt(i) == '"' ) result.append("\\\""); else result.append(s.charAt(i)); return result.toString(); } }
src/jade/lang/acl/ACLMessage.java
/***************************************************************** JADE - Java Agent DEvelopment Framework is a framework to develop multi-agent systems in compliance with the FIPA specifications. Copyright (C) 2000 CSELT S.p.A. GNU Lesser General Public License 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, version 2.1 of the License. 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 jade.lang.acl; import java.io.Reader; import java.io.Writer; import java.io.Serializable; import java.io.IOException; import java.io.StringWriter; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import java.io.ObjectOutputStream; import java.io.ObjectInputStream; import java.lang.ClassNotFoundException; import java.util.Date; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.util.Properties; import java.util.Enumeration; import jade.core.AID; import jade.domain.FIPAAgentManagement.Envelope; import starlight.util.Base64; /** * The class ACLMessage implements an ACL message compliant to the <b>FIPA 97</b> specs. * All parameters are couples <em>keyword: value</em>. * All keywords are <code>private final String</code>. * All values can be set by using the methods <em>set</em> and can be read by using * the methods <em>get</em>. <p> * Notice that the <em>get</em> methods never * return null, rather they return an empty String. <p> * The methods <code> setContentObject() </code> and * <code> getContentObject() </code> allow to send * serialized Java objects over the content of an ACLMessage. * These method are not FIPA compliant so their usage is not encouraged. @author Fabio Bellifemine - CSELT @version $Date$ $Revision$ */ public class ACLMessage implements Cloneable, Serializable { /** constant identifying the FIPA performative **/ public static final int ACCEPT_PROPOSAL = 0; /** constant identifying the FIPA performative **/ public static final int AGREE = 1; /** constant identifying the FIPA performative **/ public static final int CANCEL = 2; /** constant identifying the FIPA performative **/ public static final int CFP = 3; /** constant identifying the FIPA performative **/ public static final int CONFIRM = 4; /** constant identifying the FIPA performative **/ public static final int DISCONFIRM = 5; /** constant identifying the FIPA performative **/ public static final int FAILURE = 6; /** constant identifying the FIPA performative **/ public static final int INFORM = 7; /** constant identifying the FIPA performative **/ public static final int INFORM_IF = 8; /** constant identifying the FIPA performative **/ public static final int INFORM_REF = 9; /** constant identifying the FIPA performative **/ public static final int NOT_UNDERSTOOD = 10; /** constant identifying the FIPA performative **/ public static final int PROPOSE = 11; /** constant identifying the FIPA performative **/ public static final int QUERY_IF = 12; /** constant identifying the FIPA performative **/ public static final int QUERY_REF = 13; /** constant identifying the FIPA performative **/ public static final int REFUSE = 14; /** constant identifying the FIPA performative **/ public static final int REJECT_PROPOSAL = 15; /** constant identifying the FIPA performative **/ public static final int REQUEST = 16; /** constant identifying the FIPA performative **/ public static final int REQUEST_WHEN = 17; /** constant identifying the FIPA performative **/ public static final int REQUEST_WHENEVER = 18; /** constant identifying the FIPA performative **/ public static final int SUBSCRIBE = 19; /** constant identifying the FIPA performative **/ public static final int PROXY = 20; /** constant identifying the FIPA performative **/ public static final int PROPAGATE = 21; /** constant identifying an unknown performative **/ public static final int UNKNOWN = -1; /** @serial */ private int performative; // keeps the performative type of this object private static List performatives = new ArrayList(22); static { // initialization of the Vector of performatives performatives.add("ACCEPT-PROPOSAL"); performatives.add("AGREE"); performatives.add("CANCEL"); performatives.add("CFP"); performatives.add("CONFIRM"); performatives.add("DISCONFIRM"); performatives.add("FAILURE"); performatives.add("INFORM"); performatives.add("INFORM-IF"); performatives.add("INFORM-REF"); performatives.add("NOT-UNDERSTOOD"); performatives.add("PROPOSE"); performatives.add("QUERY-IF"); performatives.add("QUERY-REF"); performatives.add("REFUSE"); performatives.add("REJECT-PROPOSAL"); performatives.add("REQUEST"); performatives.add("REQUEST-WHEN"); performatives.add("REQUEST-WHENEVER"); performatives.add("SUBSCRIBE"); performatives.add("PROXY"); performatives.add("PROPAGATE"); } private static final String SENDER = new String(" :sender "); private static final String RECEIVER = new String(" :receiver "); private static final String CONTENT = new String(" :content "); private static final String REPLY_WITH = new String(" :reply-with "); private static final String IN_REPLY_TO = new String(" :in-reply-to "); private static final String REPLY_TO = new String(" :reply-to "); private static final String LANGUAGE = new String(" :language "); private static final String ENCODING = new String(" :encoding "); private static final String ONTOLOGY = new String(" :ontology "); private static final String REPLY_BY = new String(" :reply-by "); private static final String PROTOCOL = new String(" :protocol "); private static final String CONVERSATION_ID = new String(" :conversation-id "); /** @serial */ private AID source = null; /** @serial */ private ArrayList dests = new ArrayList(); /** @serial */ private ArrayList reply_to = new ArrayList(); /** @serial */ private StringBuffer content = null; /** @serial */ private StringBuffer reply_with = null; /** @serial */ private StringBuffer in_reply_to = null; /** @serial */ private StringBuffer encoding = null; /** @serial */ private StringBuffer language = null; /** @serial */ private StringBuffer ontology = null; /** @serial */ private StringBuffer reply_by = null; /** @serial */ private long reply_byInMillisec; /** @serial */ private StringBuffer protocol = null; /** @serial */ private StringBuffer conversation_id = null; /** @serial */ private Properties userDefProps = new Properties(); private Envelope messageEnvelope; /** Returns the list of the communicative acts. */ public static List getAllPerformatives() { return performatives; } /** @deprecated Since every ACL Message must have a message type, you should use the new constructor which gets a message type as a parameter. To avoid problems, now this constructor silently sets the message type to <code>not-understood</code>. @see jade.lang.acl.ACLMessage#ACLMessage(String type) */ public ACLMessage() { performative = NOT_UNDERSTOOD; } /** @deprecated It increases the probability of error when the passed String does not belong to the set of performatives supported by FIPA. This constructor creates an ACL message object with the specified type. To avoid problems, the constructor <code>ACLMessage(int)</code> should be used instead. @param type The type of the communicative act represented by this message. @see jade.lang.acl.ACLMessage#ACLMessage(int type) */ public ACLMessage(String type) { performative = performatives.indexOf(type.toUpperCase()); } /** * This constructor creates an ACL message object with the specified * performative. If the passed integer does not correspond to any of * the known performatives, it silently initializes the message to * <code>not-understood</code>. **/ public ACLMessage(int perf) { performative = perf; } /** Writes the <code>:sender</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param source The new value for the slot. @see jade.lang.acl.ACLMessage#getSender() */ public void setSender(AID s) { if (s != null) source = (AID)s.clone(); else source = null; } /** Adds a value to <code>:receiver</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param r The value to add to the slot value set. */ public void addReceiver(AID r) { if(r != null) dests.add(r); } /** Removes a value from <code>:receiver</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param r The value to remove from the slot value set. @return true if the AID has been found and removed, false otherwise */ public boolean removeReceiver(AID r) { if (r != null) return dests.remove(r); else return false; } /** Removes all values from <code>:receiver</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> */ public void clearAllReceiver() { dests.clear(); } /** Adds a value to <code>:reply-to</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param dest The value to add to the slot value set. */ public void addReplyTo(AID dest) { if (dest != null) reply_to.add(dest); } /** Removes a value from <code>:reply_to</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param dest The value to remove from the slot value set. @return true if the AID has been found and removed, false otherwise */ public boolean removeReplyTo(AID dest) { if (dest != null) return reply_to.remove(dest); else return false; } /** Removes all values from <code>:reply_to</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> */ public void clearAllReplyTo() { reply_to.clear(); } /** * set the performative of this ACL message object to the passed constant. * Remind to * use the set of constants (i.e. <code> INFORM, REQUEST, ... </code>) * defined in this class */ public void setPerformative(int perf) { performative = perf; } /** * Writes the <code>:content</code> slot. <em><b>Warning:</b> no * checks are made to validate the slot value.</em> <p> * In order to transport serialized Java objects, * or arbitrary sequence of bytes (i.e. something different from * a Java <code>String</code>) over an ACL message, it is suggested to use * the method <code>ACLMessage.setContentObject()</code> instead. * @param content The new value for the slot. * @see jade.lang.acl.ACLMessage#getContent() * @see jade.lang.acl.ACLMessage#setContentObject(Serializable s) */ public void setContent(String content) { if (content != null) this.content = new StringBuffer(content); else this.content = null; } /** * This method sets the current content of this ACLmessage to * the passed sequence of bytes. * Base64 encoding is applied. <p> * This method should be used to write serialized Java objects over the * content of an ACL Message to override the limitations of the Strings. <p> * For example, to write Java objects into the content: <br> * <PRE> * ACLMessage msg; * ByteArrayOutputStream c = new ByteArrayOutputStream(); * ObjectOutputStream oos = new ObjectOutputStream(c); * oos.writeInt(1234); * oos.writeObject("Today"); * oos.writeObject(new Date()); * oos.flush(); * msg.setContentBase64(c.toByteArray()); * * </PRE> * * @see jade.lang.acl.ACLMessage#getContentBase64() * @see jade.lang.acl.ACLMessage#getContent() * @see java.io.ObjectOutputStream#writeObject(Object o) * @param bytes is the the sequence of bytes to be appended to the content of this message */ private void setContentBase64(byte[] bytes) { try { content = new StringBuffer().append(Base64.encode(bytes)); } catch(java.lang.NoClassDefFoundError jlncdfe) { System.err.println("\n\t===== E R R O R !!! =======\n"); System.err.println("Missing support for Base64 conversions"); System.err.println("Please refer to the documentation for details."); System.err.println("=============================================\n\n"); System.err.println(""); try { Thread.currentThread().sleep(3000); } catch(InterruptedException ie) { } content = null; } } /** * This method sets the content of this ACLMessage to a Java object. * It is not FIPA compliant so its usage is not encouraged. * For example:<br> * <PRE> * ACLMessage msg = new ACLMessage(ACLMessage.INFORM); * Date d = new Date(); * try{ * msg.setContentObject(d); * }catch(IOException e){} * </PRE> * * @param s the object that will be used to set the content of the ACLMessage. * @exception IOException if an I/O error occurs. */ public void setContentObject(Serializable s) throws IOException { ByteArrayOutputStream c = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(c); oos.writeObject(s); oos.flush(); setContentBase64(c.toByteArray()); } /** * This method returns the content of this ACLmessage * after decoding according to Base64. * For example to read Java objects from the content * (when they have been written by using the setContentBase64() method,: <br> * <PRE> * ACLMessage msg; * ObjectInputStream oin = new ObjectInputStream(new ByteArrayInputStream(msg.getContentBase64()));; * * int i = oin.readInt(); * String today = (String)oin.readObject(); * Date date = (Date)oin.readObject(); * * </PRE> * @see jade.lang.acl.ACLMessage#setContentBase64(byte[]) * @see jade.lang.acl.ACLMessage#getContent() * @see java.io.ObjectInputStream#readObject() */ private byte[] getContentBase64() { try { char[] cc = new char[content.length()]; content.getChars(0,content.length(),cc,0); return Base64.decode(cc); } catch(java.lang.StringIndexOutOfBoundsException e){ return new byte[0]; } catch(java.lang.NullPointerException e){ return new byte[0]; } catch(java.lang.NoClassDefFoundError jlncdfe) { System.err.println("\t\t===== E R R O R !!! =======\n"); System.err.println("Missing support for Base64 conversions"); System.err.println("Please refer to the documentation for details."); System.err.println("=============================================\n\n"); try { Thread.currentThread().sleep(3000); }catch(InterruptedException ie) { } return new byte[0]; } } /** * This method returns the content of this ACLMessage after decoding according to Base64. * It is not FIPA compliant so its usage is not encouraged. * For example to read Java objects from the content * (when they have been written by using the setContentOnbject() method): <br> * <PRE> * ACLMessage msg = blockingReceive(); * try{ * Date d = (Date)msg.getContentObject(); * }catch(UnreadableException e){} * </PRE> * * @return the object read from the content of this ACLMessage * @exception UnreadableException when an error occurs during the deconding. */ public Serializable getContentObject() throws UnreadableException { try{ ObjectInputStream oin = new ObjectInputStream(new ByteArrayInputStream(getContentBase64())); Serializable s = (Serializable)oin.readObject(); return s; } catch (java.lang.Error e) { throw new UnreadableException(e.getMessage()); } catch (IOException e1) { throw new UnreadableException(e1.getMessage()); } catch(ClassNotFoundException e2) { throw new UnreadableException(e2.getMessage()); } } /** Writes the <code>:reply-with</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param reply The new value for the slot. @see jade.lang.acl.ACLMessage#getReplyWith() */ public void setReplyWith(String reply) { if (reply != null) reply_with = new StringBuffer(reply); else reply_with = null; } /** Writes the <code>:in-reply-to</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param reply The new value for the slot. @see jade.lang.acl.ACLMessage#getInReplyTo() */ public void setInReplyTo(String reply) { if (reply != null) in_reply_to = new StringBuffer(reply); else in_reply_to = null; } /** Writes the <code>:encoding</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param str The new value for the slot. @see jade.lang.acl.ACLMessage#getEncoding() */ public void setEncoding(String str) { if (str != null) encoding = new StringBuffer(str); else encoding = null; } /** Writes the <code>:language</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param str The new value for the slot. @see jade.lang.acl.ACLMessage#getLanguage() */ public void setLanguage(String str) { if (str != null) language = new StringBuffer(str); else language = null; } /** Writes the <code>:ontology</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param str The new value for the slot. @see jade.lang.acl.ACLMessage#getOntology() */ public void setOntology(String str) { if (str != null) ontology = new StringBuffer(str); else ontology = null; } /** Writes the <code>:reply-by</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param str The new value for the slot, as ISO8601 time. @see jade.lang.acl.ACLMessage#getReplyBy() */ public void setReplyBy(String str) { if (str != null) { reply_by = new StringBuffer(str); try { reply_byInMillisec = ISO8601.toDate(str).getTime(); } catch (Exception e) { reply_byInMillisec = new Date().getTime(); // now } } else { reply_by = null; reply_byInMillisec = new Date().getTime(); } } /** Writes the <code>:reply-by</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param date The new value for the slot. @see jade.lang.acl.ACLMessage#getReplyByDate() */ public void setReplyByDate(Date date) { reply_byInMillisec = date.getTime(); reply_by = new StringBuffer(ISO8601.toString(date)); } /** Writes the <code>:protocol</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param str The new value for the slot. @see jade.lang.acl.ACLMessage#getProtocol() */ public void setProtocol( String str ) { if (str != null) protocol = new StringBuffer(str); else protocol = null; } /** Writes the <code>:conversation-id</code> slot. <em><b>Warning:</b> no checks are made to validate the slot value.</em> @param str The new value for the slot. @see jade.lang.acl.ACLMessage#getConversationId() */ public void setConversationId( String str ) { if (str != null) conversation_id = new StringBuffer(str); else conversation_id = null; } /** Reads <code>:receiver</code> slot. @return An <code>Iterator</code> containing the Agent IDs of the receiver agents for this message. */ public Iterator getAllReceiver() { return dests.iterator(); } /** Reads <code>:reply_to</code> slot. @return An <code>Iterator</code> containing the Agent IDs of the reply_to agents for this message. */ public Iterator getAllReplyTo() { return reply_to.iterator(); } /** Reads <code>:sender</code> slot. @return The value of <code>:sender</code>slot. @see jade.lang.acl.ACLMessage#setSender(AID). */ public AID getSender() { if(source != null) return (AID)source.clone(); else return null; } /** Returns the string corresponding to the integer for the performative @return the string corresponding to the integer for the performative; "NOT-UNDERSTOOD" if the integer is out of range. */ public static String getPerformative(int perf){ try { return new String((String)performatives.get(perf)); } catch (Exception e) { return new String((String)performatives.get(NOT_UNDERSTOOD)); } } /** Returns the integer corresponding to the performative @returns the integer corresponding to the performative; -1 otherwise */ public static int getInteger(String perf) { return performatives.indexOf(perf.toUpperCase()); } /** * return the integer representing the performative of this object * @return an integer representing the performative of this object */ public int getPerformative() { return performative; } /** * Reads <code>:content</code> slot. <p> * It is sometimes useful to transport serialized Java objects, * or arbitrary sequence of bytes (i.e. something different from * a Java <code>String</code>) over an ACL message. See * getContentObject(). * @return The value of <code>:content</code> slot. * @see jade.lang.acl.ACLMessage#setContent(String) * @see jade.lang.acl.ACLMessage#getContentObject() * @see java.io.ObjectInputStream */ public String getContent() { if(content != null) return new String(content); else return null; } /** Reads <code>:reply-with</code> slot. @return The value of <code>:reply-with</code>slot. @see jade.lang.acl.ACLMessage#setReplyWith(String). */ public String getReplyWith() { if(reply_with != null) return new String(reply_with); else return null; } /** Reads <code>:reply-to</code> slot. @return The value of <code>:reply-to</code>slot. @see jade.lang.acl.ACLMessage#setInReplyTo(String). */ public String getInReplyTo() { if(in_reply_to != null) return new String(in_reply_to); else return null; } /** Reads <code>:encoding</code> slot. @return The value of <code>:encoding</code>slot. @see jade.lang.acl.ACLMessage#setEncoding(String). */ public String getEncoding() { if(encoding != null) return new String(encoding); else return null; } /** Reads <code>:language</code> slot. @return The value of <code>:language</code>slot. @see jade.lang.acl.ACLMessage#setLanguage(String). */ public String getLanguage() { if(language != null) return new String(language); else return null; } /** Reads <code>:ontology</code> slot. @return The value of <code>:ontology</code>slot. @see jade.lang.acl.ACLMessage#setOntology(String). */ public String getOntology() { if(ontology != null) return new String(ontology); else return null; } /** Reads <code>:reply-by</code> slot. @return The value of <code>:reply-by</code>slot, as a string. @see jade.lang.acl.ACLMessage#setReplyBy(String). */ public String getReplyBy() { if(reply_by != null) return new String(reply_by); else return null; } /** Reads <code>:reply-by</code> slot. @return The value of <code>:reply-by</code>slot, as a <code>Date</code> object. @see jade.lang.acl.ACLMessage#setReplyByDate(Date). */ public Date getReplyByDate() { if(reply_by != null) return new Date(reply_byInMillisec); else return null; } /** Reads <code>:protocol</code> slot. @return The value of <code>:protocol</code>slot. @see jade.lang.acl.ACLMessage#setProtocol(String). */ public String getProtocol() { if(protocol != null) return new String(protocol); else return null; } /** Reads <code>:conversation-id</code> slot. @return The value of <code>:conversation-id</code>slot. @see jade.lang.acl.ACLMessage#setConversationId(String). */ public String getConversationId() { if(conversation_id != null) return new String(conversation_id); else return null; } /** * Add a new user defined parameter to this ACLMessage. * Notice that according to the FIPA specifications, the keyword of a * user-defined parameter must start with the String ":X-". * If it does not, then this method adds the prefix silently! * @param key the property key. * @param value the property value **/ public void addUserDefinedParameter(String key, String value) { if (key.startsWith(":X-") || key.startsWith(":x-")) userDefProps.setProperty(key,value); else { System.err.println("WARNING: ACLMessage.addUserDefinedParameter. The key must start with :X-. Prefix has been silently added."); if (key.startsWith("X-") || key.startsWith("x-")) userDefProps.setProperty(":"+key,value); else userDefProps.setProperty(":X-"+key,value); } } /** * Searches for the user defined parameter with the specified key. * The method returns * <code>null</code> if the parameter is not found. * * @param key the parameter key. * @return the value in this ACLMessage with the specified key value. */ public String getUserDefinedParameter(String key){ return userDefProps.getProperty(key); } /** * get a clone of the data structure with all the user defined parameters **/ public Properties getAllUserDefinedParameters() { return (Properties)userDefProps.clone(); } /** * Removes the key and its corresponding value from the list of user * defined parameters in this ACLMessage. * @param key the key that needs to be removed @return true if the property has been found and removed, false otherwise */ public boolean removeUserDefinedParameter(String key) { return (userDefProps.remove(key) != null); } /** Attaches an envelope to this message. The envelope is used by the <b><it>ACC</it></b> for inter-platform messaging. @param e The <code>Envelope</code> object to attach to this message. @see jade.lang.acl#getEnvelope() @see jade.lang.acl#setDefaultEnvelope() */ public void setEnvelope(Envelope e) { messageEnvelope = e; } /** Writes the message envelope for this message, using the <code>:sender</code> and <code>:receiver</code> message slots to fill in the envelope. @see jade.lang.acl#setEnvelope(Envelope e) @see jade.lang.acl#getEnvelope() */ public void setDefaultEnvelope() { messageEnvelope = new Envelope(); messageEnvelope.setFrom(source); Iterator it = dests.iterator(); while(it.hasNext()) messageEnvelope.addTo((AID)it.next()); messageEnvelope.setAclRepresentation(StringACLCodec.NAME); messageEnvelope.setDate(new Date()); } /** Reads the envelope attached to this message, if any. @return The envelope for this message. @see jade.lang.acl#setEnvelope(Envelope e) @see jade.lang.acl#setDefaultEnvelope() */ public Envelope getEnvelope() { return messageEnvelope; } /** Writes an ACL message object on a stream as a character string. This method allows to write a string representation of an <code>ACLMessage</code> object onto a character stream. @param w A <code>Writer</code> object to write the message onto. */ public void toText(Writer w) { try { w.write("("); w.write(getPerformative(getPerformative()) + "\n"); if (source != null) { w.write(SENDER + " "); source.toText(w); w.write("\n"); } if (dests.size() > 0) { w.write(RECEIVER + " (set "); Iterator it = dests.iterator(); while(it.hasNext()) { ((AID)it.next()).toText(w); w.write(" "); } w.write(")\n"); } if (reply_to.size() > 0) { w.write(REPLY_TO + " (set \n"); Iterator it = reply_to.iterator(); while(it.hasNext()) { ((AID)it.next()).toText(w); w.write(" "); } w.write(")\n"); } if(content != null) if(content.length() > 0) w.write(CONTENT + " \"" + escape(content) + " \"\n"); if(reply_with != null) if(reply_with.length() > 0) w.write(REPLY_WITH + " " + reply_with + "\n"); if(in_reply_to != null) if(in_reply_to.length() > 0) w.write(IN_REPLY_TO + " " + in_reply_to + "\n"); if(encoding != null) if(encoding.length() > 0) w.write(ENCODING + " " + encoding + "\n"); if(language != null) if(language.length() > 0) w.write(LANGUAGE + " " + language + "\n"); if(ontology != null) if(ontology.length() > 0) w.write(ONTOLOGY + " " + ontology + "\n"); if(reply_by != null) if(reply_by.length() > 0) w.write(REPLY_BY + " " + reply_by + "\n"); if(protocol != null) if(protocol.length() > 0) w.write(PROTOCOL + " " + protocol + "\n"); if(conversation_id != null) if(conversation_id.length() > 0) w.write(CONVERSATION_ID + " " + conversation_id + "\n"); Enumeration e = userDefProps.propertyNames(); String tmp; while (e.hasMoreElements()) { tmp = (String)e.nextElement(); w.write(" " + tmp + " " + userDefProps.getProperty(tmp) + "\n"); } w.write(")"); w.flush(); } catch(IOException ioe) { ioe.printStackTrace(); } } /** Clone an <code>ACLMessage</code> object. @return A copy of this <code>ACLMessage</code> object. The copy must be casted back to <code>ACLMessage</code> type before being used. */ public synchronized Object clone() { ACLMessage result; try { result = (ACLMessage)super.clone(); result.dests = (ArrayList)dests.clone(); // Deep copy result.reply_to = (ArrayList)reply_to.clone(); // Deep copy } catch(CloneNotSupportedException cnse) { throw new InternalError(); // This should never happen } return result; } /** Convert an ACL message to its string representation. This method writes a representation of this <code>ACLMessage</code> into a character string. @return A <code>String</code> representing this message. */ public String toString(){ StringWriter text = new StringWriter(); toText(text); return text.toString(); } /** * Resets all the message slots. */ public void reset() { source = null; dests.clear(); reply_to.clear(); performative = NOT_UNDERSTOOD; content = null; reply_with = null; in_reply_to = null; encoding = null; language = null; ontology = null; reply_by = null; reply_byInMillisec = new Date().getTime(); protocol = null; conversation_id = null; userDefProps.clear(); } /** * create a new ACLMessage that is a reply to this message. * In particular, it sets the following parameters of the new message: * receiver, language, ontology, protocol, conversation-id, * in-reply-to, reply-with. * The programmer needs to set the communicative-act and the content. * Of course, if he wishes to do that, he can reset any of the fields. * @return the ACLMessage to send as a reply */ public ACLMessage createReply() { ACLMessage m = (ACLMessage)clone(); m.clearAllReceiver(); Iterator it = reply_to.iterator(); while (it.hasNext()) m.addReceiver((AID)it.next()); if (reply_to.isEmpty()) m.addReceiver(getSender()); m.clearAllReplyTo(); m.setLanguage(getLanguage()); m.setOntology(getOntology()); m.setProtocol(getProtocol()); m.setSender(null); m.setInReplyTo(getReplyWith()); if (source != null) m.setReplyWith(source.getName() + java.lang.System.currentTimeMillis()); else m.setReplyWith("X"+java.lang.System.currentTimeMillis()); m.setConversationId(getConversationId()); m.setReplyBy(null); m.setContent(null); m.setEncoding(null); //Set the Aclrepresentation of the reply message to the aclrepresentation of the sent message if (messageEnvelope != null) { String aclCodec= messageEnvelope.getAclRepresentation(); if (aclCodec != null) { m.setDefaultEnvelope(); m.getEnvelope().setAclRepresentation(aclCodec); } } else m.setEnvelope(null); return m; } private String escape(StringBuffer s) { // Make the stringBuffer a little larger than strictly // necessary in case we need to insert any additional // characters. (If our size estimate is wrong, the // StringBuffer will automatically grow as needed). StringBuffer result = new StringBuffer(s.length()+20); for( int i=0; i<s.length(); i++) if( s.charAt(i) == '"' ) result.append("\\\""); else result.append(s.charAt(i)); return result.toString(); } }
Removed an additional blank at the end of the content slot.
src/jade/lang/acl/ACLMessage.java
Removed an additional blank at the end of the content slot.
<ide><path>rc/jade/lang/acl/ACLMessage.java <ide> } <ide> if(content != null) <ide> if(content.length() > 0) <del> w.write(CONTENT + " \"" + escape(content) + " \"\n"); <add> w.write(CONTENT + " \"" + escape(content) + "\" \n"); <ide> if(reply_with != null) <ide> if(reply_with.length() > 0) <ide> w.write(REPLY_WITH + " " + reply_with + "\n");
Java
apache-2.0
ce2ae87908dec60e86b8720a35da1648bd1d3a56
0
babble/babble,babble/babble,babble/babble,babble/babble,babble/babble,babble/babble
// JxpServlet.java /** * Copyright (C) 2008 10gen Inc. * * 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 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 ed.appserver.jxp; import java.io.*; import java.util.regex.*; import ed.js.*; import ed.util.*; import ed.js.engine.*; import ed.js.func.*; import ed.lang.*; import ed.appserver.*; import ed.net.httpserver.*; public class JxpServlet { public static final int MAX_WRITTEN_LENGTH = 1024 * 1024 * 15; public static final boolean NOCDN = Config.get().getBoolean( "NO-CDN" ); public JxpServlet( AppContext context , JSFunction func ){ _context = context; _theFunction = func; } public void handle( HttpRequest request , HttpResponse response , AppRequest ar ){ final Scope scope = ar.getScope(); if ( scope.get( "request" ) == null ) scope.put( "request" , request , true ); if ( scope.get( "response" ) == null ) scope.put( "response" , response , true ); Object cdnFromScope = scope.get( "CDN" ); MyWriter writer = new MyWriter( response.getWriter() , ar.getURLFixer() ); scope.put( "print" , writer , true ); try { _theFunction.call( scope , request , response , writer ); if ( writer._writer.hasSpot() ){ writer._writer.backToSpot(); if ( ar.getContext() != null ) for ( Object foo : ar.getContext().getGlobalHead() ) { writer.print( foo.toString() ); writer.print( "\n" ); } if ( ar != null ) for ( Object foo : ar.getHeadToPrint() ) { writer.print( foo.toString() ); writer.print( "\n" ); } writer._writer.backToEnd(); } else { if ( ( ar.getContext() != null && ar.getContext().getGlobalHead().size() > 0 ) || ( ar != null && ar.getHeadToPrint().size() > 0 ) ){ // this is interesting // maybe i should do it only for html files // so i have to know that //throw new RuntimeException( "have head to print but no </head>" ); } } } catch ( RuntimeException re ){ if ( re instanceof JSException ){ if ( re.getCause() != null && re.getCause() instanceof RuntimeException ) re = (RuntimeException)re.getCause(); } StackTraceHolder.getInstance().fix( re ); throw re; } } public static class MyWriter extends JSFunctionCalls1 { public MyWriter( JxpWriter writer , String cdnPrefix , String cdnSuffix , AppContext context ){ this( writer , new URLFixer( cdnPrefix , cdnSuffix , context ) ); } public MyWriter( JxpWriter writer , URLFixer fixer ){ _writer = writer; _fixer = fixer; if ( _writer == null ) throw new NullPointerException( "writer can't be null" ); set( "setFormObject" , new JSFunctionCalls1(){ public Object call( Scope scope , Object o , Object extra[] ){ if ( o == null ){ _formInput = null; return null; } if ( ! ( o instanceof JSObject ) ) throw new RuntimeException( "must be a JSObject" ); _formInput = (JSObject)o; _formInputPrefix = null; if ( extra != null && extra.length > 0 ) _formInputPrefix = extra[0].toString(); return o; } } ); } public Object get( Object n ){ if ( "cdnPrefix".equals( n ) ) return _fixer.getCDNPrefix(); if ( "cdnSuffix".equals( n ) ) return _fixer.getCDNSuffix(); return super.get( n ); } public Object set( Object n , Object v ){ if ( "cdnPrefix".equals( n ) ) return _fixer.setCDNPrefix( v.toString() ); if ( "cdnSuffix".equals( n ) ) return _fixer.setCDNSuffix( v.toString() ); return super.set( n , v ); } public Object call( Scope scope , Object o , Object extra[] ){ if ( o == null ) print( "null" ); else print( JSInternalFunctions.JS_toString( o ) ); return null; } public void print( String s ){ if ( ( _writtenLength += s.length() ) > MAX_WRITTEN_LENGTH ) throw new RuntimeException( "trying to write a dynamic page more than " + MAX_WRITTEN_LENGTH + " chars long" ); if ( _writer.closed() ) throw new RuntimeException( "output closed. are you using an old print function" ); while ( s.length() > 0 ){ if ( _extra.length() > 0 ){ _extra.append( s ); s = _extra.toString(); _extra.setLength( 0 ); } _matcher.reset( s ); if ( ! _matcher.find() ){ _writer.print( s ); return; } _writer.print( s.substring( 0 , _matcher.start() ) ); s = s.substring( _matcher.start() ); int end = endOfTag( s ); if ( end == -1 ){ _extra.append( s ); return; } String wholeTag = s.substring( 0 , end + 1 ); if ( ! printTag( _matcher.group(1) , wholeTag ) ) _writer.print( wholeTag ); s = s.substring( end + 1 ); } } /** * @return true if i printed tag so you should not */ boolean printTag( String tag , String s ){ if ( tag == null ) throw new NullPointerException( "tag can't be null" ); if ( s == null ) throw new NullPointerException( "show tag can't be null" ); if ( tag.equalsIgnoreCase( "/head" ) && ! _writer.hasSpot() ){ _writer.saveSpot(); return false; } { // CDN stuff String srcName = null; if ( tag.equalsIgnoreCase( "img" ) || tag.equalsIgnoreCase( "script" ) ) srcName = "src"; else if ( tag.equalsIgnoreCase( "link" ) ) srcName = "href"; if ( srcName != null ){ s = s.substring( 2 + tag.length() ); // TODO: cache pattern or something Matcher m = Pattern.compile( srcName + " *= *['\"](.+?)['\"]" , Pattern.CASE_INSENSITIVE ).matcher( s ); if ( ! m.find() ) return false; _writer.print( "<" ); _writer.print( tag ); _writer.print( " " ); _writer.print( s.substring( 0 , m.start(1) ) ); String src = m.group(1); printSRC( src ); _writer.print( s.substring( m.end(1) ) ); return true; } } if ( _formInput != null && tag.equalsIgnoreCase( "input" ) ){ Matcher m = Pattern.compile( "\\bname *= *['\"](.+?)[\"']" ).matcher( s ); if ( ! m.find() ) return false; String name = m.group(1); if ( name.length() == 0 ) return false; if ( _formInputPrefix != null ) name = name.substring( _formInputPrefix.length() ); Object val = _formInput.get( name ); if ( val == null ) return false; if ( s.toString().matches( "value *=" ) ) return false; _writer.print( s.substring( 0 , s.length() - 1 ) ); _writer.print( " value=\"" ); _writer.print( HtmlEscape.escape( val.toString() ) ); _writer.print( "\" >" ); return true; } return false; } /** * takes the actual src of the asset and fixes and prints * i.e. /foo -> static.com/foo */ void printSRC( String src ){ if ( src == null || src.length() == 0 ) return; _fixer.fix( src , _writer ); } int endOfTag( String s ){ for ( int i=0; i<s.length(); i++ ){ char c = s.charAt( i ); if ( c == '>' ) return i; if ( c == '"' || c == '\'' ){ for ( ; i<s.length(); i++) if ( c == s.charAt( i ) ) break; } } return -1; } static final Pattern _tagPattern = Pattern.compile( "<(/?\\w+)[ >]" , Pattern.CASE_INSENSITIVE ); final Matcher _matcher = _tagPattern.matcher(""); final StringBuilder _extra = new StringBuilder(); final JxpWriter _writer; final URLFixer _fixer; JSObject _formInput = null; String _formInputPrefix = null; int _writtenLength = 0; } final AppContext _context; final JSFunction _theFunction; }
src/main/ed/appserver/jxp/JxpServlet.java
// JxpServlet.java /** * Copyright (C) 2008 10gen Inc. * * 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 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 ed.appserver.jxp; import java.io.*; import java.util.regex.*; import ed.js.*; import ed.util.*; import ed.js.engine.*; import ed.js.func.*; import ed.lang.*; import ed.appserver.*; import ed.net.httpserver.*; public class JxpServlet { public static final int MAX_WRITTEN_LENGTH = 1024 * 1024 * 15; public static final boolean NOCDN = Config.get().getBoolean( "NO-CDN" ); public JxpServlet( AppContext context , JSFunction func ){ _context = context; _theFunction = func; } public void handle( HttpRequest request , HttpResponse response , AppRequest ar ){ final Scope scope = ar.getScope(); if ( scope.get( "request" ) == null ) scope.put( "request" , request , true ); if ( scope.get( "response" ) == null ) scope.put( "response" , response , true ); Object cdnFromScope = scope.get( "CDN" ); MyWriter writer = new MyWriter( response.getWriter() , ar.getURLFixer() ); scope.put( "print" , writer , true ); try { _theFunction.call( scope ); if ( writer._writer.hasSpot() ){ writer._writer.backToSpot(); if ( ar.getContext() != null ) for ( Object foo : ar.getContext().getGlobalHead() ) { writer.print( foo.toString() ); writer.print( "\n" ); } if ( ar != null ) for ( Object foo : ar.getHeadToPrint() ) { writer.print( foo.toString() ); writer.print( "\n" ); } writer._writer.backToEnd(); } else { if ( ( ar.getContext() != null && ar.getContext().getGlobalHead().size() > 0 ) || ( ar != null && ar.getHeadToPrint().size() > 0 ) ){ // this is interesting // maybe i should do it only for html files // so i have to know that //throw new RuntimeException( "have head to print but no </head>" ); } } } catch ( RuntimeException re ){ if ( re instanceof JSException ){ if ( re.getCause() != null && re.getCause() instanceof RuntimeException ) re = (RuntimeException)re.getCause(); } StackTraceHolder.getInstance().fix( re ); throw re; } } public static class MyWriter extends JSFunctionCalls1 { public MyWriter( JxpWriter writer , String cdnPrefix , String cdnSuffix , AppContext context ){ this( writer , new URLFixer( cdnPrefix , cdnSuffix , context ) ); } public MyWriter( JxpWriter writer , URLFixer fixer ){ _writer = writer; _fixer = fixer; if ( _writer == null ) throw new NullPointerException( "writer can't be null" ); set( "setFormObject" , new JSFunctionCalls1(){ public Object call( Scope scope , Object o , Object extra[] ){ if ( o == null ){ _formInput = null; return null; } if ( ! ( o instanceof JSObject ) ) throw new RuntimeException( "must be a JSObject" ); _formInput = (JSObject)o; _formInputPrefix = null; if ( extra != null && extra.length > 0 ) _formInputPrefix = extra[0].toString(); return o; } } ); } public Object get( Object n ){ if ( "cdnPrefix".equals( n ) ) return _fixer.getCDNPrefix(); if ( "cdnSuffix".equals( n ) ) return _fixer.getCDNSuffix(); return super.get( n ); } public Object set( Object n , Object v ){ if ( "cdnPrefix".equals( n ) ) return _fixer.setCDNPrefix( v.toString() ); if ( "cdnSuffix".equals( n ) ) return _fixer.setCDNSuffix( v.toString() ); return super.set( n , v ); } public Object call( Scope scope , Object o , Object extra[] ){ if ( o == null ) print( "null" ); else print( JSInternalFunctions.JS_toString( o ) ); return null; } public void print( String s ){ if ( ( _writtenLength += s.length() ) > MAX_WRITTEN_LENGTH ) throw new RuntimeException( "trying to write a dynamic page more than " + MAX_WRITTEN_LENGTH + " chars long" ); if ( _writer.closed() ) throw new RuntimeException( "output closed. are you using an old print function" ); while ( s.length() > 0 ){ if ( _extra.length() > 0 ){ _extra.append( s ); s = _extra.toString(); _extra.setLength( 0 ); } _matcher.reset( s ); if ( ! _matcher.find() ){ _writer.print( s ); return; } _writer.print( s.substring( 0 , _matcher.start() ) ); s = s.substring( _matcher.start() ); int end = endOfTag( s ); if ( end == -1 ){ _extra.append( s ); return; } String wholeTag = s.substring( 0 , end + 1 ); if ( ! printTag( _matcher.group(1) , wholeTag ) ) _writer.print( wholeTag ); s = s.substring( end + 1 ); } } /** * @return true if i printed tag so you should not */ boolean printTag( String tag , String s ){ if ( tag == null ) throw new NullPointerException( "tag can't be null" ); if ( s == null ) throw new NullPointerException( "show tag can't be null" ); if ( tag.equalsIgnoreCase( "/head" ) && ! _writer.hasSpot() ){ _writer.saveSpot(); return false; } { // CDN stuff String srcName = null; if ( tag.equalsIgnoreCase( "img" ) || tag.equalsIgnoreCase( "script" ) ) srcName = "src"; else if ( tag.equalsIgnoreCase( "link" ) ) srcName = "href"; if ( srcName != null ){ s = s.substring( 2 + tag.length() ); // TODO: cache pattern or something Matcher m = Pattern.compile( srcName + " *= *['\"](.+?)['\"]" , Pattern.CASE_INSENSITIVE ).matcher( s ); if ( ! m.find() ) return false; _writer.print( "<" ); _writer.print( tag ); _writer.print( " " ); _writer.print( s.substring( 0 , m.start(1) ) ); String src = m.group(1); printSRC( src ); _writer.print( s.substring( m.end(1) ) ); return true; } } if ( _formInput != null && tag.equalsIgnoreCase( "input" ) ){ Matcher m = Pattern.compile( "\\bname *= *['\"](.+?)[\"']" ).matcher( s ); if ( ! m.find() ) return false; String name = m.group(1); if ( name.length() == 0 ) return false; if ( _formInputPrefix != null ) name = name.substring( _formInputPrefix.length() ); Object val = _formInput.get( name ); if ( val == null ) return false; if ( s.toString().matches( "value *=" ) ) return false; _writer.print( s.substring( 0 , s.length() - 1 ) ); _writer.print( " value=\"" ); _writer.print( HtmlEscape.escape( val.toString() ) ); _writer.print( "\" >" ); return true; } return false; } /** * takes the actual src of the asset and fixes and prints * i.e. /foo -> static.com/foo */ void printSRC( String src ){ if ( src == null || src.length() == 0 ) return; _fixer.fix( src , _writer ); } int endOfTag( String s ){ for ( int i=0; i<s.length(); i++ ){ char c = s.charAt( i ); if ( c == '>' ) return i; if ( c == '"' || c == '\'' ){ for ( ; i<s.length(); i++) if ( c == s.charAt( i ) ) break; } } return -1; } static final Pattern _tagPattern = Pattern.compile( "<(/?\\w+)[ >]" , Pattern.CASE_INSENSITIVE ); final Matcher _matcher = _tagPattern.matcher(""); final StringBuilder _extra = new StringBuilder(); final JxpWriter _writer; final URLFixer _fixer; JSObject _formInput = null; String _formInputPrefix = null; int _writtenLength = 0; } final AppContext _context; final JSFunction _theFunction; }
servlets technically take request, response, print as parameters
src/main/ed/appserver/jxp/JxpServlet.java
servlets technically take request, response, print as parameters
<ide><path>rc/main/ed/appserver/jxp/JxpServlet.java <ide> scope.put( "print" , writer , true ); <ide> <ide> try { <del> _theFunction.call( scope ); <add> _theFunction.call( scope , request , response , writer ); <ide> <ide> if ( writer._writer.hasSpot() ){ <ide> writer._writer.backToSpot();
Java
lgpl-2.1
a1aa2c16f5227a5ed42a8ae8120fb16968835925
0
xcv58/polyglot,blue-systems-group/project.maybe.polyglot,xcv58/polyglot,liujed/polyglot-eclipse,blue-systems-group/project.maybe.polyglot,liujed/polyglot-eclipse,blue-systems-group/project.maybe.polyglot,liujed/polyglot-eclipse,xcv58/polyglot,blue-systems-group/project.maybe.polyglot,liujed/polyglot-eclipse,xcv58/polyglot
/* * This file is part of the Polyglot extensible compiler framework. * * Copyright (c) 2000-2006 Polyglot project group, Cornell University * */ package polyglot.types; import java.lang.reflect.Modifier; import java.util.*; import polyglot.frontend.ExtensionInfo; import polyglot.frontend.Source; import polyglot.main.Report; import polyglot.types.*; import polyglot.types.Package; import polyglot.types.reflect.ClassFile; import polyglot.types.reflect.ClassFileLazyClassInitializer; import polyglot.util.*; /** * TypeSystem_c * * Overview: * A TypeSystem_c is a universe of types, including all Java types. **/ public class TypeSystem_c implements TypeSystem { protected SystemResolver systemResolver; protected TopLevelResolver loadedResolver; protected Map flagsForName; protected ExtensionInfo extInfo; public TypeSystem_c() {} /** * Initializes the type system and its internal constants (which depend on * the resolver). */ public void initialize(TopLevelResolver loadedResolver, ExtensionInfo extInfo) throws SemanticException { if (Report.should_report(Report.types, 1)) Report.report(1, "Initializing " + getClass().getName()); this.extInfo = extInfo; // The loaded class resolver. This resolver automatically loads types // from class files and from source files not mentioned on the command // line. this.loadedResolver = loadedResolver; // The system class resolver. The class resolver contains a map from // fully qualified names to instances of Named. A pass over a // compilation unit looks up classes first in its // import table and then in the system resolver. this.systemResolver = new SystemResolver(loadedResolver, extInfo); initEnums(); initFlags(); initTypes(); } protected void initEnums() { // Ensure the enums in the type system are initialized and interned // before any deserialization occurs. // Just force the static initializers of ClassType and PrimitiveType // to run. Object o; o = ClassType.TOP_LEVEL; o = PrimitiveType.VOID; } protected void initTypes() throws SemanticException { // FIXME: don't do this when rewriting a type system! // Prime the resolver cache so that we don't need to check // later if these are loaded. // We cache the most commonly used ones in fields. /* DISABLED CACHING OF COMMON CLASSES; CAUSES PROBLEMS IF COMPILING CORE CLASSES (e.g. java.lang package). TODO: Longer term fix. Maybe a flag to tell if we are compiling core classes? XXX Object(); Class(); String(); Throwable(); systemResolver.find("java.lang.Error"); systemResolver.find("java.lang.Exception"); systemResolver.find("java.lang.RuntimeException"); systemResolver.find("java.lang.Cloneable"); systemResolver.find("java.io.Serializable"); systemResolver.find("java.lang.NullPointerException"); systemResolver.find("java.lang.ClassCastException"); systemResolver.find("java.lang.ArrayIndexOutOfBoundsException"); systemResolver.find("java.lang.ArrayStoreException"); systemResolver.find("java.lang.ArithmeticException"); */ } /** Return the language extension this type system is for. */ public ExtensionInfo extensionInfo() { return extInfo; } public SystemResolver systemResolver() { return systemResolver; } public SystemResolver saveSystemResolver() { SystemResolver r = this.systemResolver; this.systemResolver = (SystemResolver) r.copy(); return r; } public void restoreSystemResolver(SystemResolver r) { if (r != this.systemResolver.previous()) { throw new InternalCompilerError("Inconsistent systemResolver.previous"); } this.systemResolver = r; } /** * Return the system resolver. This used to return a different resolver. * enclosed in the system resolver. * @deprecated */ public CachingResolver parsedResolver() { return systemResolver; } public TopLevelResolver loadedResolver() { return loadedResolver; } public ClassFileLazyClassInitializer classFileLazyClassInitializer(ClassFile clazz) { return new ClassFileLazyClassInitializer(clazz, this); } public ImportTable importTable(String sourceName, Package pkg) { assert_(pkg); return new ImportTable(this, pkg, sourceName); } public ImportTable importTable(Package pkg) { assert_(pkg); return new ImportTable(this, pkg); } /** * Returns true if the package named <code>name</code> exists. */ public boolean packageExists(String name) { return systemResolver.packageExists(name); } protected void assert_(Collection l) { for (Iterator i = l.iterator(); i.hasNext(); ) { TypeObject o = (TypeObject) i.next(); assert_(o); } } protected void assert_(TypeObject o) { if (o != null && o.typeSystem() != this) { throw new InternalCompilerError("we are " + this + " but " + o + " ("+o.getClass()+")" + " is from " + o.typeSystem()); } } public String wrapperTypeString(PrimitiveType t) { assert_(t); if (t.kind() == PrimitiveType.BOOLEAN) { return "java.lang.Boolean"; } if (t.kind() == PrimitiveType.CHAR) { return "java.lang.Character"; } if (t.kind() == PrimitiveType.BYTE) { return "java.lang.Byte"; } if (t.kind() == PrimitiveType.SHORT) { return "java.lang.Short"; } if (t.kind() == PrimitiveType.INT) { return "java.lang.Integer"; } if (t.kind() == PrimitiveType.LONG) { return "java.lang.Long"; } if (t.kind() == PrimitiveType.FLOAT) { return "java.lang.Float"; } if (t.kind() == PrimitiveType.DOUBLE) { return "java.lang.Double"; } if (t.kind() == PrimitiveType.VOID) { return "java.lang.Void"; } throw new InternalCompilerError("Unrecognized primitive type."); } public Context createContext() { return new Context_c(this); } /** @deprecated */ public Resolver packageContextResolver(Resolver cr, Package p) { return packageContextResolver(p); } public AccessControlResolver createPackageContextResolver(Package p) { assert_(p); return new PackageContextResolver(this, p); } public Resolver packageContextResolver(Package p, ClassType accessor) { if (accessor == null) { return p.resolver(); } else { return new AccessControlWrapperResolver(createPackageContextResolver(p), accessor); } } public Resolver packageContextResolver(Package p) { assert_(p); return packageContextResolver(p, null); } public Resolver classContextResolver(ClassType type, ClassType accessor) { assert_(type); if (accessor == null) { return type.resolver(); } else { return new AccessControlWrapperResolver(createClassContextResolver(type), accessor); } } public Resolver classContextResolver(ClassType type) { return classContextResolver(type, null); } public AccessControlResolver createClassContextResolver(ClassType type) { assert_(type); return new ClassContextResolver(this, type); } public FieldInstance fieldInstance(Position pos, ReferenceType container, Flags flags, Type type, String name) { assert_(container); assert_(type); return new FieldInstance_c(this, pos, container, flags, type, name); } public LocalInstance localInstance(Position pos, Flags flags, Type type, String name) { assert_(type); return new LocalInstance_c(this, pos, flags, type, name); } public ConstructorInstance defaultConstructor(Position pos, ClassType container) { assert_(container); // access for the default constructor is determined by the // access of the containing class. See the JLS, 2nd Ed., 8.8.7. Flags access = Flags.NONE; if (container.flags().isPrivate()) { access = access.Private(); } if (container.flags().isProtected()) { access = access.Protected(); } if (container.flags().isPublic()) { access = access.Public(); } return constructorInstance(pos, container, access, Collections.EMPTY_LIST, Collections.EMPTY_LIST); } public ConstructorInstance constructorInstance(Position pos, ClassType container, Flags flags, List argTypes, List excTypes) { assert_(container); assert_(argTypes); assert_(excTypes); return new ConstructorInstance_c(this, pos, container, flags, argTypes, excTypes); } public InitializerInstance initializerInstance(Position pos, ClassType container, Flags flags) { assert_(container); return new InitializerInstance_c(this, pos, container, flags); } public MethodInstance methodInstance(Position pos, ReferenceType container, Flags flags, Type returnType, String name, List argTypes, List excTypes) { assert_(container); assert_(returnType); assert_(argTypes); assert_(excTypes); return new MethodInstance_c(this, pos, container, flags, returnType, name, argTypes, excTypes); } /** * Returns true iff child and ancestor are distinct * reference types, and child descends from ancestor. **/ public boolean descendsFrom(Type child, Type ancestor) { assert_(child); assert_(ancestor); return child.descendsFromImpl(ancestor); } /** * Requires: all type arguments are canonical. ToType is not a NullType. * * Returns true iff a cast from fromType to toType is valid; in other * words, some non-null members of fromType are also members of toType. **/ public boolean isCastValid(Type fromType, Type toType) { assert_(fromType); assert_(toType); return fromType.isCastValidImpl(toType); } /** * Requires: all type arguments are canonical. * * Returns true iff an implicit cast from fromType to toType is valid; * in other words, every member of fromType is member of toType. * * Returns true iff child and ancestor are non-primitive * types, and a variable of type child may be legally assigned * to a variable of type ancestor. * */ public boolean isImplicitCastValid(Type fromType, Type toType) { assert_(fromType); assert_(toType); return fromType.isImplicitCastValidImpl(toType); } /** * Returns true iff type1 and type2 represent the same type object. */ public boolean equals(TypeObject type1, TypeObject type2) { assert_(type1); assert_(type2); if (type1 == type2) return true; if (type1 == null || type2 == null) return false; return type1.equalsImpl(type2); } /** * Returns true iff type1 and type2 are equivalent. */ public boolean typeEquals(Type type1, Type type2) { assert_(type1); assert_(type2); return type1.typeEqualsImpl(type2); } /** * Returns true iff type1 and type2 are equivalent. */ public boolean packageEquals(Package type1, Package type2) { assert_(type1); assert_(type2); return type1.packageEqualsImpl(type2); } /** * Returns true if <code>value</code> can be implicitly cast to Primitive * type <code>t</code>. */ public boolean numericConversionValid(Type t, Object value) { assert_(t); return t.numericConversionValidImpl(value); } /** * Returns true if <code>value</code> can be implicitly cast to Primitive * type <code>t</code>. This method should be removed. It is kept for * backward compatibility. */ public boolean numericConversionValid(Type t, long value) { assert_(t); return t.numericConversionValidImpl(value); } //// // Functions for one-type checking and resolution. //// /** * Returns true iff <type> is a canonical (fully qualified) type. */ public boolean isCanonical(Type type) { assert_(type); return type.isCanonical(); } /** * Checks whether the member mi can be accessed from Context "context". */ public boolean isAccessible(MemberInstance mi, Context context) { return isAccessible(mi, context.currentClass()); } /** * Checks whether the member mi can be accessed from code that is * declared in the class contextClass. */ public boolean isAccessible(MemberInstance mi, ClassType contextClass) { assert_(mi); ReferenceType target = mi.container(); Flags flags = mi.flags(); if (! target.isClass()) { // public members of non-classes are accessible; // non-public members of non-classes are inaccessible return flags.isPublic(); } ClassType targetClass = target.toClass(); if (! classAccessible(targetClass, contextClass)) { return false; } if (equals(targetClass, contextClass)) return true; // If the current class and the target class are both in the // same class body, then protection doesn't matter, i.e. // protected and private members may be accessed. Do this by // working up through contextClass's containers. if (isEnclosed(contextClass, targetClass) || isEnclosed(targetClass, contextClass)) return true; ClassType ct = contextClass; while (!ct.isTopLevel()) { ct = ct.outer(); if (isEnclosed(targetClass, ct)) return true; } // protected if (flags.isProtected()) { // If the current class is in a // class body that extends/implements the target class, then // protected members can be accessed. Do this by // working up through contextClass's containers. if (descendsFrom(contextClass, targetClass)) { return true; } ct = contextClass; while (!ct.isTopLevel()) { ct = ct.outer(); if (descendsFrom(ct, targetClass)) { return true; } } } return accessibleFromPackage(flags, targetClass.package_(), contextClass.package_()); } /** True if the class targetClass accessible from the context. */ public boolean classAccessible(ClassType targetClass, Context context) { if (context.currentClass() == null) { return classAccessibleFromPackage(targetClass, context.importTable().package_()); } else { return classAccessible(targetClass, context.currentClass()); } } /** True if the class targetClass accessible from the body of class contextClass. */ public boolean classAccessible(ClassType targetClass, ClassType contextClass) { assert_(targetClass); if (targetClass.isMember()) { return isAccessible(targetClass, contextClass); } // Local and anonymous classes are accessible if they can be named. // This method wouldn't be called if they weren't named. if (! targetClass.isTopLevel()) { return true; } // targetClass must be a top-level class // same class if (equals(targetClass, contextClass)) return true; if (isEnclosed(contextClass, targetClass)) return true; return classAccessibleFromPackage(targetClass, contextClass.package_()); } /** True if the class targetClass accessible from the package pkg. */ public boolean classAccessibleFromPackage(ClassType targetClass, Package pkg) { assert_(targetClass); // Local and anonymous classes are not accessible from the outermost // scope of a compilation unit. if (! targetClass.isTopLevel() && ! targetClass.isMember()) return false; Flags flags = targetClass.flags(); if (targetClass.isMember()) { if (! targetClass.container().isClass()) { // public members of non-classes are accessible return flags.isPublic(); } if (! classAccessibleFromPackage(targetClass.container().toClass(), pkg)) { return false; } } return accessibleFromPackage(flags, targetClass.package_(), pkg); } /** * Return true if a member (in an accessible container) or a * top-level class with access flags <code>flags</code> * in package <code>pkg1</code> is accessible from package * <code>pkg2</code>. */ protected boolean accessibleFromPackage(Flags flags, Package pkg1, Package pkg2) { // Check if public. if (flags.isPublic()) { return true; } // Check if same package. if (flags.isPackage() || flags.isProtected()) { if (pkg1 == null && pkg2 == null) return true; if (pkg1 != null && pkg1.equals(pkg2)) return true; } // Otherwise private. return false; } public boolean isEnclosed(ClassType inner, ClassType outer) { return inner.isEnclosedImpl(outer); } public boolean hasEnclosingInstance(ClassType inner, ClassType encl) { return inner.hasEnclosingInstanceImpl(encl); } public void checkCycles(ReferenceType goal) throws SemanticException { checkCycles(goal, goal); } protected void checkCycles(ReferenceType curr, ReferenceType goal) throws SemanticException { assert_(curr); assert_(goal); if (curr == null) { return; } ReferenceType superType = null; if (curr.superType() != null) { superType = curr.superType().toReference(); } if (goal == superType) { throw new SemanticException("Circular inheritance involving " + goal, curr.position()); } checkCycles(superType, goal); for (Iterator i = curr.interfaces().iterator(); i.hasNext(); ) { Type si = (Type) i.next(); if (si == goal) { throw new SemanticException("Circular inheritance involving " + goal, curr.position()); } checkCycles(si.toReference(), goal); } if (curr.isClass()) { checkCycles(curr.toClass().outer(), goal); } } //// // Various one-type predicates. //// /** * Returns true iff the type t can be coerced to a String in the given * Context. If a type can be coerced to a String then it can be * concatenated with Strings, e.g. if o is of type T, then the code snippet * "" + o * would be allowed. */ public boolean canCoerceToString(Type t, Context c) { // every Object can be coerced to a string, as can any primitive, // except void. return ! t.isVoid(); } /** * Returns true iff an object of type <type> may be thrown. **/ public boolean isThrowable(Type type) { assert_(type); return type.isThrowable(); } /** * Returns a true iff the type or a supertype is in the list * returned by uncheckedExceptions(). */ public boolean isUncheckedException(Type type) { assert_(type); return type.isUncheckedException(); } /** * Returns a list of the Throwable types that need not be declared * in method and constructor signatures. */ public Collection uncheckedExceptions() { List l = new ArrayList(2); l.add(Error()); l.add(RuntimeException()); return l; } public boolean isSubtype(Type t1, Type t2) { assert_(t1); assert_(t2); return t1.isSubtypeImpl(t2); } //// // Functions for type membership. //// /** * @deprecated */ public FieldInstance findField(ReferenceType container, String name, Context c) throws SemanticException { ClassType ct = null; if (c != null) ct = c.currentClass(); return findField(container, name, ct); } /** * Returns the FieldInstance for the field <code>name</code> defined * in type <code>container</code> or a supertype, and visible from * <code>currClass</code>. If no such field is found, a SemanticException * is thrown. <code>currClass</code> may be null. **/ public FieldInstance findField(ReferenceType container, String name, ClassType currClass) throws SemanticException { Collection fields = findFields(container, name); if (fields.size() == 0) { throw new NoMemberException(NoMemberException.FIELD, "Field \"" + name + "\" not found in type \"" + container + "\"."); } Iterator i = fields.iterator(); FieldInstance fi = (FieldInstance) i.next(); if (i.hasNext()) { FieldInstance fi2 = (FieldInstance) i.next(); throw new SemanticException("Field \"" + name + "\" is ambiguous; it is defined in both " + fi.container() + " and " + fi2.container() + "."); } if (currClass != null && ! isAccessible(fi, currClass)) { throw new SemanticException("Cannot access " + fi + "."); } return fi; } /** * Returns the FieldInstance for the field <code>name</code> defined * in type <code>container</code> or a supertype. If no such field is * found, a SemanticException is thrown. */ public FieldInstance findField(ReferenceType container, String name) throws SemanticException { return findField(container, name, (ClassType) null); } /** * Returns a set of fields named <code>name</code> defined * in type <code>container</code> or a supertype. The list * returned may be empty. */ protected Set findFields(ReferenceType container, String name) { assert_(container); if (container == null) { throw new InternalCompilerError("Cannot access field \"" + name + "\" within a null container type."); } FieldInstance fi = container.fieldNamed(name); if (fi != null) { return Collections.singleton(fi); } Set fields = new HashSet(); if (container.superType() != null && container.superType().isReference()) { Set superFields = findFields(container.superType().toReference(), name); fields.addAll(superFields); } if (container.isClass()) { // Need to check interfaces for static fields. ClassType ct = container.toClass(); for (Iterator i = ct.interfaces().iterator(); i.hasNext(); ) { Type it = (Type) i.next(); Set superFields = findFields(it.toReference(), name); fields.addAll(superFields); } } return fields; } /** * @deprecated */ public ClassType findMemberClass(ClassType container, String name, Context c) throws SemanticException { return findMemberClass(container, name, c.currentClass()); } public ClassType findMemberClass(ClassType container, String name, ClassType currClass) throws SemanticException { assert_(container); Named n = classContextResolver(container, currClass).find(name); if (n instanceof ClassType) { return (ClassType) n; } throw new NoClassException(name, container); } public ClassType findMemberClass(ClassType container, String name) throws SemanticException { return findMemberClass(container, name, (ClassType) null); } protected static String listToString(List l) { StringBuffer sb = new StringBuffer(); for (Iterator i = l.iterator(); i.hasNext(); ) { Object o = i.next(); sb.append(o.toString()); if (i.hasNext()) { sb.append(", "); } } return sb.toString(); } /** * @deprecated */ public MethodInstance findMethod(ReferenceType container, String name, List argTypes, Context c) throws SemanticException { return findMethod(container, name, argTypes, c.currentClass()); } /** * Returns the list of methods with the given name defined or inherited * into container, checking if the methods are accessible from the * body of currClass */ public boolean hasMethodNamed(ReferenceType container, String name) { assert_(container); if (container == null) { throw new InternalCompilerError("Cannot access method \"" + name + "\" within a null container type."); } if (! container.methodsNamed(name).isEmpty()) { return true; } if (container.superType() != null && container.superType().isReference()) { if (hasMethodNamed(container.superType().toReference(), name)) { return true; } } if (container.isClass()) { ClassType ct = container.toClass(); for (Iterator i = ct.interfaces().iterator(); i.hasNext(); ) { Type it = (Type) i.next(); if (hasMethodNamed(it.toReference(), name)) { return true; } } } return false; } /** * Requires: all type arguments are canonical. * * Returns the MethodInstance named 'name' defined on 'type' visible in * context. If no such field may be found, returns a fieldmatch * with an error explaining why. Access flags are considered. **/ public MethodInstance findMethod(ReferenceType container, String name, List argTypes, ClassType currClass) throws SemanticException { assert_(container); assert_(argTypes); List acceptable = findAcceptableMethods(container, name, argTypes, currClass); if (acceptable.size() == 0) { throw new NoMemberException(NoMemberException.METHOD, "No valid method call found for " + name + "(" + listToString(argTypes) + ")" + " in " + container + "."); } Collection maximal = findMostSpecificProcedures(acceptable); if (maximal.size() > 1) { StringBuffer sb = new StringBuffer(); for (Iterator i = maximal.iterator(); i.hasNext();) { MethodInstance ma = (MethodInstance) i.next(); sb.append(ma.returnType()); sb.append(" "); sb.append(ma.container()); sb.append("."); sb.append(ma.signature()); if (i.hasNext()) { if (maximal.size() == 2) { sb.append(" and "); } else { sb.append(", "); } } } throw new SemanticException("Reference to " + name + " is ambiguous, multiple methods match: " + sb.toString()); } MethodInstance mi = (MethodInstance) maximal.iterator().next(); return mi; } /** * @deprecated */ public ConstructorInstance findConstructor(ClassType container, List argTypes, Context c) throws SemanticException { return findConstructor(container, argTypes, c.currentClass()); } public ConstructorInstance findConstructor(ClassType container, List argTypes, ClassType currClass) throws SemanticException { assert_(container); assert_(argTypes); List acceptable = findAcceptableConstructors(container, argTypes, currClass); if (acceptable.size() == 0) { throw new NoMemberException(NoMemberException.CONSTRUCTOR, "No valid constructor found for " + container + "(" + listToString(argTypes) + ")."); } Collection maximal = findMostSpecificProcedures(acceptable); if (maximal.size() > 1) { throw new NoMemberException(NoMemberException.CONSTRUCTOR, "Reference to " + container + " is ambiguous, multiple " + "constructors match: " + maximal); } ConstructorInstance ci = (ConstructorInstance) maximal.iterator().next(); return ci; } protected ProcedureInstance findProcedure(List acceptable, ReferenceType container, List argTypes, ClassType currClass) throws SemanticException { Collection maximal = findMostSpecificProcedures(acceptable); if (maximal.size() == 1) { return (ProcedureInstance) maximal.iterator().next(); } return null; } protected Collection findMostSpecificProcedures(List acceptable) throws SemanticException { // now, use JLS 15.11.2.2 // First sort from most- to least-specific. MostSpecificComparator msc = new MostSpecificComparator(); acceptable = new ArrayList(acceptable); // make into array list to sort Collections.sort(acceptable, msc); List maximal = new ArrayList(acceptable.size()); Iterator i = acceptable.iterator(); ProcedureInstance first = (ProcedureInstance) i.next(); maximal.add(first); // Now check to make sure that we have a maximal most-specific method. while (i.hasNext()) { ProcedureInstance p = (ProcedureInstance) i.next(); if (msc.compare(first, p) >= 0) { maximal.add(p); } } if (maximal.size() > 1) { // If exactly one method is not abstract, it is the most specific. List notAbstract = new ArrayList(maximal.size()); for (Iterator j = maximal.iterator(); j.hasNext(); ) { ProcedureInstance p = (ProcedureInstance) j.next(); if (! p.flags().isAbstract()) { notAbstract.add(p); } } if (notAbstract.size() == 1) { maximal = notAbstract; } else if (notAbstract.size() == 0) { // all are abstract; if all signatures match, any will do. Iterator j = maximal.iterator(); first = (ProcedureInstance) j.next(); while (j.hasNext()) { ProcedureInstance p = (ProcedureInstance) j.next(); // Use the declarations to compare formals. ProcedureInstance firstDecl = first; ProcedureInstance pDecl = p; if (first instanceof Declaration) { firstDecl = (ProcedureInstance) ((Declaration) first).declaration(); } if (p instanceof Declaration) { pDecl = (ProcedureInstance) ((Declaration) p).declaration(); } if (! firstDecl.hasFormals(pDecl.formalTypes())) { // not all signatures match; must be ambiguous return maximal; } } // all signatures match, just take the first maximal = Collections.singletonList(first); } } return maximal; } /** * Class to handle the comparisons; dispatches to moreSpecific method. */ protected static class MostSpecificComparator implements Comparator { public int compare(Object o1, Object o2) { ProcedureInstance p1 = (ProcedureInstance) o1; ProcedureInstance p2 = (ProcedureInstance) o2; if (p1.moreSpecific(p2)) return -1; if (p2.moreSpecific(p1)) return 1; return 0; } } /** * Populates the list acceptable with those MethodInstances which are * Applicable and Accessible as defined by JLS 15.11.2.1 */ protected List findAcceptableMethods(ReferenceType container, String name, List argTypes, ClassType currClass) throws SemanticException { assert_(container); assert_(argTypes); SemanticException error = null; // The list of acceptable methods. These methods are accessible from // currClass, the method call is valid, and they are not overridden // by an unacceptable method (which can occur with protected methods // only). List acceptable = new ArrayList(); // A list of unacceptable methods, where the method call is valid, but // the method is not accessible. This list is needed to make sure that // the acceptable methods are not overridden by an unacceptable method. List unacceptable = new ArrayList(); Set visitedTypes = new HashSet(); LinkedList typeQueue = new LinkedList(); typeQueue.addLast(container); while (! typeQueue.isEmpty()) { Type type = (Type) typeQueue.removeFirst(); if (visitedTypes.contains(type)) { continue; } visitedTypes.add(type); if (Report.should_report(Report.types, 2)) Report.report(2, "Searching type " + type + " for method " + name + "(" + listToString(argTypes) + ")"); if (! type.isReference()) { throw new SemanticException("Cannot call method in " + " non-reference type " + type + "."); } for (Iterator i = type.toReference().methods().iterator(); i.hasNext(); ) { MethodInstance mi = (MethodInstance) i.next(); if (Report.should_report(Report.types, 3)) Report.report(3, "Trying " + mi); if (! mi.name().equals(name)) { continue; } if (methodCallValid(mi, name, argTypes)) { if (isAccessible(mi, currClass)) { if (Report.should_report(Report.types, 3)) { Report.report(3, "->acceptable: " + mi + " in " + mi.container()); } acceptable.add(mi); } else { // method call is valid, but the method is // unacceptable. unacceptable.add(mi); if (error == null) { error = new NoMemberException(NoMemberException.METHOD, "Method " + mi.signature() + " in " + container + " is inaccessible."); } } } else { if (error == null) { error = new NoMemberException(NoMemberException.METHOD, "Method " + mi.signature() + " in " + container + " cannot be called with arguments " + "(" + listToString(argTypes) + ")."); } } } if (type.toReference().superType() != null) { typeQueue.addLast(type.toReference().superType()); } typeQueue.addAll(type.toReference().interfaces()); } if (error == null) { error = new NoMemberException(NoMemberException.METHOD, "No valid method call found for " + name + "(" + listToString(argTypes) + ")" + " in " + container + "."); } if (acceptable.size() == 0) { throw error; } // remove any method in acceptable that are overridden by an // unacceptable // method. for (Iterator i = unacceptable.iterator(); i.hasNext();) { MethodInstance mi = (MethodInstance)i.next(); acceptable.removeAll(mi.overrides()); } if (acceptable.size() == 0) { throw error; } return acceptable; } /** * Populates the list acceptable with those MethodInstances which are * Applicable and Accessible as defined by JLS 15.11.2.1 */ protected List findAcceptableConstructors(ClassType container, List argTypes, ClassType currClass) throws SemanticException { assert_(container); assert_(argTypes); SemanticException error = null; List acceptable = new ArrayList(); if (Report.should_report(Report.types, 2)) Report.report(2, "Searching type " + container + " for constructor " + container + "(" + listToString(argTypes) + ")"); for (Iterator i = container.constructors().iterator(); i.hasNext(); ) { ConstructorInstance ci = (ConstructorInstance) i.next(); if (Report.should_report(Report.types, 3)) Report.report(3, "Trying " + ci); if (callValid(ci, argTypes)) { if (isAccessible(ci, currClass)) { if (Report.should_report(Report.types, 3)) Report.report(3, "->acceptable: " + ci); acceptable.add(ci); } else { if (error == null) { error = new NoMemberException(NoMemberException.CONSTRUCTOR, "Constructor " + ci.signature() + " is inaccessible."); } } } else { if (error == null) { error = new NoMemberException(NoMemberException.CONSTRUCTOR, "Constructor " + ci.signature() + " cannot be invoked with arguments " + "(" + listToString(argTypes) + ")."); } } } if (acceptable.size() == 0) { if (error == null) { error = new NoMemberException(NoMemberException.CONSTRUCTOR, "No valid constructor found for " + container + "(" + listToString(argTypes) + ")."); } throw error; } return acceptable; } /** * Returns whether method 1 is <i>more specific</i> than method 2, * where <i>more specific</i> is defined as JLS 15.11.2.2 */ public boolean moreSpecific(ProcedureInstance p1, ProcedureInstance p2) { return p1.moreSpecificImpl(p2); } /** * Returns the supertype of type, or null if type has no supertype. **/ public Type superType(ReferenceType type) { assert_(type); return type.superType(); } /** * Returns an immutable list of all the interface types which type * implements. **/ public List interfaces(ReferenceType type) { assert_(type); return type.interfaces(); } /** * Requires: all type arguments are canonical. * Returns the least common ancestor of Type1 and Type2 **/ public Type leastCommonAncestor(Type type1, Type type2) throws SemanticException { assert_(type1); assert_(type2); if (typeEquals(type1, type2)) return type1; if (type1.isNumeric() && type2.isNumeric()) { if (isImplicitCastValid(type1, type2)) { return type2; } if (isImplicitCastValid(type2, type1)) { return type1; } if (type1.isChar() && type2.isByte() || type1.isByte() && type2.isChar()) { return Int(); } if (type1.isChar() && type2.isShort() || type1.isShort() && type2.isChar()) { return Int(); } } if (type1.isArray() && type2.isArray()) { return arrayOf(leastCommonAncestor(type1.toArray().base(), type2.toArray().base())); } if (type1.isReference() && type2.isNull()) return type1; if (type2.isReference() && type1.isNull()) return type2; if (type1.isReference() && type2.isReference()) { // Don't consider interfaces. if (type1.isClass() && type1.toClass().flags().isInterface()) { return Object(); } if (type2.isClass() && type2.toClass().flags().isInterface()) { return Object(); } // Check against Object to ensure superType() is not null. if (typeEquals(type1, Object())) return type1; if (typeEquals(type2, Object())) return type2; if (isSubtype(type1, type2)) return type2; if (isSubtype(type2, type1)) return type1; // Walk up the hierarchy Type t1 = leastCommonAncestor(type1.toReference().superType(), type2); Type t2 = leastCommonAncestor(type2.toReference().superType(), type1); if (typeEquals(t1, t2)) return t1; return Object(); } throw new SemanticException( "No least common ancestor found for types \"" + type1 + "\" and \"" + type2 + "\"."); } //// // Functions for method testing. //// /** * Returns true iff <p1> throws fewer exceptions than <p2>. */ public boolean throwsSubset(ProcedureInstance p1, ProcedureInstance p2) { assert_(p1); assert_(p2); return p1.throwsSubsetImpl(p2); } /** Return true if t overrides mi */ public boolean hasFormals(ProcedureInstance pi, List formalTypes) { assert_(pi); assert_(formalTypes); return pi.hasFormalsImpl(formalTypes); } /** Return true if t overrides mi */ public boolean hasMethod(ReferenceType t, MethodInstance mi) { assert_(t); assert_(mi); return t.hasMethodImpl(mi); } public List overrides(MethodInstance mi) { return mi.overridesImpl(); } public List implemented(MethodInstance mi) { return mi.implementedImpl(mi.container()); } public boolean canOverride(MethodInstance mi, MethodInstance mj) { try { return mi.canOverrideImpl(mj, true); } catch (SemanticException e) { // this is the exception thrown by the canOverrideImpl check. // It should never be thrown if the quiet argument of // canOverrideImpl is true. throw new InternalCompilerError(e); } } public void checkOverride(MethodInstance mi, MethodInstance mj) throws SemanticException { mi.canOverrideImpl(mj, false); } /** * Returns true iff <m1> is the same method as <m2> */ public boolean isSameMethod(MethodInstance m1, MethodInstance m2) { assert_(m1); assert_(m2); return m1.isSameMethodImpl(m2); } public boolean methodCallValid(MethodInstance prototype, String name, List argTypes) { assert_(prototype); assert_(argTypes); return prototype.methodCallValidImpl(name, argTypes); } public boolean callValid(ProcedureInstance prototype, List argTypes) { assert_(prototype); assert_(argTypes); return prototype.callValidImpl(argTypes); } //// // Functions which yield particular types. //// public NullType Null() { return NULL_; } public PrimitiveType Void() { return VOID_; } public PrimitiveType Boolean() { return BOOLEAN_; } public PrimitiveType Char() { return CHAR_; } public PrimitiveType Byte() { return BYTE_; } public PrimitiveType Short() { return SHORT_; } public PrimitiveType Int() { return INT_; } public PrimitiveType Long() { return LONG_; } public PrimitiveType Float() { return FLOAT_; } public PrimitiveType Double() { return DOUBLE_; } protected ClassType load(String name) { try { return (ClassType) typeForName(name); } catch (SemanticException e) { throw new InternalCompilerError("Cannot find class \"" + name + "\"; " + e.getMessage(), e); } } public Named forName(String name) throws SemanticException { return forName(systemResolver, name); } protected Named forName(Resolver resolver, String name) throws SemanticException { try { return resolver.find(name); } catch (SemanticException e) { if (! StringUtil.isNameShort(name)) { String containerName = StringUtil.getPackageComponent(name); String shortName = StringUtil.getShortNameComponent(name); try { Named container = forName(resolver, containerName); if (container instanceof ClassType) { return classContextResolver((ClassType) container).find(shortName); } } catch (SemanticException e2) { } } // throw the original exception throw e; } } public Type typeForName(String name) throws SemanticException { return (Type) forName(name); } protected ClassType OBJECT_; protected ClassType CLASS_; protected ClassType STRING_; protected ClassType THROWABLE_; public ClassType Object() { if (OBJECT_ != null) return OBJECT_; return OBJECT_ = load("java.lang.Object"); } public ClassType Class() { if (CLASS_ != null) return CLASS_; return CLASS_ = load("java.lang.Class"); } public ClassType String() { if (STRING_ != null) return STRING_; return STRING_ = load("java.lang.String"); } public ClassType Throwable() { if (THROWABLE_ != null) return THROWABLE_; return THROWABLE_ = load("java.lang.Throwable"); } public ClassType Error() { return load("java.lang.Error"); } public ClassType Exception() { return load("java.lang.Exception"); } public ClassType RuntimeException() { return load("java.lang.RuntimeException"); } public ClassType Cloneable() { return load("java.lang.Cloneable"); } public ClassType Serializable() { return load("java.io.Serializable"); } public ClassType NullPointerException() { return load("java.lang.NullPointerException"); } public ClassType ClassCastException() { return load("java.lang.ClassCastException"); } public ClassType OutOfBoundsException() { return load("java.lang.ArrayIndexOutOfBoundsException"); } public ClassType ArrayStoreException() { return load("java.lang.ArrayStoreException"); } public ClassType ArithmeticException() { return load("java.lang.ArithmeticException"); } protected NullType createNull() { return new NullType_c(this); } protected PrimitiveType createPrimitive(PrimitiveType.Kind kind) { return new PrimitiveType_c(this, kind); } protected final NullType NULL_ = createNull(); protected final PrimitiveType VOID_ = createPrimitive(PrimitiveType.VOID); protected final PrimitiveType BOOLEAN_ = createPrimitive(PrimitiveType.BOOLEAN); protected final PrimitiveType CHAR_ = createPrimitive(PrimitiveType.CHAR); protected final PrimitiveType BYTE_ = createPrimitive(PrimitiveType.BYTE); protected final PrimitiveType SHORT_ = createPrimitive(PrimitiveType.SHORT); protected final PrimitiveType INT_ = createPrimitive(PrimitiveType.INT); protected final PrimitiveType LONG_ = createPrimitive(PrimitiveType.LONG); protected final PrimitiveType FLOAT_ = createPrimitive(PrimitiveType.FLOAT); protected final PrimitiveType DOUBLE_ = createPrimitive(PrimitiveType.DOUBLE); public Object placeHolder(TypeObject o) { return placeHolder(o, Collections.EMPTY_SET); } public Object placeHolder(TypeObject o, Set roots) { assert_(o); if (o instanceof ParsedClassType) { ParsedClassType ct = (ParsedClassType) o; // This should never happen: anonymous and local types cannot // appear in signatures. if (ct.isLocal() || ct.isAnonymous()) { throw new InternalCompilerError("Cannot serialize " + o + "."); } // Use the transformed name so that member classes will // be sought in the correct class file. String name = getTransformedClassName(ct); return new PlaceHolder_c(name); } return o; } protected UnknownType unknownType = new UnknownType_c(this); protected UnknownPackage unknownPackage = new UnknownPackage_c(this); protected UnknownQualifier unknownQualifier = new UnknownQualifier_c(this); public UnknownType unknownType(Position pos) { return unknownType; } public UnknownPackage unknownPackage(Position pos) { return unknownPackage; } public UnknownQualifier unknownQualifier(Position pos) { return unknownQualifier; } public Package packageForName(Package prefix, String name) throws SemanticException { return createPackage(prefix, name); } public Package packageForName(String name) throws SemanticException { if (name == null || name.equals("")) { return null; } String s = StringUtil.getShortNameComponent(name); String p = StringUtil.getPackageComponent(name); return packageForName(packageForName(p), s); } /** @deprecated */ public Package createPackage(Package prefix, String name) { assert_(prefix); return new Package_c(this, prefix, name); } /** @deprecated */ public Package createPackage(String name) { if (name == null || name.equals("")) { return null; } String s = StringUtil.getShortNameComponent(name); String p = StringUtil.getPackageComponent(name); return createPackage(createPackage(p), s); } /** * Returns a type identical to <type>, but with <dims> more array * dimensions. */ public ArrayType arrayOf(Type type) { assert_(type); return arrayOf(type.position(), type); } public ArrayType arrayOf(Position pos, Type type) { assert_(type); return arrayType(pos, type); } Map arrayTypeCache = new HashMap(); /** * Factory method for ArrayTypes. */ protected ArrayType createArrayType(Position pos, Type type) { return new ArrayType_c(this, pos, type); } protected ArrayType arrayType(Position pos, Type type) { ArrayType t = (ArrayType) arrayTypeCache.get(type); if (t == null) { t = createArrayType(pos, type); arrayTypeCache.put(type, t); } return t; } public ArrayType arrayOf(Type type, int dims) { return arrayOf(null, type, dims); } public ArrayType arrayOf(Position pos, Type type, int dims) { if (dims > 1) { return arrayOf(pos, arrayOf(pos, type, dims-1)); } else if (dims == 1) { return arrayOf(pos, type); } else { throw new InternalCompilerError( "Must call arrayOf(type, dims) with dims > 0"); } } /** * Returns a canonical type corresponding to the Java Class object * theClass. Does not require that <theClass> have a JavaClass * registered in this typeSystem. Does not register the type in * this TypeSystem. For use only by JavaClass implementations. **/ public Type typeForClass(Class clazz) throws SemanticException { return typeForClass(systemResolver, clazz); } protected Type typeForClass(Resolver resolver, Class clazz) throws SemanticException { if (clazz == Void.TYPE) return VOID_; if (clazz == Boolean.TYPE) return BOOLEAN_; if (clazz == Byte.TYPE) return BYTE_; if (clazz == Character.TYPE) return CHAR_; if (clazz == Short.TYPE) return SHORT_; if (clazz == Integer.TYPE) return INT_; if (clazz == Long.TYPE) return LONG_; if (clazz == Float.TYPE) return FLOAT_; if (clazz == Double.TYPE) return DOUBLE_; if (clazz.isArray()) { return arrayOf(typeForClass(clazz.getComponentType())); } return (Type) resolver.find(clazz.getName()); } /** * Return the set of objects that should be serialized into the * type information for the given TypeObject. * Usually only the object itself should get encoded, and references * to other classes should just have their name written out. * If it makes sense for additional types to be fully encoded, * (i.e., they're necessary to correctly reconstruct the given clazz, * and the usual class resolvers can't otherwise find them) they * should be returned in the set in addition to clazz. */ public Set getTypeEncoderRootSet(TypeObject t) { return Collections.singleton(t); } /** * Get the transformed class name of a class. * This utility method returns the "mangled" name of the given class, * whereby all periods ('.') following the toplevel class name * are replaced with dollar signs ('$'). If any of the containing * classes is not a member class or a top level class, then null is * returned. */ public String getTransformedClassName(ClassType ct) { StringBuffer sb = new StringBuffer(ct.fullName().length()); if (!ct.isMember() && !ct.isTopLevel()) { return null; } while (ct.isMember()) { sb.insert(0, ct.name()); sb.insert(0, '$'); ct = ct.outer(); if (!ct.isMember() && !ct.isTopLevel()) { return null; } } sb.insert(0, ct.fullName()); return sb.toString(); } public String translatePackage(Resolver c, Package p) { return p.translate(c); } public String translateArray(Resolver c, ArrayType t) { return t.translate(c); } public String translateClass(Resolver c, ClassType t) { return t.translate(c); } public String translatePrimitive(Resolver c, PrimitiveType t) { return t.translate(c); } public PrimitiveType primitiveForName(String name) throws SemanticException { if (name.equals("void")) return Void(); if (name.equals("boolean")) return Boolean(); if (name.equals("char")) return Char(); if (name.equals("byte")) return Byte(); if (name.equals("short")) return Short(); if (name.equals("int")) return Int(); if (name.equals("long")) return Long(); if (name.equals("float")) return Float(); if (name.equals("double")) return Double(); throw new SemanticException("Unrecognized primitive type \"" + name + "\"."); } public LazyClassInitializer defaultClassInitializer() { return new SchedulerClassInitializer(this); } /** * The lazy class initializer for deserialized classes. */ public LazyClassInitializer deserializedClassInitializer() { return new DeserializedClassInitializer(this); } public final ParsedClassType createClassType() { return createClassType(defaultClassInitializer(), null); } public final ParsedClassType createClassType(Source fromSource) { return createClassType(defaultClassInitializer(), fromSource); } public final ParsedClassType createClassType(LazyClassInitializer init) { return createClassType(init, null); } public ParsedClassType createClassType(LazyClassInitializer init, Source fromSource) { return new ParsedClassType_c(this, init, fromSource); } public List defaultPackageImports() { List l = new ArrayList(1); l.add("java.lang"); return l; } public PrimitiveType promote(Type t1, Type t2) throws SemanticException { if (! t1.isNumeric()) { throw new SemanticException( "Cannot promote non-numeric type " + t1); } if (! t2.isNumeric()) { throw new SemanticException( "Cannot promote non-numeric type " + t2); } return promoteNumeric(t1.toPrimitive(), t2.toPrimitive()); } protected PrimitiveType promoteNumeric(PrimitiveType t1, PrimitiveType t2) { if (t1.isDouble() || t2.isDouble()) { return Double(); } if (t1.isFloat() || t2.isFloat()) { return Float(); } if (t1.isLong() || t2.isLong()) { return Long(); } return Int(); } public PrimitiveType promote(Type t) throws SemanticException { if (! t.isNumeric()) { throw new SemanticException( "Cannot promote non-numeric type " + t); } return promoteNumeric(t.toPrimitive()); } protected PrimitiveType promoteNumeric(PrimitiveType t) { if (t.isByte() || t.isShort() || t.isChar()) { return Int(); } return t.toPrimitive(); } /** All possible <i>access</i> flags. */ public Flags legalAccessFlags() { return Public().Protected().Private(); } protected final Flags ACCESS_FLAGS = legalAccessFlags(); /** All flags allowed for a local variable. */ public Flags legalLocalFlags() { return Final(); } protected final Flags LOCAL_FLAGS = legalLocalFlags(); /** All flags allowed for a field. */ public Flags legalFieldFlags() { return legalAccessFlags().Static().Final().Transient().Volatile(); } protected final Flags FIELD_FLAGS = legalFieldFlags(); /** All flags allowed for a constructor. */ public Flags legalConstructorFlags() { return legalAccessFlags().Synchronized().Native(); } protected final Flags CONSTRUCTOR_FLAGS = legalConstructorFlags(); /** All flags allowed for an initializer block. */ public Flags legalInitializerFlags() { return Static(); } protected final Flags INITIALIZER_FLAGS = legalInitializerFlags(); /** All flags allowed for a method. */ public Flags legalMethodFlags() { return legalAccessFlags().Abstract().Static().Final().Native().Synchronized().StrictFP(); } protected final Flags METHOD_FLAGS = legalMethodFlags(); public Flags legalAbstractMethodFlags() { return legalAccessFlags().clear(Private()).Abstract(); } protected final Flags ABSTRACT_METHOD_FLAGS = legalAbstractMethodFlags(); /** All flags allowed for a top-level class. */ public Flags legalTopLevelClassFlags() { return legalAccessFlags().clear(Private()).Abstract().Final().StrictFP().Interface(); } protected final Flags TOP_LEVEL_CLASS_FLAGS = legalTopLevelClassFlags(); /** All flags allowed for an interface. */ public Flags legalInterfaceFlags() { return legalAccessFlags().Abstract().Interface().Static(); } protected final Flags INTERFACE_FLAGS = legalInterfaceFlags(); /** All flags allowed for a member class. */ public Flags legalMemberClassFlags() { return legalAccessFlags().Static().Abstract().Final().StrictFP().Interface(); } protected final Flags MEMBER_CLASS_FLAGS = legalMemberClassFlags(); /** All flags allowed for a local class. */ public Flags legalLocalClassFlags() { return Abstract().Final().StrictFP().Interface(); } protected final Flags LOCAL_CLASS_FLAGS = legalLocalClassFlags(); public void checkMethodFlags(Flags f) throws SemanticException { if (! f.clear(METHOD_FLAGS).equals(Flags.NONE)) { throw new SemanticException( "Cannot declare method with flags " + f.clear(METHOD_FLAGS) + "."); } if (f.isAbstract() && ! f.clear(ABSTRACT_METHOD_FLAGS).equals(Flags.NONE)) { throw new SemanticException( "Cannot declare abstract method with flags " + f.clear(ABSTRACT_METHOD_FLAGS) + "."); } checkAccessFlags(f); } public void checkLocalFlags(Flags f) throws SemanticException { if (! f.clear(LOCAL_FLAGS).equals(Flags.NONE)) { throw new SemanticException( "Cannot declare local variable with flags " + f.clear(LOCAL_FLAGS) + "."); } } public void checkFieldFlags(Flags f) throws SemanticException { if (! f.clear(FIELD_FLAGS).equals(Flags.NONE)) { throw new SemanticException( "Cannot declare field with flags " + f.clear(FIELD_FLAGS) + "."); } checkAccessFlags(f); } public void checkConstructorFlags(Flags f) throws SemanticException { if (! f.clear(CONSTRUCTOR_FLAGS).equals(Flags.NONE)) { throw new SemanticException( "Cannot declare constructor with flags " + f.clear(CONSTRUCTOR_FLAGS) + "."); } checkAccessFlags(f); } public void checkInitializerFlags(Flags f) throws SemanticException { if (! f.clear(INITIALIZER_FLAGS).equals(Flags.NONE)) { throw new SemanticException( "Cannot declare initializer with flags " + f.clear(INITIALIZER_FLAGS) + "."); } } public void checkTopLevelClassFlags(Flags f) throws SemanticException { if (! f.clear(TOP_LEVEL_CLASS_FLAGS).equals(Flags.NONE)) { throw new SemanticException( "Cannot declare a top-level class with flag(s) " + f.clear(TOP_LEVEL_CLASS_FLAGS) + "."); } if (f.isInterface() && ! f.clear(INTERFACE_FLAGS).equals(Flags.NONE)) { throw new SemanticException("Cannot declare interface with flags " + f.clear(INTERFACE_FLAGS) + "."); } checkAccessFlags(f); } public void checkMemberClassFlags(Flags f) throws SemanticException { if (! f.clear(MEMBER_CLASS_FLAGS).equals(Flags.NONE)) { throw new SemanticException( "Cannot declare a member class with flag(s) " + f.clear(MEMBER_CLASS_FLAGS) + "."); } checkAccessFlags(f); } public void checkLocalClassFlags(Flags f) throws SemanticException { if (f.isInterface()) { throw new SemanticException("Cannot declare a local interface."); } if (! f.clear(LOCAL_CLASS_FLAGS).equals(Flags.NONE)) { throw new SemanticException( "Cannot declare a local class with flag(s) " + f.clear(LOCAL_CLASS_FLAGS) + "."); } checkAccessFlags(f); } public void checkAccessFlags(Flags f) throws SemanticException { int count = 0; if (f.isPublic()) count++; if (f.isProtected()) count++; if (f.isPrivate()) count++; if (count > 1) { throw new SemanticException( "Invalid access flags: " + f.retain(ACCESS_FLAGS) + "."); } } /** * Utility method to gather all the superclasses and interfaces of * <code>ct</code> that may contain abstract methods that must be * implemented by <code>ct</code>. The list returned also contains * <code>rt</code>. */ protected List abstractSuperInterfaces(ReferenceType rt) { List superInterfaces = new LinkedList(); superInterfaces.add(rt); for (Iterator iter = rt.interfaces().iterator(); iter.hasNext(); ) { ClassType interf = (ClassType)iter.next(); superInterfaces.addAll(abstractSuperInterfaces(interf)); } if (rt.superType() != null) { ClassType c = rt.superType().toClass(); if (c.flags().isAbstract()) { // the superclass is abstract, so it may contain methods // that must be implemented. superInterfaces.addAll(abstractSuperInterfaces(c)); } else { // the superclass is not abstract, so it must implement // all abstract methods of any interfaces it implements, and // any superclasses it may have. } } return superInterfaces; } /** * Assert that <code>ct</code> implements all abstract methods required; * that is, if it is a concrete class, then it must implement all * interfaces and abstract methods that it or it's superclasses declare, and if * it is an abstract class then any methods that it overrides are overridden * correctly. */ public void checkClassConformance(ClassType ct) throws SemanticException { if (ct.flags().isAbstract()) { // don't need to check interfaces or abstract classes return; } // build up a list of superclasses and interfaces that ct // extends/implements that may contain abstract methods that // ct must define. List superInterfaces = abstractSuperInterfaces(ct); // check each abstract method of the classes and interfaces in // superInterfaces for (Iterator i = superInterfaces.iterator(); i.hasNext(); ) { ReferenceType rt = (ReferenceType)i.next(); for (Iterator j = rt.methods().iterator(); j.hasNext(); ) { MethodInstance mi = (MethodInstance)j.next(); if (!mi.flags().isAbstract()) { // the method isn't abstract, so ct doesn't have to // implement it. continue; } MethodInstance mj = findImplementingMethod(ct, mi); if (mj == null) { if (!ct.flags().isAbstract()) { throw new SemanticException(ct.fullName() + " should be " + "declared abstract; it does not define " + mi.signature() + ", which is declared in " + rt.toClass().fullName(), ct.position()); } else { // no implementation, but that's ok, the class is abstract. } } else if (!equals(ct, mj.container()) && !equals(ct, mi.container())) { try { // check that mj can override mi, which // includes access protection checks. checkOverride(mj, mi); } catch (SemanticException e) { // change the position of the semantic // exception to be the class that we // are checking. throw new SemanticException(e.getMessage(), ct.position()); } } else { // the method implementation mj or mi was // declared in ct. So other checks will take // care of access issues } } } } public MethodInstance findImplementingMethod(ClassType ct, MethodInstance mi) { ReferenceType curr = ct; while (curr != null) { List possible = curr.methods(mi.name(), mi.formalTypes()); for (Iterator k = possible.iterator(); k.hasNext(); ) { MethodInstance mj = (MethodInstance)k.next(); if (!mj.flags().isAbstract() && ((isAccessible(mi, ct) && isAccessible(mj, ct)) || isAccessible(mi, mj.container().toClass()))) { // The method mj may be a suitable implementation of mi. // mj is not abstract, and either mj's container // can access mi (thus mj can really override mi), or // mi and mj are both accessible from ct (e.g., // mi is declared in an interface that ct implements, // and mj is defined in a superclass of ct). return mj; } } if (curr == mi.container()) { // we've reached the definition of the abstract // method. We don't want to look higher in the // hierarchy; this is not an optimization, but is // required for correctness. break; } curr = curr.superType() == null ? null : curr.superType().toReference(); } return null; } /** * Returns t, modified as necessary to make it a legal * static target. */ public Type staticTarget(Type t) { // Nothing needs done in standard Java. return t; } protected void initFlags() { flagsForName = new HashMap(); flagsForName.put("public", Flags.PUBLIC); flagsForName.put("private", Flags.PRIVATE); flagsForName.put("protected", Flags.PROTECTED); flagsForName.put("static", Flags.STATIC); flagsForName.put("final", Flags.FINAL); flagsForName.put("synchronized", Flags.SYNCHRONIZED); flagsForName.put("transient", Flags.TRANSIENT); flagsForName.put("native", Flags.NATIVE); flagsForName.put("interface", Flags.INTERFACE); flagsForName.put("abstract", Flags.ABSTRACT); flagsForName.put("volatile", Flags.VOLATILE); flagsForName.put("strictfp", Flags.STRICTFP); } public Flags createNewFlag(String name, Flags after) { Flags f = Flags.createFlag(name, after); flagsForName.put(name, f); return f; } public Flags NoFlags() { return Flags.NONE; } public Flags Public() { return Flags.PUBLIC; } public Flags Private() { return Flags.PRIVATE; } public Flags Protected() { return Flags.PROTECTED; } public Flags Static() { return Flags.STATIC; } public Flags Final() { return Flags.FINAL; } public Flags Synchronized() { return Flags.SYNCHRONIZED; } public Flags Transient() { return Flags.TRANSIENT; } public Flags Native() { return Flags.NATIVE; } public Flags Interface() { return Flags.INTERFACE; } public Flags Abstract() { return Flags.ABSTRACT; } public Flags Volatile() { return Flags.VOLATILE; } public Flags StrictFP() { return Flags.STRICTFP; } public Flags flagsForBits(int bits) { Flags f = Flags.NONE; if ((bits & Modifier.PUBLIC) != 0) f = f.Public(); if ((bits & Modifier.PRIVATE) != 0) f = f.Private(); if ((bits & Modifier.PROTECTED) != 0) f = f.Protected(); if ((bits & Modifier.STATIC) != 0) f = f.Static(); if ((bits & Modifier.FINAL) != 0) f = f.Final(); if ((bits & Modifier.SYNCHRONIZED) != 0) f = f.Synchronized(); if ((bits & Modifier.TRANSIENT) != 0) f = f.Transient(); if ((bits & Modifier.NATIVE) != 0) f = f.Native(); if ((bits & Modifier.INTERFACE) != 0) f = f.Interface(); if ((bits & Modifier.ABSTRACT) != 0) f = f.Abstract(); if ((bits & Modifier.VOLATILE) != 0) f = f.Volatile(); if ((bits & Modifier.STRICT) != 0) f = f.StrictFP(); return f; } public Flags flagsForName(String name) { Flags f = (Flags) flagsForName.get(name); if (f == null) { throw new InternalCompilerError("No flag named \"" + name + "\"."); } return f; } public String toString() { return StringUtil.getShortNameComponent(getClass().getName()); } }
src/polyglot/types/TypeSystem_c.java
/* * This file is part of the Polyglot extensible compiler framework. * * Copyright (c) 2000-2006 Polyglot project group, Cornell University * */ package polyglot.types; import java.lang.reflect.Modifier; import java.util.*; import polyglot.frontend.ExtensionInfo; import polyglot.frontend.Source; import polyglot.main.Report; import polyglot.types.*; import polyglot.types.Package; import polyglot.types.reflect.ClassFile; import polyglot.types.reflect.ClassFileLazyClassInitializer; import polyglot.util.*; /** * TypeSystem_c * * Overview: * A TypeSystem_c is a universe of types, including all Java types. **/ public class TypeSystem_c implements TypeSystem { protected SystemResolver systemResolver; protected TopLevelResolver loadedResolver; protected Map flagsForName; protected ExtensionInfo extInfo; public TypeSystem_c() {} /** * Initializes the type system and its internal constants (which depend on * the resolver). */ public void initialize(TopLevelResolver loadedResolver, ExtensionInfo extInfo) throws SemanticException { if (Report.should_report(Report.types, 1)) Report.report(1, "Initializing " + getClass().getName()); this.extInfo = extInfo; // The loaded class resolver. This resolver automatically loads types // from class files and from source files not mentioned on the command // line. this.loadedResolver = loadedResolver; // The system class resolver. The class resolver contains a map from // fully qualified names to instances of Named. A pass over a // compilation unit looks up classes first in its // import table and then in the system resolver. this.systemResolver = new SystemResolver(loadedResolver, extInfo); initEnums(); initFlags(); initTypes(); } protected void initEnums() { // Ensure the enums in the type system are initialized and interned // before any deserialization occurs. // Just force the static initializers of ClassType and PrimitiveType // to run. Object o; o = ClassType.TOP_LEVEL; o = PrimitiveType.VOID; } protected void initTypes() throws SemanticException { // FIXME: don't do this when rewriting a type system! // Prime the resolver cache so that we don't need to check // later if these are loaded. // We cache the most commonly used ones in fields. /* DISABLED CACHING OF COMMON CLASSES; CAUSES PROBLEMS IF COMPILING CORE CLASSES (e.g. java.lang package). TODO: Longer term fix. Maybe a flag to tell if we are compiling core classes? XXX Object(); Class(); String(); Throwable(); systemResolver.find("java.lang.Error"); systemResolver.find("java.lang.Exception"); systemResolver.find("java.lang.RuntimeException"); systemResolver.find("java.lang.Cloneable"); systemResolver.find("java.io.Serializable"); systemResolver.find("java.lang.NullPointerException"); systemResolver.find("java.lang.ClassCastException"); systemResolver.find("java.lang.ArrayIndexOutOfBoundsException"); systemResolver.find("java.lang.ArrayStoreException"); systemResolver.find("java.lang.ArithmeticException"); */ } /** Return the language extension this type system is for. */ public ExtensionInfo extensionInfo() { return extInfo; } public SystemResolver systemResolver() { return systemResolver; } public SystemResolver saveSystemResolver() { SystemResolver r = this.systemResolver; this.systemResolver = (SystemResolver) r.copy(); return r; } public void restoreSystemResolver(SystemResolver r) { if (r != this.systemResolver.previous()) { throw new InternalCompilerError("Inconsistent systemResolver.previous"); } this.systemResolver = r; } /** * Return the system resolver. This used to return a different resolver. * enclosed in the system resolver. * @deprecated */ public CachingResolver parsedResolver() { return systemResolver; } public TopLevelResolver loadedResolver() { return loadedResolver; } public ClassFileLazyClassInitializer classFileLazyClassInitializer(ClassFile clazz) { return new ClassFileLazyClassInitializer(clazz, this); } public ImportTable importTable(String sourceName, Package pkg) { assert_(pkg); return new ImportTable(this, pkg, sourceName); } public ImportTable importTable(Package pkg) { assert_(pkg); return new ImportTable(this, pkg); } /** * Returns true if the package named <code>name</code> exists. */ public boolean packageExists(String name) { return systemResolver.packageExists(name); } protected void assert_(Collection l) { for (Iterator i = l.iterator(); i.hasNext(); ) { TypeObject o = (TypeObject) i.next(); assert_(o); } } protected void assert_(TypeObject o) { if (o != null && o.typeSystem() != this) { throw new InternalCompilerError("we are " + this + " but " + o + " ("+o.getClass()+")" + " is from " + o.typeSystem()); } } public String wrapperTypeString(PrimitiveType t) { assert_(t); if (t.kind() == PrimitiveType.BOOLEAN) { return "java.lang.Boolean"; } if (t.kind() == PrimitiveType.CHAR) { return "java.lang.Character"; } if (t.kind() == PrimitiveType.BYTE) { return "java.lang.Byte"; } if (t.kind() == PrimitiveType.SHORT) { return "java.lang.Short"; } if (t.kind() == PrimitiveType.INT) { return "java.lang.Integer"; } if (t.kind() == PrimitiveType.LONG) { return "java.lang.Long"; } if (t.kind() == PrimitiveType.FLOAT) { return "java.lang.Float"; } if (t.kind() == PrimitiveType.DOUBLE) { return "java.lang.Double"; } if (t.kind() == PrimitiveType.VOID) { return "java.lang.Void"; } throw new InternalCompilerError("Unrecognized primitive type."); } public Context createContext() { return new Context_c(this); } /** @deprecated */ public Resolver packageContextResolver(Resolver cr, Package p) { return packageContextResolver(p); } public AccessControlResolver createPackageContextResolver(Package p) { assert_(p); return new PackageContextResolver(this, p); } public Resolver packageContextResolver(Package p, ClassType accessor) { if (accessor == null) { return p.resolver(); } else { return new AccessControlWrapperResolver(createPackageContextResolver(p), accessor); } } public Resolver packageContextResolver(Package p) { assert_(p); return packageContextResolver(p, null); } public Resolver classContextResolver(ClassType type, ClassType accessor) { assert_(type); if (accessor == null) { return type.resolver(); } else { return new AccessControlWrapperResolver(createClassContextResolver(type), accessor); } } public Resolver classContextResolver(ClassType type) { return classContextResolver(type, null); } public AccessControlResolver createClassContextResolver(ClassType type) { assert_(type); return new ClassContextResolver(this, type); } public FieldInstance fieldInstance(Position pos, ReferenceType container, Flags flags, Type type, String name) { assert_(container); assert_(type); return new FieldInstance_c(this, pos, container, flags, type, name); } public LocalInstance localInstance(Position pos, Flags flags, Type type, String name) { assert_(type); return new LocalInstance_c(this, pos, flags, type, name); } public ConstructorInstance defaultConstructor(Position pos, ClassType container) { assert_(container); // access for the default constructor is determined by the // access of the containing class. See the JLS, 2nd Ed., 8.8.7. Flags access = Flags.NONE; if (container.flags().isPrivate()) { access = access.Private(); } if (container.flags().isProtected()) { access = access.Protected(); } if (container.flags().isPublic()) { access = access.Public(); } return constructorInstance(pos, container, access, Collections.EMPTY_LIST, Collections.EMPTY_LIST); } public ConstructorInstance constructorInstance(Position pos, ClassType container, Flags flags, List argTypes, List excTypes) { assert_(container); assert_(argTypes); assert_(excTypes); return new ConstructorInstance_c(this, pos, container, flags, argTypes, excTypes); } public InitializerInstance initializerInstance(Position pos, ClassType container, Flags flags) { assert_(container); return new InitializerInstance_c(this, pos, container, flags); } public MethodInstance methodInstance(Position pos, ReferenceType container, Flags flags, Type returnType, String name, List argTypes, List excTypes) { assert_(container); assert_(returnType); assert_(argTypes); assert_(excTypes); return new MethodInstance_c(this, pos, container, flags, returnType, name, argTypes, excTypes); } /** * Returns true iff child and ancestor are distinct * reference types, and child descends from ancestor. **/ public boolean descendsFrom(Type child, Type ancestor) { assert_(child); assert_(ancestor); return child.descendsFromImpl(ancestor); } /** * Requires: all type arguments are canonical. ToType is not a NullType. * * Returns true iff a cast from fromType to toType is valid; in other * words, some non-null members of fromType are also members of toType. **/ public boolean isCastValid(Type fromType, Type toType) { assert_(fromType); assert_(toType); return fromType.isCastValidImpl(toType); } /** * Requires: all type arguments are canonical. * * Returns true iff an implicit cast from fromType to toType is valid; * in other words, every member of fromType is member of toType. * * Returns true iff child and ancestor are non-primitive * types, and a variable of type child may be legally assigned * to a variable of type ancestor. * */ public boolean isImplicitCastValid(Type fromType, Type toType) { assert_(fromType); assert_(toType); return fromType.isImplicitCastValidImpl(toType); } /** * Returns true iff type1 and type2 represent the same type object. */ public boolean equals(TypeObject type1, TypeObject type2) { assert_(type1); assert_(type2); if (type1 == type2) return true; if (type1 == null || type2 == null) return false; return type1.equalsImpl(type2); } /** * Returns true iff type1 and type2 are equivalent. */ public boolean typeEquals(Type type1, Type type2) { assert_(type1); assert_(type2); return type1.typeEqualsImpl(type2); } /** * Returns true iff type1 and type2 are equivalent. */ public boolean packageEquals(Package type1, Package type2) { assert_(type1); assert_(type2); return type1.packageEqualsImpl(type2); } /** * Returns true if <code>value</code> can be implicitly cast to Primitive * type <code>t</code>. */ public boolean numericConversionValid(Type t, Object value) { assert_(t); return t.numericConversionValidImpl(value); } /** * Returns true if <code>value</code> can be implicitly cast to Primitive * type <code>t</code>. This method should be removed. It is kept for * backward compatibility. */ public boolean numericConversionValid(Type t, long value) { assert_(t); return t.numericConversionValidImpl(value); } //// // Functions for one-type checking and resolution. //// /** * Returns true iff <type> is a canonical (fully qualified) type. */ public boolean isCanonical(Type type) { assert_(type); return type.isCanonical(); } /** * Checks whether the member mi can be accessed from Context "context". */ public boolean isAccessible(MemberInstance mi, Context context) { return isAccessible(mi, context.currentClass()); } /** * Checks whether the member mi can be accessed from code that is * declared in the class contextClass. */ public boolean isAccessible(MemberInstance mi, ClassType contextClass) { assert_(mi); ReferenceType target = mi.container(); Flags flags = mi.flags(); if (! target.isClass()) { // public members of non-classes are accessible; // non-public members of non-classes are inaccessible return flags.isPublic(); } ClassType targetClass = target.toClass(); if (! classAccessible(targetClass, contextClass)) { return false; } if (equals(targetClass, contextClass)) return true; // If the current class and the target class are both in the // same class body, then protection doesn't matter, i.e. // protected and private members may be accessed. Do this by // working up through contextClass's containers. if (isEnclosed(contextClass, targetClass) || isEnclosed(targetClass, contextClass)) return true; ClassType ct = contextClass; while (!ct.isTopLevel()) { ct = ct.outer(); if (isEnclosed(targetClass, ct)) return true; } // protected if (flags.isProtected()) { // If the current class is in a // class body that extends/implements the target class, then // protected members can be accessed. Do this by // working up through contextClass's containers. if (descendsFrom(contextClass, targetClass)) { return true; } ct = contextClass; while (!ct.isTopLevel()) { ct = ct.outer(); if (descendsFrom(ct, targetClass)) { return true; } } } return accessibleFromPackage(flags, targetClass.package_(), contextClass.package_()); } /** True if the class targetClass accessible from the context. */ public boolean classAccessible(ClassType targetClass, Context context) { if (context.currentClass() == null) { return classAccessibleFromPackage(targetClass, context.importTable().package_()); } else { return classAccessible(targetClass, context.currentClass()); } } /** True if the class targetClass accessible from the body of class contextClass. */ public boolean classAccessible(ClassType targetClass, ClassType contextClass) { assert_(targetClass); if (targetClass.isMember()) { return isAccessible(targetClass, contextClass); } // Local and anonymous classes are accessible if they can be named. // This method wouldn't be called if they weren't named. if (! targetClass.isTopLevel()) { return true; } // targetClass must be a top-level class // same class if (equals(targetClass, contextClass)) return true; if (isEnclosed(contextClass, targetClass)) return true; return classAccessibleFromPackage(targetClass, contextClass.package_()); } /** True if the class targetClass accessible from the package pkg. */ public boolean classAccessibleFromPackage(ClassType targetClass, Package pkg) { assert_(targetClass); // Local and anonymous classes are not accessible from the outermost // scope of a compilation unit. if (! targetClass.isTopLevel() && ! targetClass.isMember()) return false; Flags flags = targetClass.flags(); if (targetClass.isMember()) { if (! targetClass.container().isClass()) { // public members of non-classes are accessible return flags.isPublic(); } if (! classAccessibleFromPackage(targetClass.container().toClass(), pkg)) { return false; } } return accessibleFromPackage(flags, targetClass.package_(), pkg); } /** * Return true if a member (in an accessible container) or a * top-level class with access flags <code>flags</code> * in package <code>pkg1</code> is accessible from package * <code>pkg2</code>. */ protected boolean accessibleFromPackage(Flags flags, Package pkg1, Package pkg2) { // Check if public. if (flags.isPublic()) { return true; } // Check if same package. if (flags.isPackage() || flags.isProtected()) { if (pkg1 == null && pkg2 == null) return true; if (pkg1 != null && pkg1.equals(pkg2)) return true; } // Otherwise private. return false; } public boolean isEnclosed(ClassType inner, ClassType outer) { return inner.isEnclosedImpl(outer); } public boolean hasEnclosingInstance(ClassType inner, ClassType encl) { return inner.hasEnclosingInstanceImpl(encl); } public void checkCycles(ReferenceType goal) throws SemanticException { checkCycles(goal, goal); } protected void checkCycles(ReferenceType curr, ReferenceType goal) throws SemanticException { assert_(curr); assert_(goal); if (curr == null) { return; } ReferenceType superType = null; if (curr.superType() != null) { superType = curr.superType().toReference(); } if (goal == superType) { throw new SemanticException("Circular inheritance involving " + goal, curr.position()); } checkCycles(superType, goal); for (Iterator i = curr.interfaces().iterator(); i.hasNext(); ) { Type si = (Type) i.next(); if (si == goal) { throw new SemanticException("Circular inheritance involving " + goal, curr.position()); } checkCycles(si.toReference(), goal); } if (curr.isClass()) { checkCycles(curr.toClass().outer(), goal); } } //// // Various one-type predicates. //// /** * Returns true iff the type t can be coerced to a String in the given * Context. If a type can be coerced to a String then it can be * concatenated with Strings, e.g. if o is of type T, then the code snippet * "" + o * would be allowed. */ public boolean canCoerceToString(Type t, Context c) { // every Object can be coerced to a string, as can any primitive, // except void. return ! t.isVoid(); } /** * Returns true iff an object of type <type> may be thrown. **/ public boolean isThrowable(Type type) { assert_(type); return type.isThrowable(); } /** * Returns a true iff the type or a supertype is in the list * returned by uncheckedExceptions(). */ public boolean isUncheckedException(Type type) { assert_(type); return type.isUncheckedException(); } /** * Returns a list of the Throwable types that need not be declared * in method and constructor signatures. */ public Collection uncheckedExceptions() { List l = new ArrayList(2); l.add(Error()); l.add(RuntimeException()); return l; } public boolean isSubtype(Type t1, Type t2) { assert_(t1); assert_(t2); return t1.isSubtypeImpl(t2); } //// // Functions for type membership. //// /** * @deprecated */ public FieldInstance findField(ReferenceType container, String name, Context c) throws SemanticException { ClassType ct = null; if (c != null) ct = c.currentClass(); return findField(container, name, ct); } /** * Returns the FieldInstance for the field <code>name</code> defined * in type <code>container</code> or a supertype, and visible from * <code>currClass</code>. If no such field is found, a SemanticException * is thrown. <code>currClass</code> may be null. **/ public FieldInstance findField(ReferenceType container, String name, ClassType currClass) throws SemanticException { Collection fields = findFields(container, name); if (fields.size() == 0) { throw new NoMemberException(NoMemberException.FIELD, "Field \"" + name + "\" not found in type \"" + container + "\"."); } Iterator i = fields.iterator(); FieldInstance fi = (FieldInstance) i.next(); if (i.hasNext()) { FieldInstance fi2 = (FieldInstance) i.next(); throw new SemanticException("Field \"" + name + "\" is ambiguous; it is defined in both " + fi.container() + " and " + fi2.container() + "."); } if (currClass != null && ! isAccessible(fi, currClass)) { throw new SemanticException("Cannot access " + fi + "."); } return fi; } /** * Returns the FieldInstance for the field <code>name</code> defined * in type <code>container</code> or a supertype. If no such field is * found, a SemanticException is thrown. */ public FieldInstance findField(ReferenceType container, String name) throws SemanticException { return findField(container, name, (ClassType) null); } /** * Returns a set of fields named <code>name</code> defined * in type <code>container</code> or a supertype. The list * returned may be empty. */ protected Set findFields(ReferenceType container, String name) { assert_(container); if (container == null) { throw new InternalCompilerError("Cannot access field \"" + name + "\" within a null container type."); } FieldInstance fi = container.fieldNamed(name); if (fi != null) { return Collections.singleton(fi); } Set fields = new HashSet(); if (container.superType() != null && container.superType().isReference()) { Set superFields = findFields(container.superType().toReference(), name); fields.addAll(superFields); } if (container.isClass()) { // Need to check interfaces for static fields. ClassType ct = container.toClass(); for (Iterator i = ct.interfaces().iterator(); i.hasNext(); ) { Type it = (Type) i.next(); Set superFields = findFields(it.toReference(), name); fields.addAll(superFields); } } return fields; } /** * @deprecated */ public ClassType findMemberClass(ClassType container, String name, Context c) throws SemanticException { return findMemberClass(container, name, c.currentClass()); } public ClassType findMemberClass(ClassType container, String name, ClassType currClass) throws SemanticException { assert_(container); Named n = classContextResolver(container, currClass).find(name); if (n instanceof ClassType) { return (ClassType) n; } throw new NoClassException(name, container); } public ClassType findMemberClass(ClassType container, String name) throws SemanticException { return findMemberClass(container, name, (ClassType) null); } protected static String listToString(List l) { StringBuffer sb = new StringBuffer(); for (Iterator i = l.iterator(); i.hasNext(); ) { Object o = i.next(); sb.append(o.toString()); if (i.hasNext()) { sb.append(", "); } } return sb.toString(); } /** * @deprecated */ public MethodInstance findMethod(ReferenceType container, String name, List argTypes, Context c) throws SemanticException { return findMethod(container, name, argTypes, c.currentClass()); } /** * Returns the list of methods with the given name defined or inherited * into container, checking if the methods are accessible from the * body of currClass */ public boolean hasMethodNamed(ReferenceType container, String name) { assert_(container); if (container == null) { throw new InternalCompilerError("Cannot access method \"" + name + "\" within a null container type."); } if (! container.methodsNamed(name).isEmpty()) { return true; } if (container.superType() != null && container.superType().isReference()) { if (hasMethodNamed(container.superType().toReference(), name)) { return true; } } if (container.isClass()) { ClassType ct = container.toClass(); for (Iterator i = ct.interfaces().iterator(); i.hasNext(); ) { Type it = (Type) i.next(); if (hasMethodNamed(it.toReference(), name)) { return true; } } } return false; } /** * Requires: all type arguments are canonical. * * Returns the MethodInstance named 'name' defined on 'type' visible in * context. If no such field may be found, returns a fieldmatch * with an error explaining why. Access flags are considered. **/ public MethodInstance findMethod(ReferenceType container, String name, List argTypes, ClassType currClass) throws SemanticException { assert_(container); assert_(argTypes); List acceptable = findAcceptableMethods(container, name, argTypes, currClass); if (acceptable.size() == 0) { throw new NoMemberException(NoMemberException.METHOD, "No valid method call found for " + name + "(" + listToString(argTypes) + ")" + " in " + container + "."); } Collection maximal = findMostSpecificProcedures(acceptable); if (maximal.size() > 1) { StringBuffer sb = new StringBuffer(); for (Iterator i = maximal.iterator(); i.hasNext();) { MethodInstance ma = (MethodInstance) i.next(); sb.append(ma.returnType()); sb.append(" "); sb.append(ma.container()); sb.append("."); sb.append(ma.signature()); if (i.hasNext()) { if (maximal.size() == 2) { sb.append(" and "); } else { sb.append(", "); } } } throw new SemanticException("Reference to " + name + " is ambiguous, multiple methods match: " + sb.toString()); } MethodInstance mi = (MethodInstance) maximal.iterator().next(); return mi; } /** * @deprecated */ public ConstructorInstance findConstructor(ClassType container, List argTypes, Context c) throws SemanticException { return findConstructor(container, argTypes, c.currentClass()); } public ConstructorInstance findConstructor(ClassType container, List argTypes, ClassType currClass) throws SemanticException { assert_(container); assert_(argTypes); List acceptable = findAcceptableConstructors(container, argTypes, currClass); if (acceptable.size() == 0) { throw new NoMemberException(NoMemberException.CONSTRUCTOR, "No valid constructor found for " + container + "(" + listToString(argTypes) + ")."); } Collection maximal = findMostSpecificProcedures(acceptable); if (maximal.size() > 1) { throw new NoMemberException(NoMemberException.CONSTRUCTOR, "Reference to " + container + " is ambiguous, multiple " + "constructors match: " + maximal); } ConstructorInstance ci = (ConstructorInstance) maximal.iterator().next(); return ci; } protected ProcedureInstance findProcedure(List acceptable, ReferenceType container, List argTypes, ClassType currClass) throws SemanticException { Collection maximal = findMostSpecificProcedures(acceptable); if (maximal.size() == 1) { return (ProcedureInstance) maximal.iterator().next(); } return null; } protected Collection findMostSpecificProcedures(List acceptable) throws SemanticException { // now, use JLS 15.11.2.2 // First sort from most- to least-specific. MostSpecificComparator msc = new MostSpecificComparator(); acceptable = new ArrayList(acceptable); // make into array list to sort Collections.sort(acceptable, msc); List maximal = new ArrayList(acceptable.size()); Iterator i = acceptable.iterator(); ProcedureInstance first = (ProcedureInstance) i.next(); maximal.add(first); // Now check to make sure that we have a maximal most-specific method. while (i.hasNext()) { ProcedureInstance p = (ProcedureInstance) i.next(); if (msc.compare(first, p) >= 0) { maximal.add(p); } } if (maximal.size() > 1) { // If exactly one method is not abstract, it is the most specific. List notAbstract = new ArrayList(maximal.size()); for (Iterator j = maximal.iterator(); j.hasNext(); ) { ProcedureInstance p = (ProcedureInstance) j.next(); if (! p.flags().isAbstract()) { notAbstract.add(p); } } if (notAbstract.size() == 1) { maximal = notAbstract; } else if (notAbstract.size() == 0) { // all are abstract; if all signatures match, any will do. Iterator j = maximal.iterator(); first = (ProcedureInstance) j.next(); while (j.hasNext()) { ProcedureInstance p = (ProcedureInstance) j.next(); // Use the declarations to compare formals. ProcedureInstance firstDecl = first; ProcedureInstance pDecl = p; if (first instanceof Declaration) { firstDecl = (ProcedureInstance) ((Declaration) first).declaration(); } if (p instanceof Declaration) { pDecl = (ProcedureInstance) ((Declaration) p).declaration(); } if (! firstDecl.hasFormals(pDecl.formalTypes())) { // not all signatures match; must be ambiguous return maximal; } } // all signatures match, just take the first maximal = Collections.singletonList(first); } } return maximal; } /** * Class to handle the comparisons; dispatches to moreSpecific method. */ protected static class MostSpecificComparator implements Comparator { public int compare(Object o1, Object o2) { ProcedureInstance p1 = (ProcedureInstance) o1; ProcedureInstance p2 = (ProcedureInstance) o2; if (p1.moreSpecific(p2)) return -1; if (p2.moreSpecific(p1)) return 1; return 0; } } /** * Populates the list acceptable with those MethodInstances which are * Applicable and Accessible as defined by JLS 15.11.2.1 */ protected List findAcceptableMethods(ReferenceType container, String name, List argTypes, ClassType currClass) throws SemanticException { assert_(container); assert_(argTypes); SemanticException error = null; // The list of acceptable methods. These methods are accessible from // currClass, the method call is valid, and they are not overridden // by an unacceptable method (which can occur with protected methods // only). List acceptable = new ArrayList(); // A list of unacceptable methods, where the method call is valid, but // the method is not accessible. This list is needed to make sure that // the acceptable methods are not overridden by an unacceptable method. List unacceptable = new ArrayList(); Set visitedTypes = new HashSet(); LinkedList typeQueue = new LinkedList(); typeQueue.addLast(container); while (! typeQueue.isEmpty()) { Type type = (Type) typeQueue.removeFirst(); if (visitedTypes.contains(type)) { continue; } visitedTypes.add(type); if (Report.should_report(Report.types, 2)) Report.report(2, "Searching type " + type + " for method " + name + "(" + listToString(argTypes) + ")"); if (! type.isReference()) { throw new SemanticException("Cannot call method in " + " non-reference type " + type + "."); } for (Iterator i = type.toReference().methods().iterator(); i.hasNext(); ) { MethodInstance mi = (MethodInstance) i.next(); if (Report.should_report(Report.types, 3)) Report.report(3, "Trying " + mi); if (! mi.name().equals(name)) { continue; } if (methodCallValid(mi, name, argTypes)) { if (isAccessible(mi, currClass)) { if (Report.should_report(Report.types, 3)) { Report.report(3, "->acceptable: " + mi + " in " + mi.container()); } acceptable.add(mi); } else { // method call is valid, but the method is // unacceptable. unacceptable.add(mi); if (error == null) { error = new NoMemberException(NoMemberException.METHOD, "Method " + mi.signature() + " in " + container + " is inaccessible."); } } } else { if (error == null) { error = new NoMemberException(NoMemberException.METHOD, "Method " + mi.signature() + " in " + container + " cannot be called with arguments " + "(" + listToString(argTypes) + ")."); } } } if (type.toReference().superType() != null) { typeQueue.addLast(type.toReference().superType()); } typeQueue.addAll(type.toReference().interfaces()); } if (error == null) { error = new NoMemberException(NoMemberException.METHOD, "No valid method call found for " + name + "(" + listToString(argTypes) + ")" + " in " + container + "."); } if (acceptable.size() == 0) { throw error; } // remove any method in acceptable that are overridden by an // unacceptable // method. for (Iterator i = unacceptable.iterator(); i.hasNext();) { MethodInstance mi = (MethodInstance)i.next(); acceptable.removeAll(mi.overrides()); } if (acceptable.size() == 0) { throw error; } return acceptable; } /** * Populates the list acceptable with those MethodInstances which are * Applicable and Accessible as defined by JLS 15.11.2.1 */ protected List findAcceptableConstructors(ClassType container, List argTypes, ClassType currClass) throws SemanticException { assert_(container); assert_(argTypes); SemanticException error = null; List acceptable = new ArrayList(); if (Report.should_report(Report.types, 2)) Report.report(2, "Searching type " + container + " for constructor " + container + "(" + listToString(argTypes) + ")"); for (Iterator i = container.constructors().iterator(); i.hasNext(); ) { ConstructorInstance ci = (ConstructorInstance) i.next(); if (Report.should_report(Report.types, 3)) Report.report(3, "Trying " + ci); if (callValid(ci, argTypes)) { if (isAccessible(ci, currClass)) { if (Report.should_report(Report.types, 3)) Report.report(3, "->acceptable: " + ci); acceptable.add(ci); } else { if (error == null) { error = new NoMemberException(NoMemberException.CONSTRUCTOR, "Constructor " + ci.signature() + " is inaccessible."); } } } else { if (error == null) { error = new NoMemberException(NoMemberException.CONSTRUCTOR, "Constructor " + ci.signature() + " cannot be invoked with arguments " + "(" + listToString(argTypes) + ")."); } } } if (acceptable.size() == 0) { if (error == null) { error = new NoMemberException(NoMemberException.CONSTRUCTOR, "No valid constructor found for " + container + "(" + listToString(argTypes) + ")."); } throw error; } return acceptable; } /** * Returns whether method 1 is <i>more specific</i> than method 2, * where <i>more specific</i> is defined as JLS 15.11.2.2 */ public boolean moreSpecific(ProcedureInstance p1, ProcedureInstance p2) { return p1.moreSpecificImpl(p2); } /** * Returns the supertype of type, or null if type has no supertype. **/ public Type superType(ReferenceType type) { assert_(type); return type.superType(); } /** * Returns an immutable list of all the interface types which type * implements. **/ public List interfaces(ReferenceType type) { assert_(type); return type.interfaces(); } /** * Requires: all type arguments are canonical. * Returns the least common ancestor of Type1 and Type2 **/ public Type leastCommonAncestor(Type type1, Type type2) throws SemanticException { assert_(type1); assert_(type2); if (typeEquals(type1, type2)) return type1; if (type1.isNumeric() && type2.isNumeric()) { if (isImplicitCastValid(type1, type2)) { return type2; } if (isImplicitCastValid(type2, type1)) { return type1; } if (type1.isChar() && type2.isByte() || type1.isByte() && type2.isChar()) { return Int(); } if (type1.isChar() && type2.isShort() || type1.isShort() && type2.isChar()) { return Int(); } } if (type1.isArray() && type2.isArray()) { return arrayOf(leastCommonAncestor(type1.toArray().base(), type2.toArray().base())); } if (type1.isReference() && type2.isNull()) return type1; if (type2.isReference() && type1.isNull()) return type2; if (type1.isReference() && type2.isReference()) { // Don't consider interfaces. if (type1.isClass() && type1.toClass().flags().isInterface()) { return Object(); } if (type2.isClass() && type2.toClass().flags().isInterface()) { return Object(); } // Check against Object to ensure superType() is not null. if (typeEquals(type1, Object())) return type1; if (typeEquals(type2, Object())) return type2; if (isSubtype(type1, type2)) return type2; if (isSubtype(type2, type1)) return type1; // Walk up the hierarchy Type t1 = leastCommonAncestor(type1.toReference().superType(), type2); Type t2 = leastCommonAncestor(type2.toReference().superType(), type1); if (typeEquals(t1, t2)) return t1; return Object(); } throw new SemanticException( "No least common ancestor found for types \"" + type1 + "\" and \"" + type2 + "\"."); } //// // Functions for method testing. //// /** * Returns true iff <p1> throws fewer exceptions than <p2>. */ public boolean throwsSubset(ProcedureInstance p1, ProcedureInstance p2) { assert_(p1); assert_(p2); return p1.throwsSubsetImpl(p2); } /** Return true if t overrides mi */ public boolean hasFormals(ProcedureInstance pi, List formalTypes) { assert_(pi); assert_(formalTypes); return pi.hasFormalsImpl(formalTypes); } /** Return true if t overrides mi */ public boolean hasMethod(ReferenceType t, MethodInstance mi) { assert_(t); assert_(mi); return t.hasMethodImpl(mi); } public List overrides(MethodInstance mi) { return mi.overridesImpl(); } public List implemented(MethodInstance mi) { return mi.implementedImpl(mi.container()); } public boolean canOverride(MethodInstance mi, MethodInstance mj) { try { return mi.canOverrideImpl(mj, true); } catch (SemanticException e) { // this is the exception thrown by the canOverrideImpl check. // It should never be thrown if the quiet argument of // canOverrideImpl is true. throw new InternalCompilerError(e); } } public void checkOverride(MethodInstance mi, MethodInstance mj) throws SemanticException { mi.canOverrideImpl(mj, false); } /** * Returns true iff <m1> is the same method as <m2> */ public boolean isSameMethod(MethodInstance m1, MethodInstance m2) { assert_(m1); assert_(m2); return m1.isSameMethodImpl(m2); } public boolean methodCallValid(MethodInstance prototype, String name, List argTypes) { assert_(prototype); assert_(argTypes); return prototype.methodCallValidImpl(name, argTypes); } public boolean callValid(ProcedureInstance prototype, List argTypes) { assert_(prototype); assert_(argTypes); return prototype.callValidImpl(argTypes); } //// // Functions which yield particular types. //// public NullType Null() { return NULL_; } public PrimitiveType Void() { return VOID_; } public PrimitiveType Boolean() { return BOOLEAN_; } public PrimitiveType Char() { return CHAR_; } public PrimitiveType Byte() { return BYTE_; } public PrimitiveType Short() { return SHORT_; } public PrimitiveType Int() { return INT_; } public PrimitiveType Long() { return LONG_; } public PrimitiveType Float() { return FLOAT_; } public PrimitiveType Double() { return DOUBLE_; } protected ClassType load(String name) { try { return (ClassType) typeForName(name); } catch (SemanticException e) { throw new InternalCompilerError("Cannot find class \"" + name + "\"; " + e.getMessage(), e); } } public Named forName(String name) throws SemanticException { try { return systemResolver.find(name); } catch (SemanticException e) { if (! StringUtil.isNameShort(name)) { String containerName = StringUtil.getPackageComponent(name); String shortName = StringUtil.getShortNameComponent(name); try { Named container = forName(containerName); if (container instanceof ClassType) { return classContextResolver((ClassType) container).find(shortName); } } catch (SemanticException e2) { } } // throw the original exception throw e; } } public Type typeForName(String name) throws SemanticException { return (Type) forName(name); } protected ClassType OBJECT_; protected ClassType CLASS_; protected ClassType STRING_; protected ClassType THROWABLE_; public ClassType Object() { if (OBJECT_ != null) return OBJECT_; return OBJECT_ = load("java.lang.Object"); } public ClassType Class() { if (CLASS_ != null) return CLASS_; return CLASS_ = load("java.lang.Class"); } public ClassType String() { if (STRING_ != null) return STRING_; return STRING_ = load("java.lang.String"); } public ClassType Throwable() { if (THROWABLE_ != null) return THROWABLE_; return THROWABLE_ = load("java.lang.Throwable"); } public ClassType Error() { return load("java.lang.Error"); } public ClassType Exception() { return load("java.lang.Exception"); } public ClassType RuntimeException() { return load("java.lang.RuntimeException"); } public ClassType Cloneable() { return load("java.lang.Cloneable"); } public ClassType Serializable() { return load("java.io.Serializable"); } public ClassType NullPointerException() { return load("java.lang.NullPointerException"); } public ClassType ClassCastException() { return load("java.lang.ClassCastException"); } public ClassType OutOfBoundsException() { return load("java.lang.ArrayIndexOutOfBoundsException"); } public ClassType ArrayStoreException() { return load("java.lang.ArrayStoreException"); } public ClassType ArithmeticException() { return load("java.lang.ArithmeticException"); } protected NullType createNull() { return new NullType_c(this); } protected PrimitiveType createPrimitive(PrimitiveType.Kind kind) { return new PrimitiveType_c(this, kind); } protected final NullType NULL_ = createNull(); protected final PrimitiveType VOID_ = createPrimitive(PrimitiveType.VOID); protected final PrimitiveType BOOLEAN_ = createPrimitive(PrimitiveType.BOOLEAN); protected final PrimitiveType CHAR_ = createPrimitive(PrimitiveType.CHAR); protected final PrimitiveType BYTE_ = createPrimitive(PrimitiveType.BYTE); protected final PrimitiveType SHORT_ = createPrimitive(PrimitiveType.SHORT); protected final PrimitiveType INT_ = createPrimitive(PrimitiveType.INT); protected final PrimitiveType LONG_ = createPrimitive(PrimitiveType.LONG); protected final PrimitiveType FLOAT_ = createPrimitive(PrimitiveType.FLOAT); protected final PrimitiveType DOUBLE_ = createPrimitive(PrimitiveType.DOUBLE); public Object placeHolder(TypeObject o) { return placeHolder(o, Collections.EMPTY_SET); } public Object placeHolder(TypeObject o, Set roots) { assert_(o); if (o instanceof ParsedClassType) { ParsedClassType ct = (ParsedClassType) o; // This should never happen: anonymous and local types cannot // appear in signatures. if (ct.isLocal() || ct.isAnonymous()) { throw new InternalCompilerError("Cannot serialize " + o + "."); } // Use the transformed name so that member classes will // be sought in the correct class file. String name = getTransformedClassName(ct); return new PlaceHolder_c(name); } return o; } protected UnknownType unknownType = new UnknownType_c(this); protected UnknownPackage unknownPackage = new UnknownPackage_c(this); protected UnknownQualifier unknownQualifier = new UnknownQualifier_c(this); public UnknownType unknownType(Position pos) { return unknownType; } public UnknownPackage unknownPackage(Position pos) { return unknownPackage; } public UnknownQualifier unknownQualifier(Position pos) { return unknownQualifier; } public Package packageForName(Package prefix, String name) throws SemanticException { return createPackage(prefix, name); } public Package packageForName(String name) throws SemanticException { if (name == null || name.equals("")) { return null; } String s = StringUtil.getShortNameComponent(name); String p = StringUtil.getPackageComponent(name); return packageForName(packageForName(p), s); } /** @deprecated */ public Package createPackage(Package prefix, String name) { assert_(prefix); return new Package_c(this, prefix, name); } /** @deprecated */ public Package createPackage(String name) { if (name == null || name.equals("")) { return null; } String s = StringUtil.getShortNameComponent(name); String p = StringUtil.getPackageComponent(name); return createPackage(createPackage(p), s); } /** * Returns a type identical to <type>, but with <dims> more array * dimensions. */ public ArrayType arrayOf(Type type) { assert_(type); return arrayOf(type.position(), type); } public ArrayType arrayOf(Position pos, Type type) { assert_(type); return arrayType(pos, type); } Map arrayTypeCache = new HashMap(); /** * Factory method for ArrayTypes. */ protected ArrayType createArrayType(Position pos, Type type) { return new ArrayType_c(this, pos, type); } protected ArrayType arrayType(Position pos, Type type) { ArrayType t = (ArrayType) arrayTypeCache.get(type); if (t == null) { t = createArrayType(pos, type); arrayTypeCache.put(type, t); } return t; } public ArrayType arrayOf(Type type, int dims) { return arrayOf(null, type, dims); } public ArrayType arrayOf(Position pos, Type type, int dims) { if (dims > 1) { return arrayOf(pos, arrayOf(pos, type, dims-1)); } else if (dims == 1) { return arrayOf(pos, type); } else { throw new InternalCompilerError( "Must call arrayOf(type, dims) with dims > 0"); } } /** * Returns a canonical type corresponding to the Java Class object * theClass. Does not require that <theClass> have a JavaClass * registered in this typeSystem. Does not register the type in * this TypeSystem. For use only by JavaClass implementations. **/ public Type typeForClass(Class clazz) throws SemanticException { if (clazz == Void.TYPE) return VOID_; if (clazz == Boolean.TYPE) return BOOLEAN_; if (clazz == Byte.TYPE) return BYTE_; if (clazz == Character.TYPE) return CHAR_; if (clazz == Short.TYPE) return SHORT_; if (clazz == Integer.TYPE) return INT_; if (clazz == Long.TYPE) return LONG_; if (clazz == Float.TYPE) return FLOAT_; if (clazz == Double.TYPE) return DOUBLE_; if (clazz.isArray()) { return arrayOf(typeForClass(clazz.getComponentType())); } return (Type) systemResolver.find(clazz.getName()); } /** * Return the set of objects that should be serialized into the * type information for the given TypeObject. * Usually only the object itself should get encoded, and references * to other classes should just have their name written out. * If it makes sense for additional types to be fully encoded, * (i.e., they're necessary to correctly reconstruct the given clazz, * and the usual class resolvers can't otherwise find them) they * should be returned in the set in addition to clazz. */ public Set getTypeEncoderRootSet(TypeObject t) { return Collections.singleton(t); } /** * Get the transformed class name of a class. * This utility method returns the "mangled" name of the given class, * whereby all periods ('.') following the toplevel class name * are replaced with dollar signs ('$'). If any of the containing * classes is not a member class or a top level class, then null is * returned. */ public String getTransformedClassName(ClassType ct) { StringBuffer sb = new StringBuffer(ct.fullName().length()); if (!ct.isMember() && !ct.isTopLevel()) { return null; } while (ct.isMember()) { sb.insert(0, ct.name()); sb.insert(0, '$'); ct = ct.outer(); if (!ct.isMember() && !ct.isTopLevel()) { return null; } } sb.insert(0, ct.fullName()); return sb.toString(); } public String translatePackage(Resolver c, Package p) { return p.translate(c); } public String translateArray(Resolver c, ArrayType t) { return t.translate(c); } public String translateClass(Resolver c, ClassType t) { return t.translate(c); } public String translatePrimitive(Resolver c, PrimitiveType t) { return t.translate(c); } public PrimitiveType primitiveForName(String name) throws SemanticException { if (name.equals("void")) return Void(); if (name.equals("boolean")) return Boolean(); if (name.equals("char")) return Char(); if (name.equals("byte")) return Byte(); if (name.equals("short")) return Short(); if (name.equals("int")) return Int(); if (name.equals("long")) return Long(); if (name.equals("float")) return Float(); if (name.equals("double")) return Double(); throw new SemanticException("Unrecognized primitive type \"" + name + "\"."); } public LazyClassInitializer defaultClassInitializer() { return new SchedulerClassInitializer(this); } /** * The lazy class initializer for deserialized classes. */ public LazyClassInitializer deserializedClassInitializer() { return new DeserializedClassInitializer(this); } public final ParsedClassType createClassType() { return createClassType(defaultClassInitializer(), null); } public final ParsedClassType createClassType(Source fromSource) { return createClassType(defaultClassInitializer(), fromSource); } public final ParsedClassType createClassType(LazyClassInitializer init) { return createClassType(init, null); } public ParsedClassType createClassType(LazyClassInitializer init, Source fromSource) { return new ParsedClassType_c(this, init, fromSource); } public List defaultPackageImports() { List l = new ArrayList(1); l.add("java.lang"); return l; } public PrimitiveType promote(Type t1, Type t2) throws SemanticException { if (! t1.isNumeric()) { throw new SemanticException( "Cannot promote non-numeric type " + t1); } if (! t2.isNumeric()) { throw new SemanticException( "Cannot promote non-numeric type " + t2); } return promoteNumeric(t1.toPrimitive(), t2.toPrimitive()); } protected PrimitiveType promoteNumeric(PrimitiveType t1, PrimitiveType t2) { if (t1.isDouble() || t2.isDouble()) { return Double(); } if (t1.isFloat() || t2.isFloat()) { return Float(); } if (t1.isLong() || t2.isLong()) { return Long(); } return Int(); } public PrimitiveType promote(Type t) throws SemanticException { if (! t.isNumeric()) { throw new SemanticException( "Cannot promote non-numeric type " + t); } return promoteNumeric(t.toPrimitive()); } protected PrimitiveType promoteNumeric(PrimitiveType t) { if (t.isByte() || t.isShort() || t.isChar()) { return Int(); } return t.toPrimitive(); } /** All possible <i>access</i> flags. */ public Flags legalAccessFlags() { return Public().Protected().Private(); } protected final Flags ACCESS_FLAGS = legalAccessFlags(); /** All flags allowed for a local variable. */ public Flags legalLocalFlags() { return Final(); } protected final Flags LOCAL_FLAGS = legalLocalFlags(); /** All flags allowed for a field. */ public Flags legalFieldFlags() { return legalAccessFlags().Static().Final().Transient().Volatile(); } protected final Flags FIELD_FLAGS = legalFieldFlags(); /** All flags allowed for a constructor. */ public Flags legalConstructorFlags() { return legalAccessFlags().Synchronized().Native(); } protected final Flags CONSTRUCTOR_FLAGS = legalConstructorFlags(); /** All flags allowed for an initializer block. */ public Flags legalInitializerFlags() { return Static(); } protected final Flags INITIALIZER_FLAGS = legalInitializerFlags(); /** All flags allowed for a method. */ public Flags legalMethodFlags() { return legalAccessFlags().Abstract().Static().Final().Native().Synchronized().StrictFP(); } protected final Flags METHOD_FLAGS = legalMethodFlags(); public Flags legalAbstractMethodFlags() { return legalAccessFlags().clear(Private()).Abstract(); } protected final Flags ABSTRACT_METHOD_FLAGS = legalAbstractMethodFlags(); /** All flags allowed for a top-level class. */ public Flags legalTopLevelClassFlags() { return legalAccessFlags().clear(Private()).Abstract().Final().StrictFP().Interface(); } protected final Flags TOP_LEVEL_CLASS_FLAGS = legalTopLevelClassFlags(); /** All flags allowed for an interface. */ public Flags legalInterfaceFlags() { return legalAccessFlags().Abstract().Interface().Static(); } protected final Flags INTERFACE_FLAGS = legalInterfaceFlags(); /** All flags allowed for a member class. */ public Flags legalMemberClassFlags() { return legalAccessFlags().Static().Abstract().Final().StrictFP().Interface(); } protected final Flags MEMBER_CLASS_FLAGS = legalMemberClassFlags(); /** All flags allowed for a local class. */ public Flags legalLocalClassFlags() { return Abstract().Final().StrictFP().Interface(); } protected final Flags LOCAL_CLASS_FLAGS = legalLocalClassFlags(); public void checkMethodFlags(Flags f) throws SemanticException { if (! f.clear(METHOD_FLAGS).equals(Flags.NONE)) { throw new SemanticException( "Cannot declare method with flags " + f.clear(METHOD_FLAGS) + "."); } if (f.isAbstract() && ! f.clear(ABSTRACT_METHOD_FLAGS).equals(Flags.NONE)) { throw new SemanticException( "Cannot declare abstract method with flags " + f.clear(ABSTRACT_METHOD_FLAGS) + "."); } checkAccessFlags(f); } public void checkLocalFlags(Flags f) throws SemanticException { if (! f.clear(LOCAL_FLAGS).equals(Flags.NONE)) { throw new SemanticException( "Cannot declare local variable with flags " + f.clear(LOCAL_FLAGS) + "."); } } public void checkFieldFlags(Flags f) throws SemanticException { if (! f.clear(FIELD_FLAGS).equals(Flags.NONE)) { throw new SemanticException( "Cannot declare field with flags " + f.clear(FIELD_FLAGS) + "."); } checkAccessFlags(f); } public void checkConstructorFlags(Flags f) throws SemanticException { if (! f.clear(CONSTRUCTOR_FLAGS).equals(Flags.NONE)) { throw new SemanticException( "Cannot declare constructor with flags " + f.clear(CONSTRUCTOR_FLAGS) + "."); } checkAccessFlags(f); } public void checkInitializerFlags(Flags f) throws SemanticException { if (! f.clear(INITIALIZER_FLAGS).equals(Flags.NONE)) { throw new SemanticException( "Cannot declare initializer with flags " + f.clear(INITIALIZER_FLAGS) + "."); } } public void checkTopLevelClassFlags(Flags f) throws SemanticException { if (! f.clear(TOP_LEVEL_CLASS_FLAGS).equals(Flags.NONE)) { throw new SemanticException( "Cannot declare a top-level class with flag(s) " + f.clear(TOP_LEVEL_CLASS_FLAGS) + "."); } if (f.isInterface() && ! f.clear(INTERFACE_FLAGS).equals(Flags.NONE)) { throw new SemanticException("Cannot declare interface with flags " + f.clear(INTERFACE_FLAGS) + "."); } checkAccessFlags(f); } public void checkMemberClassFlags(Flags f) throws SemanticException { if (! f.clear(MEMBER_CLASS_FLAGS).equals(Flags.NONE)) { throw new SemanticException( "Cannot declare a member class with flag(s) " + f.clear(MEMBER_CLASS_FLAGS) + "."); } checkAccessFlags(f); } public void checkLocalClassFlags(Flags f) throws SemanticException { if (f.isInterface()) { throw new SemanticException("Cannot declare a local interface."); } if (! f.clear(LOCAL_CLASS_FLAGS).equals(Flags.NONE)) { throw new SemanticException( "Cannot declare a local class with flag(s) " + f.clear(LOCAL_CLASS_FLAGS) + "."); } checkAccessFlags(f); } public void checkAccessFlags(Flags f) throws SemanticException { int count = 0; if (f.isPublic()) count++; if (f.isProtected()) count++; if (f.isPrivate()) count++; if (count > 1) { throw new SemanticException( "Invalid access flags: " + f.retain(ACCESS_FLAGS) + "."); } } /** * Utility method to gather all the superclasses and interfaces of * <code>ct</code> that may contain abstract methods that must be * implemented by <code>ct</code>. The list returned also contains * <code>rt</code>. */ protected List abstractSuperInterfaces(ReferenceType rt) { List superInterfaces = new LinkedList(); superInterfaces.add(rt); for (Iterator iter = rt.interfaces().iterator(); iter.hasNext(); ) { ClassType interf = (ClassType)iter.next(); superInterfaces.addAll(abstractSuperInterfaces(interf)); } if (rt.superType() != null) { ClassType c = rt.superType().toClass(); if (c.flags().isAbstract()) { // the superclass is abstract, so it may contain methods // that must be implemented. superInterfaces.addAll(abstractSuperInterfaces(c)); } else { // the superclass is not abstract, so it must implement // all abstract methods of any interfaces it implements, and // any superclasses it may have. } } return superInterfaces; } /** * Assert that <code>ct</code> implements all abstract methods required; * that is, if it is a concrete class, then it must implement all * interfaces and abstract methods that it or it's superclasses declare, and if * it is an abstract class then any methods that it overrides are overridden * correctly. */ public void checkClassConformance(ClassType ct) throws SemanticException { if (ct.flags().isAbstract()) { // don't need to check interfaces or abstract classes return; } // build up a list of superclasses and interfaces that ct // extends/implements that may contain abstract methods that // ct must define. List superInterfaces = abstractSuperInterfaces(ct); // check each abstract method of the classes and interfaces in // superInterfaces for (Iterator i = superInterfaces.iterator(); i.hasNext(); ) { ReferenceType rt = (ReferenceType)i.next(); for (Iterator j = rt.methods().iterator(); j.hasNext(); ) { MethodInstance mi = (MethodInstance)j.next(); if (!mi.flags().isAbstract()) { // the method isn't abstract, so ct doesn't have to // implement it. continue; } MethodInstance mj = findImplementingMethod(ct, mi); if (mj == null) { if (!ct.flags().isAbstract()) { throw new SemanticException(ct.fullName() + " should be " + "declared abstract; it does not define " + mi.signature() + ", which is declared in " + rt.toClass().fullName(), ct.position()); } else { // no implementation, but that's ok, the class is abstract. } } else if (!equals(ct, mj.container()) && !equals(ct, mi.container())) { try { // check that mj can override mi, which // includes access protection checks. checkOverride(mj, mi); } catch (SemanticException e) { // change the position of the semantic // exception to be the class that we // are checking. throw new SemanticException(e.getMessage(), ct.position()); } } else { // the method implementation mj or mi was // declared in ct. So other checks will take // care of access issues } } } } public MethodInstance findImplementingMethod(ClassType ct, MethodInstance mi) { ReferenceType curr = ct; while (curr != null) { List possible = curr.methods(mi.name(), mi.formalTypes()); for (Iterator k = possible.iterator(); k.hasNext(); ) { MethodInstance mj = (MethodInstance)k.next(); if (!mj.flags().isAbstract() && ((isAccessible(mi, ct) && isAccessible(mj, ct)) || isAccessible(mi, mj.container().toClass()))) { // The method mj may be a suitable implementation of mi. // mj is not abstract, and either mj's container // can access mi (thus mj can really override mi), or // mi and mj are both accessible from ct (e.g., // mi is declared in an interface that ct implements, // and mj is defined in a superclass of ct). return mj; } } if (curr == mi.container()) { // we've reached the definition of the abstract // method. We don't want to look higher in the // hierarchy; this is not an optimization, but is // required for correctness. break; } curr = curr.superType() == null ? null : curr.superType().toReference(); } return null; } /** * Returns t, modified as necessary to make it a legal * static target. */ public Type staticTarget(Type t) { // Nothing needs done in standard Java. return t; } protected void initFlags() { flagsForName = new HashMap(); flagsForName.put("public", Flags.PUBLIC); flagsForName.put("private", Flags.PRIVATE); flagsForName.put("protected", Flags.PROTECTED); flagsForName.put("static", Flags.STATIC); flagsForName.put("final", Flags.FINAL); flagsForName.put("synchronized", Flags.SYNCHRONIZED); flagsForName.put("transient", Flags.TRANSIENT); flagsForName.put("native", Flags.NATIVE); flagsForName.put("interface", Flags.INTERFACE); flagsForName.put("abstract", Flags.ABSTRACT); flagsForName.put("volatile", Flags.VOLATILE); flagsForName.put("strictfp", Flags.STRICTFP); } public Flags createNewFlag(String name, Flags after) { Flags f = Flags.createFlag(name, after); flagsForName.put(name, f); return f; } public Flags NoFlags() { return Flags.NONE; } public Flags Public() { return Flags.PUBLIC; } public Flags Private() { return Flags.PRIVATE; } public Flags Protected() { return Flags.PROTECTED; } public Flags Static() { return Flags.STATIC; } public Flags Final() { return Flags.FINAL; } public Flags Synchronized() { return Flags.SYNCHRONIZED; } public Flags Transient() { return Flags.TRANSIENT; } public Flags Native() { return Flags.NATIVE; } public Flags Interface() { return Flags.INTERFACE; } public Flags Abstract() { return Flags.ABSTRACT; } public Flags Volatile() { return Flags.VOLATILE; } public Flags StrictFP() { return Flags.STRICTFP; } public Flags flagsForBits(int bits) { Flags f = Flags.NONE; if ((bits & Modifier.PUBLIC) != 0) f = f.Public(); if ((bits & Modifier.PRIVATE) != 0) f = f.Private(); if ((bits & Modifier.PROTECTED) != 0) f = f.Protected(); if ((bits & Modifier.STATIC) != 0) f = f.Static(); if ((bits & Modifier.FINAL) != 0) f = f.Final(); if ((bits & Modifier.SYNCHRONIZED) != 0) f = f.Synchronized(); if ((bits & Modifier.TRANSIENT) != 0) f = f.Transient(); if ((bits & Modifier.NATIVE) != 0) f = f.Native(); if ((bits & Modifier.INTERFACE) != 0) f = f.Interface(); if ((bits & Modifier.ABSTRACT) != 0) f = f.Abstract(); if ((bits & Modifier.VOLATILE) != 0) f = f.Volatile(); if ((bits & Modifier.STRICT) != 0) f = f.StrictFP(); return f; } public Flags flagsForName(String name) { Flags f = (Flags) flagsForName.get(name); if (f == null) { throw new InternalCompilerError("No flag named \"" + name + "\"."); } return f; } public String toString() { return StringUtil.getShortNameComponent(getClass().getName()); } }
Added hooks to let subclasses find classes using something besides the SystemResolver.
src/polyglot/types/TypeSystem_c.java
Added hooks to let subclasses find classes using something besides the SystemResolver.
<ide><path>rc/polyglot/types/TypeSystem_c.java <ide> } <ide> <ide> public Named forName(String name) throws SemanticException { <add> return forName(systemResolver, name); <add> } <add> <add> protected Named forName(Resolver resolver, String name) throws SemanticException { <ide> try { <del> return systemResolver.find(name); <add> return resolver.find(name); <ide> } <ide> catch (SemanticException e) { <ide> if (! StringUtil.isNameShort(name)) { <ide> String shortName = StringUtil.getShortNameComponent(name); <ide> <ide> try { <del> Named container = forName(containerName); <add> Named container = forName(resolver, containerName); <ide> if (container instanceof ClassType) { <ide> return classContextResolver((ClassType) container).find(shortName); <ide> } <ide> * registered in this typeSystem. Does not register the type in <ide> * this TypeSystem. For use only by JavaClass implementations. <ide> **/ <del> public Type typeForClass(Class clazz) throws SemanticException <del> { <add> public Type typeForClass(Class clazz) throws SemanticException { <add> return typeForClass(systemResolver, clazz); <add> } <add> <add> protected Type typeForClass(Resolver resolver, Class clazz) <add> throws SemanticException { <ide> if (clazz == Void.TYPE) return VOID_; <ide> if (clazz == Boolean.TYPE) return BOOLEAN_; <ide> if (clazz == Byte.TYPE) return BYTE_; <ide> return arrayOf(typeForClass(clazz.getComponentType())); <ide> } <ide> <del> return (Type) systemResolver.find(clazz.getName()); <add> return (Type) resolver.find(clazz.getName()); <ide> } <ide> <ide> /**
Java
agpl-3.0
fe02cb48c8623f36b29e0064c3dcb44311c1e307
0
thebigg73/OpenSongTablet,thebigg73/OpenSongTablet,thebigg73/OpenSongTablet
package com.garethevans.church.opensongtablet; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.Button; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.fragment.app.DialogFragment; import com.google.android.material.floatingactionbutton.FloatingActionButton; public class PopUpSongDetailsFragment extends DialogFragment { static PopUpSongDetailsFragment newInstance() { PopUpSongDetailsFragment frag; frag = new PopUpSongDetailsFragment(); return frag; } public interface MyInterface { void doEdit(); } private MyInterface mListener; @Override public void onAttach(@NonNull Context context) { mListener = (MyInterface) context; super.onAttach(context); } @Override public void onDetach() { mListener = null; super.onDetach(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { this.dismiss(); } } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (getDialog()!=null) { getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE); getDialog().setCanceledOnTouchOutside(true); } View V = inflater.inflate(R.layout.popup_song_details, container, false); TextView title = V.findViewById(R.id.dialogtitle); // IV - If ReceivedSong then, if available, use the stored received song filename if (StaticVariables.songfilename.equals("ReceivedSong") && !StaticVariables.receivedSongfilename.equals("")) { title.setText("ReceivedSong: " + StaticVariables.receivedSongfilename); } else { title.setText(StaticVariables.songfilename); } final FloatingActionButton closeMe = V.findViewById(R.id.closeMe); closeMe.setOnClickListener(view -> { CustomAnimations.animateFAB(closeMe,getContext()); closeMe.setEnabled(false); dismiss(); }); FloatingActionButton saveMe = V.findViewById(R.id.saveMe); saveMe.hide(); ProcessSong processSong = new ProcessSong(); Preferences preferences = new Preferences(); Button editSongDetails = V.findViewById(R.id.editSongDetails); editSongDetails.setOnClickListener(v -> { mListener.doEdit(); dismiss(); }); TextView t_mPresentation = V.findViewById(R.id.t_mPresentation); TextView t_mHymnNumber = V.findViewById(R.id.t_mHymnNumber); TextView t_mCCLI = V.findViewById(R.id.t_mCCLI); TextView t_mNotes = V.findViewById(R.id.t_mNotes); TextView t_mLyrics = V.findViewById(R.id.t_mLyrics); TextView v_mTitle = V.findViewById(R.id.v_mTitle); TextView v_mAuthor = V.findViewById(R.id.v_mAuthor); TextView v_mKey = V.findViewById(R.id.v_mKey); TextView v_mCopyright = V.findViewById(R.id.v_mCopyright); TextView v_mPresentation = V.findViewById(R.id.v_mPresentation); TextView v_mHymnNumber = V.findViewById(R.id.v_mHymnNumber); TextView v_mCCLI = V.findViewById(R.id.v_mCCLI); TextView v_mNotes = V.findViewById(R.id.v_mNotes); TextView v_mLyrics = V.findViewById(R.id.v_mLyrics); // IV - Try to generate a capo/key/tempo/time line StringBuilder songInformation = new StringBuilder(); String sprefix = ""; if (!StaticVariables.mCapo.equals("") && !StaticVariables.mCapo.equals("0")) { // If we are using a capo, add the capo display songInformation.append(sprefix).append("Capo: "); sprefix = " | "; int mcapo; try { mcapo = Integer.parseInt("0" + StaticVariables.mCapo); } catch (Exception e) { mcapo = -1; } if ((mcapo > 0) && (preferences.getMyPreferenceBoolean(getContext(), "capoInfoAsNumerals", false))) { songInformation.append(numberToNumeral(mcapo)); } else { songInformation.append("").append(mcapo); } Transpose transpose = new Transpose(); if (!StaticVariables.mKey.equals("")) { songInformation.append(" (").append(transpose.capoTranspose(getContext(), preferences, StaticVariables.mKey)).append(")"); } } if (!StaticVariables.mKey.equals("")) { songInformation.append(sprefix).append(getContext().getResources().getString(R.string.edit_song_key)).append(": ").append(StaticVariables.mKey); sprefix = " | "; } if (!StaticVariables.mTempo.equals("")) { songInformation.append(sprefix).append(getContext().getResources().getString(R.string.edit_song_tempo)).append(": ").append(StaticVariables.mTempo); sprefix = " | "; } if (!StaticVariables.mTimeSig.equals("")) { songInformation.append(sprefix).append(getContext().getResources().getString(R.string.edit_song_timesig)).append(": ").append(StaticVariables.mTimeSig); sprefix = " | "; } String copyright = ""; if (!StaticVariables.mCopyright.equals("")) { copyright = "© " + StaticVariables.mCopyright; } // Decide what should or should be shown v_mTitle.setText(StaticVariables.mTitle); setContentInfo(null,v_mAuthor, StaticVariables.mAuthor); setContentInfo(null,v_mCopyright, copyright); setContentInfo(null,v_mKey, songInformation.toString()); setContentInfo(t_mCCLI,v_mCCLI, StaticVariables.mCCLI); setContentInfo(t_mPresentation,v_mPresentation, StaticVariables.mPresentation); setContentInfo(t_mHymnNumber,v_mHymnNumber, StaticVariables.mHymnNumber); setContentInfo(t_mNotes,v_mNotes, StaticVariables.mNotes); v_mLyrics.setTypeface(StaticVariables.typefaceLyrics); v_mLyrics.setTextSize(8.0f); // IV - No Lyrics for PDF and Image songs if (FullscreenActivity.isPDF || FullscreenActivity.isImage) { StaticVariables.mLyrics = ""; } setContentInfo(t_mLyrics, v_mLyrics, StaticVariables.mLyrics); PopUpSizeAndAlpha.decoratePopUp(getActivity(),getDialog(), preferences); return V; } private void setContentInfo(TextView tv_t, TextView tv_v, String s) { if (s!=null && !s.equals("")) { if (tv_t != null) { tv_t.setVisibility(View.VISIBLE); } tv_v.setVisibility(View.VISIBLE); tv_v.setText(s); } else { if (tv_t != null) { tv_t.setVisibility(View.GONE); } tv_v.setVisibility(View.GONE); } } @Override public void onCancel(@NonNull DialogInterface dialog) { this.dismiss(); } private String numberToNumeral(int num) { String s; switch (num) { default: s = ""; break; case 1: s = "I"; break; case 2: s = "II"; break; case 3: s = "III"; break; case 4: s = "IV"; break; case 5: s = "V"; break; case 6: s = "VI"; break; case 7: s = "VII"; break; case 8: s = "VIII"; break; case 9: s = "IX"; break; case 10: s = "X"; break; case 11: s = "XI"; break; case 12: s = "XII"; break; } return s; } }
app/src/main/java/com/garethevans/church/opensongtablet/PopUpSongDetailsFragment.java
package com.garethevans.church.opensongtablet; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.Button; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.fragment.app.DialogFragment; import com.google.android.material.floatingactionbutton.FloatingActionButton; public class PopUpSongDetailsFragment extends DialogFragment { static PopUpSongDetailsFragment newInstance() { PopUpSongDetailsFragment frag; frag = new PopUpSongDetailsFragment(); return frag; } public interface MyInterface { void doEdit(); } private MyInterface mListener; @Override public void onAttach(@NonNull Context context) { mListener = (MyInterface) context; super.onAttach(context); } @Override public void onDetach() { mListener = null; super.onDetach(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { this.dismiss(); } } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (getDialog()!=null) { getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE); getDialog().setCanceledOnTouchOutside(true); } View V = inflater.inflate(R.layout.popup_song_details, container, false); TextView title = V.findViewById(R.id.dialogtitle); // IV - If ReceivedSong then, if available, use the stored received song filename if (StaticVariables.songfilename.equals("ReceivedSong") && !StaticVariables.receivedSongfilename.equals("")) { title.setText("ReceivedSong: " + StaticVariables.receivedSongfilename); } else { title.setText(StaticVariables.songfilename); } final FloatingActionButton closeMe = V.findViewById(R.id.closeMe); closeMe.setOnClickListener(view -> { CustomAnimations.animateFAB(closeMe,getContext()); closeMe.setEnabled(false); dismiss(); }); FloatingActionButton saveMe = V.findViewById(R.id.saveMe); saveMe.hide(); ProcessSong processSong = new ProcessSong(); Preferences preferences = new Preferences(); Button editSongDetails = V.findViewById(R.id.editSongDetails); editSongDetails.setOnClickListener(v -> { mListener.doEdit(); dismiss(); }); TextView t_mPresentation = V.findViewById(R.id.t_mPresentation); TextView t_mHymnNumber = V.findViewById(R.id.t_mHymnNumber); TextView t_mCCLI = V.findViewById(R.id.t_mCCLI); TextView t_mNotes = V.findViewById(R.id.t_mNotes); TextView t_mLyrics = V.findViewById(R.id.t_mLyrics); TextView v_mTitle = V.findViewById(R.id.v_mTitle); TextView v_mAuthor = V.findViewById(R.id.v_mAuthor); TextView v_mKey = V.findViewById(R.id.v_mKey); TextView v_mCopyright = V.findViewById(R.id.v_mCopyright); TextView v_mPresentation = V.findViewById(R.id.v_mPresentation); TextView v_mHymnNumber = V.findViewById(R.id.v_mHymnNumber); TextView v_mCCLI = V.findViewById(R.id.v_mCCLI); TextView v_mNotes = V.findViewById(R.id.v_mNotes); TextView v_mLyrics = V.findViewById(R.id.v_mLyrics); // IV - Try to generate a capo/key/tempo/time line StringBuilder songInformation = new StringBuilder(); String sprefix = ""; if (!StaticVariables.mCapo.equals("") && !StaticVariables.mCapo.equals("0")) { // If we are using a capo, add the capo display songInformation.append(sprefix).append("Capo: "); sprefix = " | "; int mcapo; try { mcapo = Integer.parseInt("0" + StaticVariables.mCapo); } catch (Exception e) { mcapo = -1; } if ((mcapo > 0) && (preferences.getMyPreferenceBoolean(getContext(), "capoInfoAsNumerals", false))) { songInformation.append(numberToNumeral(mcapo)); } else { songInformation.append("").append(mcapo); } Transpose transpose = new Transpose(); if (!StaticVariables.mKey.equals("")) { songInformation.append(" (").append(transpose.capoTranspose(getContext(), preferences, StaticVariables.mKey)).append(")"); } } if (!StaticVariables.mKey.equals("")) { songInformation.append(sprefix).append(getContext().getResources().getString(R.string.edit_song_key)).append(": ").append(StaticVariables.mKey); sprefix = " | "; } if (!StaticVariables.mTempo.equals("")) { songInformation.append(sprefix).append(getContext().getResources().getString(R.string.edit_song_tempo)).append(": ").append(StaticVariables.mTempo); sprefix = " | "; } if (!StaticVariables.mTimeSig.equals("")) { songInformation.append(sprefix).append(getContext().getResources().getString(R.string.edit_song_timesig)).append(": ").append(StaticVariables.mTimeSig); sprefix = " | "; } // Decide what should or should be shown v_mTitle.setText(StaticVariables.mTitle); setContentInfo(null,v_mAuthor, StaticVariables.mAuthor); setContentInfo(null,v_mCopyright, StaticVariables.mCopyright); setContentInfo(null,v_mKey, songInformation.toString()); setContentInfo(t_mCCLI,v_mCCLI, StaticVariables.mCCLI); setContentInfo(t_mPresentation,v_mPresentation, StaticVariables.mPresentation); setContentInfo(t_mHymnNumber,v_mHymnNumber, StaticVariables.mHymnNumber); setContentInfo(t_mNotes,v_mNotes, StaticVariables.mNotes); v_mLyrics.setTypeface(StaticVariables.typefaceLyrics); v_mLyrics.setTextSize(8.0f); // IV - No Lyrics for PDF and Image songs if (FullscreenActivity.isPDF || FullscreenActivity.isImage) { StaticVariables.mLyrics = ""; } setContentInfo(t_mLyrics, v_mLyrics, StaticVariables.mLyrics); PopUpSizeAndAlpha.decoratePopUp(getActivity(),getDialog(), preferences); return V; } private void setContentInfo(TextView tv_t, TextView tv_v, String s) { if (s!=null && !s.equals("")) { if (tv_t != null) { tv_t.setVisibility(View.VISIBLE); } tv_v.setVisibility(View.VISIBLE); tv_v.setText(s); } else { if (tv_t != null) { tv_t.setVisibility(View.GONE); } tv_v.setVisibility(View.GONE); } } @Override public void onCancel(@NonNull DialogInterface dialog) { this.dismiss(); } private String numberToNumeral(int num) { String s; switch (num) { default: s = ""; break; case 1: s = "I"; break; case 2: s = "II"; break; case 3: s = "III"; break; case 4: s = "IV"; break; case 5: s = "V"; break; case 6: s = "VI"; break; case 7: s = "VII"; break; case 8: s = "VIII"; break; case 9: s = "IX"; break; case 10: s = "X"; break; case 11: s = "XI"; break; case 12: s = "XII"; break; } return s; } }
Enh: PopupCustomPadsFragment: Added © symbol
app/src/main/java/com/garethevans/church/opensongtablet/PopUpSongDetailsFragment.java
Enh: PopupCustomPadsFragment: Added © symbol
<ide><path>pp/src/main/java/com/garethevans/church/opensongtablet/PopUpSongDetailsFragment.java <ide> sprefix = " | "; <ide> } <ide> <add> String copyright = ""; <add> if (!StaticVariables.mCopyright.equals("")) { <add> copyright = "© " + StaticVariables.mCopyright; <add> } <add> <ide> // Decide what should or should be shown <ide> v_mTitle.setText(StaticVariables.mTitle); <ide> setContentInfo(null,v_mAuthor, StaticVariables.mAuthor); <del> setContentInfo(null,v_mCopyright, StaticVariables.mCopyright); <add> setContentInfo(null,v_mCopyright, copyright); <ide> setContentInfo(null,v_mKey, songInformation.toString()); <ide> setContentInfo(t_mCCLI,v_mCCLI, StaticVariables.mCCLI); <ide> setContentInfo(t_mPresentation,v_mPresentation, StaticVariables.mPresentation);
Java
apache-2.0
b48c760d422ec8cd0e31f18236730d0ef0460e73
0
eitchnet/strolch,eitchnet/strolch,eitchnet/strolch,4treesCH/strolch,4treesCH/strolch,eitchnet/strolch,4treesCH/strolch,4treesCH/strolch
package li.strolch.rest.helper; import static li.strolch.rest.StrolchRestfulConstants.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import li.strolch.privilege.base.AccessDeniedException; import li.strolch.privilege.base.PrivilegeException; import li.strolch.service.api.ServiceResult; import li.strolch.utils.collections.Paging; import li.strolch.utils.helper.ExceptionHelper; import li.strolch.utils.helper.StringHelper; /** * Created by eitch on 29.08.16. */ public class ResponseUtil { public static Response toResponse() { JsonObject response = new JsonObject(); response.addProperty(MSG, StringHelper.DASH); String json = new Gson().toJson(response); return Response.ok(json, MediaType.APPLICATION_JSON).build(); } public static Response toResponse(String errorMsg) { JsonObject response = new JsonObject(); response.addProperty(MSG, errorMsg); String json = new Gson().toJson(response); return Response.serverError().entity(json).type(MediaType.APPLICATION_JSON).build(); } public static Response toResponse(String prop, String value) { JsonObject response = new JsonObject(); response.addProperty(MSG, StringHelper.DASH); response.addProperty(prop, value); String json = new Gson().toJson(response); return Response.ok(json, MediaType.APPLICATION_JSON).build(); } public static Response toResponse(String prop1, String value1, String prop2, String value2) { JsonObject response = new JsonObject(); response.addProperty(MSG, StringHelper.DASH); response.addProperty(prop1, value1); response.addProperty(prop2, value2); String json = new Gson().toJson(response); return Response.ok(json, MediaType.APPLICATION_JSON).build(); } public static <T> Response toResponse(String member, T t, Function<T, JsonObject> toJson) { return toResponse(member, toJson.apply(t)); } public static Response toResponse(String member, JsonElement jsonElement) { JsonObject response = new JsonObject(); response.addProperty(MSG, StringHelper.DASH); response.add(member, jsonElement); String json = new Gson().toJson(response); return Response.ok(json, MediaType.APPLICATION_JSON).build(); } public static <T> Response toResponse(String member, List<T> list, Function<T, JsonObject> toJson) { return toResponse(member, list.stream().map(toJson).collect(Collectors.toList())); } public static Response toResponse(String member, List<JsonObject> jsonObjects) { JsonObject response = new JsonObject(); response.addProperty(MSG, StringHelper.DASH); JsonArray arrayJ = new JsonArray(); for (JsonElement obj : jsonObjects) { arrayJ.add(obj); } response.add(member, arrayJ); String json = new Gson().toJson(response); return Response.ok(json, MediaType.APPLICATION_JSON).build(); } public static Response toResponse(ServiceResult svcResult) { String msg = StringHelper.DASH; String exceptionMsg = StringHelper.DASH; Throwable t = svcResult.getThrowable(); if (svcResult.isNok()) { msg = svcResult.getMessage(); if (t != null) { exceptionMsg = StringHelper.formatExceptionMessage(t); if (StringHelper.isEmpty(msg)) msg = exceptionMsg; } } JsonObject response = new JsonObject(); response.addProperty(MSG, msg); if (!exceptionMsg.equals(StringHelper.DASH)) response.addProperty(EXCEPTION_MSG, exceptionMsg); String json = new Gson().toJson(response); if (svcResult.isOk()) return Response.ok().entity(json).type(MediaType.APPLICATION_JSON).build(); Status status; if (t instanceof AccessDeniedException) { status = Status.FORBIDDEN; } else if (t instanceof PrivilegeException) { status = Status.UNAUTHORIZED; } else { status = Status.INTERNAL_SERVER_ERROR; } return Response.status(status).entity(json).type(MediaType.APPLICATION_JSON).build(); } public static Response toResponse(Throwable t) { if (t instanceof AccessDeniedException) { return ResponseUtil.toResponse(Status.FORBIDDEN, t); } else if (t instanceof PrivilegeException) { return ResponseUtil.toResponse(Status.UNAUTHORIZED, t); } else { return toResponse(Status.INTERNAL_SERVER_ERROR, t); } } public static Response toResponse(Status status, String msg) { JsonObject response = new JsonObject(); response.addProperty(MSG, msg); String json = new Gson().toJson(response); return Response.status(status).entity(json).type(MediaType.APPLICATION_JSON).build(); } public static Response toResponse(Status status, Throwable t) { JsonObject response = new JsonObject(); response.addProperty(MSG, ExceptionHelper.getExceptionMessageWithCauses(t)); String json = new Gson().toJson(response); return Response.status(status).entity(json).type(MediaType.APPLICATION_JSON).build(); } public static <T> Response toResponse(Paging<T> paging, Function<T, JsonObject> visitor) { JsonObject response = new JsonObject(); addPagingInfo(paging, response); List<T> page = paging.getPage(); JsonArray data = new JsonArray(); page.forEach(t -> data.add(visitor.apply(t))); response.add(DATA, data); String json = new Gson().toJson(response); return Response.ok(json, MediaType.APPLICATION_JSON).build(); } public static Response toResponse(Paging<JsonObject> paging) { JsonObject response = new JsonObject(); addPagingInfo(paging, response); List<JsonObject> page = paging.getPage(); JsonArray data = new JsonArray(); for (JsonObject jsonObject : page) { JsonObject element = jsonObject; data.add(element); } response.add(DATA, data); String json = new Gson().toJson(response); return Response.ok(json, MediaType.APPLICATION_JSON).build(); } private static <T> void addPagingInfo(Paging<T> paging, JsonObject response) { response.addProperty(MSG, StringHelper.DASH); response.addProperty(LIMIT, paging.getLimit()); response.addProperty(OFFSET, paging.getOffset()); response.addProperty(SIZE, paging.getSize()); response.addProperty(PREVIOUS_OFFSET, paging.getPreviousOffset()); response.addProperty(NEXT_OFFSET, paging.getNextOffset()); response.addProperty(LAST_OFFSET, paging.getLastOffset()); } }
li.strolch.rest/src/main/java/li/strolch/rest/helper/ResponseUtil.java
package li.strolch.rest.helper; import static li.strolch.rest.StrolchRestfulConstants.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import java.util.List; import java.util.function.Function; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import li.strolch.privilege.base.AccessDeniedException; import li.strolch.privilege.base.PrivilegeException; import li.strolch.service.api.ServiceResult; import li.strolch.utils.collections.Paging; import li.strolch.utils.helper.ExceptionHelper; import li.strolch.utils.helper.StringHelper; /** * Created by eitch on 29.08.16. */ public class ResponseUtil { public static Response toResponse() { JsonObject response = new JsonObject(); response.addProperty(MSG, StringHelper.DASH); String json = new Gson().toJson(response); return Response.ok(json, MediaType.APPLICATION_JSON).build(); } public static Response toResponse(String errorMsg) { JsonObject response = new JsonObject(); response.addProperty(MSG, errorMsg); String json = new Gson().toJson(response); return Response.serverError().entity(json).type(MediaType.APPLICATION_JSON).build(); } public static Response toResponse(String prop, String value) { JsonObject response = new JsonObject(); response.addProperty(MSG, StringHelper.DASH); response.addProperty(prop, value); String json = new Gson().toJson(response); return Response.ok(json, MediaType.APPLICATION_JSON).build(); } public static Response toResponse(String prop1, String value1, String prop2, String value2) { JsonObject response = new JsonObject(); response.addProperty(MSG, StringHelper.DASH); response.addProperty(prop1, value1); response.addProperty(prop2, value2); String json = new Gson().toJson(response); return Response.ok(json, MediaType.APPLICATION_JSON).build(); } public static Response toResponse(String member, JsonElement jsonElement) { JsonObject response = new JsonObject(); response.addProperty(MSG, StringHelper.DASH); response.add(member, jsonElement); String json = new Gson().toJson(response); return Response.ok(json, MediaType.APPLICATION_JSON).build(); } public static Response toResponse(String member, List<JsonObject> jsonObjects) { JsonObject response = new JsonObject(); response.addProperty(MSG, StringHelper.DASH); JsonArray arrayJ = new JsonArray(); for (JsonElement obj : jsonObjects) { arrayJ.add(obj); } response.add(member, arrayJ); String json = new Gson().toJson(response); return Response.ok(json, MediaType.APPLICATION_JSON).build(); } public static Response toResponse(ServiceResult svcResult) { String msg = StringHelper.DASH; String exceptionMsg = StringHelper.DASH; Throwable t = svcResult.getThrowable(); if (svcResult.isNok()) { msg = svcResult.getMessage(); if (t != null) { exceptionMsg = StringHelper.formatExceptionMessage(t); if (StringHelper.isEmpty(msg)) msg = exceptionMsg; } } JsonObject response = new JsonObject(); response.addProperty(MSG, msg); if (!exceptionMsg.equals(StringHelper.DASH)) response.addProperty(EXCEPTION_MSG, exceptionMsg); String json = new Gson().toJson(response); if (svcResult.isOk()) return Response.ok().entity(json).type(MediaType.APPLICATION_JSON).build(); Status status; if (t instanceof AccessDeniedException) { status = Status.FORBIDDEN; } else if (t instanceof PrivilegeException) { status = Status.UNAUTHORIZED; } else { status = Status.INTERNAL_SERVER_ERROR; } return Response.status(status).entity(json).type(MediaType.APPLICATION_JSON).build(); } public static Response toResponse(Throwable t) { if (t instanceof AccessDeniedException) { return ResponseUtil.toResponse(Status.FORBIDDEN, t); } else if (t instanceof PrivilegeException) { return ResponseUtil.toResponse(Status.UNAUTHORIZED, t); } else { return toResponse(Status.INTERNAL_SERVER_ERROR, t); } } public static Response toResponse(Status status, String msg) { JsonObject response = new JsonObject(); response.addProperty(MSG, msg); String json = new Gson().toJson(response); return Response.status(status).entity(json).type(MediaType.APPLICATION_JSON).build(); } public static Response toResponse(Status status, Throwable t) { JsonObject response = new JsonObject(); response.addProperty(MSG, ExceptionHelper.getExceptionMessageWithCauses(t)); String json = new Gson().toJson(response); return Response.status(status).entity(json).type(MediaType.APPLICATION_JSON).build(); } public static <T> Response toResponse(Paging<T> paging, Function<T, JsonObject> visitor) { JsonObject response = new JsonObject(); addPagingInfo(paging, response); List<T> page = paging.getPage(); JsonArray data = new JsonArray(); page.forEach(t -> data.add(visitor.apply(t))); response.add(DATA, data); String json = new Gson().toJson(response); return Response.ok(json, MediaType.APPLICATION_JSON).build(); } public static Response toResponse(Paging<JsonObject> paging) { JsonObject response = new JsonObject(); addPagingInfo(paging, response); List<JsonObject> page = paging.getPage(); JsonArray data = new JsonArray(); for (JsonObject jsonObject : page) { JsonObject element = jsonObject; data.add(element); } response.add(DATA, data); String json = new Gson().toJson(response); return Response.ok(json, MediaType.APPLICATION_JSON).build(); } private static <T> void addPagingInfo(Paging<T> paging, JsonObject response) { response.addProperty(MSG, StringHelper.DASH); response.addProperty(LIMIT, paging.getLimit()); response.addProperty(OFFSET, paging.getOffset()); response.addProperty(SIZE, paging.getSize()); response.addProperty(PREVIOUS_OFFSET, paging.getPreviousOffset()); response.addProperty(NEXT_OFFSET, paging.getNextOffset()); response.addProperty(LAST_OFFSET, paging.getLastOffset()); } }
[New] New ResponseUtil.toResponse() methods
li.strolch.rest/src/main/java/li/strolch/rest/helper/ResponseUtil.java
[New] New ResponseUtil.toResponse() methods
<ide><path>i.strolch.rest/src/main/java/li/strolch/rest/helper/ResponseUtil.java <ide> import javax.ws.rs.core.Response.Status; <ide> import java.util.List; <ide> import java.util.function.Function; <add>import java.util.stream.Collectors; <ide> <ide> import com.google.gson.Gson; <ide> import com.google.gson.JsonArray; <ide> return Response.ok(json, MediaType.APPLICATION_JSON).build(); <ide> } <ide> <add> public static <T> Response toResponse(String member, T t, Function<T, JsonObject> toJson) { <add> return toResponse(member, toJson.apply(t)); <add> } <add> <ide> public static Response toResponse(String member, JsonElement jsonElement) { <ide> JsonObject response = new JsonObject(); <ide> response.addProperty(MSG, StringHelper.DASH); <ide> String json = new Gson().toJson(response); <ide> <ide> return Response.ok(json, MediaType.APPLICATION_JSON).build(); <add> } <add> <add> public static <T> Response toResponse(String member, List<T> list, Function<T, JsonObject> toJson) { <add> return toResponse(member, list.stream().map(toJson).collect(Collectors.toList())); <ide> } <ide> <ide> public static Response toResponse(String member, List<JsonObject> jsonObjects) {
JavaScript
mit
216064329e068676d68cc6cd6ed9ff7f950a7659
0
react-materialize/react-materialize,react-materialize/react-materialize,react-materialize/react-materialize
import React from 'react'; import { storiesOf } from '@storybook/react'; import MediaBox from '../src/MediaBox'; import Slider from '../src/Slider'; import Slide from '../src/Slide'; const stories = storiesOf('javascript/Media', module); stories.addParameters({ info: { text: `Media components include things that have to do with large media objects like Images, Video, Audio, etc.` } }); stories.add('Default', () => ( <MediaBox src="https://lorempixel.com/350/350/nature/1" caption="A demo media box1"/> )); stories.add('Slider', () => ( <Slider> <Slide image={<MediaBox src="http://lorempixel.com/780/580/nature/1" caption="A demo media box1"/>}> <div className="caption center-align"> <h3>This is our big Tagline!</h3> <h5 className="light grey-text text-lighten-3">Here's our small slogan.</h5> </div> </Slide> <Slide image={<MediaBox src="http://lorempixel.com/780/580//nature/2" caption="A demo media box1"/>}> <div className="caption left-align"> <h3>Left Aligned Caption</h3> <h5 className="light grey-text text-lighten-3">Here's our small slogan.</h5> </div> </Slide> <Slide image={<MediaBox src="http://lorempixel.com/780/580//nature/3" caption="A demo media box1"/>}> <div className="caption right-align"> <h3>Right Aligned Caption</h3> <h5 className="light grey-text text-lighten-3">Here's our small slogan.</h5> </div> </Slide> </Slider> ));
stories/Media.stories.js
import React from 'react'; import { storiesOf } from '@storybook/react'; import MediaBox from '../src/MediaBox'; import Slider from '../src/Slider'; import Slide from '../src/Slide'; const stories = storiesOf('javascript/Media', module); stories.addParameters({ info: { text: `Media components include things that have to do with large media objects like Images, Video, Audio, etc.` } }); stories.add('Default', () => ( <MediaBox src="https://lorempixel.com/350/350/nature/1" caption="A demo media box1"/> )); stories.add('Slider', () => ( <Slider> <Slide image={<MediaBox src="http://lorempixel.com/780/580/nature/1" caption="A demo media box1"/>}> <div class="caption center-align"> <h3>This is our big Tagline!</h3> <h5 class="light grey-text text-lighten-3">Here's our small slogan.</h5> </div> </Slide> <Slide image={<MediaBox src="http://lorempixel.com/780/580//nature/2" caption="A demo media box1"/>}> <div class="caption left-align"> <h3>Left Aligned Caption</h3> <h5 class="light grey-text text-lighten-3">Here's our small slogan.</h5> </div> </Slide> <Slide image={<MediaBox src="http://lorempixel.com/780/580//nature/3" caption="A demo media box1"/>}> <div class="caption right-align"> <h3>Right Aligned Caption</h3> <h5 class="light grey-text text-lighten-3">Here's our small slogan.</h5> </div> </Slide> </Slider> ));
Fix className at Media.stories.js
stories/Media.stories.js
Fix className at Media.stories.js
<ide><path>tories/Media.stories.js <ide> <Slider> <ide> <Slide <ide> image={<MediaBox src="http://lorempixel.com/780/580/nature/1" caption="A demo media box1"/>}> <del> <div class="caption center-align"> <add> <div className="caption center-align"> <ide> <h3>This is our big Tagline!</h3> <del> <h5 class="light grey-text text-lighten-3">Here's our small slogan.</h5> <add> <h5 className="light grey-text text-lighten-3">Here's our small slogan.</h5> <ide> </div> <ide> </Slide> <ide> <Slide <ide> image={<MediaBox src="http://lorempixel.com/780/580//nature/2" caption="A demo media box1"/>}> <del> <div class="caption left-align"> <add> <div className="caption left-align"> <ide> <h3>Left Aligned Caption</h3> <del> <h5 class="light grey-text text-lighten-3">Here's our small slogan.</h5> <add> <h5 className="light grey-text text-lighten-3">Here's our small slogan.</h5> <ide> </div> <ide> </Slide> <ide> <Slide <ide> image={<MediaBox src="http://lorempixel.com/780/580//nature/3" caption="A demo media box1"/>}> <del> <div class="caption right-align"> <add> <div className="caption right-align"> <ide> <h3>Right Aligned Caption</h3> <del> <h5 class="light grey-text text-lighten-3">Here's our small slogan.</h5> <add> <h5 className="light grey-text text-lighten-3">Here's our small slogan.</h5> <ide> </div> <ide> </Slide> <ide> </Slider>
Java
apache-2.0
8966b0394eb16266c95ef56a137197676df17083
0
opensingular/singular-core,opensingular/singular-core,opensingular/singular-core,opensingular/singular-core
/* * Copyright (c) 2016, Mirante and/or its affiliates. All rights reserved. * Mirante PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package br.net.mirante.singular.form.wicket.mapper.attachment; import br.net.mirante.singular.commons.base.SingularException; import br.net.mirante.singular.form.SInstance; import br.net.mirante.singular.form.type.core.attachment.IAttachmentPersistenceHandler; import br.net.mirante.singular.form.type.core.attachment.IAttachmentRef; import org.apache.tika.io.IOUtils; import org.apache.wicket.Component; import org.apache.wicket.IResourceListener; import org.apache.wicket.ajax.json.JSONObject; import org.apache.wicket.behavior.Behavior; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.model.IModel; import org.apache.wicket.protocol.http.WebApplication; import org.apache.wicket.request.IRequestParameters; import org.apache.wicket.request.cycle.RequestCycle; import org.apache.wicket.request.http.WebRequest; import org.apache.wicket.request.http.WebResponse; import org.apache.wicket.request.http.flow.AbortWithHttpErrorCodeException; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.request.resource.AbstractResource; import org.apache.wicket.request.resource.PackageResourceReference; import org.apache.wicket.request.resource.SharedResourceReference; import org.apache.wicket.util.string.StringValue; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; import static org.apache.wicket.markup.head.JavaScriptHeaderItem.forReference; /** * Behavior a ser adicionado ao componente de upload/download para permitir download dos arquivos * Busca o arquivo por meio do hash e do nome e retorna uma url com um link temporário para download * o link retornado funciona apenas uma vez. * <p> * A busca é feita primeiro no armazenamento temporárioe em seguida no permanente. * * @author vinicius */ public class DownloadSupportedBehavior extends Behavior implements IResourceListener { private static final String DOWNLOAD_PATH = "/download"; private Component component; private IModel<? extends SInstance> model; public DownloadSupportedBehavior(IModel<? extends SInstance> model) { this.model = model; } private List<IAttachmentPersistenceHandler> getHandlers() { List<IAttachmentPersistenceHandler> services = new ArrayList<>(); if (model.getObject().getDocument().isAttachmentPersistenceTemporaryHandlerSupported()) { services.add(model.getObject().getDocument().getAttachmentPersistenceTemporaryHandler()); } if (model.getObject().getDocument().isAttachmentPersistencePermanentHandlerSupported()) { services.add(model.getObject().getDocument().getAttachmentPersistencePermanentHandler()); } return services; } @Override public void renderHead(Component component, IHeaderResponse response) { super.renderHead(component, response); response.render(forReference(new PackageResourceReference(getClass(), "DownloadSupportedBehavior.js"))); } @Override public void bind(Component component) { this.component = component; } @Override public void onResourceRequested() { try { handleRequest(); } catch (IOException e) { throw new AbortWithHttpErrorCodeException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } private IAttachmentRef findAttachmentRef(String id) { IAttachmentRef ref = null; for (IAttachmentPersistenceHandler service : getHandlers()) { ref = service.getAttachment(id); if (ref != null) { break; } } return ref; } private void handleRequest() throws IOException { WebRequest request = (WebRequest) RequestCycle.get().getRequest(); IRequestParameters parameters = request.getRequestParameters(); StringValue id = parameters.getParameterValue("fileId"); StringValue name = parameters.getParameterValue("fileName"); writeResponse(getDownloadURL(id.toString(), name.toString())); } private void writeResponse(String url) throws IOException { JSONObject jsonFile = new JSONObject(); jsonFile.put("url", url); WebResponse response = (WebResponse) RequestCycle.get().getResponse(); response.setContentType("application/json"); response.setHeader("Cache-Control", "no-store, no-cache"); response.getOutputStream().write(jsonFile.toString().getBytes()); response.flush(); } public String getUrl() { return component.urlFor(this, IResourceListener.INTERFACE, new PageParameters()).toString(); } /** * Registra um recurso compartilhado do wicket para permitir o download * sem bloquear a fila de ajax do wicket. * O recurso compartilhado é removido tão logo o download é executado * Esse procedimento visa garantir que somente quem tem acesso à página pode fazer * download dos arquivos. * * @param filename * @return */ private String getDownloadURL(String id, String filename) { String url = DOWNLOAD_PATH + "/" + id + "/" + new Date().getTime(); SharedResourceReference ref = new SharedResourceReference(String.valueOf(id)); AbstractResource resource = new AbstractResource() { @Override protected ResourceResponse newResourceResponse(Attributes attributes) { IAttachmentRef fileRef = findAttachmentRef(id); ResourceResponse resourceResponse = new ResourceResponse(); resourceResponse.setContentType("application/octet-stream"); resourceResponse.setFileName(filename); if (fileRef.getSize() > 0) { resourceResponse.setContentLength(fileRef.getSize()); } resourceResponse.setWriteCallback(new WriteCallback() { @Override public void writeData(Attributes attributes) throws IOException { try ( InputStream inputStream = fileRef.newInputStream(); ) { IOUtils.copy(inputStream, attributes.getResponse().getOutputStream()); /*Desregistrando recurso compartilhado*/ WebApplication.get().unmount(url); WebApplication.get().getSharedResources().remove(ref.getKey()); } catch (Exception e) { throw new SingularException(e); } } }); return resourceResponse; } }; /*registrando recurso compartilhado*/ WebApplication.get().getSharedResources().add(String.valueOf(id), resource); WebApplication.get().mountResource(url, ref); return WebApplication.get().getServletContext().getContextPath() + url; } }
form/wicket/src/main/java/br/net/mirante/singular/form/wicket/mapper/attachment/DownloadSupportedBehavior.java
/* * Copyright (c) 2016, Mirante and/or its affiliates. All rights reserved. * Mirante PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package br.net.mirante.singular.form.wicket.mapper.attachment; import br.net.mirante.singular.commons.base.SingularException; import br.net.mirante.singular.form.SInstance; import br.net.mirante.singular.form.type.core.attachment.IAttachmentPersistenceHandler; import br.net.mirante.singular.form.type.core.attachment.IAttachmentRef; import org.apache.tika.io.IOUtils; import org.apache.wicket.Component; import org.apache.wicket.IResourceListener; import org.apache.wicket.ajax.json.JSONObject; import org.apache.wicket.behavior.Behavior; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.model.IModel; import org.apache.wicket.protocol.http.WebApplication; import org.apache.wicket.request.IRequestParameters; import org.apache.wicket.request.cycle.RequestCycle; import org.apache.wicket.request.http.WebRequest; import org.apache.wicket.request.http.WebResponse; import org.apache.wicket.request.http.flow.AbortWithHttpErrorCodeException; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.request.resource.AbstractResource; import org.apache.wicket.request.resource.PackageResourceReference; import org.apache.wicket.request.resource.SharedResourceReference; import org.apache.wicket.util.string.StringValue; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; import static org.apache.wicket.markup.head.JavaScriptHeaderItem.forReference; /** * Behavior a ser adicionado ao componente de upload/download para permitir download dos arquivos * Busca o arquivo por meio do hash e do nome e retorna uma url com um link temporário para download * o link retornado funciona apenas uma vez. * <p> * A busca é feita primeiro no armazenamento temporárioe em seguida no permanente. * * @author vinicius */ public class DownloadSupportedBehavior extends Behavior implements IResourceListener { private static final String DOWNLOAD_PATH = "/download"; private Component component; private IModel<? extends SInstance> model; public DownloadSupportedBehavior(IModel<? extends SInstance> model) { this.model = model; } private List<IAttachmentPersistenceHandler> getHandlers() { List<IAttachmentPersistenceHandler> services = new ArrayList<>(); if (model.getObject().getDocument().isAttachmentPersistenceTemporaryHandlerSupported()) { services.add(model.getObject().getDocument().getAttachmentPersistenceTemporaryHandler()); } if (model.getObject().getDocument().isAttachmentPersistencePermanentHandlerSupported()) { services.add(model.getObject().getDocument().getAttachmentPersistencePermanentHandler()); } return services; } @Override public void renderHead(Component component, IHeaderResponse response) { super.renderHead(component, response); response.render(forReference(new PackageResourceReference(getClass(), "DownloadSupportedBehavior.js"))); } @Override public void bind(Component component) { this.component = component; } @Override public void onResourceRequested() { try { handleRequest(); } catch (IOException e) { throw new AbortWithHttpErrorCodeException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } private IAttachmentRef findAttachmentRef(String id) { IAttachmentRef ref = null; for (IAttachmentPersistenceHandler service : getHandlers()) { ref = service.getAttachment(id); if (ref != null) { break; } } return ref; } private void handleRequest() throws IOException { WebRequest request = (WebRequest) RequestCycle.get().getRequest(); IRequestParameters parameters = request.getRequestParameters(); StringValue id = parameters.getParameterValue("fileId"); StringValue name = parameters.getParameterValue("fileName"); writeResponse(getDownloadURL(id.toString(), name.toString())); } private void writeResponse(String url) throws IOException { JSONObject jsonFile = new JSONObject(); jsonFile.put("url", url); WebResponse response = (WebResponse) RequestCycle.get().getResponse(); response.setContentType("application/json"); response.setHeader("Cache-Control", "no-store, no-cache"); response.getOutputStream().write(jsonFile.toString().getBytes()); response.flush(); } public String getUrl() { return component.urlFor(this, IResourceListener.INTERFACE, new PageParameters()).toString(); } /** * Registra um recurso compartilhado do wicket para permitir o download * sem bloquear a fila de ajax do wicket. * O recurso compartilhado é removido tão logo o download é executado * Esse procedimento visa garantir que somente quem tem acesso à página pode fazer * download dos arquivos. * * @param filename * @return */ private String getDownloadURL(String id, String filename) { String url = DOWNLOAD_PATH + "/" + id + "/" + new Date().getTime(); SharedResourceReference ref = new SharedResourceReference(String.valueOf(id)); AbstractResource resource = new AbstractResource() { @Override protected ResourceResponse newResourceResponse(Attributes attributes) { ResourceResponse resourceResponse = new ResourceResponse(); resourceResponse.setContentType("application/octet-stream"); resourceResponse.setFileName(filename); resourceResponse.setWriteCallback(new WriteCallback() { @Override public void writeData(Attributes attributes) throws IOException { IAttachmentRef fileRef = findAttachmentRef(id); try ( InputStream inputStream = fileRef.newInputStream(); ) { IOUtils.copy(inputStream, attributes.getResponse().getOutputStream()); /*Desregistrando recurso compartilhado*/ WebApplication.get().unmount(url); WebApplication.get().getSharedResources().remove(ref.getKey()); } catch (Exception e) { throw new SingularException(e); } } }); return resourceResponse; } }; /*registrando recurso compartilhado*/ WebApplication.get().getSharedResources().add(String.valueOf(id), resource); WebApplication.get().mountResource(url, ref); return WebApplication.get().getServletContext().getContextPath() + url; } }
[SINGULAR-FORM] adicionando header de tamanho do arquivo
form/wicket/src/main/java/br/net/mirante/singular/form/wicket/mapper/attachment/DownloadSupportedBehavior.java
[SINGULAR-FORM] adicionando header de tamanho do arquivo
<ide><path>orm/wicket/src/main/java/br/net/mirante/singular/form/wicket/mapper/attachment/DownloadSupportedBehavior.java <ide> AbstractResource resource = new AbstractResource() { <ide> @Override <ide> protected ResourceResponse newResourceResponse(Attributes attributes) { <del> <add> IAttachmentRef fileRef = findAttachmentRef(id); <ide> ResourceResponse resourceResponse = new ResourceResponse(); <ide> resourceResponse.setContentType("application/octet-stream"); <ide> resourceResponse.setFileName(filename); <add> if (fileRef.getSize() > 0) { <add> resourceResponse.setContentLength(fileRef.getSize()); <add> } <ide> resourceResponse.setWriteCallback(new WriteCallback() { <ide> @Override <ide> public void writeData(Attributes attributes) throws IOException { <del> IAttachmentRef fileRef = findAttachmentRef(id); <ide> try ( <ide> InputStream inputStream = fileRef.newInputStream(); <ide> ) {
Java
mit
15fcd39454d7bc2a6d873a99afc48be39a69d3cc
0
trancee/PushPlugin,trancee/PushPlugin,trancee/PushPlugin,trancee/PushPlugin,trancee/PushPlugin
package com.plugin.gcm; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.content.res.AssetManager; import android.content.res.Resources; import android.media.RingtoneManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.StrictMode; import android.os.StrictMode.ThreadPolicy; import android.util.DisplayMetrics; import android.view.WindowManager; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import com.google.android.gcm.GCMBaseIntentService; @SuppressLint("NewApi") public class GCMIntentService extends GCMBaseIntentService { private static final String TAG = "GCMIntentService"; private static String packageName = null; private static float devicePixelRatio = 1.0f; private static int LargeIconSize = 256; private static int BigPictureSize = 640; public GCMIntentService() { super("GCMIntentService"); } @Override public void onRegistered(Context context, String regId) { Log.v(TAG, "onRegistered: "+ regId); JSONObject json; try { json = new JSONObject().put("event", "registered"); json.put("regid", regId); Log.v(TAG, "onRegistered: " + json.toString()); // Send this JSON data to the JavaScript application above EVENT should be set to the msg type // In this case this is the registration ID PushPlugin.sendJavascript( json ); } catch( JSONException e) { // No message to the user is sent, JSON failed Log.e(TAG, "onRegistered: JSON exception"); } } @Override public void onUnregistered(Context context, String regId) { Log.d(TAG, "onUnregistered - regId: " + regId); } @Override protected void onMessage(Context context, Intent intent) { Log.d(TAG, "onMessage - context: " + context); // Extract the payload from the message Bundle extras = intent.getExtras(); if (extras != null) { // if we are in the foreground, just surface the payload, else post it to the statusbar if (PushPlugin.isInForeground()) { extras.putBoolean("foreground", true); PushPlugin.sendExtras(extras); } else { extras.putBoolean("foreground", false); // Send a notification if there is a message if (extras.getString("message") != null && extras.getString("message").length() != 0) { createNotification(context, extras); } } } } public void createNotification(Context context, Bundle extras) { packageName = context.getPackageName(); DisplayMetrics metrics = new DisplayMetrics(); WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE); windowManager.getDefaultDisplay().getMetrics(metrics); devicePixelRatio = metrics.density; Log.d(TAG, "devicePixelRatio: "+ devicePixelRatio); String appName = getAppName(this); Intent notificationIntent = new Intent(this, PushHandlerActivity.class); notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); notificationIntent.putExtra("pushBundle", extras); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); int defaults = extras.getInt("defaults", (Notification.DEFAULT_ALL)); NotificationCompat.Builder notification = new NotificationCompat.Builder(context) // Set which notification properties will be inherited from system defaults. .setDefaults(defaults) // Set the "ticker" text which is displayed in the status bar when the notification first arrives. .setTicker(extras.getString("summary", extras.getString("title"))) // Set the first line of text in the platform notification template. .setContentTitle(extras.getString("title")) // Set the second line of text in the platform notification template. .setContentText(extras.getString("message")) // Set the third line of text in the platform notification template. .setSubText(extras.getString("summary")) // Supply a PendingIntent to be sent when the notification is clicked. .setContentIntent(contentIntent) // Set the large number at the right-hand side of the notification. .setNumber(extras.getInt("badge", extras.getInt("msgcnt", 0))) // A variant of setSmallIcon(int) that takes an additional level parameter for when the icon is a LevelListDrawable. .setSmallIcon(getSmallIcon(extras.getString("smallIcon"), context.getApplicationInfo().icon)) // Add a large icon to the notification (and the ticker on some devices). .setLargeIcon(getLargeIcon(this, extras.getString("icon"))) // Set the desired color for the indicator LED on the device, as well as the blink duty cycle (specified in milliseconds). .setLights(getColor(extras.getString("led", "000000")), 500, 500) // Make this notification automatically dismissed when the user touches it. .setPriority(Notification.PRIORITY_HIGH) .setAutoCancel(extras.getBoolean("autoCancel", true) ); Uri sound = getSound(extras.getString("sound")); if (sound != null) { // Set the sound to play. notification.setSound(sound); } if (Build.VERSION.SDK_INT >= 16) { String message = extras.getString("message"); String pictureUrl = extras.getString("picture"); if (pictureUrl != null && pictureUrl.length() > 0) { // Add a rich notification style to be applied at build time. notification.setStyle( new NotificationCompat.BigPictureStyle() // Overrides ContentTitle in the big form of the template. .setBigContentTitle(extras.getString("title")) // Set the first line of text after the detail section in the big form of the template. .setSummaryText(message) // Override the large icon when the big notification is shown. .bigLargeIcon(getLargeIcon(this, extras.getString("avatar", "https://img.andygreen.com/image.cf?Width=" + LargeIconSize + "&Path=avatar.png"))) // Provide the bitmap to be used as the payload for the BigPicture notification. .bigPicture(getPicture(this, pictureUrl)) ); // remove the third line as this is confusing for BigPicture style. notification.setSubText(null); } else if (message != null && message.length() > 30) { // Add a rich notification style to be applied at build time. notification.setStyle( new NotificationCompat.BigTextStyle() // Overrides ContentTitle in the big form of the template. .setBigContentTitle(extras.getString("title")) // Provide the longer text to be displayed in the big form of the template in place of the content text. .bigText(message) // Set the first line of text after the detail section in the big form of the template. .setSummaryText(extras.getString("summary")) ); } } ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify((String) appName, extras.getInt("notificationId", 0), notification.build()); } /** * Returns the path of the notification's sound file */ private static Uri getSound(String sound) { if (sound != null) { try { int soundId = (Integer) RingtoneManager.class.getDeclaredField(sound).get(Integer.class); return RingtoneManager.getDefaultUri(soundId); } catch (Exception e) { return Uri.parse(sound); } } return null; } /** * Returns the small icon's ID */ private static int getSmallIcon(String iconName, int iconId) { int resId = 0; resId = getIconValue(packageName, iconName); if (resId == 0) { resId = getIconValue("android", iconName); } if (resId == 0) { resId = getIconValue(packageName, "icon"); } if (resId == 0) { return iconId; } return resId; } /** * Returns the icon's ID */ private static Bitmap getLargeIcon(Context context, String icon) { Bitmap bmp = null; if (icon != null) { if (icon.startsWith("http://") || icon.startsWith("https://")) { bmp = getIconFromURL(icon); } else if (icon.startsWith("file://")) { bmp = getIconFromURI(context, icon); } else { bmp = getIconFromURL("https://img.andygreen.com/photo.cf?Width=" + LargeIconSize + "&Height=" + LargeIconSize + "&Ratio=" + devicePixelRatio + "&Checksum=" + icon); } if (bmp == null) { bmp = getIconFromRes(context, icon); } } else { bmp = BitmapFactory.decodeResource(context.getResources(), context.getApplicationInfo().icon); } return bmp; } /** * Returns the bitmap */ private static Bitmap getPicture(Context context, String pictureUrl) { Bitmap bmp = null; if (pictureUrl != null) { if (pictureUrl.startsWith("http://") || pictureUrl.startsWith("https://")) { bmp = getIconFromURL(pictureUrl); } else if (pictureUrl.startsWith("file://")) { bmp = getIconFromURI(context, pictureUrl); } else { bmp = getIconFromURL("https://img.andygreen.com/photo.cf?Width=" + BigPictureSize + "&Ratio=" + devicePixelRatio + "&Checksum=" + pictureUrl); } if (bmp == null) { bmp = getIconFromRes(context, pictureUrl); } } return bmp; } /** * @return * The notification color for LED */ private static int getColor(String hexColor) { int aRGB = Integer.parseInt(hexColor,16); aRGB += 0xFF000000; return aRGB; } private static String getAppName(Context context) { CharSequence appName = context .getPackageManager() .getApplicationLabel(context.getApplicationInfo()); return (String)appName; } /** * Returns numerical icon Value * * @param {String} className * @param {String} iconName */ private static int getIconValue (String className, String iconName) { int icon = 0; try { Class<?> klass = Class.forName(className + ".R$drawable"); icon = (Integer) klass.getDeclaredField(iconName).get(Integer.class); } catch (Exception e) {} return icon; } /** * Converts an resource to Bitmap. * * @param icon * The resource name * @return * The corresponding bitmap */ private static Bitmap getIconFromRes (Context context, String icon) { Resources res = context.getResources(); int iconId = 0; iconId = getIconValue(packageName, icon); if (iconId == 0) { iconId = getIconValue("android", icon); } if (iconId == 0) { iconId = android.R.drawable.ic_menu_info_details; } Bitmap bmp = BitmapFactory.decodeResource(res, iconId); return bmp; } /** * Converts an Image URL to Bitmap. * * @param src * The external image URL * @return * The corresponding bitmap */ private static Bitmap getIconFromURL (String src) { Bitmap bmp = null; ThreadPolicy origMode = StrictMode.getThreadPolicy(); try { URL url = new URL(src); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); bmp = BitmapFactory.decodeStream(input); } catch (Exception e) { e.printStackTrace(); } StrictMode.setThreadPolicy(origMode); return bmp; } /** * Converts an Image URI to Bitmap. * * @param src * The internal image URI * @return * The corresponding bitmap */ private static Bitmap getIconFromURI (Context context, String src) { AssetManager assets = context.getAssets(); Bitmap bmp = null; try { String path = src.replace("file:/", "www"); InputStream input = assets.open(path); bmp = BitmapFactory.decodeStream(input); } catch (IOException e) { e.printStackTrace(); } return bmp; } @Override public void onError(Context context, String errorId) { Log.e(TAG, "onError - errorId: " + errorId); } }
src/android/com/plugin/gcm/GCMIntentService.java
package com.plugin.gcm; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.content.res.AssetManager; import android.content.res.Resources; import android.media.RingtoneManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.StrictMode; import android.os.StrictMode.ThreadPolicy; import android.util.DisplayMetrics; import android.view.WindowManager; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import com.google.android.gcm.GCMBaseIntentService; @SuppressLint("NewApi") public class GCMIntentService extends GCMBaseIntentService { private static final String TAG = "GCMIntentService"; private static String packageName = null; private static float devicePixelRatio = 1.0f; private static int LargeIconSize = 256; private static int BigPictureSize = 640; public GCMIntentService() { super("GCMIntentService"); } @Override public void onRegistered(Context context, String regId) { Log.v(TAG, "onRegistered: "+ regId); JSONObject json; try { json = new JSONObject().put("event", "registered"); json.put("regid", regId); Log.v(TAG, "onRegistered: " + json.toString()); // Send this JSON data to the JavaScript application above EVENT should be set to the msg type // In this case this is the registration ID PushPlugin.sendJavascript( json ); } catch( JSONException e) { // No message to the user is sent, JSON failed Log.e(TAG, "onRegistered: JSON exception"); } } @Override public void onUnregistered(Context context, String regId) { Log.d(TAG, "onUnregistered - regId: " + regId); } @Override protected void onMessage(Context context, Intent intent) { Log.d(TAG, "onMessage - context: " + context); // Extract the payload from the message Bundle extras = intent.getExtras(); if (extras != null) { // if we are in the foreground, just surface the payload, else post it to the statusbar if (PushPlugin.isInForeground()) { extras.putBoolean("foreground", true); PushPlugin.sendExtras(extras); } else { extras.putBoolean("foreground", false); // Send a notification if there is a message if (extras.getString("message") != null && extras.getString("message").length() != 0) { createNotification(context, extras); } } } } public void createNotification(Context context, Bundle extras) { packageName = context.getPackageName(); DisplayMetrics metrics = new DisplayMetrics(); WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE); windowManager.getDefaultDisplay().getMetrics(metrics); devicePixelRatio = metrics.density; Log.d(TAG, "devicePixelRatio: "+ devicePixelRatio); String appName = getAppName(this); Intent notificationIntent = new Intent(this, PushHandlerActivity.class); notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); notificationIntent.putExtra("pushBundle", extras); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); int defaults = extras.getInt("defaults", (Notification.DEFAULT_ALL)); NotificationCompat.Builder notification = new NotificationCompat.Builder(context) // Set which notification properties will be inherited from system defaults. .setDefaults(defaults) // Set the "ticker" text which is displayed in the status bar when the notification first arrives. .setTicker(extras.getString("summary", extras.getString("title"))) // Set the first line of text in the platform notification template. .setContentTitle(extras.getString("title")) // Set the second line of text in the platform notification template. .setContentText(extras.getString("message")) // Set the third line of text in the platform notification template. .setSubText(extras.getString("summary")) // Supply a PendingIntent to be sent when the notification is clicked. .setContentIntent(contentIntent) // Set the large number at the right-hand side of the notification. .setNumber(extras.getInt("badge", extras.getInt("msgcnt", 0))) // A variant of setSmallIcon(int) that takes an additional level parameter for when the icon is a LevelListDrawable. .setSmallIcon(getSmallIcon(extras.getString("smallIcon"), context.getApplicationInfo().icon)) // Add a large icon to the notification (and the ticker on some devices). .setLargeIcon(getLargeIcon(this, extras.getString("icon"))) // Set the desired color for the indicator LED on the device, as well as the blink duty cycle (specified in milliseconds). .setLights(getColor(extras.getString("led", "000000")), 500, 500) // Make this notification automatically dismissed when the user touches it. .setPriority(Notification.PRIORITY_HIGH) .setAutoCancel(extras.getBoolean("autoCancel", true) ); Uri sound = getSound(extras.getString("sound")); if (sound != null) { // Set the sound to play. notification.setSound(sound); } if (Build.VERSION.SDK_INT >= 16) { String message = extras.getString("message"); String pictureUrl = extras.getString("picture"); if (pictureUrl != null && pictureUrl.length() > 0) { // Add a rich notification style to be applied at build time. notification.setStyle( new NotificationCompat.BigPictureStyle() // Overrides ContentTitle in the big form of the template. .setBigContentTitle(extras.getString("title")) // Set the first line of text after the detail section in the big form of the template. .setSummaryText(message) // Override the large icon when the big notification is shown. .bigLargeIcon(getLargeIcon(this, extras.getString("avatar", "https://img.andygreen.com/image.cf?Width=" + LargeIconSize + "&Path=avatar.png"))) // Provide the bitmap to be used as the payload for the BigPicture notification. .bigPicture(getPicture(this, pictureUrl)) ); // remove the third line as this is confusing for BigPicture style. notification.setSubText(null); } else if (message != null && message.length() > 30) { // Add a rich notification style to be applied at build time. notification.setStyle( new NotificationCompat.BigTextStyle() // Overrides ContentTitle in the big form of the template. .setBigContentTitle(extras.getString("title")) // Provide the longer text to be displayed in the big form of the template in place of the content text. .bigText(message) // Set the first line of text after the detail section in the big form of the template. .setSummaryText(extras.getString("summary")) ); } } ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify((String) appName, extras.getInt("notificationId", 0), notification.build()); } /** * Returns the path of the notification's sound file */ private static Uri getSound(String sound) { if (sound != null) { try { int soundId = (Integer) RingtoneManager.class.getDeclaredField(sound).get(Integer.class); return RingtoneManager.getDefaultUri(soundId); } catch (Exception e) { return Uri.parse(sound); } } return null; } /** * Returns the small icon's ID */ private static int getSmallIcon(String iconName, int iconId) { int resId = 0; resId = getIconValue(packageName, iconName); if (resId == 0) { resId = getIconValue("android", iconName); } if (resId == 0) { resId = getIconValue(packageName, "icon"); } if (resId == 0) { return iconId; } return resId; } /** * Returns the icon's ID */ private static Bitmap getLargeIcon(Context context, String icon) { Bitmap bmp = null; if (icon != null) { if (icon.startsWith("http://") || icon.startsWith("https://")) { bmp = getIconFromURL(icon); } else if (icon.startsWith("file://")) { bmp = getIconFromURI(context, icon); } else { bmp = getIconFromURL("https://img.andygreen.com/photo.cf?Width=" + LargeIconSize + "&Ratio=" + devicePixelRatio + "&Checksum=" + icon); } if (bmp == null) { bmp = getIconFromRes(context, icon); } } else { bmp = BitmapFactory.decodeResource(context.getResources(), context.getApplicationInfo().icon); } return bmp; } /** * Returns the bitmap */ private static Bitmap getPicture(Context context, String pictureUrl) { Bitmap bmp = null; if (pictureUrl != null) { if (pictureUrl.startsWith("http://") || pictureUrl.startsWith("https://")) { bmp = getIconFromURL(pictureUrl); } else if (pictureUrl.startsWith("file://")) { bmp = getIconFromURI(context, pictureUrl); } else { bmp = getIconFromURL("https://img.andygreen.com/photo.cf?Width=" + BigPictureSize + "&Ratio=" + devicePixelRatio + "&Checksum=" + pictureUrl); } if (bmp == null) { bmp = getIconFromRes(context, pictureUrl); } } return bmp; } /** * @return * The notification color for LED */ private static int getColor(String hexColor) { int aRGB = Integer.parseInt(hexColor,16); aRGB += 0xFF000000; return aRGB; } private static String getAppName(Context context) { CharSequence appName = context .getPackageManager() .getApplicationLabel(context.getApplicationInfo()); return (String)appName; } /** * Returns numerical icon Value * * @param {String} className * @param {String} iconName */ private static int getIconValue (String className, String iconName) { int icon = 0; try { Class<?> klass = Class.forName(className + ".R$drawable"); icon = (Integer) klass.getDeclaredField(iconName).get(Integer.class); } catch (Exception e) {} return icon; } /** * Converts an resource to Bitmap. * * @param icon * The resource name * @return * The corresponding bitmap */ private static Bitmap getIconFromRes (Context context, String icon) { Resources res = context.getResources(); int iconId = 0; iconId = getIconValue(packageName, icon); if (iconId == 0) { iconId = getIconValue("android", icon); } if (iconId == 0) { iconId = android.R.drawable.ic_menu_info_details; } Bitmap bmp = BitmapFactory.decodeResource(res, iconId); return bmp; } /** * Converts an Image URL to Bitmap. * * @param src * The external image URL * @return * The corresponding bitmap */ private static Bitmap getIconFromURL (String src) { Bitmap bmp = null; ThreadPolicy origMode = StrictMode.getThreadPolicy(); try { URL url = new URL(src); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); bmp = BitmapFactory.decodeStream(input); } catch (Exception e) { e.printStackTrace(); } StrictMode.setThreadPolicy(origMode); return bmp; } /** * Converts an Image URI to Bitmap. * * @param src * The internal image URI * @return * The corresponding bitmap */ private static Bitmap getIconFromURI (Context context, String src) { AssetManager assets = context.getAssets(); Bitmap bmp = null; try { String path = src.replace("file:/", "www"); InputStream input = assets.open(path); bmp = BitmapFactory.decodeStream(input); } catch (IOException e) { e.printStackTrace(); } return bmp; } @Override public void onError(Context context, String errorId) { Log.e(TAG, "onError - errorId: " + errorId); } }
Fixed icon to be square.
src/android/com/plugin/gcm/GCMIntentService.java
Fixed icon to be square.
<ide><path>rc/android/com/plugin/gcm/GCMIntentService.java <ide> } else if (icon.startsWith("file://")) { <ide> bmp = getIconFromURI(context, icon); <ide> } else { <del> bmp = getIconFromURL("https://img.andygreen.com/photo.cf?Width=" + LargeIconSize + "&Ratio=" + devicePixelRatio + "&Checksum=" + icon); <add> bmp = getIconFromURL("https://img.andygreen.com/photo.cf?Width=" + LargeIconSize + "&Height=" + LargeIconSize + "&Ratio=" + devicePixelRatio + "&Checksum=" + icon); <ide> } <ide> <ide> if (bmp == null) {
Java
apache-2.0
1768d8637aa11a18783bbd57ec48df39b72b1aa4
0
lucwillems/JavaLinuxNet,lucwillems/JavaLinuxNet,lucwillems/JavaLinuxNet
package org.it4y.net.protocols.IP; import junit.framework.Assert; import org.it4y.net.protocols.IP.ICMP.ICMPPacket; import org.it4y.net.protocols.IP.TCP.TCPPacket; import org.it4y.net.protocols.IP.UDP.UDPPacket; import org.junit.Test; import java.nio.ByteBuffer; /** * Created by luc on 3/21/14. */ public class IPFactoryTest { /* Frame (71 bytes) */ static final byte[] DNSrequest = { (byte)0x45, (byte)0x00, (byte)/* 8/....E. */ (byte)0x00, (byte)0x39, (byte)0xf5, (byte)0x10, (byte)0x00, (byte)0x00, (byte)0x40, (byte)0x11, (byte)/* .9....@. */ (byte)0xb4, (byte)0x5b, (byte)0xc0, (byte)0xa8, (byte)0x00, (byte)0x90, (byte)0x08, (byte)0x08, (byte)/* .[...... */ (byte)0x08, (byte)0x08, (byte)0xca, (byte)0xfd, (byte)0x00, (byte)0x35, (byte)0x00, (byte)0x25, (byte)/* .....5.% */ (byte)0xd5, (byte)0x7e, (byte)0x32, (byte)0x14, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x01, (byte)/* .~2..... */ (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x03, (byte)0x77, (byte)/* .......w */ (byte)0x77, (byte)0x77, (byte)0x03, (byte)0x6b, (byte)0x64, (byte)0x65, (byte)0x03, (byte)0x6f, (byte)/* ww.kde.o */ (byte)0x72, (byte)0x67, (byte)0x00, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x01 /* rg..... */ }; /* Frame (98 bytes) : ping request */ static final byte[] pingRequest = { (byte)0x45, (byte)0x00, /* 8/....E. */ (byte)0x00, (byte)0x54, (byte)0xea, (byte)0xf3, (byte)0x40, (byte)0x00, (byte)0x40, (byte)0x01, /* .T..@.@. */ (byte)0x7e, (byte)0x6d, (byte)0xc0, (byte)0xa8, (byte)0x00, (byte)0x90, (byte)0x08, (byte)0x08, /* ~m...... */ (byte)0x08, (byte)0x08, (byte)0x08, (byte)0x00, (byte)0x61, (byte)0x60, (byte)0x42, (byte)0x95, /* ....a`B. */ (byte)0x00, (byte)0x23, (byte)0x1f, (byte)0x53, (byte)0x2c, (byte)0x53, (byte)0x11, (byte)0x3e, /* .#.S,S.> */ (byte)0x0c, (byte)0x00, (byte)0x08, (byte)0x09, (byte)0x0a, (byte)0x0b, (byte)0x0c, (byte)0x0d, /* ........ */ (byte)0x0e, (byte)0x0f, (byte)0x10, (byte)0x11, (byte)0x12, (byte)0x13, (byte)0x14, (byte)0x15, /* ........ */ (byte)0x16, (byte)0x17, (byte)0x18, (byte)0x19, (byte)0x1a, (byte)0x1b, (byte)0x1c, (byte)0x1d, /* ........ */ (byte)0x1e, (byte)0x1f, (byte)0x20, (byte)0x21, (byte)0x22, (byte)0x23, (byte)0x24, (byte)0x25, /* .. !"#$% */ (byte)0x26, (byte)0x27, (byte)0x28, (byte)0x29, (byte)0x2a, (byte)0x2b, (byte)0x2c, (byte)0x2d, /* &'()*+,- */ (byte)0x2e, (byte)0x2f, (byte)0x30, (byte)0x31, (byte)0x32, (byte)0x33, (byte)0x34, (byte)0x35, /* ./012345 */ (byte)0x36, (byte)0x37 /* 67 */ }; /* Frame (74 bytes) * wget http://8.8.8.8 from 192.168.0.144 * */ static final byte[] tcp_sync = { (byte)0x45, (byte)0x00, /* 8/....E. */ (byte)0x00, (byte)0x3c, (byte)0xd9, (byte)0xa5, (byte)0x40, (byte)0x00, (byte)0x40, (byte)0x06, /* .<..@.@. */ (byte)0x8f, (byte)0xce, (byte)0xc0, (byte)0xa8, (byte)0x00, (byte)0x90, (byte)0x08, (byte)0x08, /* ........ */ (byte)0x08, (byte)0x08, (byte)0xdd, (byte)0x60, (byte)0x00, (byte)0x50, (byte)0xf5, (byte)0x73, /* ...`.P.s */ (byte)0xd7, (byte)0xd3, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xa0, (byte)0x02, /* ........ */ (byte)0x72, (byte)0x10, (byte)0x4a, (byte)0x39, (byte)0x00, (byte)0x00, (byte)0x02, (byte)0x04, /* r.J9.... */ (byte)0x05, (byte)0xb4, (byte)0x04, (byte)0x02, (byte)0x08, (byte)0x0a, (byte)0x00, (byte)0xfd, /* ........ */ (byte)0x0e, (byte)0x76, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x01, (byte)0x03, /* .v...... */ (byte)0x03, (byte)0x0a /* .. */ }; /* Frame (74 bytes) * some dummy packet , copy from icmp but change protocol number * */ static final byte[] unknownIpProtocol = { (byte)0x45, (byte)0x00, (byte)/* 8/....E. */ (byte)0x00, (byte)0x39, (byte)0xf5, (byte)0x10, (byte)0x00, (byte)0x00, (byte)0x40, (byte)0xff, (byte)/* .9....@. */ (byte)0xb4, (byte)0x5b, (byte)0xc0, (byte)0xa8, (byte)0x00, (byte)0x90, (byte)0x08, (byte)0x08, (byte)/* .[...... */ (byte)0x08, (byte)0x08, (byte)0xca, (byte)0xfd, (byte)0x00, (byte)0x35, (byte)0x00, (byte)0x25, (byte)/* .....5.% */ (byte)0xd5, (byte)0x7e, (byte)0x32, (byte)0x14, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x01, (byte)/* .~2..... */ (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x03, (byte)0x77, (byte)/* .......w */ (byte)0x77, (byte)0x77, (byte)0x03, (byte)0x6b, (byte)0x64, (byte)0x65, (byte)0x03, (byte)0x6f, (byte)/* ww.kde.o */ (byte)0x72, (byte)0x67, (byte)0x00, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x01 /* rg..... */ }; @Test public void testProcessRawPacket() throws Exception { Object result=IPFactory.processRawPacket(null,0); Assert.assertNull(result); } @Test public void testProcessUDPPacket() throws Exception { ByteBuffer rawData = ByteBuffer.allocate(DNSrequest.length); rawData.put(DNSrequest); IpPacket result=IPFactory.processRawPacket(rawData,rawData.limit()); Assert.assertNotNull(result); org.junit.Assert.assertTrue(result instanceof UDPPacket); org.junit.Assert.assertEquals(IpPacket.UDP,result.getProtocol()); } @Test public void testProcessICMPPacket() throws Exception { ByteBuffer rawData = ByteBuffer.allocate(pingRequest.length); rawData.put(pingRequest); IpPacket result=IPFactory.processRawPacket(rawData,rawData.limit()); Assert.assertNotNull(result); org.junit.Assert.assertTrue(result instanceof ICMPPacket); org.junit.Assert.assertEquals(IpPacket.ICMP,result.getProtocol()); } @Test public void testProcessTCPPacket() throws Exception { ByteBuffer rawData = ByteBuffer.allocate(tcp_sync.length); rawData.put(tcp_sync); IpPacket result=IPFactory.processRawPacket(rawData,rawData.limit()); Assert.assertNotNull(result); org.junit.Assert.assertTrue(result instanceof TCPPacket); org.junit.Assert.assertEquals(IpPacket.TCP,result.getProtocol()); } @Test public void testProcessUnkownPacket() throws Exception { ByteBuffer rawData = ByteBuffer.allocate(unknownIpProtocol.length); rawData.put(unknownIpProtocol); IpPacket result=IPFactory.processRawPacket(rawData,rawData.limit()); Assert.assertNotNull(result); org.junit.Assert.assertEquals((byte)0xff,result.getProtocol()); } }
src/test/java/org/it4y/net/protocols/IP/IPFactoryTest.java
package org.it4y.net.protocols.IP; import junit.framework.Assert; import org.it4y.net.protocols.IP.ICMP.ICMPPacket; import org.it4y.net.protocols.IP.TCP.TCPPacket; import org.it4y.net.protocols.IP.UDP.UDPPacket; import org.junit.Test; import java.nio.ByteBuffer; /** * Created by luc on 3/21/14. */ public class IPFactoryTest { /* Frame (71 bytes) */ static final byte[] DNSrequest = { (byte)0x45, (byte)0x00, (byte)/* 8/....E. */ (byte)0x00, (byte)0x39, (byte)0xf5, (byte)0x10, (byte)0x00, (byte)0x00, (byte)0x40, (byte)0x11, (byte)/* .9....@. */ (byte)0xb4, (byte)0x5b, (byte)0xc0, (byte)0xa8, (byte)0x00, (byte)0x90, (byte)0x08, (byte)0x08, (byte)/* .[...... */ (byte)0x08, (byte)0x08, (byte)0xca, (byte)0xfd, (byte)0x00, (byte)0x35, (byte)0x00, (byte)0x25, (byte)/* .....5.% */ (byte)0xd5, (byte)0x7e, (byte)0x32, (byte)0x14, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x01, (byte)/* .~2..... */ (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x03, (byte)0x77, (byte)/* .......w */ (byte)0x77, (byte)0x77, (byte)0x03, (byte)0x6b, (byte)0x64, (byte)0x65, (byte)0x03, (byte)0x6f, (byte)/* ww.kde.o */ (byte)0x72, (byte)0x67, (byte)0x00, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x01 /* rg..... */ }; /* Frame (98 bytes) : ping request */ static final byte[] pingRequest = { (byte)0x45, (byte)0x00, /* 8/....E. */ (byte)0x00, (byte)0x54, (byte)0xea, (byte)0xf3, (byte)0x40, (byte)0x00, (byte)0x40, (byte)0x01, /* .T..@.@. */ (byte)0x7e, (byte)0x6d, (byte)0xc0, (byte)0xa8, (byte)0x00, (byte)0x90, (byte)0x08, (byte)0x08, /* ~m...... */ (byte)0x08, (byte)0x08, (byte)0x08, (byte)0x00, (byte)0x61, (byte)0x60, (byte)0x42, (byte)0x95, /* ....a`B. */ (byte)0x00, (byte)0x23, (byte)0x1f, (byte)0x53, (byte)0x2c, (byte)0x53, (byte)0x11, (byte)0x3e, /* .#.S,S.> */ (byte)0x0c, (byte)0x00, (byte)0x08, (byte)0x09, (byte)0x0a, (byte)0x0b, (byte)0x0c, (byte)0x0d, /* ........ */ (byte)0x0e, (byte)0x0f, (byte)0x10, (byte)0x11, (byte)0x12, (byte)0x13, (byte)0x14, (byte)0x15, /* ........ */ (byte)0x16, (byte)0x17, (byte)0x18, (byte)0x19, (byte)0x1a, (byte)0x1b, (byte)0x1c, (byte)0x1d, /* ........ */ (byte)0x1e, (byte)0x1f, (byte)0x20, (byte)0x21, (byte)0x22, (byte)0x23, (byte)0x24, (byte)0x25, /* .. !"#$% */ (byte)0x26, (byte)0x27, (byte)0x28, (byte)0x29, (byte)0x2a, (byte)0x2b, (byte)0x2c, (byte)0x2d, /* &'()*+,- */ (byte)0x2e, (byte)0x2f, (byte)0x30, (byte)0x31, (byte)0x32, (byte)0x33, (byte)0x34, (byte)0x35, /* ./012345 */ (byte)0x36, (byte)0x37 /* 67 */ }; /* Frame (74 bytes) * wget http://8.8.8.8 from 192.168.0.144 * */ static final byte[] tcp_sync = { (byte)0x45, (byte)0x00, /* 8/....E. */ (byte)0x00, (byte)0x3c, (byte)0xd9, (byte)0xa5, (byte)0x40, (byte)0x00, (byte)0x40, (byte)0x06, /* .<..@.@. */ (byte)0x8f, (byte)0xce, (byte)0xc0, (byte)0xa8, (byte)0x00, (byte)0x90, (byte)0x08, (byte)0x08, /* ........ */ (byte)0x08, (byte)0x08, (byte)0xdd, (byte)0x60, (byte)0x00, (byte)0x50, (byte)0xf5, (byte)0x73, /* ...`.P.s */ (byte)0xd7, (byte)0xd3, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xa0, (byte)0x02, /* ........ */ (byte)0x72, (byte)0x10, (byte)0x4a, (byte)0x39, (byte)0x00, (byte)0x00, (byte)0x02, (byte)0x04, /* r.J9.... */ (byte)0x05, (byte)0xb4, (byte)0x04, (byte)0x02, (byte)0x08, (byte)0x0a, (byte)0x00, (byte)0xfd, /* ........ */ (byte)0x0e, (byte)0x76, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x01, (byte)0x03, /* .v...... */ (byte)0x03, (byte)0x0a /* .. */ }; /* Frame (74 bytes) * some dummy packet , copy from icmp but change protocol number * */ static final byte[] unknownIpProtocol = { (byte)0x45, (byte)0x00, (byte)/* 8/....E. */ (byte)0x00, (byte)0x39, (byte)0xf5, (byte)0x10, (byte)0x00, (byte)0x00, (byte)0x40, (byte)0x11, (byte)/* .9....@. */ (byte)0xb4, (byte)0x5b, (byte)0xc0, (byte)0xa8, (byte)0x00, (byte)0x90, (byte)0x08, (byte)0x08, (byte)/* .[...... */ (byte)0x08, (byte)0x08, (byte)0xca, (byte)0xfd, (byte)0x00, (byte)0x35, (byte)0x00, (byte)0x25, (byte)/* .....5.% */ (byte)0xd5, (byte)0x7e, (byte)0x32, (byte)0x14, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x01, (byte)/* .~2..... */ (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x03, (byte)0x77, (byte)/* .......w */ (byte)0x77, (byte)0x77, (byte)0x03, (byte)0x6b, (byte)0x64, (byte)0x65, (byte)0x03, (byte)0x6f, (byte)/* ww.kde.o */ (byte)0x72, (byte)0x67, (byte)0x00, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x01 /* rg..... */ }; @Test public void testProcessRawPacket() throws Exception { Object result=IPFactory.processRawPacket(null,0); Assert.assertNull(result); } @Test public void testProcessUDPPacket() throws Exception { ByteBuffer rawData = ByteBuffer.allocate(DNSrequest.length); rawData.put(DNSrequest); Object result=IPFactory.processRawPacket(rawData,rawData.limit()); Assert.assertNotNull(result); org.junit.Assert.assertTrue(result instanceof UDPPacket); } @Test public void testProcessICMPPacket() throws Exception { ByteBuffer rawData = ByteBuffer.allocate(pingRequest.length); rawData.put(pingRequest); Object result=IPFactory.processRawPacket(rawData,rawData.limit()); Assert.assertNotNull(result); org.junit.Assert.assertTrue(result instanceof ICMPPacket); } @Test public void testProcessTCPPacket() throws Exception { ByteBuffer rawData = ByteBuffer.allocate(tcp_sync.length); rawData.put(tcp_sync); Object result=IPFactory.processRawPacket(rawData,rawData.limit()); Assert.assertNotNull(result); org.junit.Assert.assertTrue(result instanceof TCPPacket); } @Test public void testProcessUnkownPacket() throws Exception { ByteBuffer rawData = ByteBuffer.allocate(unknownIpProtocol.length); rawData.put(unknownIpProtocol); Object result=IPFactory.processRawPacket(rawData,rawData.limit()); Assert.assertNotNull(result); } }
- more Ip factory testing
src/test/java/org/it4y/net/protocols/IP/IPFactoryTest.java
- more Ip factory testing
<ide><path>rc/test/java/org/it4y/net/protocols/IP/IPFactoryTest.java <ide> * */ <ide> static final byte[] unknownIpProtocol = { <ide> (byte)0x45, (byte)0x00, (byte)/* 8/....E. */ <del> (byte)0x00, (byte)0x39, (byte)0xf5, (byte)0x10, (byte)0x00, (byte)0x00, (byte)0x40, (byte)0x11, (byte)/* .9....@. */ <add> (byte)0x00, (byte)0x39, (byte)0xf5, (byte)0x10, (byte)0x00, (byte)0x00, (byte)0x40, (byte)0xff, (byte)/* .9....@. */ <ide> (byte)0xb4, (byte)0x5b, (byte)0xc0, (byte)0xa8, (byte)0x00, (byte)0x90, (byte)0x08, (byte)0x08, (byte)/* .[...... */ <ide> (byte)0x08, (byte)0x08, (byte)0xca, (byte)0xfd, (byte)0x00, (byte)0x35, (byte)0x00, (byte)0x25, (byte)/* .....5.% */ <ide> (byte)0xd5, (byte)0x7e, (byte)0x32, (byte)0x14, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x01, (byte)/* .~2..... */ <ide> public void testProcessUDPPacket() throws Exception { <ide> ByteBuffer rawData = ByteBuffer.allocate(DNSrequest.length); <ide> rawData.put(DNSrequest); <del> Object result=IPFactory.processRawPacket(rawData,rawData.limit()); <add> IpPacket result=IPFactory.processRawPacket(rawData,rawData.limit()); <ide> Assert.assertNotNull(result); <ide> org.junit.Assert.assertTrue(result instanceof UDPPacket); <add> org.junit.Assert.assertEquals(IpPacket.UDP,result.getProtocol()); <ide> } <ide> <ide> @Test <ide> public void testProcessICMPPacket() throws Exception { <ide> ByteBuffer rawData = ByteBuffer.allocate(pingRequest.length); <ide> rawData.put(pingRequest); <del> Object result=IPFactory.processRawPacket(rawData,rawData.limit()); <add> IpPacket result=IPFactory.processRawPacket(rawData,rawData.limit()); <ide> Assert.assertNotNull(result); <ide> org.junit.Assert.assertTrue(result instanceof ICMPPacket); <add> org.junit.Assert.assertEquals(IpPacket.ICMP,result.getProtocol()); <ide> } <ide> <ide> @Test <ide> public void testProcessTCPPacket() throws Exception { <ide> ByteBuffer rawData = ByteBuffer.allocate(tcp_sync.length); <ide> rawData.put(tcp_sync); <del> Object result=IPFactory.processRawPacket(rawData,rawData.limit()); <add> IpPacket result=IPFactory.processRawPacket(rawData,rawData.limit()); <ide> Assert.assertNotNull(result); <ide> org.junit.Assert.assertTrue(result instanceof TCPPacket); <add> org.junit.Assert.assertEquals(IpPacket.TCP,result.getProtocol()); <ide> } <ide> <ide> @Test <ide> public void testProcessUnkownPacket() throws Exception { <ide> ByteBuffer rawData = ByteBuffer.allocate(unknownIpProtocol.length); <ide> rawData.put(unknownIpProtocol); <del> Object result=IPFactory.processRawPacket(rawData,rawData.limit()); <add> IpPacket result=IPFactory.processRawPacket(rawData,rawData.limit()); <ide> Assert.assertNotNull(result); <add> org.junit.Assert.assertEquals((byte)0xff,result.getProtocol()); <ide> } <ide> <ide> }
Java
apache-2.0
c19f3ab832178d882ce3fb59cae3bb18babba2c8
0
Zhuinden/simple-stack,Zhuinden/simple-stack
package com.zhuinden.simplestackdemo.stack; import android.os.Parcelable; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Created by Owner on 2017. 01. 12.. */ public class Backstack { private ArrayList<Parcelable> stack = new ArrayList<>(); private StateChanger stateChanger; private boolean isStateChangeInProgress; public Backstack(Parcelable... initialKeys) { if(initialKeys == null || initialKeys.length <= 0) { throw new IllegalArgumentException("At least one initial key must be defined"); } Collections.addAll(stack, initialKeys); } public Backstack(List<Parcelable> initialKeys) { if(initialKeys == null) { throw new NullPointerException("Initial key list should not be null"); } if(initialKeys.size() <= 0) { throw new IllegalArgumentException("Initial key list should contain at least one element"); } stack.addAll(initialKeys); } public void setStateChanger(StateChanger stateChanger) { if(stateChanger == null) { throw new NullPointerException("New state changer cannot be null"); } this.stateChanger = stateChanger; ArrayList<Parcelable> newHistory = new ArrayList<>(); newHistory.addAll(stack); changeState(newHistory, StateChange.Direction.REPLACE, true); } public void removeStateChanger() { this.stateChanger = null; } public void goTo(Parcelable newKey) { checkNewKey(newKey); checkStateChanger(); checkStateChangeInProgress(); ArrayList<Parcelable> newHistory = new ArrayList<>(); boolean isNewKey = true; for(Parcelable key : stack) { newHistory.add(key); if(key.equals(newKey)) { isNewKey = false; break; } } StateChange.Direction direction; if(isNewKey) { newHistory.add(newKey); direction = StateChange.Direction.FORWARD; } else { direction = StateChange.Direction.BACKWARD; } changeState(newHistory, direction, false); } public boolean goBack() { if(isStateChangeInProgress) { return true; } checkStateChanger(); if(stack.size() <= 0) { throw new IllegalStateException("Cannot go back when stack has no items"); } if(stack.size() == 1) { stack.clear(); return false; } ArrayList<Parcelable> newHistory = new ArrayList<>(); for(int i = 0; i < stack.size() - 1; i++) { newHistory.add(stack.get(i)); } changeState(newHistory, StateChange.Direction.BACKWARD, false); return true; } public void setHistory(List<Parcelable> newHistory, StateChange.Direction direction) { checkStateChanger(); checkStateChangeInProgress(); if(newHistory == null || newHistory.isEmpty()) { throw new NullPointerException("New history cannot be null or empty"); } changeState(newHistory, direction, false); } public List<Parcelable> getHistory() { return Collections.unmodifiableList(stack); } // private void checkStateChangeInProgress() { if(isStateChangeInProgress) { throw new IllegalStateException("Cannot execute state change while another state change is in progress"); // FIXME: Flow allows queueing traversals } } private void checkStateChanger() { if(stateChanger == null) { throw new IllegalStateException("State changes are not possible while state changer is not set"); // FIXME: Flow allows queueing traversals } } private void checkNewKey(Parcelable newKey) { if(newKey == null) { throw new NullPointerException("Key cannot be null"); } } private void changeState(List<Parcelable> newHistory, StateChange.Direction direction, boolean initialization) { List<Parcelable> previousState; if(initialization) { previousState = Collections.emptyList(); } else { previousState = new ArrayList<>(); previousState.addAll(stack); } final StateChange stateChange = new StateChange(previousState, Collections.unmodifiableList(newHistory), direction); isStateChangeInProgress = true; stateChanger.handleStateChange(stateChange, new StateChanger.Callback() { @Override public void stateChangeComplete() { completeStateChange(stateChange); } }); } private void completeStateChange(StateChange stateChange) { this.stack.clear(); this.stack.addAll(stateChange.newState); isStateChangeInProgress = false; } }
demo-stack/src/main/java/com/zhuinden/simplestackdemo/stack/Backstack.java
package com.zhuinden.simplestackdemo.stack; import android.os.Parcelable; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Created by Owner on 2017. 01. 12.. */ public class Backstack { private ArrayList<Parcelable> stack = new ArrayList<>(); private StateChanger stateChanger; private boolean isStateChangeInProgress; public Backstack(Parcelable... initialKeys) { if(initialKeys == null || initialKeys.length <= 0) { throw new IllegalArgumentException("At least one initial key must be defined"); } Collections.addAll(stack, initialKeys); } public Backstack(List<Parcelable> initialKeys) { if(initialKeys == null) { throw new NullPointerException("Initial key list should not be null"); } if(initialKeys.size() <= 0) { throw new IllegalArgumentException("Initial key list should contain at least one element"); } stack.addAll(initialKeys); } public void setStateChanger(StateChanger stateChanger) { if(stateChanger == null) { throw new NullPointerException("New state changer cannot be null"); } this.stateChanger = stateChanger; ArrayList<Parcelable> newHistory = new ArrayList<>(); newHistory.addAll(stack); changeState(newHistory, StateChange.Direction.REPLACE, true); } public void removeStateChanger() { this.stateChanger = null; } public void goTo(Parcelable newKey) { checkNewKey(newKey); checkStateChanger(); checkStateChangeInProgress(); ArrayList<Parcelable> newHistory = new ArrayList<>(); boolean isNewKey = true; for(Parcelable key : stack) { newHistory.add(key); if(key.equals(newKey)) { isNewKey = false; break; } } StateChange.Direction direction; if(isNewKey) { newHistory.add(newKey); direction = StateChange.Direction.FORWARD; } else { direction = StateChange.Direction.BACKWARD; } changeState(newHistory, direction, false); } public boolean goBack() { if(isStateChangeInProgress) { return true; } checkStateChanger(); if(stack.size() <= 0) { throw new IllegalStateException("Cannot go back when stack has no items"); } if(stack.size() == 1) { stack.clear(); return false; } ArrayList<Parcelable> newHistory = new ArrayList<>(); for(int i = 0; i < stack.size() - 1; i++) { newHistory.add(stack.get(i)); } changeState(newHistory, StateChange.Direction.BACKWARD, false); return true; } public void setHistory(ArrayList<Parcelable> newHistory, StateChange.Direction direction) { checkStateChanger(); checkStateChangeInProgress(); if(newHistory == null || newHistory.isEmpty()) { throw new NullPointerException("New history cannot be null or empty"); } changeState(newHistory, direction, false); } public List<Parcelable> getHistory() { return Collections.unmodifiableList(stack); } // private void checkStateChangeInProgress() { if(isStateChangeInProgress) { throw new IllegalStateException("Cannot execute state change while another state change is in progress"); // FIXME: Flow allows queueing traversals } } private void checkStateChanger() { if(stateChanger == null) { throw new IllegalStateException("State changes are not possible while state changer is not set"); // FIXME: Flow allows queueing traversals } } private void checkNewKey(Parcelable newKey) { if(newKey == null) { throw new NullPointerException("Key cannot be null"); } } private void changeState(ArrayList<Parcelable> newHistory, StateChange.Direction direction, boolean initialization) { List<Parcelable> previousState; if(initialization) { previousState = Collections.emptyList(); } else { previousState = new ArrayList<>(); previousState.addAll(stack); } final StateChange stateChange = new StateChange(previousState, Collections.unmodifiableList(newHistory), direction); isStateChangeInProgress = true; stateChanger.handleStateChange(stateChange, new StateChanger.Callback() { @Override public void stateChangeComplete() { completeStateChange(stateChange); } }); } private void completeStateChange(StateChange stateChange) { this.stack.clear(); this.stack.addAll(stateChange.newState); isStateChangeInProgress = false; } }
ArrayList => List
demo-stack/src/main/java/com/zhuinden/simplestackdemo/stack/Backstack.java
ArrayList => List
<ide><path>emo-stack/src/main/java/com/zhuinden/simplestackdemo/stack/Backstack.java <ide> return true; <ide> } <ide> <del> public void setHistory(ArrayList<Parcelable> newHistory, StateChange.Direction direction) { <add> public void setHistory(List<Parcelable> newHistory, StateChange.Direction direction) { <ide> checkStateChanger(); <ide> checkStateChangeInProgress(); <ide> if(newHistory == null || newHistory.isEmpty()) { <ide> } <ide> } <ide> <del> private void changeState(ArrayList<Parcelable> newHistory, StateChange.Direction direction, boolean initialization) { <add> private void changeState(List<Parcelable> newHistory, StateChange.Direction direction, boolean initialization) { <ide> List<Parcelable> previousState; <ide> if(initialization) { <ide> previousState = Collections.emptyList();
Java
apache-2.0
6fdfa0705447ca871b70e4a7ca0341938fc3c851
0
jphp-compiler/jphp,jphp-compiler/jphp,jphp-compiler/jphp,jphp-compiler/jphp
package org.develnext.jphp.zend.ext.standard; import php.runtime.Memory; import php.runtime.ext.support.compile.ConstantsContainer; import php.runtime.memory.StringMemory; public class DateConstants extends ConstantsContainer { public static final Memory DATE_ATOM = StringMemory.valueOf("Y-m-d\\TH:i:sP"); public static final Memory DATE_COOKIE = StringMemory.valueOf("l, d-M-Y H:i:s T"); public static final Memory DATE_ISO8601 = StringMemory.valueOf("Y-m-d\\TH:i:sO"); public static final Memory DATE_RFC822 = StringMemory.valueOf("D, d M y H:i:s O"); public static final Memory DATE_RFC850 = StringMemory.valueOf("l, d-M-y H:i:s T"); public static final Memory DATE_RFC1036 = StringMemory.valueOf("D, d M y H:i:s O"); public static final Memory DATE_RFC1123 = StringMemory.valueOf("D, d M Y H:i:s O"); public static final Memory DATE_RFC2822 = StringMemory.valueOf("D, d M Y H:i:s O"); public static final Memory DATE_RFC3339 = StringMemory.valueOf("Y-m-d\\TH:i:sP"); public static final Memory DATE_RFC3339_EXTENDED = StringMemory.valueOf("Y-m-d\\TH:i:s.vP"); public static final Memory DATE_RSS = StringMemory.valueOf("D, d M Y H:i:s O"); public static final Memory DATE_W3C = StringMemory.valueOf("Y-m-d\\TH:i:sP"); }
exts/jphp-zend-ext/src/main/java/org/develnext/jphp/zend/ext/standard/DateConstants.java
package org.develnext.jphp.zend.ext.standard; import php.runtime.Memory; import php.runtime.ext.support.compile.ConstantsContainer; import php.runtime.memory.StringMemory; public class DateConstants extends ConstantsContainer { public static final Memory DATE_ATOM = StringMemory.valueOf("Y-m-d\\TH:i:sP"); public static final Memory DATE_COOKIE = StringMemory.valueOf("l, d-M-Y H:i:s T"); public static final Memory DATE_ISO8601 = StringMemory.valueOf("Y-m-d\\TH:i:sO"); public static final Memory DATE_RFC822 = StringMemory.valueOf("D, d M y H:i:s O"); public static final Memory DATE_RFC850 = StringMemory.valueOf("l, d-M-y H:i:s T"); public static final Memory DATE_RFC1036 = StringMemory.valueOf("D, d M y H:i:s O"); public static final Memory DATE_RFC1123 = StringMemory.valueOf("D, d M y H:i:s O"); public static final Memory DATE_RFC2822 = StringMemory.valueOf("D, d M y H:i:s O"); public static final Memory DATE_RFC3339 = StringMemory.valueOf("Y-m-d\\TH:i:sP"); public static final Memory DATE_RFC3339_EXTENDED = StringMemory.valueOf("Y-m-d\\TH:i:s.vP"); public static final Memory DATE_RSS = StringMemory.valueOf("Y-m-d\\TH:i:s.vP"); public static final Memory DATE_W3C = StringMemory.valueOf("Y-m-d\\TH:i:sP"); }
[WIP] Well known date-time formats now correct.
exts/jphp-zend-ext/src/main/java/org/develnext/jphp/zend/ext/standard/DateConstants.java
[WIP] Well known date-time formats now correct.
<ide><path>xts/jphp-zend-ext/src/main/java/org/develnext/jphp/zend/ext/standard/DateConstants.java <ide> public static final Memory DATE_RFC822 = StringMemory.valueOf("D, d M y H:i:s O"); <ide> public static final Memory DATE_RFC850 = StringMemory.valueOf("l, d-M-y H:i:s T"); <ide> public static final Memory DATE_RFC1036 = StringMemory.valueOf("D, d M y H:i:s O"); <del> public static final Memory DATE_RFC1123 = StringMemory.valueOf("D, d M y H:i:s O"); <del> public static final Memory DATE_RFC2822 = StringMemory.valueOf("D, d M y H:i:s O"); <add> public static final Memory DATE_RFC1123 = StringMemory.valueOf("D, d M Y H:i:s O"); <add> public static final Memory DATE_RFC2822 = StringMemory.valueOf("D, d M Y H:i:s O"); <ide> public static final Memory DATE_RFC3339 = StringMemory.valueOf("Y-m-d\\TH:i:sP"); <ide> public static final Memory DATE_RFC3339_EXTENDED = StringMemory.valueOf("Y-m-d\\TH:i:s.vP"); <del> public static final Memory DATE_RSS = StringMemory.valueOf("Y-m-d\\TH:i:s.vP"); <add> public static final Memory DATE_RSS = StringMemory.valueOf("D, d M Y H:i:s O"); <ide> public static final Memory DATE_W3C = StringMemory.valueOf("Y-m-d\\TH:i:sP"); <ide> }
Java
apache-2.0
57d4f999a9a3ba9d736a7554e78cadd9dcad34ed
0
thomaskrause/ANNIS,thomaskrause/ANNIS,korpling/ANNIS,zangsir/ANNIS,korpling/ANNIS,amir-zeldes/ANNIS,thomaskrause/ANNIS,zangsir/ANNIS,zangsir/ANNIS,pixeldrama/ANNIS,korpling/ANNIS,pixeldrama/ANNIS,thomaskrause/ANNIS,korpling/ANNIS,zangsir/ANNIS,pixeldrama/ANNIS,amir-zeldes/ANNIS,pixeldrama/ANNIS,thomaskrause/ANNIS,zangsir/ANNIS,korpling/ANNIS,zangsir/ANNIS,pixeldrama/ANNIS,amir-zeldes/ANNIS,amir-zeldes/ANNIS,pixeldrama/ANNIS,amir-zeldes/ANNIS,amir-zeldes/ANNIS
/* * Copyright 2011 Corpuslinguistic working group Humboldt University Berlin. * * 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 annis.gui.resultview; import annis.gui.Helper; import annis.gui.PluginSystem; import annis.gui.visualizers.VisualizerInput; import annis.gui.visualizers.VisualizerPlugin; import annis.gui.visualizers.component.KWICPanel.KWICPanelImpl; import annis.resolver.ResolverEntry; import com.sun.jersey.api.client.WebResource; import com.vaadin.terminal.ApplicationResource; import com.vaadin.terminal.StreamResource; import com.vaadin.terminal.ThemeResource; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Component; import com.vaadin.ui.CustomLayout; import com.vaadin.ui.Panel; import com.vaadin.ui.themes.ChameleonTheme; import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.SaltProject; import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sCorpusStructure.SDocument; import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.STextualDS; import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.SToken; import de.hu_berlin.german.korpling.saltnpepper.salt.saltCore.SNode; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.URLEncoder; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Controls the visibility of visualizer plugins and provides some control * methods for the media visualizers. * * @author Thomas Krause <[email protected]> * @author Benjamin Weißenfels <[email protected]> * * TODO test, if this works with mediaplayer */ public class VisualizerPanel extends Panel implements Button.ClickListener { private final Logger log = LoggerFactory.getLogger(VisualizerPanel.class); public static final ThemeResource ICON_COLLAPSE = new ThemeResource( "icon-collapse.gif"); public static final ThemeResource ICON_EXPAND = new ThemeResource( "icon-expand.gif"); private ApplicationResource resource = null; private Component vis; private SDocument result; private PluginSystem ps; private ResolverEntry entry; private Random rand = new Random(); private Map<SNode, Long> markedAndCovered; private List<SToken> token; private Map<String, String> markersExact; private Map<String, String> markersCovered; private Button btEntry; private KWICPanelImpl kwicPanel; private List<String> mediaIDs; private String htmlID; private CustomLayout visContainer; private VisualizerPlugin visPlugin; private Set<String> visibleTokenAnnos; private STextualDS text; private SingleResultPanel parentPanel; private String segmentationName; private List<VisualizerPanel> mediaVisualizer; private final String PERMANENT = "permanent"; private final String ISVISIBLE = "visible"; private final String NOTVISIBLE = "hidden"; /** * This Constructor should be used for {@link ComponentVisualizerPlugin} * Visualizer. * */ public VisualizerPanel( final ResolverEntry entry, SDocument result, List<SToken> token, Set<String> visibleTokenAnnos, Map<SNode, Long> markedAndCovered, @Deprecated Map<String, String> markedAndCoveredMap, @Deprecated Map<String, String> markedExactMap, STextualDS text, List<String> mediaIDs, List<VisualizerPanel> mediaVisualizer, String htmlID, SingleResultPanel parent, String segmentationName, PluginSystem ps, CustomLayout visContainer) { visPlugin = ps.getVisualizer(entry.getVisType()); this.ps = ps; this.entry = entry; this.markersExact = markedExactMap; this.markersCovered = markedAndCoveredMap; this.result = result; this.token = token; this.visibleTokenAnnos = visibleTokenAnnos; this.markedAndCovered = markedAndCovered; this.text = text; this.parentPanel = parent; this.segmentationName = segmentationName; this.mediaVisualizer = mediaVisualizer; this.mediaIDs = mediaIDs; this.htmlID = htmlID; this.visContainer = visContainer; this.addStyleName(ChameleonTheme.PANEL_BORDERLESS); this.setWidth("100%"); this.setContent(this.visContainer); } @Override public void attach() { if (visPlugin == null) { entry.setVisType(PluginSystem.DEFAULT_VISUALIZER); visPlugin = ps.getVisualizer(entry.getVisType()); } if(entry != null) { if(PERMANENT.equalsIgnoreCase(entry.getVisibility())) { // create the visualizer and calc input vis = this.visPlugin.createComponent(createInput()); vis.setVisible(true); visContainer.addComponent(vis, "iframe"); } else if ( ISVISIBLE.equalsIgnoreCase(entry.getVisibility())) { // build button for visualizer btEntry = new Button(entry.getDisplayName()); btEntry.setIcon(ICON_COLLAPSE); btEntry.setStyleName(ChameleonTheme.BUTTON_BORDERLESS + " " + ChameleonTheme.BUTTON_SMALL); btEntry.addListener((Button.ClickListener) this); visContainer.addComponent(btEntry, "btEntry"); // create the visualizer and calc input vis = this.visPlugin.createComponent(createInput()); vis.setVisible(true); visContainer.addComponent(vis, "iframe"); } else { // build button for visualizer btEntry = new Button(entry.getDisplayName()); btEntry.setIcon(ICON_EXPAND); btEntry.setStyleName(ChameleonTheme.BUTTON_BORDERLESS + " " + ChameleonTheme.BUTTON_SMALL); btEntry.addListener((Button.ClickListener) this); visContainer.addComponent(btEntry, "btEntry"); } } } private VisualizerInput createInput() { VisualizerInput input = new VisualizerInput(); input.setAnnisWebServiceURL(getApplication().getProperty( "AnnisWebService.URL")); input.setContextPath(Helper.getContext(getApplication())); input.setDotPath(getApplication().getProperty("DotPath")); input.setId("" + rand.nextLong()); input.setMarkableExactMap(markersExact); input.setMarkableMap(markersCovered); input.setMediaIDs(mediaIDs); input.setMarkedAndCovered(markedAndCovered); input.setVisPanel(this); input.setResult(result); input.setToken(token); input.setVisibleTokenAnnos(visibleTokenAnnos); input.setText(text); input.setSegmentationName(segmentationName); input.setMediaIDs(mediaIDs); input.setMediaVisualizer(mediaVisualizer); if (entry != null) { input.setMappings(entry.getMappings()); input.setNamespace(entry.getNamespace()); String template = Helper.getContext(getApplication()) + "/Resource/" + entry.getVisType() + "/%s"; input.setResourcePathTemplate(template); } if (visPlugin.isUsingText() && result.getSDocumentGraph().getSNodes().size() > 0) { SaltProject p = getText(result.getSCorpusGraph().getSRootCorpus(). get(0).getSName(), result.getSName()); input.setDocument(p.getSCorpusGraphs().get(0).getSDocuments().get(0)); } else { input.setDocument(result); } return input; } public void setVisibleTokenAnnosVisible(Set<String> annos) { this.visibleTokenAnnos = annos; if(visPlugin != null && vis != null) { visPlugin.setVisibleTokenAnnosVisible(vis, annos); } } public void setSegmentationLayer(List<SToken> token, String segmentationName) { this.token = token; this.segmentationName = segmentationName; if(visPlugin != null && vis != null) { visPlugin.setSegmentationLayer(vis, segmentationName); } } public ApplicationResource createResource( final ByteArrayOutputStream byteStream, String mimeType) { StreamResource r; r = new StreamResource(new StreamResource.StreamSource() { @Override public InputStream getStream() { return new ByteArrayInputStream(byteStream.toByteArray()); } }, entry.getVisType() + "_" + Math.abs(rand.nextLong()), getApplication()); r.setMIMEType(mimeType); return r; } private SaltProject getText(String toplevelCorpusName, String documentName) { SaltProject text = null; try { toplevelCorpusName = URLEncoder.encode(toplevelCorpusName, "UTF-8"); documentName = URLEncoder.encode(documentName, "UTF-8"); WebResource annisResource = Helper.getAnnisWebResource(getApplication()); text = annisResource.path("graphs").path(toplevelCorpusName).path( documentName).get(SaltProject.class); } catch (Exception e) { log.error("General remote service exception", e); } return text; } @Override public void detach() { super.detach(); if (resource != null) { getApplication().removeResource(resource); } } @Override public void buttonClick(ClickEvent event) { toggleVisualizer(true); } /** * Opens and closes visualizer. * * @param collapse when collapse is false, the Visualizer would never be * closed */ public void toggleVisualizer(boolean collapse) { if (resource != null && collapse) { getApplication().removeResource(resource); } if (btEntry.getIcon() == ICON_EXPAND) { // check if it's necessary to create input if (visPlugin != null && vis == null) { vis = this.visPlugin.createComponent(createInput()); this.visContainer.addComponent(vis, "iframe"); } btEntry.setIcon(ICON_COLLAPSE); vis.setVisible(true); } else if (btEntry.getIcon() == ICON_COLLAPSE && collapse) { if (vis != null) { vis.setVisible(false); stopMediaVisualizers(); } btEntry.setIcon(ICON_EXPAND); } } public void setKwicPanel(KWICPanelImpl kwicPanel) { this.kwicPanel = kwicPanel; } public void startMediaVisFromKWIC() { if (kwicPanel != null) { kwicPanel.startMediaVisualizers(); // set back to null, otherwise the movie will stop kwicPanel = null; } } private void stopMediaVisualizers() { String stopCommand = "" + "document.getElementById(\"" + this.htmlID + "\")" + ".getElementsByTagName(\"iframe\")[0].contentWindow.stop()"; getWindow().executeJavaScript(stopCommand); } }
annis-gui/src/main/java/annis/gui/resultview/VisualizerPanel.java
/* * Copyright 2011 Corpuslinguistic working group Humboldt University Berlin. * * 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 annis.gui.resultview; import annis.gui.Helper; import annis.gui.PluginSystem; import annis.gui.visualizers.VisualizerInput; import annis.gui.visualizers.VisualizerPlugin; import annis.gui.visualizers.component.KWICPanel.KWICPanelImpl; import annis.resolver.ResolverEntry; import com.sun.jersey.api.client.WebResource; import com.vaadin.terminal.ApplicationResource; import com.vaadin.terminal.StreamResource; import com.vaadin.terminal.ThemeResource; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Component; import com.vaadin.ui.CustomLayout; import com.vaadin.ui.Panel; import com.vaadin.ui.themes.ChameleonTheme; import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.SaltProject; import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sCorpusStructure.SDocument; import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.STextualDS; import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.SToken; import de.hu_berlin.german.korpling.saltnpepper.salt.saltCore.SNode; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.URLEncoder; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Controls the visibility of visualizer plugins and provides some control * methods for the media visualizers. * * @author Thomas Krause <[email protected]> * @author Benjamin Weißenfels <[email protected]> * * TODO test, if this works with mediaplayer */ public class VisualizerPanel extends Panel implements Button.ClickListener { private final Logger log = LoggerFactory.getLogger(VisualizerPanel.class); public static final ThemeResource ICON_COLLAPSE = new ThemeResource( "icon-collapse.gif"); public static final ThemeResource ICON_EXPAND = new ThemeResource( "icon-expand.gif"); private ApplicationResource resource = null; private Component vis; private SDocument result; private PluginSystem ps; private ResolverEntry entry; private Random rand = new Random(); private Map<SNode, Long> markedAndCovered; private List<SToken> token; private Map<String, String> markersExact; private Map<String, String> markersCovered; private Button btEntry; private KWICPanelImpl kwicPanel; private List<String> mediaIDs; private String htmlID; private CustomLayout visContainer; private VisualizerPlugin visPlugin; private Set<String> visibleTokenAnnos; private STextualDS text; private SingleResultPanel parentPanel; private String segmentationName; private List<VisualizerPanel> mediaVisualizer; private final String PERMANENT = "permanent"; private final String ISVISIBLE = "visible"; private final String NOTVISIBLE = "hidden"; /** * This Constructor should be used for {@link ComponentVisualizerPlugin} * Visualizer. * */ public VisualizerPanel( final ResolverEntry entry, SDocument result, List<SToken> token, Set<String> visibleTokenAnnos, Map<SNode, Long> markedAndCovered, @Deprecated Map<String, String> markedAndCoveredMap, @Deprecated Map<String, String> markedExactMap, STextualDS text, List<String> mediaIDs, List<VisualizerPanel> mediaVisualizer, String htmlID, SingleResultPanel parent, String segmentationName, PluginSystem ps, CustomLayout visContainer) { visPlugin = ps.getVisualizer(entry.getVisType()); this.ps = ps; this.entry = entry; this.markersExact = markedExactMap; this.markersCovered = markedAndCoveredMap; this.result = result; this.token = token; this.visibleTokenAnnos = visibleTokenAnnos; this.markedAndCovered = markedAndCovered; this.text = text; this.parentPanel = parent; this.segmentationName = segmentationName; this.mediaVisualizer = mediaVisualizer; this.mediaIDs = mediaIDs; this.htmlID = htmlID; this.visContainer = visContainer; this.addStyleName(ChameleonTheme.PANEL_BORDERLESS); this.setWidth("100%"); this.setContent(this.visContainer); } @Override public void attach() { if (visPlugin == null) { entry.setVisType(PluginSystem.DEFAULT_VISUALIZER); visPlugin = ps.getVisualizer(entry.getVisType()); } if(entry != null) { if(PERMANENT.equalsIgnoreCase(entry.getVisibility())) { // create the visualizer and calc input vis = this.visPlugin.createComponent(createInput()); vis.setVisible(true); visContainer.addComponent(vis, "iframe"); } else if ( ISVISIBLE.equalsIgnoreCase(entry.getVisibility())) { // build button for visualizer btEntry = new Button(entry.getDisplayName()); btEntry.setIcon(ICON_COLLAPSE); btEntry.setStyleName(ChameleonTheme.BUTTON_BORDERLESS + " " + ChameleonTheme.BUTTON_SMALL); btEntry.addListener((Button.ClickListener) this); visContainer.addComponent(btEntry, "btEntry"); // create the visualizer and calc input vis = this.visPlugin.createComponent(createInput()); vis.setVisible(true); visContainer.addComponent(vis, "iframe"); } else { // build button for visualizer btEntry = new Button(entry.getDisplayName()); btEntry.setIcon(ICON_EXPAND); btEntry.setStyleName(ChameleonTheme.BUTTON_BORDERLESS + " " + ChameleonTheme.BUTTON_SMALL); btEntry.addListener((Button.ClickListener) this); visContainer.addComponent(btEntry, "btEntry"); } } } private VisualizerInput createInput() { VisualizerInput input = new VisualizerInput(); input.setAnnisWebServiceURL(getApplication().getProperty( "AnnisWebService.URL")); input.setContextPath(Helper.getContext(getApplication())); input.setDotPath(getApplication().getProperty("DotPath")); input.setId("" + rand.nextLong()); input.setMarkableExactMap(markersExact); input.setMarkableMap(markersCovered); input.setMediaIDs(mediaIDs); input.setMarkedAndCovered(markedAndCovered); input.setVisPanel(this); input.setResult(result); input.setToken(token); input.setVisibleTokenAnnos(visibleTokenAnnos); input.setText(text); input.setSegmentationName(segmentationName); input.setMediaIDs(mediaIDs); input.setMediaVisualizer(mediaVisualizer); if (entry != null) { input.setMappings(entry.getMappings()); input.setNamespace(entry.getNamespace()); String template = Helper.getContext(getApplication()) + "/Resource/" + entry.getVisType() + "/%s"; input.setResourcePathTemplate(template); } if (visPlugin.isUsingText() && result.getSDocumentGraph().getSNodes().size() > 0) { SaltProject p = getText(result.getSCorpusGraph().getSRootCorpus(). get(0).getSName(), result.getSName()); input.setDocument(p.getSCorpusGraphs().get(0).getSDocuments().get(0)); } else { input.setDocument(result); } return input; } public void setVisibleTokenAnnosVisible(Set<String> annos) { this.visibleTokenAnnos = annos; if(visPlugin != null && vis != null && visContainer != null) { Component newVis = visPlugin.createComponent(createInput()); visContainer.replaceComponent(vis, newVis); vis = newVis; } } public void setSegmentationLayer(List<SToken> token, String segmentationName) { this.token = token; this.segmentationName = segmentationName; if(visPlugin != null && vis != null && visContainer != null) { Component newVis = visPlugin.createComponent(createInput()); visContainer.replaceComponent(vis, newVis); vis = newVis; } } public ApplicationResource createResource( final ByteArrayOutputStream byteStream, String mimeType) { StreamResource r; r = new StreamResource(new StreamResource.StreamSource() { @Override public InputStream getStream() { return new ByteArrayInputStream(byteStream.toByteArray()); } }, entry.getVisType() + "_" + Math.abs(rand.nextLong()), getApplication()); r.setMIMEType(mimeType); return r; } private SaltProject getText(String toplevelCorpusName, String documentName) { SaltProject text = null; try { toplevelCorpusName = URLEncoder.encode(toplevelCorpusName, "UTF-8"); documentName = URLEncoder.encode(documentName, "UTF-8"); WebResource annisResource = Helper.getAnnisWebResource(getApplication()); text = annisResource.path("graphs").path(toplevelCorpusName).path( documentName).get(SaltProject.class); } catch (Exception e) { log.error("General remote service exception", e); } return text; } @Override public void detach() { super.detach(); if (resource != null) { getApplication().removeResource(resource); } } @Override public void buttonClick(ClickEvent event) { toggleVisualizer(true); } /** * Opens and closes visualizer. * * @param collapse when collapse is false, the Visualizer would never be * closed */ public void toggleVisualizer(boolean collapse) { if (resource != null && collapse) { getApplication().removeResource(resource); } if (btEntry.getIcon() == ICON_EXPAND) { // check if it's necessary to create input if (visPlugin != null && vis == null) { vis = this.visPlugin.createComponent(createInput()); this.visContainer.addComponent(vis, "iframe"); } btEntry.setIcon(ICON_COLLAPSE); vis.setVisible(true); } else if (btEntry.getIcon() == ICON_COLLAPSE && collapse) { if (vis != null) { vis.setVisible(false); stopMediaVisualizers(); } btEntry.setIcon(ICON_EXPAND); } } public void setKwicPanel(KWICPanelImpl kwicPanel) { this.kwicPanel = kwicPanel; } public void startMediaVisFromKWIC() { if (kwicPanel != null) { kwicPanel.startMediaVisualizers(); // set back to null, otherwise the movie will stop kwicPanel = null; } } private void stopMediaVisualizers() { String stopCommand = "" + "document.getElementById(\"" + this.htmlID + "\")" + ".getElementsByTagName(\"iframe\")[0].contentWindow.stop()"; getWindow().executeJavaScript(stopCommand); } }
actually use the new mechanism
annis-gui/src/main/java/annis/gui/resultview/VisualizerPanel.java
actually use the new mechanism
<ide><path>nnis-gui/src/main/java/annis/gui/resultview/VisualizerPanel.java <ide> public void setVisibleTokenAnnosVisible(Set<String> annos) <ide> { <ide> this.visibleTokenAnnos = annos; <del> if(visPlugin != null && vis != null && visContainer != null) <del> { <del> Component newVis = visPlugin.createComponent(createInput()); <del> visContainer.replaceComponent(vis, newVis); <del> vis = newVis; <add> if(visPlugin != null && vis != null) <add> { <add> visPlugin.setVisibleTokenAnnosVisible(vis, annos); <ide> } <ide> } <ide> <ide> this.token = token; <ide> this.segmentationName = segmentationName; <ide> <del> if(visPlugin != null && vis != null && visContainer != null) <del> { <del> Component newVis = visPlugin.createComponent(createInput()); <del> visContainer.replaceComponent(vis, newVis); <del> vis = newVis; <add> if(visPlugin != null && vis != null) <add> { <add> visPlugin.setSegmentationLayer(vis, segmentationName); <ide> } <ide> } <ide>
Java
mit
b190bd831d3ca522c71d50a90820299248f219cd
0
BloodWorkXGaming/ExNihiloCreatio,BloodWorkXGaming/ExNihiloCreatio
package exnihilocreatio.util; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import javax.annotation.Nonnull; public interface StackInfo { String toString(); @Nonnull ItemStack getItemStack(); boolean hasBlock(); @Nonnull Block getBlock(); int getMeta(); @Nonnull IBlockState getBlockState(); boolean isValid(); NBTTagCompound writeToNBT(NBTTagCompound tag); int hashCode(); /** * This is used to check if the contents equals the objects, based on what the object is * @param obj The object to check * @return Returns true if the output ItemStacks match */ @Override boolean equals(Object obj); }
src/main/java/exnihilocreatio/util/StackInfo.java
package exnihilocreatio.util; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import javax.annotation.Nonnull; public abstract class StackInfo { public abstract String toString(); @Nonnull public abstract ItemStack getItemStack(); public abstract boolean hasBlock(); @Nonnull public abstract Block getBlock(); public abstract int getMeta(); @Nonnull public abstract IBlockState getBlockState(); public abstract boolean isValid(); public abstract NBTTagCompound writeToNBT(NBTTagCompound tag); public abstract int hashCode(); /** * This is used to check if the contents equals the objects, based on what the object is * @param obj The object to check * @return Returns true if the output ItemStacks match */ @Override public abstract boolean equals(Object obj); }
moved StackInfo to interface
src/main/java/exnihilocreatio/util/StackInfo.java
moved StackInfo to interface
<ide><path>rc/main/java/exnihilocreatio/util/StackInfo.java <ide> <ide> import javax.annotation.Nonnull; <ide> <del>public abstract class StackInfo { <add>public interface StackInfo { <ide> <del> public abstract String toString(); <add> String toString(); <ide> <ide> @Nonnull <del> public abstract ItemStack getItemStack(); <add> ItemStack getItemStack(); <ide> <del> public abstract boolean hasBlock(); <add> boolean hasBlock(); <ide> <ide> @Nonnull <del> public abstract Block getBlock(); <add> Block getBlock(); <ide> <del> public abstract int getMeta(); <add> int getMeta(); <ide> <ide> @Nonnull <del> public abstract IBlockState getBlockState(); <add> IBlockState getBlockState(); <ide> <del> public abstract boolean isValid(); <add> boolean isValid(); <ide> <del> public abstract NBTTagCompound writeToNBT(NBTTagCompound tag); <add> NBTTagCompound writeToNBT(NBTTagCompound tag); <ide> <del> public abstract int hashCode(); <add> int hashCode(); <ide> <ide> /** <ide> * This is used to check if the contents equals the objects, based on what the object is <ide> * @return Returns true if the output ItemStacks match <ide> */ <ide> @Override <del> public abstract boolean equals(Object obj); <add> boolean equals(Object obj); <ide> }
JavaScript
isc
3c227b6d8bc11bf4e252ba3fc9a054740af7e68e
0
vigour-io/vjs
'use strict' module.exports = function resolvePattern (obs, map) { return resolve(obs, map, [], 0) } function resolve (obs, map, path, length) { if (typeof map !== 'object') { let pattern = obs.pattern if (!length) { return pattern.upward || pattern } for (let i = length - 1; i >= 0; i--) { let key = path[i] if (key === 'sub_parent') { pattern = pattern.sub_parent || pattern.upward || pattern } else { pattern = pattern[key] } } return pattern } else { for (let i in map) { let mapValue = map[i] if (mapValue) { let next = obs[i] if (next) { if (i === 'parent') { path.push(obs.key) } else { path.push('sub_parent') } return resolve(next, mapValue, path, ++length) } } } } }
lib/observable/subscribe/resolve.js
'use strict' module.exports = function resolvePattern (obs, map) { console.error(obs, map) return resolve(obs, map, [], 0) } function resolve (obs, map, path, length) { if (typeof map !== 'object') { let pattern = obs.pattern if (!length) { return pattern.upward || pattern } for (let i = length - 1; i >= 0; i--) { let key = path[i] if (key === 'sub_parent') { pattern = pattern.sub_parent || pattern.upward || pattern } else { pattern = pattern[key] } } return pattern } else { for (let i in map) { let mapValue = map[i] if (mapValue) { console.log(i,obs) let next = obs[i] if (next) { if (i === 'parent') { path.push(obs.key) } else { path.push('sub_parent') } return resolve(next, mapValue, path, ++length) } } } } }
making tests
lib/observable/subscribe/resolve.js
making tests
<ide><path>ib/observable/subscribe/resolve.js <ide> 'use strict' <ide> module.exports = function resolvePattern (obs, map) { <del> console.error(obs, map) <ide> return resolve(obs, map, [], 0) <ide> } <ide> <ide> for (let i in map) { <ide> let mapValue = map[i] <ide> if (mapValue) { <del> console.log(i,obs) <ide> let next = obs[i] <ide> if (next) { <ide> if (i === 'parent') {
Java
apache-2.0
81d3a523bfdaf17dd2c7ece1bfc844cce331311a
0
brwe/es-token-plugin,brwe/es-token-plugin,brwe/es-token-plugin
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.script.models; import org.dmg.pmml.RegressionModel; import org.elasticsearch.common.collect.Tuple; import java.util.HashMap; import java.util.Map; public class EsLogisticRegressionModel extends EsRegressionModelEvaluator { public EsLogisticRegressionModel(RegressionModel model) { super(model); } public EsLogisticRegressionModel(double[] coefficients, double intercept, String[] classes) { super(coefficients, intercept, classes); } @Override public Map<String, Object> evaluateDebug(Tuple<int[], double[]> featureValues) { double val = linearFunction(featureValues, intercept, coefficients); return prepareResult(val); } @Override Object evaluate(Tuple<int[], double[]> featureValues) { double val = linearFunction(featureValues, intercept, coefficients); double prob = 1 / (1 + Math.exp(-1.0 * val)); return prob > 0.5 ? classes[0] : classes[1]; } protected Map<String, Object> prepareResult(double val) { // TODO: this should be several classes really... double prob = 1 / (1 + Math.exp(-1.0 * val)); String classValue = prob > 0.5 ? classes[0] : classes[1]; Map<String, Object> result = new HashMap<>(); result.put("class", classValue); Map<String, Object> probs = new HashMap<>(); probs.put(classes[0], prob); probs.put(classes[1], 1.0 - prob); result.put("probs", probs); return result; } public Map<String, Object> evaluateDebug(double[] featureValues) { double val = linearFunction(featureValues, intercept, coefficients); return prepareResult(val); } }
src/main/java/org/elasticsearch/script/models/EsLogisticRegressionModel.java
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.script.models; import org.dmg.pmml.RegressionModel; import org.elasticsearch.common.collect.Tuple; import java.util.HashMap; import java.util.Map; public class EsLogisticRegressionModel extends EsRegressionModelEvaluator { public EsLogisticRegressionModel(RegressionModel model) { super(model); } public EsLogisticRegressionModel(double[] coefficients, double intercept, String[] classes) { super(coefficients, intercept, classes); } @Override public Map<String, Object> evaluateDebug(Tuple<int[], double[]> featureValues) { double val = linearFunction(featureValues, intercept, coefficients); return prepareResult(val); } @Override Map<String, Object> evaluate(Tuple<int[], double[]> featureValues) { throw new UnsupportedOperationException("can only run with parameter debug: true"); } protected Map<String, Object> prepareResult(double val) { // TODO: this should be several classes really... double prob = 1 / (1 + Math.exp(-1.0 * val)); String classValue = prob > 0.5 ? classes[0] : classes[1]; Map<String, Object> result = new HashMap<>(); result.put("class", classValue); Map<String, Object> probs = new HashMap<>(); probs.put(classes[0], prob); probs.put(classes[1], 1.0 - prob); result.put("probs", probs); return result; } public Map<String, Object> evaluateDebug(double[] featureValues) { double val = linearFunction(featureValues, intercept, coefficients); return prepareResult(val); } }
debug for lr
src/main/java/org/elasticsearch/script/models/EsLogisticRegressionModel.java
debug for lr
<ide><path>rc/main/java/org/elasticsearch/script/models/EsLogisticRegressionModel.java <ide> } <ide> <ide> @Override <del> Map<String, Object> evaluate(Tuple<int[], double[]> featureValues) { <del> throw new UnsupportedOperationException("can only run with parameter debug: true"); <add> Object evaluate(Tuple<int[], double[]> featureValues) { <add> double val = linearFunction(featureValues, intercept, coefficients); <add> double prob = 1 / (1 + Math.exp(-1.0 * val)); <add> return prob > 0.5 ? classes[0] : classes[1]; <ide> } <ide> <ide> protected Map<String, Object> prepareResult(double val) {
Java
mit
9a8c8071085d47696af09123378ccddf24ce6cdf
0
aroelke/deck-editor-java
package editor.gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.SystemColor; import java.awt.Toolkit; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyVetoException; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Files; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Queue; import java.util.concurrent.CancellationException; import java.util.stream.Collectors; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDesktopPane; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.ScrollPaneConstants; import javax.swing.SwingUtilities; import javax.swing.TransferHandler; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.WindowConstants; import javax.swing.event.DocumentEvent; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import javax.swing.text.BadLocationException; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.JsonParser; import editor.collection.CardList; import editor.collection.Inventory; import editor.collection.deck.CategorySpec; import editor.collection.deck.Deck; import editor.collection.export.CardListFormat; import editor.collection.export.DelimitedCardListFormat; import editor.collection.export.TextCardListFormat; import editor.database.attributes.CardAttribute; import editor.database.attributes.Expansion; import editor.database.attributes.Rarity; import editor.database.card.Card; import editor.database.symbol.Symbol; import editor.database.version.DatabaseVersion; import editor.database.version.UpdateFrequency; import editor.filter.Filter; import editor.filter.leaf.TextFilter; import editor.gui.display.CardImagePanel; import editor.gui.display.CardTable; import editor.gui.display.CardTableCellRenderer; import editor.gui.display.CardTableModel; import editor.gui.editor.DeckLoadException; import editor.gui.editor.DeckSerializer; import editor.gui.editor.EditorFrame; import editor.gui.filter.FilterGroupPanel; import editor.gui.generic.CardMenuItems; import editor.gui.generic.ComponentUtils; import editor.gui.generic.DocumentChangeListener; import editor.gui.generic.OverwriteFileChooser; import editor.gui.generic.ScrollablePanel; import editor.gui.generic.TableMouseAdapter; import editor.gui.generic.VerticalButtonList; import editor.gui.generic.WizardDialog; import editor.gui.inventory.InventoryDownloadDialog; import editor.gui.inventory.InventoryLoadDialog; import editor.gui.settings.SettingsDialog; import editor.serialization.AttributeAdapter; import editor.serialization.CardAdapter; import editor.serialization.CategoryAdapter; import editor.serialization.DeckAdapter; import editor.serialization.FilterAdapter; import editor.serialization.VersionAdapter; import editor.serialization.legacy.DeckDeserializer; import editor.util.ColorAdapter; import editor.util.MenuListenerFactory; import editor.util.MouseListenerFactory; import editor.util.PopupMenuListenerFactory; import editor.util.UnicodeSymbols; /** * This class represents the main frame of the editor. It contains several tabs that display information * about decks. * <p> * The frame is divided into three sections: On the left side is a database of all cards that can be * added to decks with a window below it that displays the Oracle text of the currently-selected card. On * the right side is a pane which contains internal frames that allow the user to open, close, and edit * multiple decks at once. See #EditorFrame for details on the editor frames. * * @author Alec Roelke */ @SuppressWarnings("serial") public class MainFrame extends JFrame { /** * This class represents a renderer for rendering table cells that display text. If * the cell contains text and the card at the row is in the currently-active deck, * the cell is rendered bold. * * @author Alec Roelke */ private class InventoryTableCellRenderer extends CardTableCellRenderer { /** * Create a new CardTableCellRenderer. */ public InventoryTableCellRenderer() { super(); } /** * If the cell is rendered using a JLabel, make that JLabel bold. Otherwise, just use * the default renderer. * * @param table {@link JTable} to render for * @param value value being rendered * @param isSelected whether or not the cell is selected * @param hasFocus whether or not the table has focus * @param row row of the cell being rendered * @param column column of the cell being rendered * @return The {@link Component} responsible for rendering the table cell. */ @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); Card card = inventory.get(table.convertRowIndexToModel(row)); boolean main = selectedFrame.map((f) -> f.hasCard("", card)).orElse(false); boolean extra = selectedFrame.map((f) -> f.getExtraCards().contains(card)).orElse(false); if (main && extra) ComponentUtils.changeFontRecursive(c, c.getFont().deriveFont(Font.BOLD | Font.ITALIC)); else if (main) ComponentUtils.changeFontRecursive(c, c.getFont().deriveFont(Font.BOLD)); else if (extra) ComponentUtils.changeFontRecursive(c, c.getFont().deriveFont(Font.ITALIC)); return c; } } /** * Default height for displaying card images. */ public static final double DEFAULT_CARD_HEIGHT = 1.0/3.0; /** * Maximum height that the advanced filter editor panel can attain before scrolling. */ public static final int MAX_FILTER_HEIGHT = 300; /** * Serializer for saving and loading external information. */ public static final Gson SERIALIZER = new GsonBuilder() .registerTypeAdapter(CategorySpec.class, new CategoryAdapter()) .registerTypeHierarchyAdapter(Filter.class, new FilterAdapter()) .registerTypeAdapter(Color.class, new ColorAdapter()) .registerTypeHierarchyAdapter(Card.class, new CardAdapter()) .registerTypeAdapter(CardAttribute.class, new AttributeAdapter()) .registerTypeAdapter(Deck.class, new DeckAdapter()) .registerTypeAdapter(DeckSerializer.class, new DeckSerializer()) .registerTypeAdapter(DatabaseVersion.class, new VersionAdapter()) .setPrettyPrinting() .create(); /** * Update status value: update needed. */ public static final int UPDATE_NEEDED = 0; /** * Update status value: update not needed. */ public static final int NO_UPDATE = 1; /** * Update status value: update needed, but was not requested. */ public static final int UPDATE_CANCELLED = 2; /** * Inventory of all cards. */ private static Inventory inventory; /** * @return The inventory. */ public static Inventory inventory() { return inventory; } /** * Entry point for the program. All it does is set the look and feel to the * system one and create the GUI. * * @param args arguments to the program */ public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { e.printStackTrace(); } SwingUtilities.invokeLater(() -> new MainFrame(Arrays.stream(args).map(File::new).filter(File::exists).collect(Collectors.toList())).setVisible(true)); } /** * Table displaying the inventory of all cards. */ private CardTable inventoryTable; /** * Model for the table displaying the inventory of all cards. */ private CardTableModel inventoryModel; /** * Pane for showing the Oracle text of the currently-selected card. */ private JTextPane oracleTextPane; /** * Pane for showing the printed text of the currently-selected card. */ private JTextPane printedTextPane; /** * Desktop pane containing internal editor frames. */ private JDesktopPane decklistDesktop; /** * Number to append to the end of untitled decks that have just been created. */ private int untitled; /** * Currently-selected editor frame. */ private Optional<EditorFrame> selectedFrame; /** * List of open editor frames. */ private List<EditorFrame> editors; /** * File chooser for opening and saving. */ private OverwriteFileChooser fileChooser; /** * URL pointing to the site to get the latest version of the * inventory from. */ private URL versionSite; /** * File to store the inventory in. */ private File inventoryFile; /** * URL pointing to the site to get the inventory from. */ private URL inventorySite; /** * Number of recent files to display. */ private int recentCount; /** * Menu items showing recent files to open. */ private Queue<JMenuItem> recentItems; /** * Map of those menu items onto the files they should open. */ private Map<JMenuItem, File> recents; /** * Menu containing the recent menu items. */ private JMenu recentsMenu; /** * Newest version number of the inventory. */ private DatabaseVersion newestVersion; /** * Menu showing preset categories. */ private JMenu presetMenu; /** * Panel displaying the image for the currently selected card. */ private CardImagePanel imagePanel; /** * Pane displaying the currently-selected card's rulings. */ private JTextPane rulingsPane; /** * Top menu allowing editing of cards and categories in the selected deck. */ private JMenu deckMenu; /** * Currently-selected cards. Should never be null, but can be empty. */ private List<Card> selectedCards; /** * Table containing the currently-selected cards. Can be null if there is no * selection. */ private Optional<CardTable> selectedTable; /** * List backing the table containing the currently-selected cards. Can be null * if there is no selection. */ private Optional<CardList> selectedList; /** * Create a new MainFrame. */ public MainFrame(List<File> files) { super(); selectedCards = Collections.emptyList(); selectedTable = Optional.empty(); selectedList = Optional.empty(); untitled = 0; selectedFrame = Optional.empty(); editors = new ArrayList<>(); recentItems = new LinkedList<>(); recents = new HashMap<>(); // Initialize properties to their default values, then load the current values // from the properties file try { SettingsDialog.load(); } catch (IOException | JsonParseException e) { Throwable ex = e; while (ex.getCause() != null) ex = ex.getCause(); JOptionPane.showMessageDialog(this, "Error opening " + SettingsDialog.PROPERTIES_FILE + ": " + ex.getMessage() + ".", "Warning", JOptionPane.WARNING_MESSAGE); SettingsDialog.resetDefaultSettings(); } try { versionSite = new URL(SettingsDialog.settings().inventory.versionSite()); } catch (MalformedURLException e) { JOptionPane.showMessageDialog(this, "Bad version URL: " + SettingsDialog.settings().inventory.versionSite(), "Warning", JOptionPane.WARNING_MESSAGE); } try { inventorySite = new URL(SettingsDialog.settings().inventory.url() + ".zip"); } catch (MalformedURLException e) { JOptionPane.showMessageDialog(this, "Bad file URL: " + SettingsDialog.settings().inventory.url() + ".zip", "Warning", JOptionPane.WARNING_MESSAGE); } inventoryFile = new File(SettingsDialog.settings().inventory.path()); recentCount = SettingsDialog.settings().editor.recents.count; newestVersion = SettingsDialog.settings().inventory.version; setTitle("MTG Deck Editor"); setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); Dimension screenRes = Toolkit.getDefaultToolkit().getScreenSize(); setBounds(50, 50, screenRes.width - 100, screenRes.height - 100); /* MENU BAR */ JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); // File menu JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); // New file menu item JMenuItem newItem = new JMenuItem("New"); newItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_DOWN_MASK)); newItem.addActionListener((e) -> selectFrame(newEditor())); fileMenu.add(newItem); // Open file menu item JMenuItem openItem = new JMenuItem("Open..."); openItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_DOWN_MASK)); openItem.addActionListener((e) -> open()); fileMenu.add(openItem); // Close file menu item JMenuItem closeItem = new JMenuItem("Close"); closeItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_DOWN_MASK)); closeItem.addActionListener((e) -> selectedFrame.ifPresentOrElse((f) -> close(f), () -> exit())); fileMenu.add(closeItem); // Close all files menu item JMenuItem closeAllItem = new JMenuItem("Close All"); closeAllItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_DOWN_MASK|InputEvent.SHIFT_DOWN_MASK)); closeAllItem.addActionListener((e) -> closeAll()); fileMenu.add(closeAllItem); fileMenu.add(new JSeparator()); // Save file menu item JMenuItem saveItem = new JMenuItem("Save"); saveItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK)); saveItem.addActionListener((e) -> selectedFrame.ifPresent((f) -> save(f))); fileMenu.add(saveItem); // Save file as menu item JMenuItem saveAsItem = new JMenuItem("Save As..."); saveAsItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0)); saveAsItem.addActionListener((e) -> selectedFrame.ifPresent((f) -> saveAs(f))); fileMenu.add(saveAsItem); // Save all files menu item JMenuItem saveAllItem = new JMenuItem("Save All"); saveAllItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK|InputEvent.SHIFT_DOWN_MASK)); saveAllItem.addActionListener((e) -> saveAll()); fileMenu.add(saveAllItem); // Recent files menu recentsMenu = new JMenu("Open Recent"); recentsMenu.setEnabled(false); for (String fname : SettingsDialog.settings().editor.recents.files) updateRecents(new File(fname)); fileMenu.add(recentsMenu); fileMenu.add(new JSeparator()); // Import and export items final FileNameExtensionFilter text = new FileNameExtensionFilter("Text (*.txt)", "txt"); final FileNameExtensionFilter delimited = new FileNameExtensionFilter("Delimited (*.txt, *.csv)", "txt", "csv"); final FileNameExtensionFilter legacy = new FileNameExtensionFilter("Deck from v0.1 or older (*." + DeckDeserializer.EXTENSION + ')', DeckDeserializer.EXTENSION); JMenuItem importItem = new JMenuItem("Import..."); importItem.addActionListener((e) -> { JFileChooser importChooser = new JFileChooser(); importChooser.setAcceptAllFileFilterUsed(false); importChooser.addChoosableFileFilter(text); importChooser.addChoosableFileFilter(delimited); importChooser.addChoosableFileFilter(legacy); importChooser.setDialogTitle("Import"); importChooser.setCurrentDirectory(fileChooser.getCurrentDirectory()); switch (importChooser.showOpenDialog(this)) { case JFileChooser.APPROVE_OPTION: if (importChooser.getFileFilter() == legacy) { try { DeckSerializer manager = new DeckSerializer(); manager.importLegacy(importChooser.getSelectedFile(), this); selectFrame(newEditor(manager)); } catch (DeckLoadException x) { x.printStackTrace(); JOptionPane.showMessageDialog(this, "Error opening " + importChooser.getSelectedFile().getName() + ": " + x.getMessage() + ".", "Error", JOptionPane.ERROR_MESSAGE); } } else { CardListFormat format; if (importChooser.getFileFilter() == text) { format = new TextCardListFormat(""); } else if (importChooser.getFileFilter() == delimited) { JPanel dataPanel = new JPanel(new BorderLayout()); JPanel optionsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); optionsPanel.add(new JLabel("Delimiter: ")); var delimiterBox = new JComboBox<>(DelimitedCardListFormat.DELIMITERS); delimiterBox.setEditable(true); optionsPanel.add(delimiterBox); JCheckBox includeCheckBox = new JCheckBox("Read Headers"); includeCheckBox.setSelected(true); optionsPanel.add(includeCheckBox); dataPanel.add(optionsPanel, BorderLayout.NORTH); var headersList = new JList<>(CardAttribute.displayableValues()); headersList.setEnabled(!includeCheckBox.isSelected()); JScrollPane headersPane = new JScrollPane(headersList); JPanel headersPanel = new JPanel(); headersPanel.setLayout(new BoxLayout(headersPanel, BoxLayout.X_AXIS)); headersPanel.setBorder(BorderFactory.createTitledBorder("Column Data:")); VerticalButtonList rearrangeButtons = new VerticalButtonList(String.valueOf(UnicodeSymbols.UP_ARROW), String.valueOf(UnicodeSymbols.DOWN_ARROW)); for (JButton rearrange : rearrangeButtons) rearrange.setEnabled(!includeCheckBox.isSelected()); headersPanel.add(rearrangeButtons); headersPanel.add(Box.createHorizontalStrut(5)); var selectedHeadersModel = new DefaultListModel<CardAttribute>(); selectedHeadersModel.addElement(CardAttribute.NAME); selectedHeadersModel.addElement(CardAttribute.EXPANSION); selectedHeadersModel.addElement(CardAttribute.CARD_NUMBER); selectedHeadersModel.addElement(CardAttribute.COUNT); selectedHeadersModel.addElement(CardAttribute.DATE_ADDED); var selectedHeadersList = new JList<>(selectedHeadersModel); selectedHeadersList.setEnabled(!includeCheckBox.isSelected()); headersPanel.add(new JScrollPane(selectedHeadersList) { @Override public Dimension getPreferredSize() { return headersPane.getPreferredSize(); } }); headersPanel.add(Box.createHorizontalStrut(5)); VerticalButtonList moveButtons = new VerticalButtonList(String.valueOf(UnicodeSymbols.LEFT_ARROW), String.valueOf(UnicodeSymbols.RIGHT_ARROW)); for (JButton move : moveButtons) move.setEnabled(!includeCheckBox.isSelected()); headersPanel.add(moveButtons); headersPanel.add(Box.createHorizontalStrut(5)); headersPanel.add(headersPane); dataPanel.add(headersPanel, BorderLayout.CENTER); rearrangeButtons.get(String.valueOf(UnicodeSymbols.UP_ARROW)).addActionListener((v) -> { var selected = selectedHeadersList.getSelectedValuesList(); int ignore = 0; for (int index : selectedHeadersList.getSelectedIndices()) { if (index == ignore) { ignore++; continue; } CardAttribute temp = selectedHeadersModel.getElementAt(index - 1); selectedHeadersModel.setElementAt(selectedHeadersModel.getElementAt(index), index - 1); selectedHeadersModel.setElementAt(temp, index); } selectedHeadersList.clearSelection(); for (CardAttribute type : selected) { int index = selectedHeadersModel.indexOf(type); selectedHeadersList.addSelectionInterval(index, index); } }); rearrangeButtons.get(String.valueOf(UnicodeSymbols.DOWN_ARROW)).addActionListener((v) -> { var selected = selectedHeadersList.getSelectedValuesList(); var indices = Arrays.stream(selectedHeadersList.getSelectedIndices()).boxed().collect(Collectors.toList()); Collections.reverse(indices); int ignore = selectedHeadersModel.size() - 1; for (int index : indices) { if (index == ignore) { ignore--; continue; } CardAttribute temp = selectedHeadersModel.getElementAt(index + 1); selectedHeadersModel.setElementAt(selectedHeadersModel.getElementAt(index), index + 1); selectedHeadersModel.setElementAt(temp, index); } selectedHeadersList.clearSelection(); for (CardAttribute type : selected) { int index = selectedHeadersModel.indexOf(type); selectedHeadersList.addSelectionInterval(index, index); } }); moveButtons.get(String.valueOf(UnicodeSymbols.LEFT_ARROW)).addActionListener((v) -> { for (CardAttribute selected : headersList.getSelectedValuesList()) if (!selectedHeadersModel.contains(selected)) selectedHeadersModel.addElement(selected); headersList.clearSelection(); }); moveButtons.get(String.valueOf(UnicodeSymbols.RIGHT_ARROW)).addActionListener((v) -> { for (CardAttribute selected : new ArrayList<>(selectedHeadersList.getSelectedValuesList())) selectedHeadersModel.removeElement(selected); }); includeCheckBox.addActionListener((v) -> { headersList.setEnabled(!includeCheckBox.isSelected()); selectedHeadersList.setEnabled(!includeCheckBox.isSelected()); for (JButton rearrange : rearrangeButtons) rearrange.setEnabled(!includeCheckBox.isSelected()); for (JButton move : moveButtons) move.setEnabled(!includeCheckBox.isSelected()); }); JPanel previewPanel = new JPanel(new BorderLayout()); previewPanel.setBorder(BorderFactory.createTitledBorder("Data to Import:")); JTable previewTable = new JTable() { @Override public Dimension getPreferredScrollableViewportSize() { return new Dimension(0, 0); } @Override public boolean getScrollableTracksViewportWidth() { return getPreferredSize().width < getParent().getWidth(); } }; previewTable.setAutoCreateRowSorter(true); previewPanel.add(new JScrollPane(previewTable)); ActionListener updateTable = (v) -> { try { DefaultTableModel model = new DefaultTableModel(); var lines = Files.readAllLines(importChooser.getSelectedFile().toPath()); if (includeCheckBox.isSelected()) { String[] columns = lines.remove(0).split(String.valueOf(delimiterBox.getSelectedItem())); String[][] data = lines.stream().map((s) -> DelimitedCardListFormat.split(delimiterBox.getSelectedItem().toString(), s)).toArray(String[][]::new); model.setDataVector(data, columns); } else { CardAttribute[] columns = new CardAttribute[selectedHeadersModel.size()]; for (int i = 0; i < selectedHeadersModel.size(); i++) columns[i] = selectedHeadersModel.getElementAt(i); String[][] data = lines.stream().map((s) -> DelimitedCardListFormat.split(String.valueOf(delimiterBox.getSelectedItem()), s)).toArray(String[][]::new); model.setDataVector(data, columns); } previewTable.setModel(model); } catch (IOException x) { JOptionPane.showMessageDialog(this, "Could not import " + importChooser.getSelectedFile() + ": " + x.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } }; delimiterBox.addActionListener(updateTable); includeCheckBox.addActionListener(updateTable); for (JButton rearrange : rearrangeButtons) rearrange.addActionListener(updateTable); for (JButton move : moveButtons) move.addActionListener(updateTable); updateTable.actionPerformed(null); if (WizardDialog.showWizardDialog(this, "Import Wizard", dataPanel, previewPanel) == WizardDialog.FINISH_OPTION) { var selected = new ArrayList<CardAttribute>(selectedHeadersModel.size()); for (int i = 0; i < selectedHeadersModel.size(); i++) selected.add(selectedHeadersModel.getElementAt(i)); format = new DelimitedCardListFormat(String.valueOf(delimiterBox.getSelectedItem()), selected, !includeCheckBox.isSelected()); } else return; } else { JOptionPane.showMessageDialog(this, "Could not import " + importChooser.getSelectedFile() + '.', "Error", JOptionPane.ERROR_MESSAGE); return; } DeckSerializer manager = new DeckSerializer(); try { manager.importList(format, importChooser.getSelectedFile()); } catch (DeckLoadException x) { JOptionPane.showMessageDialog(this, "Could not import " + importChooser.getSelectedFile() + ": " + x.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } finally { selectFrame(newEditor(manager)); } } break; case JFileChooser.CANCEL_OPTION: break; case JFileChooser.ERROR_OPTION: JOptionPane.showMessageDialog(this, "Could not import " + importChooser.getSelectedFile() + '.', "Error", JOptionPane.ERROR_MESSAGE); break; } }); fileMenu.add(importItem); JMenuItem exportItem = new JMenuItem("Export..."); exportItem.addActionListener((e) -> selectedFrame.ifPresent((f) -> { JFileChooser exportChooser = new OverwriteFileChooser(); exportChooser.setAcceptAllFileFilterUsed(false); exportChooser.addChoosableFileFilter(text); exportChooser.addChoosableFileFilter(delimited); exportChooser.setDialogTitle("Export"); exportChooser.setCurrentDirectory(fileChooser.getCurrentDirectory()); switch (exportChooser.showSaveDialog(this)) { case JFileChooser.APPROVE_OPTION: CardListFormat format; if (exportChooser.getFileFilter() == text) { JPanel wizardPanel = new JPanel(new BorderLayout()); JPanel fieldPanel = new JPanel(new BorderLayout()); fieldPanel.setBorder(BorderFactory.createTitledBorder("List Format:")); JTextField formatField = new JTextField(TextCardListFormat.DEFAULT_FORMAT); formatField.setFont(new Font(Font.MONOSPACED, Font.PLAIN, formatField.getFont().getSize())); formatField.setColumns(50); fieldPanel.add(formatField, BorderLayout.CENTER); JPanel addDataPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); addDataPanel.add(new JLabel("Add Data: ")); var addDataBox = new JComboBox<>(CardAttribute.displayableValues()); addDataPanel.add(addDataBox); fieldPanel.add(addDataPanel, BorderLayout.SOUTH); wizardPanel.add(fieldPanel, BorderLayout.NORTH); if (f.getDeck().total() > 0 || f.getExtraCards().total() > 0) { JPanel previewPanel = new JPanel(new BorderLayout()); previewPanel.setBorder(BorderFactory.createTitledBorder("Preview:")); JTextArea previewArea = new JTextArea(); JScrollPane previewPane = new JScrollPane(previewArea); previewArea.setText(new TextCardListFormat(formatField.getText()) .format(f.getDeck().total() > 0 ? f.getDeck() : f.getExtraCards())); previewArea.setRows(1); previewArea.setCaretPosition(0); previewPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); previewPanel.add(previewPane, BorderLayout.CENTER); wizardPanel.add(previewPanel); addDataBox.addActionListener((v) -> { int pos = formatField.getCaretPosition(); String data = '{' + String.valueOf(addDataBox.getSelectedItem()).toLowerCase() + '}'; String t = formatField.getText().substring(0, pos) + data; if (pos < formatField.getText().length()) t += formatField.getText().substring(formatField.getCaretPosition()); formatField.setText(t); formatField.setCaretPosition(pos + data.length()); formatField.requestFocusInWindow(); }); formatField.getDocument().addDocumentListener(new DocumentChangeListener() { @Override public void update(DocumentEvent e) { previewArea.setText(new TextCardListFormat(formatField.getText()) .format(f.getDeck().total() > 0 ? f.getDeck() : f.getExtraCards())); previewArea.setCaretPosition(0); } }); } if (WizardDialog.showWizardDialog(this, "Export Wizard", wizardPanel) == WizardDialog.FINISH_OPTION) format = new TextCardListFormat(formatField.getText()); else return; } else if (exportChooser.getFileFilter() == delimited) { JPanel wizardPanel = new JPanel(new BorderLayout()); var headersList = new JList<>(CardAttribute.displayableValues()); JScrollPane headersPane = new JScrollPane(headersList); JPanel headersPanel = new JPanel(); headersPanel.setLayout(new BoxLayout(headersPanel, BoxLayout.X_AXIS)); headersPanel.setBorder(BorderFactory.createTitledBorder("Column Data:")); VerticalButtonList rearrangeButtons = new VerticalButtonList(String.valueOf(UnicodeSymbols.UP_ARROW), String.valueOf(UnicodeSymbols.DOWN_ARROW)); headersPanel.add(rearrangeButtons); headersPanel.add(Box.createHorizontalStrut(5)); var selectedHeadersModel = new DefaultListModel<CardAttribute>(); selectedHeadersModel.addElement(CardAttribute.NAME); selectedHeadersModel.addElement(CardAttribute.EXPANSION); selectedHeadersModel.addElement(CardAttribute.CARD_NUMBER); selectedHeadersModel.addElement(CardAttribute.COUNT); selectedHeadersModel.addElement(CardAttribute.DATE_ADDED); var selectedHeadersList = new JList<>(selectedHeadersModel); headersPanel.add(new JScrollPane(selectedHeadersList) { @Override public Dimension getPreferredSize() { return headersPane.getPreferredSize(); } }); headersPanel.add(Box.createHorizontalStrut(5)); VerticalButtonList moveButtons = new VerticalButtonList(String.valueOf(UnicodeSymbols.LEFT_ARROW), String.valueOf(UnicodeSymbols.RIGHT_ARROW)); headersPanel.add(moveButtons); headersPanel.add(Box.createHorizontalStrut(5)); headersPanel.add(headersPane); wizardPanel.add(headersPanel, BorderLayout.CENTER); rearrangeButtons.get(String.valueOf(UnicodeSymbols.UP_ARROW)).addActionListener((v) -> { var selected = selectedHeadersList.getSelectedValuesList(); int ignore = 0; for (int index : selectedHeadersList.getSelectedIndices()) { if (index == ignore) { ignore++; continue; } CardAttribute temp = selectedHeadersModel.getElementAt(index - 1); selectedHeadersModel.setElementAt(selectedHeadersModel.getElementAt(index), index - 1); selectedHeadersModel.setElementAt(temp, index); } selectedHeadersList.clearSelection(); for (CardAttribute type : selected) { int index = selectedHeadersModel.indexOf(type); selectedHeadersList.addSelectionInterval(index, index); } }); rearrangeButtons.get(String.valueOf(UnicodeSymbols.DOWN_ARROW)).addActionListener((v) -> { var selected = selectedHeadersList.getSelectedValuesList(); var indices = Arrays.stream(selectedHeadersList.getSelectedIndices()).boxed().collect(Collectors.toList()); Collections.reverse(indices); int ignore = selectedHeadersModel.size() - 1; for (int index : indices) { if (index == ignore) { ignore--; continue; } CardAttribute temp = selectedHeadersModel.getElementAt(index + 1); selectedHeadersModel.setElementAt(selectedHeadersModel.getElementAt(index), index + 1); selectedHeadersModel.setElementAt(temp, index); } selectedHeadersList.clearSelection(); for (CardAttribute type : selected) { int index = selectedHeadersModel.indexOf(type); selectedHeadersList.addSelectionInterval(index, index); } }); moveButtons.get(String.valueOf(UnicodeSymbols.LEFT_ARROW)).addActionListener((v) -> { for (CardAttribute selected : headersList.getSelectedValuesList()) if (!selectedHeadersModel.contains(selected)) selectedHeadersModel.addElement(selected); headersList.clearSelection(); }); moveButtons.get(String.valueOf(UnicodeSymbols.RIGHT_ARROW)).addActionListener((v) -> { for (CardAttribute selected : new ArrayList<>(selectedHeadersList.getSelectedValuesList())) selectedHeadersModel.removeElement(selected); }); JPanel optionsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); optionsPanel.add(new JLabel("Delimiter: ")); var delimiterBox = new JComboBox<>(DelimitedCardListFormat.DELIMITERS); delimiterBox.setEditable(true); optionsPanel.add(delimiterBox); JCheckBox includeCheckBox = new JCheckBox("Include Headers"); includeCheckBox.setSelected(true); optionsPanel.add(includeCheckBox); wizardPanel.add(optionsPanel, BorderLayout.SOUTH); if (WizardDialog.showWizardDialog(this, "Export Wizard", wizardPanel) == WizardDialog.FINISH_OPTION) { var selected = new ArrayList<CardAttribute>(selectedHeadersModel.size()); for (int i = 0; i < selectedHeadersModel.size(); i++) selected.add(selectedHeadersModel.getElementAt(i)); format = new DelimitedCardListFormat(String.valueOf(delimiterBox.getSelectedItem()), selected, includeCheckBox.isSelected()); } else return; } else { JOptionPane.showMessageDialog(this, "Could not export " + f.deckName() + '.', "Error", JOptionPane.ERROR_MESSAGE); return; } try { f.export(format, exportChooser.getSelectedFile()); } catch (UnsupportedEncodingException | FileNotFoundException x) { JOptionPane.showMessageDialog(this, "Could not export " + f.deckName() + ": " + x.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } break; case JFileChooser.CANCEL_OPTION: break; case JFileChooser.ERROR_OPTION: JOptionPane.showMessageDialog(this, "Could not export " + f.deckName() + '.', "Error", JOptionPane.ERROR_MESSAGE); break; } })); fileMenu.add(exportItem); fileMenu.add(new JSeparator()); // Exit menu item JMenuItem exitItem = new JMenuItem("Exit"); exitItem.addActionListener((e) -> exit()); exitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, InputEvent.ALT_DOWN_MASK)); fileMenu.add(exitItem); // File menu listener fileMenu.addMenuListener(MenuListenerFactory.createSelectedListener((e) -> { closeItem.setEnabled(selectedFrame.isPresent()); closeAllItem.setEnabled(!editors.isEmpty()); saveItem.setEnabled(selectedFrame.map(EditorFrame::getUnsaved).orElse(false)); saveAsItem.setEnabled(selectedFrame.isPresent()); saveAllItem.setEnabled(editors.stream().map(EditorFrame::getUnsaved).reduce(false, (a, b) -> a || b)); exportItem.setEnabled(selectedFrame.isPresent()); })); // Items are enabled while hidden so their listeners can be used fileMenu.addMenuListener(MenuListenerFactory.createDeselectedListener((e) -> { closeItem.setEnabled(true); closeAllItem.setEnabled(true); saveItem.setEnabled(true); saveAsItem.setEnabled(true); saveAllItem.setEnabled(true); exportItem.setEnabled(true); })); // Edit menu JMenu editMenu = new JMenu("Edit"); menuBar.add(editMenu); // Undo menu item JMenuItem undoItem = new JMenuItem("Undo"); undoItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, InputEvent.CTRL_DOWN_MASK)); undoItem.addActionListener((e) -> selectedFrame.ifPresent(EditorFrame::undo)); editMenu.add(undoItem); // Redo menu item JMenuItem redoItem = new JMenuItem("Redo"); redoItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, InputEvent.CTRL_DOWN_MASK)); redoItem.addActionListener((e) -> selectedFrame.ifPresent(EditorFrame::redo)); editMenu.add(redoItem); editMenu.add(new JSeparator()); // Preferences menu item JMenuItem preferencesItem = new JMenuItem("Preferences..."); preferencesItem.addActionListener((e) -> { SettingsDialog settings = new SettingsDialog(this); settings.setVisible(true); }); editMenu.add(preferencesItem); // Edit menu listener editMenu.addMenuListener(MenuListenerFactory.createSelectedListener((e) -> { undoItem.setEnabled(selectedFrame.isPresent()); redoItem.setEnabled(selectedFrame.isPresent()); })); // Items are enabled while hidden so their listeners can be used editMenu.addMenuListener(MenuListenerFactory.createDeselectedListener((e) -> { undoItem.setEnabled(true); redoItem.setEnabled(true); })); // Deck menu deckMenu = new JMenu("Deck"); deckMenu.setEnabled(false); menuBar.add(deckMenu); // Add/Remove card menus JMenu addMenu = new JMenu("Add Cards"); deckMenu.add(addMenu); JMenu removeMenu = new JMenu("Remove Cards"); deckMenu.add(removeMenu); CardMenuItems deckMenuCardItems = new CardMenuItems(() -> selectedFrame, this::getSelectedCards, true); deckMenuCardItems.addAddItems(addMenu); deckMenuCardItems.addRemoveItems(removeMenu); deckMenuCardItems.addSingle().setAccelerator(KeyStroke.getKeyStroke('+')); deckMenuCardItems.fillPlayset().setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.CTRL_DOWN_MASK)); deckMenuCardItems.removeSingle().setAccelerator(KeyStroke.getKeyStroke('-')); deckMenuCardItems.removeAll().setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, InputEvent.CTRL_DOWN_MASK)); // Sideboard menu JMenu sideboardMenu = new JMenu("Sideboard"); deckMenu.add(sideboardMenu); CardMenuItems sideboardMenuItems = new CardMenuItems(() -> selectedFrame, this::getSelectedCards, false); sideboardMenu.add(sideboardMenuItems.addSingle()); sideboardMenu.add(sideboardMenuItems.addN()); sideboardMenu.add(sideboardMenuItems.removeSingle()); sideboardMenu.add(sideboardMenuItems.removeAll()); // Category menu JMenu categoryMenu = new JMenu("Category"); deckMenu.add(categoryMenu); // Add category item JMenuItem addCategoryItem = new JMenuItem("Add..."); addCategoryItem.addActionListener((e) -> selectedFrame.ifPresent((f) -> f.createCategory().ifPresent(f::addCategory))); categoryMenu.add(addCategoryItem); // Edit category item JMenuItem editCategoryItem = new JMenuItem("Edit..."); editCategoryItem.addActionListener((e) -> selectedFrame.ifPresent((f) -> { JPanel contentPanel = new JPanel(new BorderLayout()); contentPanel.add(new JLabel("Choose a category to edit:"), BorderLayout.NORTH); var categories = new JList<>(f.getCategories().stream().map(CategorySpec::getName).sorted().toArray(String[]::new)); categories.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); contentPanel.add(new JScrollPane(categories), BorderLayout.CENTER); if (JOptionPane.showConfirmDialog(this, contentPanel, "Edit Category", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) == JOptionPane.OK_OPTION) f.editCategory(categories.getSelectedValue()); })); categoryMenu.add(editCategoryItem); // Remove category item JMenuItem removeCategoryItem = new JMenuItem("Remove..."); removeCategoryItem.addActionListener((e) -> selectedFrame.ifPresent((f) -> { JPanel contentPanel = new JPanel(new BorderLayout()); contentPanel.add(new JLabel("Choose a category to remove:"), BorderLayout.NORTH); var categories = new JList<>(f.getCategories().stream().map(CategorySpec::getName).sorted().toArray(String[]::new)); categories.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); contentPanel.add(new JScrollPane(categories), BorderLayout.CENTER); if (JOptionPane.showConfirmDialog(this, contentPanel, "Edit Category", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) == JOptionPane.OK_OPTION) f.removeCategory(categories.getSelectedValue()); })); categoryMenu.add(removeCategoryItem); // Preset categories menu presetMenu = new JMenu("Add Preset"); categoryMenu.add(presetMenu); // Deck menu listener deckMenu.addMenuListener(MenuListenerFactory.createSelectedListener((e) -> { addMenu.setEnabled(selectedFrame.isPresent() && !selectedCards.isEmpty()); removeMenu.setEnabled(selectedFrame.isPresent() && !selectedCards.isEmpty()); sideboardMenu.setEnabled(selectedFrame.map((f) -> f.getSelectedExtraName() != null).orElse(false) && !selectedCards.isEmpty()); presetMenu.setEnabled(presetMenu.getMenuComponentCount() > 0); })); // Items are enabled while hidden so their listeners can be used. deckMenu.addMenuListener(MenuListenerFactory.createDeselectedListener((e) -> { addMenu.setEnabled(true); removeMenu.setEnabled(true); })); // Help menu JMenu helpMenu = new JMenu("Help"); menuBar.add(helpMenu); // Inventory update item JMenuItem updateInventoryItem = new JMenuItem("Check for inventory update..."); updateInventoryItem.addActionListener((e) -> { switch (checkForUpdate(UpdateFrequency.DAILY)) { case UPDATE_NEEDED: if (updateInventory()) { SettingsDialog.setInventoryVersion(newestVersion); loadInventory(); } break; case NO_UPDATE: JOptionPane.showMessageDialog(this, "Inventory is up to date."); break; case UPDATE_CANCELLED: break; default: break; } }); helpMenu.add(updateInventoryItem); // Reload inventory item JMenuItem reloadInventoryItem = new JMenuItem("Reload inventory..."); reloadInventoryItem.addActionListener((e) -> loadInventory()); helpMenu.add(reloadInventoryItem); helpMenu.add(new JSeparator()); // Show expansions item JMenuItem showExpansionsItem = new JMenuItem("Show Expansions..."); showExpansionsItem.addActionListener((e) -> { TableModel expansionTableModel = new AbstractTableModel() { private final String[] columns = { "Expansion", "Block", "Code", "magiccards.info", "Gatherer" }; @Override public int getColumnCount() { return 5; } @Override public String getColumnName(int index) { return columns[index]; } @Override public int getRowCount() { return Expansion.expansions.length; } @Override public Object getValueAt(int rowIndex, int columnIndex) { final Object[] values = { Expansion.expansions[rowIndex].name, Expansion.expansions[rowIndex].block, Expansion.expansions[rowIndex].code, Expansion.expansions[rowIndex].magicCardsInfoCode, Expansion.expansions[rowIndex].gathererCode }; return values[columnIndex]; } }; JTable expansionTable = new JTable(expansionTableModel); expansionTable.setShowGrid(false); expansionTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); expansionTable.setAutoCreateRowSorter(true); expansionTable.setPreferredScrollableViewportSize(new Dimension(600, expansionTable.getPreferredScrollableViewportSize().height)); JOptionPane.showMessageDialog(this, new JScrollPane(expansionTable), "Expansions", JOptionPane.PLAIN_MESSAGE); }); helpMenu.add(showExpansionsItem); /* CONTENT PANE */ // Panel containing all content JPanel contentPane = new JPanel(new BorderLayout()); contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, InputEvent.CTRL_DOWN_MASK), "Next Frame"); contentPane.getActionMap().put("Next Frame", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { if (!editors.isEmpty()) selectedFrame.ifPresentOrElse((f) -> selectFrame(editors.get((editors.indexOf(f) + 1)%editors.size())), () -> selectFrame(editors.get(editors.size() - 1))); } }); contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, InputEvent.CTRL_DOWN_MASK), "Previous Frame"); contentPane.getActionMap().put("Previous Frame", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { if (!editors.isEmpty()) { int next = selectedFrame.map((f) -> editors.indexOf(f) - 1).orElse(0); selectFrame(editors.get(next < 0 ? editors.size() - 1 : next)); } } }); setContentPane(contentPane); // DesktopPane containing editor frames decklistDesktop = new JDesktopPane(); decklistDesktop.setBackground(SystemColor.controlShadow); JTabbedPane cardPane = new JTabbedPane(); // Panel showing the image of the currently-selected card cardPane.addTab("Image", imagePanel = new CardImagePanel()); setImageBackground(SettingsDialog.settings().inventory.background); // Pane displaying the Oracle text oracleTextPane = new JTextPane(); oracleTextPane.setEditable(false); oracleTextPane.setCursor(new Cursor(Cursor.TEXT_CURSOR)); cardPane.addTab("Oracle Text", new JScrollPane(oracleTextPane)); printedTextPane = new JTextPane(); printedTextPane.setEditable(false); printedTextPane.setCursor(new Cursor(Cursor.TEXT_CURSOR)); cardPane.addTab("Printed Text", new JScrollPane(printedTextPane)); rulingsPane = new JTextPane(); rulingsPane.setEditable(false); rulingsPane.setCursor(new Cursor(Cursor.TEXT_CURSOR)); cardPane.addTab("Rulings", new JScrollPane(rulingsPane)); // Oracle text pane popup menu JPopupMenu oraclePopupMenu = new JPopupMenu(); oracleTextPane.setComponentPopupMenu(oraclePopupMenu); printedTextPane.setComponentPopupMenu(oraclePopupMenu); imagePanel.setComponentPopupMenu(oraclePopupMenu); // Add the card to the main deck CardMenuItems oracleMenuCardItems = new CardMenuItems(() -> selectedFrame, () -> Arrays.asList(selectedCards.get(0)), true); oracleMenuCardItems.addAddItems(oraclePopupMenu); oraclePopupMenu.add(new JSeparator()); oracleMenuCardItems.addRemoveItems(oraclePopupMenu); oraclePopupMenu.add(new JSeparator()); // Add the card to the sideboard CardMenuItems oracleMenuSBCardItems = new CardMenuItems(() -> selectedFrame, () -> Arrays.asList(selectedCards.get(0)), false); oracleMenuSBCardItems.addSingle().setText("Add to Sideboard"); oraclePopupMenu.add(oracleMenuSBCardItems.addSingle()); oracleMenuSBCardItems.addN().setText("Add to Sideboard..."); oraclePopupMenu.add(oracleMenuSBCardItems.addN()); oracleMenuSBCardItems.removeSingle().setText("Remove from Sideboard"); oraclePopupMenu.add(oracleMenuSBCardItems.removeSingle()); oracleMenuSBCardItems.removeAll().setText("Remove All from Sideboard"); oraclePopupMenu.add(oracleMenuSBCardItems.removeAll()); oraclePopupMenu.add(new JSeparator()); JMenuItem oracleEditTagsItem = new JMenuItem("Edit Tags..."); oracleEditTagsItem.addActionListener((e) -> CardTagPanel.editTags(getSelectedCards(), this)); oraclePopupMenu.add(oracleEditTagsItem); // Popup listener for oracle popup menu oraclePopupMenu.addPopupMenuListener(PopupMenuListenerFactory.createVisibleListener((e) -> { for (JMenuItem item : oracleMenuCardItems) item.setEnabled(selectedFrame.isPresent() && !selectedCards.isEmpty()); for (JMenuItem item : oracleMenuSBCardItems) item.setEnabled(selectedFrame.isPresent() && !selectedCards.isEmpty()); oracleEditTagsItem.setEnabled(!selectedCards.isEmpty()); })); // Panel containing inventory and image of currently-selected card JPanel inventoryPanel = new JPanel(new BorderLayout(0, 0)); inventoryPanel.setPreferredSize(new Dimension(getWidth()/4, getHeight()*3/4)); // Panel containing the inventory and the quick-filter bar JPanel tablePanel = new JPanel(new BorderLayout(0, 0)); inventoryPanel.add(tablePanel, BorderLayout.CENTER); // Panel containing the quick-filter bar JPanel filterPanel = new JPanel(); filterPanel.setLayout(new BoxLayout(filterPanel, BoxLayout.X_AXIS)); // Text field for quickly filtering by name JTextField nameFilterField = new JTextField(); filterPanel.add(nameFilterField); // Button for clearing the filter JButton clearButton = new JButton("X"); filterPanel.add(clearButton); // Button for opening the advanced filter dialog JButton advancedFilterButton = new JButton("Advanced..."); filterPanel.add(advancedFilterButton); tablePanel.add(filterPanel, BorderLayout.NORTH); // Create the inventory and put it in the table inventoryTable = new CardTable(); inventoryTable.setDefaultRenderer(String.class, new InventoryTableCellRenderer()); inventoryTable.setDefaultRenderer(Integer.class, new InventoryTableCellRenderer()); inventoryTable.setDefaultRenderer(Rarity.class, new InventoryTableCellRenderer()); inventoryTable.setDefaultRenderer(List.class, new InventoryTableCellRenderer()); inventoryTable.setStripeColor(SettingsDialog.settings().inventory.stripe); inventoryTable.addMouseListener(MouseListenerFactory.createClickListener((e) -> selectedFrame.ifPresent((f) -> { if (e.getClickCount() % 2 == 0) f.addCards("", getSelectedCards(), 1); }))); inventoryTable.setTransferHandler(new TransferHandler() { @Override public boolean canImport(TransferHandler.TransferSupport support) { return false; } @Override protected Transferable createTransferable(JComponent c) { return new Inventory.TransferData(getSelectedCards()); } @Override public int getSourceActions(JComponent c) { return TransferHandler.COPY; } }); inventoryTable.setDragEnabled(true); tablePanel.add(new JScrollPane(inventoryTable), BorderLayout.CENTER); // Table popup menu JPopupMenu inventoryMenu = new JPopupMenu(); inventoryTable.addMouseListener(new TableMouseAdapter(inventoryTable, inventoryMenu)); // Add cards to the main deck CardMenuItems inventoryMenuCardItems = new CardMenuItems(() -> selectedFrame, this::getSelectedCards, true); inventoryMenuCardItems.addAddItems(inventoryMenu); inventoryMenu.add(new JSeparator()); inventoryMenuCardItems.addRemoveItems(inventoryMenu); inventoryMenu.add(new JSeparator()); // Add cards to the sideboard CardMenuItems inventoryMenuSBItems = new CardMenuItems(() -> selectedFrame, this::getSelectedCards, false); inventoryMenuSBItems.addSingle().setText("Add to Sideboard"); inventoryMenu.add(inventoryMenuSBItems.addSingle()); inventoryMenuSBItems.addN().setText("Add to Sideboard..."); inventoryMenu.add(inventoryMenuSBItems.addN()); inventoryMenuSBItems.removeSingle().setText("Remove from Sideboard"); inventoryMenu.add(inventoryMenuSBItems.removeSingle()); inventoryMenuSBItems.removeAll().setText("Remove All from Sideboard"); inventoryMenu.add(inventoryMenuSBItems.removeAll()); inventoryMenu.add(new JSeparator()); // Edit tags item JMenuItem editTagsItem = new JMenuItem("Edit Tags..."); editTagsItem.addActionListener((e) -> CardTagPanel.editTags(getSelectedCards(), this)); inventoryMenu.add(editTagsItem); // Inventory menu listener inventoryMenu.addPopupMenuListener(PopupMenuListenerFactory.createVisibleListener((e) -> { for (JMenuItem item : inventoryMenuCardItems) item.setEnabled(selectedFrame.isPresent() && !selectedCards.isEmpty()); for (JMenuItem item : inventoryMenuSBItems) item.setEnabled(selectedFrame.isPresent() && !selectedCards.isEmpty()); editTagsItem.setEnabled(!selectedCards.isEmpty()); })); // Action to be taken when the user presses the Enter key after entering text into the quick-filter // bar nameFilterField.addActionListener((e) -> { inventory.updateFilter(TextFilter.createQuickFilter(CardAttribute.NAME, nameFilterField.getText().toLowerCase())); inventoryModel.fireTableDataChanged(); }); // Action to be taken when the clear button is pressed (reset the filter) clearButton.addActionListener((e) -> { nameFilterField.setText(""); inventory.updateFilter(CardAttribute.createFilter(CardAttribute.ANY)); inventoryModel.fireTableDataChanged(); }); // Action to be taken when the advanced filter button is pressed (show the advanced filter // dialog) advancedFilterButton.addActionListener((e) -> { FilterGroupPanel panel = new FilterGroupPanel(); if (inventory.getFilter().equals(CardAttribute.createFilter(CardAttribute.ANY))) panel.setContents(CardAttribute.createFilter(CardAttribute.NAME)); else panel.setContents(inventory.getFilter()); panel.addChangeListener((c) -> SwingUtilities.getWindowAncestor((Component)c.getSource()).pack()); ScrollablePanel panelPanel = new ScrollablePanel(new BorderLayout(), ScrollablePanel.TRACK_WIDTH) { @Override public Dimension getPreferredScrollableViewportSize() { Dimension size = panel.getPreferredSize(); size.height = Math.min(MAX_FILTER_HEIGHT, size.height); return size; } }; panelPanel.add(panel, BorderLayout.CENTER); JScrollPane panelPane = new JScrollPane(panelPanel); panelPane.setBorder(BorderFactory.createEmptyBorder()); if (JOptionPane.showConfirmDialog(this, panelPane, "Advanced Filter", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) == JOptionPane.OK_OPTION) { nameFilterField.setText(""); inventory.updateFilter(panel.filter()); inventoryModel.fireTableDataChanged(); } }); // Action to be taken when a selection is made in the inventory table (update the relevant // panels) inventoryTable.getSelectionModel().addListSelectionListener((e) -> { if (!e.getValueIsAdjusting()) { ListSelectionModel lsm = (ListSelectionModel)e.getSource(); if (!lsm.isSelectionEmpty()) setSelectedCards(inventoryTable, inventory); } }); // Split panes dividing the panel into three sections. They can be resized at will. JSplitPane inventorySplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, cardPane, inventoryPanel); inventorySplit.setOneTouchExpandable(true); inventorySplit.setContinuousLayout(true); SwingUtilities.invokeLater(() -> inventorySplit.setDividerLocation(DEFAULT_CARD_HEIGHT)); JSplitPane editorSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, inventorySplit, decklistDesktop); editorSplit.setOneTouchExpandable(true); editorSplit.setContinuousLayout(true); contentPane.add(editorSplit, BorderLayout.CENTER); // File chooser fileChooser = new OverwriteFileChooser(SettingsDialog.settings().cwd); fileChooser.setMultiSelectionEnabled(false); fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Deck (*.json)", "json")); fileChooser.setAcceptAllFileFilterUsed(true); // Handle what happens when the window tries to close and when it opens. addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { exit(); } @Override public void windowOpened(WindowEvent e) { if (checkForUpdate(SettingsDialog.settings().inventory.update) == UPDATE_NEEDED && updateInventory()) SettingsDialog.setInventoryVersion(newestVersion); loadInventory(); if (!inventory.isEmpty()) { for (CategorySpec spec : SettingsDialog.settings().editor.categories.presets) { JMenuItem categoryItem = new JMenuItem(spec.getName()); categoryItem.addActionListener((v) -> selectedFrame.ifPresent((f) -> f.addCategory(spec))); presetMenu.add(categoryItem); } for (File f : files) open(f); } } }); } /** * Add a new preset category to the preset categories list. * * @param category new preset category to add */ public void addPreset(CategorySpec category) { CategorySpec spec = new CategorySpec(category); spec.getBlacklist().clear(); spec.getWhitelist().clear(); SettingsDialog.addPresetCategory(spec); JMenuItem categoryItem = new JMenuItem(spec.getName()); categoryItem.addActionListener((e) -> selectedFrame.ifPresent((f) -> f.addCategory(spec))); presetMenu.add(categoryItem); } /** * Apply the global settings. */ public void applySettings() { try { inventorySite = new URL(SettingsDialog.settings().inventory.url() + ".zip"); } catch (MalformedURLException e) { JOptionPane.showMessageDialog(this, "Bad file URL: " + SettingsDialog.settings().inventory.url() + ".zip", "Warning", JOptionPane.WARNING_MESSAGE); } inventoryFile = new File(SettingsDialog.settings().inventory.path()); recentCount = SettingsDialog.settings().editor.recents.count; inventoryModel.setColumns(SettingsDialog.settings().inventory.columns); inventoryTable.setStripeColor(SettingsDialog.settings().inventory.stripe); for (EditorFrame frame : editors) frame.applySettings(); presetMenu.removeAll(); for (CategorySpec spec : SettingsDialog.settings().editor.categories.presets) { JMenuItem categoryItem = new JMenuItem(spec.getName()); categoryItem.addActionListener((e) -> selectedFrame.ifPresent((f) -> f.addCategory(spec))); presetMenu.add(categoryItem); } setImageBackground(SettingsDialog.settings().inventory.background); setHandBackground(SettingsDialog.settings().editor.hand.background); revalidate(); repaint(); } /** * Check to see if the inventory needs to be updated. If it does, ask the user if it should be. * * @param freq desired frequency for downloading updates * @return an integer value representing the state of the update. It can be: * {@link #UPDATE_NEEDED} * {@link #NO_UPDATE} * {@link #UPDATE_CANCELLED} */ public int checkForUpdate(UpdateFrequency freq) { try { if (!inventoryFile.exists()) { JOptionPane.showMessageDialog(this, inventoryFile.getName() + " not found. It will be downloaded.", "Update", JOptionPane.WARNING_MESSAGE); try (BufferedReader in = new BufferedReader(new InputStreamReader(versionSite.openStream()))) { newestVersion = new DatabaseVersion(new JsonParser().parse(in.lines().collect(Collectors.joining())).getAsJsonObject().get("version").getAsString()); } return UPDATE_NEEDED; } else if (SettingsDialog.settings().inventory.update != UpdateFrequency.NEVER) { try (BufferedReader in = new BufferedReader(new InputStreamReader(versionSite.openStream()))) { newestVersion = new DatabaseVersion(new JsonParser().parse(in.lines().collect(Collectors.joining())).getAsJsonObject().get("version").getAsString()); } if (newestVersion.needsUpdate(SettingsDialog.settings().inventory.version, freq)) { int wantUpdate = JOptionPane.showConfirmDialog( this, "Inventory is out of date:\n" + UnicodeSymbols.BULLET + " Current version: " + SettingsDialog.settings().inventory.version + "\n" + UnicodeSymbols.BULLET + " Latest version: " + newestVersion + "\n" + "\n" + "Download update?", "Update", JOptionPane.YES_NO_OPTION ); return wantUpdate == JOptionPane.YES_OPTION ? UPDATE_NEEDED : UPDATE_CANCELLED; } } } catch (IOException e) { JOptionPane.showMessageDialog(this, "Error connecting to server: " + e.getMessage() + ".", "Connection Error", JOptionPane.ERROR_MESSAGE); } catch (ParseException e) { JOptionPane.showMessageDialog(this, "Could not parse version \"" + e.getMessage() + '"', "Error", JOptionPane.ERROR_MESSAGE); } return NO_UPDATE; } /** * Attempt to close the specified frame. * * @param frame frame to close * @return true if the frame was closed, and false otherwise. */ public boolean close(EditorFrame frame) { if (!editors.contains(frame) || !frame.close()) return false; else { if (frame.hasSelectedCards()) { selectedCards = Collections.emptyList(); selectedTable = Optional.empty(); selectedList = Optional.empty(); } editors.remove(frame); if (editors.size() > 0) selectFrame(editors.get(0)); else { selectedFrame = Optional.empty(); deckMenu.setEnabled(false); } revalidate(); repaint(); return true; } } /** * Attempts to close all of the open editors. If any can't be closed for * whatever reason, they will remain open, but the rest will still be closed. * * @return true if all open editors were successfully closed, and false otherwise. */ public boolean closeAll() { var e = new ArrayList<>(editors); boolean closedAll = true; for (EditorFrame editor : e) closedAll &= close(editor); return closedAll; } /** * Exit the application if all open editors successfully close. */ public void exit() { if (closeAll()) { saveSettings(); System.exit(0); } } /** * @param id multiverseid of the #Card to look for * @return the #Card with the given multiverseid. */ public Card getCard(long id) { return inventory.get(id); } /** * Get the currently-selected card(s). * * @return a List containing each currently-selected card in the inventory table. */ public List<Card> getSelectedCards() { return selectedCards; } /** * Get the list corresponding to the table with the currently-selected cards. * * @return the list containing the currently selected cards */ public Optional<CardList> getSelectedList() { return selectedList; } /** * Get the table containing the currently selected cards. * * @return the table with the selected cards */ public Optional<CardTable> getSelectedTable() { return selectedTable; } /** * Check whether or not the inventory has a selection. * * @return true if the inventory has a selection, and false otherwise. */ public boolean hasSelectedCards() { return selectedTable.filter((f) -> f == inventoryTable).isPresent(); } /** * Load the inventory and initialize the inventory table. * * @see InventoryLoadDialog */ public void loadInventory() { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); InventoryLoadDialog loadDialog = new InventoryLoadDialog(this); loadDialog.setLocationRelativeTo(this); inventory = loadDialog.createInventory(inventoryFile); inventory.sort(Card::compareName); inventoryModel = new CardTableModel(inventory, SettingsDialog.settings().inventory.columns); inventoryTable.setModel(inventoryModel); setCursor(Cursor.getDefaultCursor()); } /** * Create a new editor frame. It will not be visible or selected. * * @param manager file manager containing the deck to display * * @see EditorFrame */ public EditorFrame newEditor(DeckSerializer manager) { EditorFrame frame = new EditorFrame(this, ++untitled, manager); editors.add(frame); decklistDesktop.add(frame); return frame; } /** * Create a new editor frame. It will not be visible or selected. * * @see EditorFrame */ public EditorFrame newEditor() { return newEditor(new DeckSerializer()); } /** * Open the file chooser to select a file, and if a file was selected, * parse it and initialize a Deck from it. * * @return the EditorFrame containing the opened deck */ public EditorFrame open() { EditorFrame frame = null; switch (fileChooser.showOpenDialog(this)) { case JFileChooser.APPROVE_OPTION: frame = open(fileChooser.getSelectedFile()); if (frame != null) updateRecents(fileChooser.getSelectedFile()); break; case JFileChooser.CANCEL_OPTION: case JFileChooser.ERROR_OPTION: break; default: break; } return frame; } /** * Open the specified file and create an editor for it. * * @return the EditorFrame containing the opened deck, or <code>null</code> * if opening was canceled. */ public EditorFrame open(File f) { EditorFrame frame = null; for (EditorFrame e : editors) { if (e.file() != null && e.file().equals(f)) { frame = e; break; } } boolean canceled = false; if (frame == null) { DeckSerializer manager = new DeckSerializer(); try { manager.load(f, this); } catch (CancellationException e) { canceled = true; } catch (DeckLoadException e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "Error opening " + f.getName() + ": " + e.getMessage() + ".", "Error", JOptionPane.ERROR_MESSAGE); } finally { if (!canceled) frame = newEditor(manager); } } if (!canceled) { SettingsDialog.setStartingDir(f.getParent()); fileChooser.setCurrentDirectory(f.getParentFile()); selectFrame(frame); } return frame; } /** * If specified editor frame has a file associated with it, save * it to that file. Otherwise, open the file dialog and save it * to whatever is chosen (save as). * * @param frame #EditorFrame to save */ public void save(EditorFrame frame) { if (!frame.save()) saveAs(frame); } /** * Attempt to save all open editors. For each that needs a file, ask for a file * to save to. */ public void saveAll() { for (EditorFrame editor : editors) save(editor); } /** * Save the specified editor frame to a file chosen from a {@link JFileChooser}. * * @param frame frame to save. */ public void saveAs(EditorFrame frame) { switch (fileChooser.showSaveDialog(this)) { case JFileChooser.APPROVE_OPTION: File f = fileChooser.getSelectedFile(); String fname = f.getAbsolutePath(); if (!fname.endsWith(".json")) f = new File(fname + ".json"); frame.save(f); updateRecents(f); break; case JFileChooser.CANCEL_OPTION: break; case JFileChooser.ERROR_OPTION: JOptionPane.showMessageDialog(this, "Could not save " + frame.deckName() + '.', "Error", JOptionPane.ERROR_MESSAGE); break; } SettingsDialog.setStartingDir(fileChooser.getCurrentDirectory().getPath()); } /** * Write the latest values of the settings to the settings file. */ public void saveSettings() { SettingsDialog.setRecents(recentItems.stream().map((i) -> recents.get(i).getPath()).collect(Collectors.toList())); try (FileOutputStream out = new FileOutputStream(SettingsDialog.PROPERTIES_FILE)) { SettingsDialog.save(); } catch (IOException e) { JOptionPane.showMessageDialog(this, "Error writing " + SettingsDialog.PROPERTIES_FILE + ": " + e.getMessage() + ".", "Error", JOptionPane.ERROR_MESSAGE); } } /** * Set the currently-active frame. This is the one that will be operated on * when single-deck actions are taken from the main frame, such as saving * and closing. * * @param frame #EditorFrame to operate on from now on */ public void selectFrame(EditorFrame frame) { try { frame.setSelected(true); frame.setVisible(true); deckMenu.setEnabled(true); selectedFrame = Optional.of(frame); revalidate(); repaint(); } catch (PropertyVetoException e) {} } /** * Set the background color of the editor panels containing sample hands. * * @param col new color for sample hand panels. */ public void setHandBackground(Color col) { for (EditorFrame frame : editors) frame.setHandBackground(col); } /** * Set the selected cards from the given table backed by the given card list. Make sure * the list and the table represent the same set of cards! * * @param table table with a selection to get the selected cards from * @param list list backing the given table */ public void setSelectedCards(CardTable table, CardList list) { selectedTable = Optional.of(table); selectedList = Optional.of(list); selectedCards = Collections.unmodifiableList(Arrays.stream(table.getSelectedRows()) .mapToObj((r) -> list.get(table.convertRowIndexToModel(r))) .collect(Collectors.toList())); if (!selectedCards.isEmpty()) { final Card card = selectedCards.get(0); oracleTextPane.setText(""); StyledDocument oracleDocument = (StyledDocument)oracleTextPane.getDocument(); Style oracleTextStyle = oracleDocument.addStyle("text", null); StyleConstants.setFontFamily(oracleTextStyle, UIManager.getFont("Label.font").getFamily()); StyleConstants.setFontSize(oracleTextStyle, ComponentUtils.TEXT_SIZE); Style reminderStyle = oracleDocument.addStyle("reminder", oracleTextStyle); StyleConstants.setItalic(reminderStyle, true); card.formatDocument(oracleDocument, false); oracleTextPane.setCaretPosition(0); printedTextPane.setText(""); StyledDocument printedDocument = (StyledDocument)printedTextPane.getDocument(); Style printedTextStyle = printedDocument.addStyle("text", null); StyleConstants.setFontFamily(printedTextStyle, UIManager.getFont("Label.font").getFamily()); StyleConstants.setFontSize(printedTextStyle, ComponentUtils.TEXT_SIZE); reminderStyle = printedDocument.addStyle("reminder", oracleTextStyle); StyleConstants.setItalic(reminderStyle, true); card.formatDocument(printedDocument, true); printedTextPane.setCaretPosition(0); rulingsPane.setText(""); DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); StyledDocument rulingsDocument = (StyledDocument)rulingsPane.getDocument(); Style rulingStyle = oracleDocument.addStyle("ruling", null); StyleConstants.setFontFamily(rulingStyle, UIManager.getFont("Label.font").getFamily()); StyleConstants.setFontSize(rulingStyle, ComponentUtils.TEXT_SIZE); Style dateStyle = rulingsDocument.addStyle("date", rulingStyle); StyleConstants.setBold(dateStyle, true); if (!card.rulings().isEmpty()) { try { for (Date date : card.rulings().keySet()) { for (String ruling : card.rulings().get(date)) { rulingsDocument.insertString(rulingsDocument.getLength(), String.valueOf(UnicodeSymbols.BULLET) + " ", rulingStyle); rulingsDocument.insertString(rulingsDocument.getLength(), format.format(date), dateStyle); rulingsDocument.insertString(rulingsDocument.getLength(), ": ", rulingStyle); int start = 0; for (int i = 0; i < ruling.length(); i++) { switch (ruling.charAt(i)) { case '{': rulingsDocument.insertString(rulingsDocument.getLength(), ruling.substring(start, i), rulingStyle); start = i + 1; break; case '}': Symbol symbol = Symbol.tryParseSymbol(ruling.substring(start, i)); if (symbol == null) { System.err.println("Unexpected symbol {" + ruling.substring(start, i) + "} in ruling for " + card.unifiedName() + "."); rulingsDocument.insertString(rulingsDocument.getLength(), ruling.substring(start, i), rulingStyle); } else { Style symbolStyle = rulingsDocument.addStyle(symbol.toString(), null); StyleConstants.setIcon(symbolStyle, symbol.getIcon(ComponentUtils.TEXT_SIZE)); rulingsDocument.insertString(rulingsDocument.getLength(), " ", symbolStyle); } start = i + 1; break; default: break; } if (i == ruling.length() - 1 && ruling.charAt(i) != '}') rulingsDocument.insertString(rulingsDocument.getLength(), ruling.substring(start, i + 1) + '\n', rulingStyle); } } } } catch (BadLocationException e) { e.printStackTrace(); } } rulingsPane.setCaretPosition(0); imagePanel.setCard(card); } if (table != inventoryTable) inventoryTable.clearSelection(); for (EditorFrame editor : editors) editor.clearTableSelections(table); } /** * Set the background color of the panel containing the card image. * * @param col new color for the card image panel */ public void setImageBackground(Color col) { imagePanel.setBackground(col); } /** * Update the inventory table to bold the cards that are in the currently-selected editor. */ public void updateCardsInDeck() { inventoryModel.fireTableDataChanged(); } /** * Download the latest list of cards from the inventory site (default mtgjson.com). If the * download is taking a while, a progress bar will appear. * * @return true if the download was successful, and false otherwise. */ public boolean updateInventory() { InventoryDownloadDialog downloadDialog = new InventoryDownloadDialog(this); downloadDialog.setLocationRelativeTo(this); return downloadDialog.downloadInventory(inventorySite, inventoryFile); } /** * Update the recently-opened files to add the most recently-opened one, and delete * the oldest one if too many are there. * * @param f #File to add to the list */ public void updateRecents(File f) { if (!recents.containsValue(f)) { recentsMenu.setEnabled(true); if (recentItems.size() >= recentCount) { JMenuItem eldest = recentItems.poll(); recents.remove(eldest); recentsMenu.remove(eldest); } JMenuItem mostRecent = new JMenuItem(f.getPath()); recentItems.offer(mostRecent); recents.put(mostRecent, f); mostRecent.addActionListener((e) -> open(f)); recentsMenu.add(mostRecent); } } }
src/main/java/editor/gui/MainFrame.java
package editor.gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.SystemColor; import java.awt.Toolkit; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyVetoException; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Files; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Queue; import java.util.concurrent.CancellationException; import java.util.stream.Collectors; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDesktopPane; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.ScrollPaneConstants; import javax.swing.SwingUtilities; import javax.swing.TransferHandler; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.WindowConstants; import javax.swing.event.DocumentEvent; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import javax.swing.text.BadLocationException; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.JsonParser; import editor.collection.CardList; import editor.collection.Inventory; import editor.collection.deck.CategorySpec; import editor.collection.deck.Deck; import editor.collection.export.CardListFormat; import editor.collection.export.DelimitedCardListFormat; import editor.collection.export.TextCardListFormat; import editor.database.attributes.CardAttribute; import editor.database.attributes.Expansion; import editor.database.attributes.Rarity; import editor.database.card.Card; import editor.database.symbol.Symbol; import editor.database.version.DatabaseVersion; import editor.database.version.UpdateFrequency; import editor.filter.Filter; import editor.filter.leaf.TextFilter; import editor.gui.display.CardImagePanel; import editor.gui.display.CardTable; import editor.gui.display.CardTableCellRenderer; import editor.gui.display.CardTableModel; import editor.gui.editor.DeckLoadException; import editor.gui.editor.DeckSerializer; import editor.gui.editor.EditorFrame; import editor.gui.filter.FilterGroupPanel; import editor.gui.generic.CardMenuItems; import editor.gui.generic.ComponentUtils; import editor.gui.generic.DocumentChangeListener; import editor.gui.generic.OverwriteFileChooser; import editor.gui.generic.ScrollablePanel; import editor.gui.generic.TableMouseAdapter; import editor.gui.generic.VerticalButtonList; import editor.gui.generic.WizardDialog; import editor.gui.inventory.InventoryDownloadDialog; import editor.gui.inventory.InventoryLoadDialog; import editor.gui.settings.SettingsDialog; import editor.serialization.AttributeAdapter; import editor.serialization.CardAdapter; import editor.serialization.CategoryAdapter; import editor.serialization.DeckAdapter; import editor.serialization.FilterAdapter; import editor.serialization.VersionAdapter; import editor.serialization.legacy.DeckDeserializer; import editor.util.ColorAdapter; import editor.util.MenuListenerFactory; import editor.util.MouseListenerFactory; import editor.util.PopupMenuListenerFactory; import editor.util.UnicodeSymbols; /** * This class represents the main frame of the editor. It contains several tabs that display information * about decks. * <p> * The frame is divided into three sections: On the left side is a database of all cards that can be * added to decks with a window below it that displays the Oracle text of the currently-selected card. On * the right side is a pane which contains internal frames that allow the user to open, close, and edit * multiple decks at once. See #EditorFrame for details on the editor frames. * * @author Alec Roelke */ @SuppressWarnings("serial") public class MainFrame extends JFrame { /** * This class represents a renderer for rendering table cells that display text. If * the cell contains text and the card at the row is in the currently-active deck, * the cell is rendered bold. * * @author Alec Roelke */ private class InventoryTableCellRenderer extends CardTableCellRenderer { /** * Create a new CardTableCellRenderer. */ public InventoryTableCellRenderer() { super(); } /** * If the cell is rendered using a JLabel, make that JLabel bold. Otherwise, just use * the default renderer. * * @param table {@link JTable} to render for * @param value value being rendered * @param isSelected whether or not the cell is selected * @param hasFocus whether or not the table has focus * @param row row of the cell being rendered * @param column column of the cell being rendered * @return The {@link Component} responsible for rendering the table cell. */ @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); Card card = inventory.get(table.convertRowIndexToModel(row)); boolean main = selectedFrame.map((f) -> f.hasCard("", card)).orElse(false); boolean extra = selectedFrame.map((f) -> f.getExtraCards().contains(card)).orElse(false); if (main && extra) ComponentUtils.changeFontRecursive(c, c.getFont().deriveFont(Font.BOLD | Font.ITALIC)); else if (main) ComponentUtils.changeFontRecursive(c, c.getFont().deriveFont(Font.BOLD)); else if (extra) ComponentUtils.changeFontRecursive(c, c.getFont().deriveFont(Font.ITALIC)); return c; } } /** * Default height for displaying card images. */ public static final double DEFAULT_CARD_HEIGHT = 1.0/3.0; /** * Maximum height that the advanced filter editor panel can attain before scrolling. */ public static final int MAX_FILTER_HEIGHT = 300; /** * Serializer for saving and loading external information. */ public static final Gson SERIALIZER = new GsonBuilder() .registerTypeAdapter(CategorySpec.class, new CategoryAdapter()) .registerTypeHierarchyAdapter(Filter.class, new FilterAdapter()) .registerTypeAdapter(Color.class, new ColorAdapter()) .registerTypeHierarchyAdapter(Card.class, new CardAdapter()) .registerTypeAdapter(CardAttribute.class, new AttributeAdapter()) .registerTypeAdapter(Deck.class, new DeckAdapter()) .registerTypeAdapter(DeckSerializer.class, new DeckSerializer()) .registerTypeAdapter(DatabaseVersion.class, new VersionAdapter()) .setPrettyPrinting() .create(); /** * Update status value: update needed. */ public static final int UPDATE_NEEDED = 0; /** * Update status value: update not needed. */ public static final int NO_UPDATE = 1; /** * Update status value: update needed, but was not requested. */ public static final int UPDATE_CANCELLED = 2; /** * Inventory of all cards. */ private static Inventory inventory; /** * @return The inventory. */ public static Inventory inventory() { return inventory; } /** * Entry point for the program. All it does is set the look and feel to the * system one and create the GUI. * * @param args arguments to the program */ public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { e.printStackTrace(); } SwingUtilities.invokeLater(() -> new MainFrame(Arrays.stream(args).map(File::new).filter(File::exists).collect(Collectors.toList())).setVisible(true)); } /** * Table displaying the inventory of all cards. */ private CardTable inventoryTable; /** * Model for the table displaying the inventory of all cards. */ private CardTableModel inventoryModel; /** * Pane for showing the Oracle text of the currently-selected card. */ private JTextPane oracleTextPane; /** * Pane for showing the printed text of the currently-selected card. */ private JTextPane printedTextPane; /** * Desktop pane containing internal editor frames. */ private JDesktopPane decklistDesktop; /** * Number to append to the end of untitled decks that have just been created. */ private int untitled; /** * Currently-selected editor frame. */ private Optional<EditorFrame> selectedFrame; /** * List of open editor frames. */ private List<EditorFrame> editors; /** * File chooser for opening and saving. */ private JFileChooser fileChooser; /** * URL pointing to the site to get the latest version of the * inventory from. */ private URL versionSite; /** * File to store the inventory in. */ private File inventoryFile; /** * URL pointing to the site to get the inventory from. */ private URL inventorySite; /** * Number of recent files to display. */ private int recentCount; /** * Menu items showing recent files to open. */ private Queue<JMenuItem> recentItems; /** * Map of those menu items onto the files they should open. */ private Map<JMenuItem, File> recents; /** * Menu containing the recent menu items. */ private JMenu recentsMenu; /** * Newest version number of the inventory. */ private DatabaseVersion newestVersion; /** * Menu showing preset categories. */ private JMenu presetMenu; /** * Panel displaying the image for the currently selected card. */ private CardImagePanel imagePanel; /** * Pane displaying the currently-selected card's rulings. */ private JTextPane rulingsPane; /** * Top menu allowing editing of cards and categories in the selected deck. */ private JMenu deckMenu; /** * Currently-selected cards. Should never be null, but can be empty. */ private List<Card> selectedCards; /** * Table containing the currently-selected cards. Can be null if there is no * selection. */ private Optional<CardTable> selectedTable; /** * List backing the table containing the currently-selected cards. Can be null * if there is no selection. */ private Optional<CardList> selectedList; /** * Create a new MainFrame. */ public MainFrame(List<File> files) { super(); selectedCards = Collections.emptyList(); selectedTable = Optional.empty(); selectedList = Optional.empty(); untitled = 0; selectedFrame = Optional.empty(); editors = new ArrayList<>(); recentItems = new LinkedList<>(); recents = new HashMap<>(); // Initialize properties to their default values, then load the current values // from the properties file try { SettingsDialog.load(); } catch (IOException | JsonParseException e) { Throwable ex = e; while (ex.getCause() != null) ex = ex.getCause(); JOptionPane.showMessageDialog(this, "Error opening " + SettingsDialog.PROPERTIES_FILE + ": " + ex.getMessage() + ".", "Warning", JOptionPane.WARNING_MESSAGE); SettingsDialog.resetDefaultSettings(); } try { versionSite = new URL(SettingsDialog.settings().inventory.versionSite()); } catch (MalformedURLException e) { JOptionPane.showMessageDialog(this, "Bad version URL: " + SettingsDialog.settings().inventory.versionSite(), "Warning", JOptionPane.WARNING_MESSAGE); } try { inventorySite = new URL(SettingsDialog.settings().inventory.url() + ".zip"); } catch (MalformedURLException e) { JOptionPane.showMessageDialog(this, "Bad file URL: " + SettingsDialog.settings().inventory.url() + ".zip", "Warning", JOptionPane.WARNING_MESSAGE); } inventoryFile = new File(SettingsDialog.settings().inventory.path()); recentCount = SettingsDialog.settings().editor.recents.count; newestVersion = SettingsDialog.settings().inventory.version; setTitle("MTG Deck Editor"); setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); Dimension screenRes = Toolkit.getDefaultToolkit().getScreenSize(); setBounds(50, 50, screenRes.width - 100, screenRes.height - 100); /* MENU BAR */ JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); // File menu JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); // New file menu item JMenuItem newItem = new JMenuItem("New"); newItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_DOWN_MASK)); newItem.addActionListener((e) -> selectFrame(newEditor())); fileMenu.add(newItem); // Open file menu item JMenuItem openItem = new JMenuItem("Open..."); openItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_DOWN_MASK)); openItem.addActionListener((e) -> open()); fileMenu.add(openItem); // Close file menu item JMenuItem closeItem = new JMenuItem("Close"); closeItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_DOWN_MASK)); closeItem.addActionListener((e) -> selectedFrame.ifPresentOrElse((f) -> close(f), () -> exit())); fileMenu.add(closeItem); // Close all files menu item JMenuItem closeAllItem = new JMenuItem("Close All"); closeAllItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_DOWN_MASK|InputEvent.SHIFT_DOWN_MASK)); closeAllItem.addActionListener((e) -> closeAll()); fileMenu.add(closeAllItem); fileMenu.add(new JSeparator()); // Save file menu item JMenuItem saveItem = new JMenuItem("Save"); saveItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK)); saveItem.addActionListener((e) -> selectedFrame.ifPresent((f) -> save(f))); fileMenu.add(saveItem); // Save file as menu item JMenuItem saveAsItem = new JMenuItem("Save As..."); saveAsItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0)); saveAsItem.addActionListener((e) -> selectedFrame.ifPresent((f) -> saveAs(f))); fileMenu.add(saveAsItem); // Save all files menu item JMenuItem saveAllItem = new JMenuItem("Save All"); saveAllItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK|InputEvent.SHIFT_DOWN_MASK)); saveAllItem.addActionListener((e) -> saveAll()); fileMenu.add(saveAllItem); // Recent files menu recentsMenu = new JMenu("Open Recent"); recentsMenu.setEnabled(false); for (String fname : SettingsDialog.settings().editor.recents.files) updateRecents(new File(fname)); fileMenu.add(recentsMenu); fileMenu.add(new JSeparator()); // Import and export items final FileNameExtensionFilter text = new FileNameExtensionFilter("Text (*.txt)", "txt"); final FileNameExtensionFilter delimited = new FileNameExtensionFilter("Delimited (*.txt, *.csv)", "txt", "csv"); final FileNameExtensionFilter legacy = new FileNameExtensionFilter("Deck from v0.1 or older (*." + DeckDeserializer.EXTENSION + ')', DeckDeserializer.EXTENSION); JMenuItem importItem = new JMenuItem("Import..."); importItem.addActionListener((e) -> { JFileChooser importChooser = new JFileChooser(); importChooser.setAcceptAllFileFilterUsed(false); importChooser.addChoosableFileFilter(text); importChooser.addChoosableFileFilter(delimited); importChooser.addChoosableFileFilter(legacy); importChooser.setDialogTitle("Import"); importChooser.setCurrentDirectory(fileChooser.getCurrentDirectory()); switch (importChooser.showOpenDialog(this)) { case JFileChooser.APPROVE_OPTION: if (importChooser.getFileFilter() == legacy) { try { DeckSerializer manager = new DeckSerializer(); manager.importLegacy(importChooser.getSelectedFile(), this); selectFrame(newEditor(manager)); } catch (DeckLoadException x) { x.printStackTrace(); JOptionPane.showMessageDialog(this, "Error opening " + importChooser.getSelectedFile().getName() + ": " + x.getMessage() + ".", "Error", JOptionPane.ERROR_MESSAGE); } } else { CardListFormat format; if (importChooser.getFileFilter() == text) { format = new TextCardListFormat(""); } else if (importChooser.getFileFilter() == delimited) { JPanel dataPanel = new JPanel(new BorderLayout()); JPanel optionsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); optionsPanel.add(new JLabel("Delimiter: ")); var delimiterBox = new JComboBox<>(DelimitedCardListFormat.DELIMITERS); delimiterBox.setEditable(true); optionsPanel.add(delimiterBox); JCheckBox includeCheckBox = new JCheckBox("Read Headers"); includeCheckBox.setSelected(true); optionsPanel.add(includeCheckBox); dataPanel.add(optionsPanel, BorderLayout.NORTH); var headersList = new JList<>(CardAttribute.displayableValues()); headersList.setEnabled(!includeCheckBox.isSelected()); JScrollPane headersPane = new JScrollPane(headersList); JPanel headersPanel = new JPanel(); headersPanel.setLayout(new BoxLayout(headersPanel, BoxLayout.X_AXIS)); headersPanel.setBorder(BorderFactory.createTitledBorder("Column Data:")); VerticalButtonList rearrangeButtons = new VerticalButtonList(String.valueOf(UnicodeSymbols.UP_ARROW), String.valueOf(UnicodeSymbols.DOWN_ARROW)); for (JButton rearrange : rearrangeButtons) rearrange.setEnabled(!includeCheckBox.isSelected()); headersPanel.add(rearrangeButtons); headersPanel.add(Box.createHorizontalStrut(5)); var selectedHeadersModel = new DefaultListModel<CardAttribute>(); selectedHeadersModel.addElement(CardAttribute.NAME); selectedHeadersModel.addElement(CardAttribute.EXPANSION); selectedHeadersModel.addElement(CardAttribute.CARD_NUMBER); selectedHeadersModel.addElement(CardAttribute.COUNT); selectedHeadersModel.addElement(CardAttribute.DATE_ADDED); var selectedHeadersList = new JList<>(selectedHeadersModel); selectedHeadersList.setEnabled(!includeCheckBox.isSelected()); headersPanel.add(new JScrollPane(selectedHeadersList) { @Override public Dimension getPreferredSize() { return headersPane.getPreferredSize(); } }); headersPanel.add(Box.createHorizontalStrut(5)); VerticalButtonList moveButtons = new VerticalButtonList(String.valueOf(UnicodeSymbols.LEFT_ARROW), String.valueOf(UnicodeSymbols.RIGHT_ARROW)); for (JButton move : moveButtons) move.setEnabled(!includeCheckBox.isSelected()); headersPanel.add(moveButtons); headersPanel.add(Box.createHorizontalStrut(5)); headersPanel.add(headersPane); dataPanel.add(headersPanel, BorderLayout.CENTER); rearrangeButtons.get(String.valueOf(UnicodeSymbols.UP_ARROW)).addActionListener((v) -> { var selected = selectedHeadersList.getSelectedValuesList(); int ignore = 0; for (int index : selectedHeadersList.getSelectedIndices()) { if (index == ignore) { ignore++; continue; } CardAttribute temp = selectedHeadersModel.getElementAt(index - 1); selectedHeadersModel.setElementAt(selectedHeadersModel.getElementAt(index), index - 1); selectedHeadersModel.setElementAt(temp, index); } selectedHeadersList.clearSelection(); for (CardAttribute type : selected) { int index = selectedHeadersModel.indexOf(type); selectedHeadersList.addSelectionInterval(index, index); } }); rearrangeButtons.get(String.valueOf(UnicodeSymbols.DOWN_ARROW)).addActionListener((v) -> { var selected = selectedHeadersList.getSelectedValuesList(); var indices = Arrays.stream(selectedHeadersList.getSelectedIndices()).boxed().collect(Collectors.toList()); Collections.reverse(indices); int ignore = selectedHeadersModel.size() - 1; for (int index : indices) { if (index == ignore) { ignore--; continue; } CardAttribute temp = selectedHeadersModel.getElementAt(index + 1); selectedHeadersModel.setElementAt(selectedHeadersModel.getElementAt(index), index + 1); selectedHeadersModel.setElementAt(temp, index); } selectedHeadersList.clearSelection(); for (CardAttribute type : selected) { int index = selectedHeadersModel.indexOf(type); selectedHeadersList.addSelectionInterval(index, index); } }); moveButtons.get(String.valueOf(UnicodeSymbols.LEFT_ARROW)).addActionListener((v) -> { for (CardAttribute selected : headersList.getSelectedValuesList()) if (!selectedHeadersModel.contains(selected)) selectedHeadersModel.addElement(selected); headersList.clearSelection(); }); moveButtons.get(String.valueOf(UnicodeSymbols.RIGHT_ARROW)).addActionListener((v) -> { for (CardAttribute selected : new ArrayList<>(selectedHeadersList.getSelectedValuesList())) selectedHeadersModel.removeElement(selected); }); includeCheckBox.addActionListener((v) -> { headersList.setEnabled(!includeCheckBox.isSelected()); selectedHeadersList.setEnabled(!includeCheckBox.isSelected()); for (JButton rearrange : rearrangeButtons) rearrange.setEnabled(!includeCheckBox.isSelected()); for (JButton move : moveButtons) move.setEnabled(!includeCheckBox.isSelected()); }); JPanel previewPanel = new JPanel(new BorderLayout()); previewPanel.setBorder(BorderFactory.createTitledBorder("Data to Import:")); JTable previewTable = new JTable() { @Override public Dimension getPreferredScrollableViewportSize() { return new Dimension(0, 0); } @Override public boolean getScrollableTracksViewportWidth() { return getPreferredSize().width < getParent().getWidth(); } }; previewTable.setAutoCreateRowSorter(true); previewPanel.add(new JScrollPane(previewTable)); ActionListener updateTable = (v) -> { try { DefaultTableModel model = new DefaultTableModel(); var lines = Files.readAllLines(importChooser.getSelectedFile().toPath()); if (includeCheckBox.isSelected()) { String[] columns = lines.remove(0).split(String.valueOf(delimiterBox.getSelectedItem())); String[][] data = lines.stream().map((s) -> DelimitedCardListFormat.split(delimiterBox.getSelectedItem().toString(), s)).toArray(String[][]::new); model.setDataVector(data, columns); } else { CardAttribute[] columns = new CardAttribute[selectedHeadersModel.size()]; for (int i = 0; i < selectedHeadersModel.size(); i++) columns[i] = selectedHeadersModel.getElementAt(i); String[][] data = lines.stream().map((s) -> DelimitedCardListFormat.split(String.valueOf(delimiterBox.getSelectedItem()), s)).toArray(String[][]::new); model.setDataVector(data, columns); } previewTable.setModel(model); } catch (IOException x) { JOptionPane.showMessageDialog(this, "Could not import " + importChooser.getSelectedFile() + ": " + x.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } }; delimiterBox.addActionListener(updateTable); includeCheckBox.addActionListener(updateTable); for (JButton rearrange : rearrangeButtons) rearrange.addActionListener(updateTable); for (JButton move : moveButtons) move.addActionListener(updateTable); updateTable.actionPerformed(null); if (WizardDialog.showWizardDialog(this, "Import Wizard", dataPanel, previewPanel) == WizardDialog.FINISH_OPTION) { var selected = new ArrayList<CardAttribute>(selectedHeadersModel.size()); for (int i = 0; i < selectedHeadersModel.size(); i++) selected.add(selectedHeadersModel.getElementAt(i)); format = new DelimitedCardListFormat(String.valueOf(delimiterBox.getSelectedItem()), selected, !includeCheckBox.isSelected()); } else return; } else { JOptionPane.showMessageDialog(this, "Could not import " + importChooser.getSelectedFile() + '.', "Error", JOptionPane.ERROR_MESSAGE); return; } DeckSerializer manager = new DeckSerializer(); try { manager.importList(format, importChooser.getSelectedFile()); } catch (DeckLoadException x) { JOptionPane.showMessageDialog(this, "Could not import " + importChooser.getSelectedFile() + ": " + x.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } finally { selectFrame(newEditor(manager)); } } break; case JFileChooser.CANCEL_OPTION: break; case JFileChooser.ERROR_OPTION: JOptionPane.showMessageDialog(this, "Could not import " + importChooser.getSelectedFile() + '.', "Error", JOptionPane.ERROR_MESSAGE); break; } }); fileMenu.add(importItem); JMenuItem exportItem = new JMenuItem("Export..."); exportItem.addActionListener((e) -> selectedFrame.ifPresent((f) -> { JFileChooser exportChooser = new OverwriteFileChooser(); exportChooser.setAcceptAllFileFilterUsed(false); exportChooser.addChoosableFileFilter(text); exportChooser.addChoosableFileFilter(delimited); exportChooser.setDialogTitle("Export"); exportChooser.setCurrentDirectory(fileChooser.getCurrentDirectory()); switch (exportChooser.showSaveDialog(this)) { case JFileChooser.APPROVE_OPTION: CardListFormat format; if (exportChooser.getFileFilter() == text) { JPanel wizardPanel = new JPanel(new BorderLayout()); JPanel fieldPanel = new JPanel(new BorderLayout()); fieldPanel.setBorder(BorderFactory.createTitledBorder("List Format:")); JTextField formatField = new JTextField(TextCardListFormat.DEFAULT_FORMAT); formatField.setFont(new Font(Font.MONOSPACED, Font.PLAIN, formatField.getFont().getSize())); formatField.setColumns(50); fieldPanel.add(formatField, BorderLayout.CENTER); JPanel addDataPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); addDataPanel.add(new JLabel("Add Data: ")); var addDataBox = new JComboBox<>(CardAttribute.displayableValues()); addDataPanel.add(addDataBox); fieldPanel.add(addDataPanel, BorderLayout.SOUTH); wizardPanel.add(fieldPanel, BorderLayout.NORTH); if (f.getDeck().total() > 0 || f.getExtraCards().total() > 0) { JPanel previewPanel = new JPanel(new BorderLayout()); previewPanel.setBorder(BorderFactory.createTitledBorder("Preview:")); JTextArea previewArea = new JTextArea(); JScrollPane previewPane = new JScrollPane(previewArea); previewArea.setText(new TextCardListFormat(formatField.getText()) .format(f.getDeck().total() > 0 ? f.getDeck() : f.getExtraCards())); previewArea.setRows(1); previewArea.setCaretPosition(0); previewPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); previewPanel.add(previewPane, BorderLayout.CENTER); wizardPanel.add(previewPanel); addDataBox.addActionListener((v) -> { int pos = formatField.getCaretPosition(); String data = '{' + String.valueOf(addDataBox.getSelectedItem()).toLowerCase() + '}'; String t = formatField.getText().substring(0, pos) + data; if (pos < formatField.getText().length()) t += formatField.getText().substring(formatField.getCaretPosition()); formatField.setText(t); formatField.setCaretPosition(pos + data.length()); formatField.requestFocusInWindow(); }); formatField.getDocument().addDocumentListener(new DocumentChangeListener() { @Override public void update(DocumentEvent e) { previewArea.setText(new TextCardListFormat(formatField.getText()) .format(f.getDeck().total() > 0 ? f.getDeck() : f.getExtraCards())); previewArea.setCaretPosition(0); } }); } if (WizardDialog.showWizardDialog(this, "Export Wizard", wizardPanel) == WizardDialog.FINISH_OPTION) format = new TextCardListFormat(formatField.getText()); else return; } else if (exportChooser.getFileFilter() == delimited) { JPanel wizardPanel = new JPanel(new BorderLayout()); var headersList = new JList<>(CardAttribute.displayableValues()); JScrollPane headersPane = new JScrollPane(headersList); JPanel headersPanel = new JPanel(); headersPanel.setLayout(new BoxLayout(headersPanel, BoxLayout.X_AXIS)); headersPanel.setBorder(BorderFactory.createTitledBorder("Column Data:")); VerticalButtonList rearrangeButtons = new VerticalButtonList(String.valueOf(UnicodeSymbols.UP_ARROW), String.valueOf(UnicodeSymbols.DOWN_ARROW)); headersPanel.add(rearrangeButtons); headersPanel.add(Box.createHorizontalStrut(5)); var selectedHeadersModel = new DefaultListModel<CardAttribute>(); selectedHeadersModel.addElement(CardAttribute.NAME); selectedHeadersModel.addElement(CardAttribute.EXPANSION); selectedHeadersModel.addElement(CardAttribute.CARD_NUMBER); selectedHeadersModel.addElement(CardAttribute.COUNT); selectedHeadersModel.addElement(CardAttribute.DATE_ADDED); var selectedHeadersList = new JList<>(selectedHeadersModel); headersPanel.add(new JScrollPane(selectedHeadersList) { @Override public Dimension getPreferredSize() { return headersPane.getPreferredSize(); } }); headersPanel.add(Box.createHorizontalStrut(5)); VerticalButtonList moveButtons = new VerticalButtonList(String.valueOf(UnicodeSymbols.LEFT_ARROW), String.valueOf(UnicodeSymbols.RIGHT_ARROW)); headersPanel.add(moveButtons); headersPanel.add(Box.createHorizontalStrut(5)); headersPanel.add(headersPane); wizardPanel.add(headersPanel, BorderLayout.CENTER); rearrangeButtons.get(String.valueOf(UnicodeSymbols.UP_ARROW)).addActionListener((v) -> { var selected = selectedHeadersList.getSelectedValuesList(); int ignore = 0; for (int index : selectedHeadersList.getSelectedIndices()) { if (index == ignore) { ignore++; continue; } CardAttribute temp = selectedHeadersModel.getElementAt(index - 1); selectedHeadersModel.setElementAt(selectedHeadersModel.getElementAt(index), index - 1); selectedHeadersModel.setElementAt(temp, index); } selectedHeadersList.clearSelection(); for (CardAttribute type : selected) { int index = selectedHeadersModel.indexOf(type); selectedHeadersList.addSelectionInterval(index, index); } }); rearrangeButtons.get(String.valueOf(UnicodeSymbols.DOWN_ARROW)).addActionListener((v) -> { var selected = selectedHeadersList.getSelectedValuesList(); var indices = Arrays.stream(selectedHeadersList.getSelectedIndices()).boxed().collect(Collectors.toList()); Collections.reverse(indices); int ignore = selectedHeadersModel.size() - 1; for (int index : indices) { if (index == ignore) { ignore--; continue; } CardAttribute temp = selectedHeadersModel.getElementAt(index + 1); selectedHeadersModel.setElementAt(selectedHeadersModel.getElementAt(index), index + 1); selectedHeadersModel.setElementAt(temp, index); } selectedHeadersList.clearSelection(); for (CardAttribute type : selected) { int index = selectedHeadersModel.indexOf(type); selectedHeadersList.addSelectionInterval(index, index); } }); moveButtons.get(String.valueOf(UnicodeSymbols.LEFT_ARROW)).addActionListener((v) -> { for (CardAttribute selected : headersList.getSelectedValuesList()) if (!selectedHeadersModel.contains(selected)) selectedHeadersModel.addElement(selected); headersList.clearSelection(); }); moveButtons.get(String.valueOf(UnicodeSymbols.RIGHT_ARROW)).addActionListener((v) -> { for (CardAttribute selected : new ArrayList<>(selectedHeadersList.getSelectedValuesList())) selectedHeadersModel.removeElement(selected); }); JPanel optionsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); optionsPanel.add(new JLabel("Delimiter: ")); var delimiterBox = new JComboBox<>(DelimitedCardListFormat.DELIMITERS); delimiterBox.setEditable(true); optionsPanel.add(delimiterBox); JCheckBox includeCheckBox = new JCheckBox("Include Headers"); includeCheckBox.setSelected(true); optionsPanel.add(includeCheckBox); wizardPanel.add(optionsPanel, BorderLayout.SOUTH); if (WizardDialog.showWizardDialog(this, "Export Wizard", wizardPanel) == WizardDialog.FINISH_OPTION) { var selected = new ArrayList<CardAttribute>(selectedHeadersModel.size()); for (int i = 0; i < selectedHeadersModel.size(); i++) selected.add(selectedHeadersModel.getElementAt(i)); format = new DelimitedCardListFormat(String.valueOf(delimiterBox.getSelectedItem()), selected, includeCheckBox.isSelected()); } else return; } else { JOptionPane.showMessageDialog(this, "Could not export " + f.deckName() + '.', "Error", JOptionPane.ERROR_MESSAGE); return; } try { f.export(format, exportChooser.getSelectedFile()); } catch (UnsupportedEncodingException | FileNotFoundException x) { JOptionPane.showMessageDialog(this, "Could not export " + f.deckName() + ": " + x.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } break; case JFileChooser.CANCEL_OPTION: break; case JFileChooser.ERROR_OPTION: JOptionPane.showMessageDialog(this, "Could not export " + f.deckName() + '.', "Error", JOptionPane.ERROR_MESSAGE); break; } })); fileMenu.add(exportItem); fileMenu.add(new JSeparator()); // Exit menu item JMenuItem exitItem = new JMenuItem("Exit"); exitItem.addActionListener((e) -> exit()); exitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, InputEvent.ALT_DOWN_MASK)); fileMenu.add(exitItem); // File menu listener fileMenu.addMenuListener(MenuListenerFactory.createSelectedListener((e) -> { closeItem.setEnabled(selectedFrame.isPresent()); closeAllItem.setEnabled(!editors.isEmpty()); saveItem.setEnabled(selectedFrame.map(EditorFrame::getUnsaved).orElse(false)); saveAsItem.setEnabled(selectedFrame.isPresent()); saveAllItem.setEnabled(editors.stream().map(EditorFrame::getUnsaved).reduce(false, (a, b) -> a || b)); exportItem.setEnabled(selectedFrame.isPresent()); })); // Items are enabled while hidden so their listeners can be used fileMenu.addMenuListener(MenuListenerFactory.createDeselectedListener((e) -> { closeItem.setEnabled(true); closeAllItem.setEnabled(true); saveItem.setEnabled(true); saveAsItem.setEnabled(true); saveAllItem.setEnabled(true); exportItem.setEnabled(true); })); // Edit menu JMenu editMenu = new JMenu("Edit"); menuBar.add(editMenu); // Undo menu item JMenuItem undoItem = new JMenuItem("Undo"); undoItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, InputEvent.CTRL_DOWN_MASK)); undoItem.addActionListener((e) -> selectedFrame.ifPresent(EditorFrame::undo)); editMenu.add(undoItem); // Redo menu item JMenuItem redoItem = new JMenuItem("Redo"); redoItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, InputEvent.CTRL_DOWN_MASK)); redoItem.addActionListener((e) -> selectedFrame.ifPresent(EditorFrame::redo)); editMenu.add(redoItem); editMenu.add(new JSeparator()); // Preferences menu item JMenuItem preferencesItem = new JMenuItem("Preferences..."); preferencesItem.addActionListener((e) -> { SettingsDialog settings = new SettingsDialog(this); settings.setVisible(true); }); editMenu.add(preferencesItem); // Edit menu listener editMenu.addMenuListener(MenuListenerFactory.createSelectedListener((e) -> { undoItem.setEnabled(selectedFrame.isPresent()); redoItem.setEnabled(selectedFrame.isPresent()); })); // Items are enabled while hidden so their listeners can be used editMenu.addMenuListener(MenuListenerFactory.createDeselectedListener((e) -> { undoItem.setEnabled(true); redoItem.setEnabled(true); })); // Deck menu deckMenu = new JMenu("Deck"); deckMenu.setEnabled(false); menuBar.add(deckMenu); // Add/Remove card menus JMenu addMenu = new JMenu("Add Cards"); deckMenu.add(addMenu); JMenu removeMenu = new JMenu("Remove Cards"); deckMenu.add(removeMenu); CardMenuItems deckMenuCardItems = new CardMenuItems(() -> selectedFrame, this::getSelectedCards, true); deckMenuCardItems.addAddItems(addMenu); deckMenuCardItems.addRemoveItems(removeMenu); deckMenuCardItems.addSingle().setAccelerator(KeyStroke.getKeyStroke('+')); deckMenuCardItems.fillPlayset().setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.CTRL_DOWN_MASK)); deckMenuCardItems.removeSingle().setAccelerator(KeyStroke.getKeyStroke('-')); deckMenuCardItems.removeAll().setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, InputEvent.CTRL_DOWN_MASK)); // Sideboard menu JMenu sideboardMenu = new JMenu("Sideboard"); deckMenu.add(sideboardMenu); CardMenuItems sideboardMenuItems = new CardMenuItems(() -> selectedFrame, this::getSelectedCards, false); sideboardMenu.add(sideboardMenuItems.addSingle()); sideboardMenu.add(sideboardMenuItems.addN()); sideboardMenu.add(sideboardMenuItems.removeSingle()); sideboardMenu.add(sideboardMenuItems.removeAll()); // Category menu JMenu categoryMenu = new JMenu("Category"); deckMenu.add(categoryMenu); // Add category item JMenuItem addCategoryItem = new JMenuItem("Add..."); addCategoryItem.addActionListener((e) -> selectedFrame.ifPresent((f) -> f.createCategory().ifPresent(f::addCategory))); categoryMenu.add(addCategoryItem); // Edit category item JMenuItem editCategoryItem = new JMenuItem("Edit..."); editCategoryItem.addActionListener((e) -> selectedFrame.ifPresent((f) -> { JPanel contentPanel = new JPanel(new BorderLayout()); contentPanel.add(new JLabel("Choose a category to edit:"), BorderLayout.NORTH); var categories = new JList<>(f.getCategories().stream().map(CategorySpec::getName).sorted().toArray(String[]::new)); categories.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); contentPanel.add(new JScrollPane(categories), BorderLayout.CENTER); if (JOptionPane.showConfirmDialog(this, contentPanel, "Edit Category", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) == JOptionPane.OK_OPTION) f.editCategory(categories.getSelectedValue()); })); categoryMenu.add(editCategoryItem); // Remove category item JMenuItem removeCategoryItem = new JMenuItem("Remove..."); removeCategoryItem.addActionListener((e) -> selectedFrame.ifPresent((f) -> { JPanel contentPanel = new JPanel(new BorderLayout()); contentPanel.add(new JLabel("Choose a category to remove:"), BorderLayout.NORTH); var categories = new JList<>(f.getCategories().stream().map(CategorySpec::getName).sorted().toArray(String[]::new)); categories.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); contentPanel.add(new JScrollPane(categories), BorderLayout.CENTER); if (JOptionPane.showConfirmDialog(this, contentPanel, "Edit Category", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) == JOptionPane.OK_OPTION) f.removeCategory(categories.getSelectedValue()); })); categoryMenu.add(removeCategoryItem); // Preset categories menu presetMenu = new JMenu("Add Preset"); categoryMenu.add(presetMenu); // Deck menu listener deckMenu.addMenuListener(MenuListenerFactory.createSelectedListener((e) -> { addMenu.setEnabled(selectedFrame.isPresent() && !selectedCards.isEmpty()); removeMenu.setEnabled(selectedFrame.isPresent() && !selectedCards.isEmpty()); sideboardMenu.setEnabled(selectedFrame.map((f) -> f.getSelectedExtraName() != null).orElse(false) && !selectedCards.isEmpty()); presetMenu.setEnabled(presetMenu.getMenuComponentCount() > 0); })); // Items are enabled while hidden so their listeners can be used. deckMenu.addMenuListener(MenuListenerFactory.createDeselectedListener((e) -> { addMenu.setEnabled(true); removeMenu.setEnabled(true); })); // Help menu JMenu helpMenu = new JMenu("Help"); menuBar.add(helpMenu); // Inventory update item JMenuItem updateInventoryItem = new JMenuItem("Check for inventory update..."); updateInventoryItem.addActionListener((e) -> { switch (checkForUpdate(UpdateFrequency.DAILY)) { case UPDATE_NEEDED: if (updateInventory()) { SettingsDialog.setInventoryVersion(newestVersion); loadInventory(); } break; case NO_UPDATE: JOptionPane.showMessageDialog(this, "Inventory is up to date."); break; case UPDATE_CANCELLED: break; default: break; } }); helpMenu.add(updateInventoryItem); // Reload inventory item JMenuItem reloadInventoryItem = new JMenuItem("Reload inventory..."); reloadInventoryItem.addActionListener((e) -> loadInventory()); helpMenu.add(reloadInventoryItem); helpMenu.add(new JSeparator()); // Show expansions item JMenuItem showExpansionsItem = new JMenuItem("Show Expansions..."); showExpansionsItem.addActionListener((e) -> { TableModel expansionTableModel = new AbstractTableModel() { private final String[] columns = { "Expansion", "Block", "Code", "magiccards.info", "Gatherer" }; @Override public int getColumnCount() { return 5; } @Override public String getColumnName(int index) { return columns[index]; } @Override public int getRowCount() { return Expansion.expansions.length; } @Override public Object getValueAt(int rowIndex, int columnIndex) { final Object[] values = { Expansion.expansions[rowIndex].name, Expansion.expansions[rowIndex].block, Expansion.expansions[rowIndex].code, Expansion.expansions[rowIndex].magicCardsInfoCode, Expansion.expansions[rowIndex].gathererCode }; return values[columnIndex]; } }; JTable expansionTable = new JTable(expansionTableModel); expansionTable.setShowGrid(false); expansionTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); expansionTable.setAutoCreateRowSorter(true); expansionTable.setPreferredScrollableViewportSize(new Dimension(600, expansionTable.getPreferredScrollableViewportSize().height)); JOptionPane.showMessageDialog(this, new JScrollPane(expansionTable), "Expansions", JOptionPane.PLAIN_MESSAGE); }); helpMenu.add(showExpansionsItem); /* CONTENT PANE */ // Panel containing all content JPanel contentPane = new JPanel(new BorderLayout()); contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, InputEvent.CTRL_DOWN_MASK), "Next Frame"); contentPane.getActionMap().put("Next Frame", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { if (!editors.isEmpty()) selectedFrame.ifPresentOrElse((f) -> selectFrame(editors.get((editors.indexOf(f) + 1)%editors.size())), () -> selectFrame(editors.get(editors.size() - 1))); } }); contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, InputEvent.CTRL_DOWN_MASK), "Previous Frame"); contentPane.getActionMap().put("Previous Frame", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { if (!editors.isEmpty()) { int next = selectedFrame.map((f) -> editors.indexOf(f) - 1).orElse(0); selectFrame(editors.get(next < 0 ? editors.size() - 1 : next)); } } }); setContentPane(contentPane); // DesktopPane containing editor frames decklistDesktop = new JDesktopPane(); decklistDesktop.setBackground(SystemColor.controlShadow); JTabbedPane cardPane = new JTabbedPane(); // Panel showing the image of the currently-selected card cardPane.addTab("Image", imagePanel = new CardImagePanel()); setImageBackground(SettingsDialog.settings().inventory.background); // Pane displaying the Oracle text oracleTextPane = new JTextPane(); oracleTextPane.setEditable(false); oracleTextPane.setCursor(new Cursor(Cursor.TEXT_CURSOR)); cardPane.addTab("Oracle Text", new JScrollPane(oracleTextPane)); printedTextPane = new JTextPane(); printedTextPane.setEditable(false); printedTextPane.setCursor(new Cursor(Cursor.TEXT_CURSOR)); cardPane.addTab("Printed Text", new JScrollPane(printedTextPane)); rulingsPane = new JTextPane(); rulingsPane.setEditable(false); rulingsPane.setCursor(new Cursor(Cursor.TEXT_CURSOR)); cardPane.addTab("Rulings", new JScrollPane(rulingsPane)); // Oracle text pane popup menu JPopupMenu oraclePopupMenu = new JPopupMenu(); oracleTextPane.setComponentPopupMenu(oraclePopupMenu); printedTextPane.setComponentPopupMenu(oraclePopupMenu); imagePanel.setComponentPopupMenu(oraclePopupMenu); // Add the card to the main deck CardMenuItems oracleMenuCardItems = new CardMenuItems(() -> selectedFrame, () -> Arrays.asList(selectedCards.get(0)), true); oracleMenuCardItems.addAddItems(oraclePopupMenu); oraclePopupMenu.add(new JSeparator()); oracleMenuCardItems.addRemoveItems(oraclePopupMenu); oraclePopupMenu.add(new JSeparator()); // Add the card to the sideboard CardMenuItems oracleMenuSBCardItems = new CardMenuItems(() -> selectedFrame, () -> Arrays.asList(selectedCards.get(0)), false); oracleMenuSBCardItems.addSingle().setText("Add to Sideboard"); oraclePopupMenu.add(oracleMenuSBCardItems.addSingle()); oracleMenuSBCardItems.addN().setText("Add to Sideboard..."); oraclePopupMenu.add(oracleMenuSBCardItems.addN()); oracleMenuSBCardItems.removeSingle().setText("Remove from Sideboard"); oraclePopupMenu.add(oracleMenuSBCardItems.removeSingle()); oracleMenuSBCardItems.removeAll().setText("Remove All from Sideboard"); oraclePopupMenu.add(oracleMenuSBCardItems.removeAll()); oraclePopupMenu.add(new JSeparator()); JMenuItem oracleEditTagsItem = new JMenuItem("Edit Tags..."); oracleEditTagsItem.addActionListener((e) -> CardTagPanel.editTags(getSelectedCards(), this)); oraclePopupMenu.add(oracleEditTagsItem); // Popup listener for oracle popup menu oraclePopupMenu.addPopupMenuListener(PopupMenuListenerFactory.createVisibleListener((e) -> { for (JMenuItem item : oracleMenuCardItems) item.setEnabled(selectedFrame.isPresent() && !selectedCards.isEmpty()); for (JMenuItem item : oracleMenuSBCardItems) item.setEnabled(selectedFrame.isPresent() && !selectedCards.isEmpty()); oracleEditTagsItem.setEnabled(!selectedCards.isEmpty()); })); // Panel containing inventory and image of currently-selected card JPanel inventoryPanel = new JPanel(new BorderLayout(0, 0)); inventoryPanel.setPreferredSize(new Dimension(getWidth()/4, getHeight()*3/4)); // Panel containing the inventory and the quick-filter bar JPanel tablePanel = new JPanel(new BorderLayout(0, 0)); inventoryPanel.add(tablePanel, BorderLayout.CENTER); // Panel containing the quick-filter bar JPanel filterPanel = new JPanel(); filterPanel.setLayout(new BoxLayout(filterPanel, BoxLayout.X_AXIS)); // Text field for quickly filtering by name JTextField nameFilterField = new JTextField(); filterPanel.add(nameFilterField); // Button for clearing the filter JButton clearButton = new JButton("X"); filterPanel.add(clearButton); // Button for opening the advanced filter dialog JButton advancedFilterButton = new JButton("Advanced..."); filterPanel.add(advancedFilterButton); tablePanel.add(filterPanel, BorderLayout.NORTH); // Create the inventory and put it in the table inventoryTable = new CardTable(); inventoryTable.setDefaultRenderer(String.class, new InventoryTableCellRenderer()); inventoryTable.setDefaultRenderer(Integer.class, new InventoryTableCellRenderer()); inventoryTable.setDefaultRenderer(Rarity.class, new InventoryTableCellRenderer()); inventoryTable.setDefaultRenderer(List.class, new InventoryTableCellRenderer()); inventoryTable.setStripeColor(SettingsDialog.settings().inventory.stripe); inventoryTable.addMouseListener(MouseListenerFactory.createClickListener((e) -> selectedFrame.ifPresent((f) -> { if (e.getClickCount() % 2 == 0) f.addCards("", getSelectedCards(), 1); }))); inventoryTable.setTransferHandler(new TransferHandler() { @Override public boolean canImport(TransferHandler.TransferSupport support) { return false; } @Override protected Transferable createTransferable(JComponent c) { return new Inventory.TransferData(getSelectedCards()); } @Override public int getSourceActions(JComponent c) { return TransferHandler.COPY; } }); inventoryTable.setDragEnabled(true); tablePanel.add(new JScrollPane(inventoryTable), BorderLayout.CENTER); // Table popup menu JPopupMenu inventoryMenu = new JPopupMenu(); inventoryTable.addMouseListener(new TableMouseAdapter(inventoryTable, inventoryMenu)); // Add cards to the main deck CardMenuItems inventoryMenuCardItems = new CardMenuItems(() -> selectedFrame, this::getSelectedCards, true); inventoryMenuCardItems.addAddItems(inventoryMenu); inventoryMenu.add(new JSeparator()); inventoryMenuCardItems.addRemoveItems(inventoryMenu); inventoryMenu.add(new JSeparator()); // Add cards to the sideboard CardMenuItems inventoryMenuSBItems = new CardMenuItems(() -> selectedFrame, this::getSelectedCards, false); inventoryMenuSBItems.addSingle().setText("Add to Sideboard"); inventoryMenu.add(inventoryMenuSBItems.addSingle()); inventoryMenuSBItems.addN().setText("Add to Sideboard..."); inventoryMenu.add(inventoryMenuSBItems.addN()); inventoryMenuSBItems.removeSingle().setText("Remove from Sideboard"); inventoryMenu.add(inventoryMenuSBItems.removeSingle()); inventoryMenuSBItems.removeAll().setText("Remove All from Sideboard"); inventoryMenu.add(inventoryMenuSBItems.removeAll()); inventoryMenu.add(new JSeparator()); // Edit tags item JMenuItem editTagsItem = new JMenuItem("Edit Tags..."); editTagsItem.addActionListener((e) -> CardTagPanel.editTags(getSelectedCards(), this)); inventoryMenu.add(editTagsItem); // Inventory menu listener inventoryMenu.addPopupMenuListener(PopupMenuListenerFactory.createVisibleListener((e) -> { for (JMenuItem item : inventoryMenuCardItems) item.setEnabled(selectedFrame.isPresent() && !selectedCards.isEmpty()); for (JMenuItem item : inventoryMenuSBItems) item.setEnabled(selectedFrame.isPresent() && !selectedCards.isEmpty()); editTagsItem.setEnabled(!selectedCards.isEmpty()); })); // Action to be taken when the user presses the Enter key after entering text into the quick-filter // bar nameFilterField.addActionListener((e) -> { inventory.updateFilter(TextFilter.createQuickFilter(CardAttribute.NAME, nameFilterField.getText().toLowerCase())); inventoryModel.fireTableDataChanged(); }); // Action to be taken when the clear button is pressed (reset the filter) clearButton.addActionListener((e) -> { nameFilterField.setText(""); inventory.updateFilter(CardAttribute.createFilter(CardAttribute.ANY)); inventoryModel.fireTableDataChanged(); }); // Action to be taken when the advanced filter button is pressed (show the advanced filter // dialog) advancedFilterButton.addActionListener((e) -> { FilterGroupPanel panel = new FilterGroupPanel(); if (inventory.getFilter().equals(CardAttribute.createFilter(CardAttribute.ANY))) panel.setContents(CardAttribute.createFilter(CardAttribute.NAME)); else panel.setContents(inventory.getFilter()); panel.addChangeListener((c) -> SwingUtilities.getWindowAncestor((Component)c.getSource()).pack()); ScrollablePanel panelPanel = new ScrollablePanel(new BorderLayout(), ScrollablePanel.TRACK_WIDTH) { @Override public Dimension getPreferredScrollableViewportSize() { Dimension size = panel.getPreferredSize(); size.height = Math.min(MAX_FILTER_HEIGHT, size.height); return size; } }; panelPanel.add(panel, BorderLayout.CENTER); JScrollPane panelPane = new JScrollPane(panelPanel); panelPane.setBorder(BorderFactory.createEmptyBorder()); if (JOptionPane.showConfirmDialog(this, panelPane, "Advanced Filter", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) == JOptionPane.OK_OPTION) { nameFilterField.setText(""); inventory.updateFilter(panel.filter()); inventoryModel.fireTableDataChanged(); } }); // Action to be taken when a selection is made in the inventory table (update the relevant // panels) inventoryTable.getSelectionModel().addListSelectionListener((e) -> { if (!e.getValueIsAdjusting()) { ListSelectionModel lsm = (ListSelectionModel)e.getSource(); if (!lsm.isSelectionEmpty()) setSelectedCards(inventoryTable, inventory); } }); // Split panes dividing the panel into three sections. They can be resized at will. JSplitPane inventorySplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, cardPane, inventoryPanel); inventorySplit.setOneTouchExpandable(true); inventorySplit.setContinuousLayout(true); SwingUtilities.invokeLater(() -> inventorySplit.setDividerLocation(DEFAULT_CARD_HEIGHT)); JSplitPane editorSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, inventorySplit, decklistDesktop); editorSplit.setOneTouchExpandable(true); editorSplit.setContinuousLayout(true); contentPane.add(editorSplit, BorderLayout.CENTER); // File chooser fileChooser = new JFileChooser(SettingsDialog.settings().cwd); fileChooser.setMultiSelectionEnabled(false); fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Deck (*.json)", "json")); fileChooser.setAcceptAllFileFilterUsed(true); // Handle what happens when the window tries to close and when it opens. addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { exit(); } @Override public void windowOpened(WindowEvent e) { if (checkForUpdate(SettingsDialog.settings().inventory.update) == UPDATE_NEEDED && updateInventory()) SettingsDialog.setInventoryVersion(newestVersion); loadInventory(); if (!inventory.isEmpty()) { for (CategorySpec spec : SettingsDialog.settings().editor.categories.presets) { JMenuItem categoryItem = new JMenuItem(spec.getName()); categoryItem.addActionListener((v) -> selectedFrame.ifPresent((f) -> f.addCategory(spec))); presetMenu.add(categoryItem); } for (File f : files) open(f); } } }); } /** * Add a new preset category to the preset categories list. * * @param category new preset category to add */ public void addPreset(CategorySpec category) { CategorySpec spec = new CategorySpec(category); spec.getBlacklist().clear(); spec.getWhitelist().clear(); SettingsDialog.addPresetCategory(spec); JMenuItem categoryItem = new JMenuItem(spec.getName()); categoryItem.addActionListener((e) -> selectedFrame.ifPresent((f) -> f.addCategory(spec))); presetMenu.add(categoryItem); } /** * Apply the global settings. */ public void applySettings() { try { inventorySite = new URL(SettingsDialog.settings().inventory.url() + ".zip"); } catch (MalformedURLException e) { JOptionPane.showMessageDialog(this, "Bad file URL: " + SettingsDialog.settings().inventory.url() + ".zip", "Warning", JOptionPane.WARNING_MESSAGE); } inventoryFile = new File(SettingsDialog.settings().inventory.path()); recentCount = SettingsDialog.settings().editor.recents.count; inventoryModel.setColumns(SettingsDialog.settings().inventory.columns); inventoryTable.setStripeColor(SettingsDialog.settings().inventory.stripe); for (EditorFrame frame : editors) frame.applySettings(); presetMenu.removeAll(); for (CategorySpec spec : SettingsDialog.settings().editor.categories.presets) { JMenuItem categoryItem = new JMenuItem(spec.getName()); categoryItem.addActionListener((e) -> selectedFrame.ifPresent((f) -> f.addCategory(spec))); presetMenu.add(categoryItem); } setImageBackground(SettingsDialog.settings().inventory.background); setHandBackground(SettingsDialog.settings().editor.hand.background); revalidate(); repaint(); } /** * Check to see if the inventory needs to be updated. If it does, ask the user if it should be. * * @param freq desired frequency for downloading updates * @return an integer value representing the state of the update. It can be: * {@link #UPDATE_NEEDED} * {@link #NO_UPDATE} * {@link #UPDATE_CANCELLED} */ public int checkForUpdate(UpdateFrequency freq) { try { if (!inventoryFile.exists()) { JOptionPane.showMessageDialog(this, inventoryFile.getName() + " not found. It will be downloaded.", "Update", JOptionPane.WARNING_MESSAGE); try (BufferedReader in = new BufferedReader(new InputStreamReader(versionSite.openStream()))) { newestVersion = new DatabaseVersion(new JsonParser().parse(in.lines().collect(Collectors.joining())).getAsJsonObject().get("version").getAsString()); } return UPDATE_NEEDED; } else if (SettingsDialog.settings().inventory.update != UpdateFrequency.NEVER) { try (BufferedReader in = new BufferedReader(new InputStreamReader(versionSite.openStream()))) { newestVersion = new DatabaseVersion(new JsonParser().parse(in.lines().collect(Collectors.joining())).getAsJsonObject().get("version").getAsString()); } if (newestVersion.needsUpdate(SettingsDialog.settings().inventory.version, freq)) { int wantUpdate = JOptionPane.showConfirmDialog( this, "Inventory is out of date:\n" + UnicodeSymbols.BULLET + " Current version: " + SettingsDialog.settings().inventory.version + "\n" + UnicodeSymbols.BULLET + " Latest version: " + newestVersion + "\n" + "\n" + "Download update?", "Update", JOptionPane.YES_NO_OPTION ); return wantUpdate == JOptionPane.YES_OPTION ? UPDATE_NEEDED : UPDATE_CANCELLED; } } } catch (IOException e) { JOptionPane.showMessageDialog(this, "Error connecting to server: " + e.getMessage() + ".", "Connection Error", JOptionPane.ERROR_MESSAGE); } catch (ParseException e) { JOptionPane.showMessageDialog(this, "Could not parse version \"" + e.getMessage() + '"', "Error", JOptionPane.ERROR_MESSAGE); } return NO_UPDATE; } /** * Attempt to close the specified frame. * * @param frame frame to close * @return true if the frame was closed, and false otherwise. */ public boolean close(EditorFrame frame) { if (!editors.contains(frame) || !frame.close()) return false; else { if (frame.hasSelectedCards()) { selectedCards = Collections.emptyList(); selectedTable = Optional.empty(); selectedList = Optional.empty(); } editors.remove(frame); if (editors.size() > 0) selectFrame(editors.get(0)); else { selectedFrame = Optional.empty(); deckMenu.setEnabled(false); } revalidate(); repaint(); return true; } } /** * Attempts to close all of the open editors. If any can't be closed for * whatever reason, they will remain open, but the rest will still be closed. * * @return true if all open editors were successfully closed, and false otherwise. */ public boolean closeAll() { var e = new ArrayList<>(editors); boolean closedAll = true; for (EditorFrame editor : e) closedAll &= close(editor); return closedAll; } /** * Exit the application if all open editors successfully close. */ public void exit() { if (closeAll()) { saveSettings(); System.exit(0); } } /** * @param id multiverseid of the #Card to look for * @return the #Card with the given multiverseid. */ public Card getCard(long id) { return inventory.get(id); } /** * Get the currently-selected card(s). * * @return a List containing each currently-selected card in the inventory table. */ public List<Card> getSelectedCards() { return selectedCards; } /** * Get the list corresponding to the table with the currently-selected cards. * * @return the list containing the currently selected cards */ public Optional<CardList> getSelectedList() { return selectedList; } /** * Get the table containing the currently selected cards. * * @return the table with the selected cards */ public Optional<CardTable> getSelectedTable() { return selectedTable; } /** * Check whether or not the inventory has a selection. * * @return true if the inventory has a selection, and false otherwise. */ public boolean hasSelectedCards() { return selectedTable.filter((f) -> f == inventoryTable).isPresent(); } /** * Load the inventory and initialize the inventory table. * * @see InventoryLoadDialog */ public void loadInventory() { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); InventoryLoadDialog loadDialog = new InventoryLoadDialog(this); loadDialog.setLocationRelativeTo(this); inventory = loadDialog.createInventory(inventoryFile); inventory.sort(Card::compareName); inventoryModel = new CardTableModel(inventory, SettingsDialog.settings().inventory.columns); inventoryTable.setModel(inventoryModel); setCursor(Cursor.getDefaultCursor()); } /** * Create a new editor frame. It will not be visible or selected. * * @param manager file manager containing the deck to display * * @see EditorFrame */ public EditorFrame newEditor(DeckSerializer manager) { EditorFrame frame = new EditorFrame(this, ++untitled, manager); editors.add(frame); decklistDesktop.add(frame); return frame; } /** * Create a new editor frame. It will not be visible or selected. * * @see EditorFrame */ public EditorFrame newEditor() { return newEditor(new DeckSerializer()); } /** * Open the file chooser to select a file, and if a file was selected, * parse it and initialize a Deck from it. * * @return the EditorFrame containing the opened deck */ public EditorFrame open() { EditorFrame frame = null; switch (fileChooser.showOpenDialog(this)) { case JFileChooser.APPROVE_OPTION: frame = open(fileChooser.getSelectedFile()); if (frame != null) updateRecents(fileChooser.getSelectedFile()); break; case JFileChooser.CANCEL_OPTION: case JFileChooser.ERROR_OPTION: break; default: break; } return frame; } /** * Open the specified file and create an editor for it. * * @return the EditorFrame containing the opened deck, or <code>null</code> * if opening was canceled. */ public EditorFrame open(File f) { EditorFrame frame = null; for (EditorFrame e : editors) { if (e.file() != null && e.file().equals(f)) { frame = e; break; } } boolean canceled = false; if (frame == null) { DeckSerializer manager = new DeckSerializer(); try { manager.load(f, this); } catch (CancellationException e) { canceled = true; } catch (DeckLoadException e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "Error opening " + f.getName() + ": " + e.getMessage() + ".", "Error", JOptionPane.ERROR_MESSAGE); } finally { if (!canceled) frame = newEditor(manager); } } if (!canceled) { SettingsDialog.setStartingDir(f.getParent()); fileChooser.setCurrentDirectory(f.getParentFile()); selectFrame(frame); } return frame; } /** * If specified editor frame has a file associated with it, save * it to that file. Otherwise, open the file dialog and save it * to whatever is chosen (save as). * * @param frame #EditorFrame to save */ public void save(EditorFrame frame) { if (!frame.save()) saveAs(frame); } /** * Attempt to save all open editors. For each that needs a file, ask for a file * to save to. */ public void saveAll() { for (EditorFrame editor : editors) save(editor); } /** * Save the specified editor frame to a file chosen from a {@link JFileChooser}. * * @param frame frame to save. */ public void saveAs(EditorFrame frame) { // If the file exists, let the user choose whether or not to overwrite. If he or she chooses not to, // ask for a new file. If he or she cancels at any point, stop asking and don't open a file. // TODO: Make this an OverwriteFileChooser boolean done = false; while (!done) { switch (fileChooser.showSaveDialog(this)) { case JFileChooser.APPROVE_OPTION: File f = fileChooser.getSelectedFile(); String fname = f.getAbsolutePath(); if (!fname.endsWith(".json")) f = new File(fname + ".json"); boolean write; if (f.exists()) { int option = JOptionPane.showConfirmDialog(this, "File " + f.getName() + " already exists. Overwrite?", "Warning", JOptionPane.YES_NO_CANCEL_OPTION); write = (option == JOptionPane.YES_OPTION); done = (option != JOptionPane.NO_OPTION); } else { write = true; done = true; } if (write) { frame.save(f); updateRecents(f); } break; case JFileChooser.CANCEL_OPTION: case JFileChooser.ERROR_OPTION: done = true; break; default: break; } } SettingsDialog.setStartingDir(fileChooser.getCurrentDirectory().getPath()); } /** * Write the latest values of the settings to the settings file. */ public void saveSettings() { SettingsDialog.setRecents(recentItems.stream().map((i) -> recents.get(i).getPath()).collect(Collectors.toList())); try (FileOutputStream out = new FileOutputStream(SettingsDialog.PROPERTIES_FILE)) { SettingsDialog.save(); } catch (IOException e) { JOptionPane.showMessageDialog(this, "Error writing " + SettingsDialog.PROPERTIES_FILE + ": " + e.getMessage() + ".", "Error", JOptionPane.ERROR_MESSAGE); } } /** * Set the currently-active frame. This is the one that will be operated on * when single-deck actions are taken from the main frame, such as saving * and closing. * * @param frame #EditorFrame to operate on from now on */ public void selectFrame(EditorFrame frame) { try { frame.setSelected(true); frame.setVisible(true); deckMenu.setEnabled(true); selectedFrame = Optional.of(frame); revalidate(); repaint(); } catch (PropertyVetoException e) {} } /** * Set the background color of the editor panels containing sample hands. * * @param col new color for sample hand panels. */ public void setHandBackground(Color col) { for (EditorFrame frame : editors) frame.setHandBackground(col); } /** * Set the selected cards from the given table backed by the given card list. Make sure * the list and the table represent the same set of cards! * * @param table table with a selection to get the selected cards from * @param list list backing the given table */ public void setSelectedCards(CardTable table, CardList list) { selectedTable = Optional.of(table); selectedList = Optional.of(list); selectedCards = Collections.unmodifiableList(Arrays.stream(table.getSelectedRows()) .mapToObj((r) -> list.get(table.convertRowIndexToModel(r))) .collect(Collectors.toList())); if (!selectedCards.isEmpty()) { final Card card = selectedCards.get(0); oracleTextPane.setText(""); StyledDocument oracleDocument = (StyledDocument)oracleTextPane.getDocument(); Style oracleTextStyle = oracleDocument.addStyle("text", null); StyleConstants.setFontFamily(oracleTextStyle, UIManager.getFont("Label.font").getFamily()); StyleConstants.setFontSize(oracleTextStyle, ComponentUtils.TEXT_SIZE); Style reminderStyle = oracleDocument.addStyle("reminder", oracleTextStyle); StyleConstants.setItalic(reminderStyle, true); card.formatDocument(oracleDocument, false); oracleTextPane.setCaretPosition(0); printedTextPane.setText(""); StyledDocument printedDocument = (StyledDocument)printedTextPane.getDocument(); Style printedTextStyle = printedDocument.addStyle("text", null); StyleConstants.setFontFamily(printedTextStyle, UIManager.getFont("Label.font").getFamily()); StyleConstants.setFontSize(printedTextStyle, ComponentUtils.TEXT_SIZE); reminderStyle = printedDocument.addStyle("reminder", oracleTextStyle); StyleConstants.setItalic(reminderStyle, true); card.formatDocument(printedDocument, true); printedTextPane.setCaretPosition(0); rulingsPane.setText(""); DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); StyledDocument rulingsDocument = (StyledDocument)rulingsPane.getDocument(); Style rulingStyle = oracleDocument.addStyle("ruling", null); StyleConstants.setFontFamily(rulingStyle, UIManager.getFont("Label.font").getFamily()); StyleConstants.setFontSize(rulingStyle, ComponentUtils.TEXT_SIZE); Style dateStyle = rulingsDocument.addStyle("date", rulingStyle); StyleConstants.setBold(dateStyle, true); if (!card.rulings().isEmpty()) { try { for (Date date : card.rulings().keySet()) { for (String ruling : card.rulings().get(date)) { rulingsDocument.insertString(rulingsDocument.getLength(), String.valueOf(UnicodeSymbols.BULLET) + " ", rulingStyle); rulingsDocument.insertString(rulingsDocument.getLength(), format.format(date), dateStyle); rulingsDocument.insertString(rulingsDocument.getLength(), ": ", rulingStyle); int start = 0; for (int i = 0; i < ruling.length(); i++) { switch (ruling.charAt(i)) { case '{': rulingsDocument.insertString(rulingsDocument.getLength(), ruling.substring(start, i), rulingStyle); start = i + 1; break; case '}': Symbol symbol = Symbol.tryParseSymbol(ruling.substring(start, i)); if (symbol == null) { System.err.println("Unexpected symbol {" + ruling.substring(start, i) + "} in ruling for " + card.unifiedName() + "."); rulingsDocument.insertString(rulingsDocument.getLength(), ruling.substring(start, i), rulingStyle); } else { Style symbolStyle = rulingsDocument.addStyle(symbol.toString(), null); StyleConstants.setIcon(symbolStyle, symbol.getIcon(ComponentUtils.TEXT_SIZE)); rulingsDocument.insertString(rulingsDocument.getLength(), " ", symbolStyle); } start = i + 1; break; default: break; } if (i == ruling.length() - 1 && ruling.charAt(i) != '}') rulingsDocument.insertString(rulingsDocument.getLength(), ruling.substring(start, i + 1) + '\n', rulingStyle); } } } } catch (BadLocationException e) { e.printStackTrace(); } } rulingsPane.setCaretPosition(0); imagePanel.setCard(card); } if (table != inventoryTable) inventoryTable.clearSelection(); for (EditorFrame editor : editors) editor.clearTableSelections(table); } /** * Set the background color of the panel containing the card image. * * @param col new color for the card image panel */ public void setImageBackground(Color col) { imagePanel.setBackground(col); } /** * Update the inventory table to bold the cards that are in the currently-selected editor. */ public void updateCardsInDeck() { inventoryModel.fireTableDataChanged(); } /** * Download the latest list of cards from the inventory site (default mtgjson.com). If the * download is taking a while, a progress bar will appear. * * @return true if the download was successful, and false otherwise. */ public boolean updateInventory() { InventoryDownloadDialog downloadDialog = new InventoryDownloadDialog(this); downloadDialog.setLocationRelativeTo(this); return downloadDialog.downloadInventory(inventorySite, inventoryFile); } /** * Update the recently-opened files to add the most recently-opened one, and delete * the oldest one if too many are there. * * @param f #File to add to the list */ public void updateRecents(File f) { if (!recents.containsValue(f)) { recentsMenu.setEnabled(true); if (recentItems.size() >= recentCount) { JMenuItem eldest = recentItems.poll(); recents.remove(eldest); recentsMenu.remove(eldest); } JMenuItem mostRecent = new JMenuItem(f.getPath()); recentItems.offer(mostRecent); recents.put(mostRecent, f); mostRecent.addActionListener((e) -> open(f)); recentsMenu.add(mostRecent); } } }
Use an OverwriteFileChooser as the main chooser
src/main/java/editor/gui/MainFrame.java
Use an OverwriteFileChooser as the main chooser
<ide><path>rc/main/java/editor/gui/MainFrame.java <ide> /** <ide> * File chooser for opening and saving. <ide> */ <del> private JFileChooser fileChooser; <add> private OverwriteFileChooser fileChooser; <ide> /** <ide> * URL pointing to the site to get the latest version of the <ide> * inventory from. <ide> contentPane.add(editorSplit, BorderLayout.CENTER); <ide> <ide> // File chooser <del> fileChooser = new JFileChooser(SettingsDialog.settings().cwd); <add> fileChooser = new OverwriteFileChooser(SettingsDialog.settings().cwd); <ide> fileChooser.setMultiSelectionEnabled(false); <ide> fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Deck (*.json)", "json")); <ide> fileChooser.setAcceptAllFileFilterUsed(true); <ide> */ <ide> public void saveAs(EditorFrame frame) <ide> { <del> // If the file exists, let the user choose whether or not to overwrite. If he or she chooses not to, <del> // ask for a new file. If he or she cancels at any point, stop asking and don't open a file. <del> <del> // TODO: Make this an OverwriteFileChooser <del> boolean done = false; <del> while (!done) <del> { <del> switch (fileChooser.showSaveDialog(this)) <del> { <del> case JFileChooser.APPROVE_OPTION: <del> File f = fileChooser.getSelectedFile(); <del> String fname = f.getAbsolutePath(); <del> if (!fname.endsWith(".json")) <del> f = new File(fname + ".json"); <del> boolean write; <del> if (f.exists()) <del> { <del> int option = JOptionPane.showConfirmDialog(this, "File " + f.getName() + " already exists. Overwrite?", "Warning", JOptionPane.YES_NO_CANCEL_OPTION); <del> write = (option == JOptionPane.YES_OPTION); <del> done = (option != JOptionPane.NO_OPTION); <del> } <del> else <del> { <del> write = true; <del> done = true; <del> } <del> if (write) <del> { <del> frame.save(f); <del> updateRecents(f); <del> } <del> break; <del> case JFileChooser.CANCEL_OPTION: <del> case JFileChooser.ERROR_OPTION: <del> done = true; <del> break; <del> default: <del> break; <del> } <add> switch (fileChooser.showSaveDialog(this)) <add> { <add> case JFileChooser.APPROVE_OPTION: <add> File f = fileChooser.getSelectedFile(); <add> String fname = f.getAbsolutePath(); <add> if (!fname.endsWith(".json")) <add> f = new File(fname + ".json"); <add> frame.save(f); <add> updateRecents(f); <add> break; <add> case JFileChooser.CANCEL_OPTION: <add> break; <add> case JFileChooser.ERROR_OPTION: <add> JOptionPane.showMessageDialog(this, "Could not save " + frame.deckName() + '.', "Error", JOptionPane.ERROR_MESSAGE); <add> break; <ide> } <ide> SettingsDialog.setStartingDir(fileChooser.getCurrentDirectory().getPath()); <ide> }
Java
epl-1.0
9ae3e9175f0865d4a31be449a8511520f6001857
0
Alma-Sanchez/ChessAI2
import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.Scanner; public class BoardMouseListener implements MouseListener { static int globaldepth=4; public static Chess chess; //position of mouse public static int posx, posy, posxfinal, posyfinal; //boolean so white always moves first public static boolean whiteturn = true; public static String alphaBeta(int depth, int beta, int alpha, String move, int player) { //return in the form of 1234b########## String list=possiblemoves(); //String list="1"; if (depth==0 || list.length()==0) { return move+(rating()*(player*2-1)); } //list=""; //System.out.print("How many moves are there: "); //Scanner sc=new Scanner(System.in); //int temp=sc.nextInt(); //for (int i=0;i<temp;i++) { // list+="1111b"; //} //sort later player=1-player;//either 1 or 0 for (int i=0;i<list.length();i+=5) { makemove(list.substring(i,i+5)); flipboard(); String returnString=alphaBeta(depth-1, beta, alpha, list.substring(i,i+5), player); int value=Integer.valueOf(returnString.substring(5)); flipboard(); undomove(list.substring(i,i+5)); if (player==0) { if (value<=beta) { beta=value; if (depth==globaldepth) {move=returnString.substring(0,5); } } } else { if (value>alpha) { alpha=value; if (depth==globaldepth) { move=returnString.substring(0,5); } } } if (alpha>=beta) { if (player==0) { return move+beta; } else { return move+alpha; } } } if (player==0) { return move+beta; } else { return move+alpha; } } /*String alphaBeta(int depth, int beta, int alpha, String move, int player ) { String list= possiblemoves(); //String list="1"; if (depth==0 || list.length()==0){ return move+(rating() *(player*2-1)); } //sort with be here list=""; System.out.print("How many moves are there: "); Scanner sc=new Scanner(System.in); int temp=sc.nextInt(); for (int i=0; i<temp; i++){ list="1111b"; } player=1-player; for (int i=0; i<list.length(); i+=5){ makemove(list.substring(i, i+5)); flipboard(); String returnstring= alphaBeta(depth-1, beta, alpha, list.substring(i, +i+5), player); int value= Integer.valueOf(returnstring.substring(5)); flipboard(); undomove(list.substring(i,i+5)); if (player==0){ if (value<=beta){ beta=value; if (depth==globaldepth){ move=returnstring.substring(0,5); } } } else{ if (value>=alpha){ alpha=value; if (depth==globaldepth){ move=returnstring.substring(0,5); } } } if (alpha>=beta){ if (player==0){ return move+beta; } else{ return move+alpha; } } } if (player==0){ return move+beta; } else{ return move+alpha; } }*/ public static String possiblemoves(){ String themoves=""; int count=0; for (int i=0; i<8; i++){ for (int j=0; j<8; j++){ if (Chess.pieces[i][j]!=null){ for (int k=0; k<8; k++){ for (int l=0; l<8; l++){ //System.out.println("Initial y is "+ i+" Initial x is "+j+ " Final y is "+k+ " Final x is "+ l); if (Chess.pieces[i][j].canMove(j, i, l ,k)){ count++; String istring=Integer.toString(i); String jstring=Integer.toString(j); String kstring=Integer.toString(k); String lstring=Integer.toString(l); if (Chess.pieces[l][k]!=null){ String newmove=jstring+istring+lstring+kstring+Chess.pieces[l][k].pieceletter; if (count<100){ themoves+=newmove; } } else{ String newmove=jstring+istring+lstring+kstring+" "; if (count<100){ themoves+=newmove; } } } } } } } } return themoves; } public static int rating(){ System.out.print("What is the score: "); Scanner sc=new Scanner(System.in); return sc.nextInt(); } public static void flipboard(){ String temp; for (int i=0; i<32; i++){ int r= i/8; int c= i%8; System.out.println(r); System.out.println(c); if (Character.isUpperCase(chess.pieces[c][r].pieceletter.charAt(0))) { temp=chess.pieces[c][r].pieceletter.toLowerCase(); } else{ temp=chess.pieces[c][r].pieceletter.toUpperCase(); } if (Character.isUpperCase(chess.pieces[7-c][7-r].pieceletter.charAt(0))) { chess.pieces[c][r].pieceletter=chess.pieces[7-c][7-r].pieceletter.toLowerCase(); } else{ chess.pieces[c][r].pieceletter=chess.pieces[7-c][7-r].pieceletter.toUpperCase(); } /*if (chess.pieces[c][r].pieceletter=="k" || chess.pieces[c][r].pieceletter=="K"){ int kingtempy=c; int kingtempx=r; }*/ chess.pieces[7-c][7-r].pieceletter=temp; } } public static void makemove(String moveinfo){ int posx=Character.getNumericValue(moveinfo.charAt(0)); int posy=Character.getNumericValue(moveinfo.charAt(1)); int posxfinal=Character.getNumericValue(moveinfo.charAt(2)); int posyfinal=Character.getNumericValue(moveinfo.charAt(3)); //conditional checking to see if it's the first turn so white moves first if (whiteturn == true) { //makes it so you can click and release on empty square without null pointer exception if (Math.abs(posxfinal - posx) != 0|| Math.abs(posyfinal - posy) != 0) { //checks to see if piece can move based on initial and final coordinates, this version also only allows white to move since it is the first turn if (chess.pieces[posy][posx].canMove(posx, posy, posxfinal,posyfinal)&& chess.pieces[posy][posx].isWhite == true) { //moves piece chess.pieces[posyfinal][posxfinal] = chess.pieces[posy][posx]; //conditional prevents user from deleteing piece of mouse is clicked and release on the same position if (posy != posyfinal || posx != posxfinal) { //deletes old piece position chess.pieces[posy][posx] = null; //ends first move/whites beginning turn whiteturn = false; } //repaints board with new piece positions chess.theboard.repaint(); String test= possiblemoves(); System.out.println(test); } } } //conditionals for all turns after first turn else{ //makes it so user can click and release on empty square without null pointer exception if (Math.abs(posxfinal - posx) != 0|| Math.abs(posyfinal - posy) != 0) { //checks if piece can move if (chess.pieces[posy][posx].canMove(posx, posy, posxfinal,posyfinal)) { //changes position chess.pieces[posyfinal][posxfinal] = chess.pieces[posy][posx]; //prevents user from accidentally deleting piece by clicking and releasing on same piece if (posy != posyfinal || posx != posxfinal) { //deletes old piece position chess.pieces[posy][posx] = null; } //repaints boardå chess.theboard.repaint(); String test= possiblemoves(); //System.out.println(test); } } } } public static void undomove(String moveinfo){ posx=Character.getNumericValue(moveinfo.charAt(0)); posy=Character.getNumericValue(moveinfo.charAt(1)); posxfinal=Character.getNumericValue(moveinfo.charAt(2)); posyfinal=Character.getNumericValue(moveinfo.charAt(3)); chess.pieces[posy][posx]=chess.pieces[posyfinal][posxfinal]; if (moveinfo.charAt(4)==' '){ Chess.pieces[posyfinal][posxfinal]=null; } else if (moveinfo.charAt(4)=='r'){ Chess.pieces[posyfinal][posxfinal]=new Rook(false, chess); } else if (moveinfo.charAt(4)=='R'){ Chess.pieces[posyfinal][posxfinal]=new Rook(true, chess); } else if (moveinfo.charAt(4)=='k'){ Chess.pieces[posyfinal][posxfinal]=new Knight(false, chess); } else if (moveinfo.charAt(4)=='K'){ Chess.pieces[posyfinal][posxfinal]=new Knight(true, chess); } else if (moveinfo.charAt(4)=='b'){ Chess.pieces[posyfinal][posxfinal]=new Bishop(false, chess); } else if (moveinfo.charAt(4)=='B'){ Chess.pieces[posyfinal][posxfinal]=new Bishop(true, chess); } else if (moveinfo.charAt(4)=='q'){ Chess.pieces[posyfinal][posxfinal]=new Queen(false, chess); } else if (moveinfo.charAt(4)=='Q'){ Chess.pieces[posyfinal][posxfinal]=new Queen(true, chess); } else if (moveinfo.charAt(4)=='k'){ Chess.pieces[posyfinal][posxfinal]=new King(false, chess); } else if (moveinfo.charAt(4)=='K'){ Chess.pieces[posyfinal][posxfinal]=new King(true, chess); } else if (moveinfo.charAt(4)=='p'){ Chess.pieces[posyfinal][posxfinal]=new Pawn(false, chess); } else if(moveinfo.charAt(4)=='P'){ Chess.pieces[posyfinal][posxfinal]=new Pawn(true, chess); } } public BoardMouseListener(Chess chess) { this.chess = chess; } public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent e) { //equates initial mouse/piece position with tile position on board posx = e.getX() / 62; posy = e.getY() / 62; } public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub //equates final mouse/piece position with tile position on board posxfinal = e.getX() / 62; posyfinal = e.getY() / 62; //conditional checking to see if it's the first turn so white moves first if (whiteturn == true) { //makes it so you can click and release on empty square without null pointer exception if (Math.abs(posxfinal - posx) != 0|| Math.abs(posyfinal - posy) != 0) { //checks to see if piece can move based on initial and final coordinates, this version also only allows white to move since it is the first turn if (chess.pieces[posy][posx].canMove(posx, posy, posxfinal,posyfinal)&& chess.pieces[posy][posx].isWhite == true) { //moves piece chess.pieces[posyfinal][posxfinal] = chess.pieces[posy][posx]; //conditional prevents user from deleteing piece of mouse is clicked and release on the same position if (posy != posyfinal || posx != posxfinal) { //deletes old piece position chess.pieces[posy][posx] = null; //ends first move/whites beginning turn whiteturn = false; } //repaints board with new piece positions chess.theboard.repaint(); String test= possiblemoves(); //System.out.println(test); /*for (int i=0; i<100; i++){ if (test[i]!=null){ System.out.println(test[i]); } }*/ //System.out.println(possiblemoves()); /*if (Math.abs(posxfinal - posx) != 0|| Math.abs(posyfinal - posy) != 0) { //checks if piece can move System.out.println(chess.pieces[posy][posx]); if (chess.pieces[posy][posx].canMove(posx, posy, posxfinal,posyfinal)) { //changes position chess.pieces[posyfinal][posxfinal] = chess.pieces[posy][posx]; //prevents user from accidentally deleting piece by clicking and releasing on same piece if (posy != posyfinal || posx != posxfinal) { //deletes old piece position chess.pieces[posy][posx] = null; } //repaints board chess.theboard.repaint(); //insert ai here //System.out.println(possiblemoves()); } }*/ } } } //conditionals for all turns after first turn else{ //makes it so user can click and release on empty square without null pointer exception if (Math.abs(posxfinal - posx) != 0|| Math.abs(posyfinal - posy) != 0) { //checks if piece can move if (chess.pieces[posy][posx].canMove(posx, posy, posxfinal,posyfinal)) { //changes position chess.pieces[posyfinal][posxfinal] = chess.pieces[posy][posx]; //prevents user from accidentally deleting piece by clicking and releasing on same piece if (posy != posyfinal || posx != posxfinal) { //deletes old piece position chess.pieces[posy][posx] = null; } //repaints boardå chess.theboard.repaint(); String test= possiblemoves(); //System.out.println(test); /*for (int i=0; i<100; i++){ if (test[i]!=null){ System.out.println(test[i]); } }*/ //insert ai here /*if (Math.abs(posxfinal - posx) != 0|| Math.abs(posyfinal - posy) != 0) { //checks if piece can move if (chess.pieces[posy][posx].canMove(posx, posy, posxfinal,posyfinal)) { //changes position chess.pieces[posyfinal][posxfinal] = chess.pieces[posy][posx]; //prevents user from accidentally deleting piece by clicking and releasing on same piece if (posy != posyfinal || posx != posxfinal) { //deletes old piece position chess.pieces[posy][posx] = null; } //repaints board chess.theboard.repaint(); } }*/ } } } makemove(alphaBeta(globaldepth,1000000,-1000000,"",0)); } public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } }
src/BoardMouseListener.java
import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.Scanner; public class BoardMouseListener implements MouseListener { static int globaldepth=4; public static Chess chess; //position of mouse public static int posx, posy, posxfinal, posyfinal; //boolean so white always moves first public static boolean whiteturn = true; public static String alphaBeta(int depth, int beta, int alpha, String move, int player) { //return in the form of 1234b########## //String list=posibleMoves(); String list="1"; if (depth==0 || list.length()==0) { return move+(rating()); }//*(player*2-1));} list=""; System.out.print("How many moves are there: "); Scanner sc=new Scanner(System.in); int temp=sc.nextInt(); for (int i=0;i<temp;i++) { list+="1111b"; } //sort later player=1-player;//either 1 or 0 for (int i=0;i<list.length();i+=5) { makemove(list.substring(i,i+5)); flipboard(); String returnString=alphaBeta(depth-1, beta, alpha, list.substring(i,i+5), player); int value=Integer.valueOf(returnString.substring(5)); flipboard(); undomove(list.substring(i,i+5)); if (player==0) { if (value<=beta) { beta=value; if (depth==globaldepth) {move=returnString.substring(0,5); } } } else { if (value>alpha) { alpha=value; if (depth==globaldepth) { move=returnString.substring(0,5); } } } if (alpha>=beta) { if (player==0) { return move+beta; } else { return move+alpha; } } } if (player==0) { return move+beta; } else { return move+alpha; } } /*String alphaBeta(int depth, int beta, int alpha, String move, int player ) { String list= possiblemoves(); //String list="1"; if (depth==0 || list.length()==0){ return move+(rating() *(player*2-1)); } //sort with be here list=""; System.out.print("How many moves are there: "); Scanner sc=new Scanner(System.in); int temp=sc.nextInt(); for (int i=0; i<temp; i++){ list="1111b"; } player=1-player; for (int i=0; i<list.length(); i+=5){ makemove(list.substring(i, i+5)); flipboard(); String returnstring= alphaBeta(depth-1, beta, alpha, list.substring(i, +i+5), player); int value= Integer.valueOf(returnstring.substring(5)); flipboard(); undomove(list.substring(i,i+5)); if (player==0){ if (value<=beta){ beta=value; if (depth==globaldepth){ move=returnstring.substring(0,5); } } } else{ if (value>=alpha){ alpha=value; if (depth==globaldepth){ move=returnstring.substring(0,5); } } } if (alpha>=beta){ if (player==0){ return move+beta; } else{ return move+alpha; } } } if (player==0){ return move+beta; } else{ return move+alpha; } }*/ public static String possiblemoves(){ String themoves=""; int count=0; for (int i=0; i<8; i++){ for (int j=0; j<8; j++){ if (Chess.pieces[i][j]!=null){ for (int k=0; k<8; k++){ for (int l=0; l<8; l++){ //System.out.println("Initial y is "+ i+" Initial x is "+j+ " Final y is "+k+ " Final x is "+ l); if (Chess.pieces[i][j].canMove(j, i, l ,k)){ count++; String istring=Integer.toString(i); String jstring=Integer.toString(j); String kstring=Integer.toString(k); String lstring=Integer.toString(l); if (Chess.pieces[l][k]!=null){ String newmove=jstring+istring+lstring+kstring+Chess.pieces[l][k].pieceletter; if (count<100){ themoves+=newmove; } } else{ String newmove=jstring+istring+lstring+kstring+" "; if (count<100){ themoves+=newmove; } } } } } } } } return themoves; } public static int rating(){ System.out.print("What is the score: "); Scanner sc=new Scanner(System.in); return sc.nextInt(); } public static void flipboard(){ String temp; for (int i=0; i<32; i++){ int r= i/8; int c= i%8; if (Character.isUpperCase(chess.pieces[c][r].pieceletter.charAt(0))) { temp=chess.pieces[c][r].pieceletter.toLowerCase(); } else{ temp=chess.pieces[c][r].pieceletter.toUpperCase(); } if (Character.isUpperCase(chess.pieces[7-c][7-r].pieceletter.charAt(0))) { temp=chess.pieces[7-c][7-r].pieceletter.toLowerCase(); } else{ temp=chess.pieces[7-c][7-r].pieceletter.toUpperCase(); } /*if (chess.pieces[c][r].pieceletter=="k" || chess.pieces[c][r].pieceletter=="K"){ int kingtempy=c; int kingtempx=r; }*/ chess.pieces[7-c][7-r].pieceletter=temp; } } public static void makemove(String moveinfo){ posx=moveinfo.charAt(0); posy=moveinfo.charAt(1); posxfinal=moveinfo.charAt(2); posyfinal=moveinfo.charAt(3); //conditional checking to see if it's the first turn so white moves first if (whiteturn == true) { //makes it so you can click and release on empty square without null pointer exception if (Math.abs(posxfinal - posx) != 0|| Math.abs(posyfinal - posy) != 0) { //checks to see if piece can move based on initial and final coordinates, this version also only allows white to move since it is the first turn if (chess.pieces[posy][posx].canMove(posx, posy, posxfinal,posyfinal)&& chess.pieces[posy][posx].isWhite == true) { //moves piece chess.pieces[posyfinal][posxfinal] = chess.pieces[posy][posx]; //conditional prevents user from deleteing piece of mouse is clicked and release on the same position if (posy != posyfinal || posx != posxfinal) { //deletes old piece position chess.pieces[posy][posx] = null; //ends first move/whites beginning turn whiteturn = false; } //repaints board with new piece positions chess.theboard.repaint(); String test= possiblemoves(); //System.out.println(test); } } } //conditionals for all turns after first turn else{ //makes it so user can click and release on empty square without null pointer exception if (Math.abs(posxfinal - posx) != 0|| Math.abs(posyfinal - posy) != 0) { //checks if piece can move if (chess.pieces[posy][posx].canMove(posx, posy, posxfinal,posyfinal)) { //changes position chess.pieces[posyfinal][posxfinal] = chess.pieces[posy][posx]; //prevents user from accidentally deleting piece by clicking and releasing on same piece if (posy != posyfinal || posx != posxfinal) { //deletes old piece position chess.pieces[posy][posx] = null; } //repaints boardå chess.theboard.repaint(); String test= possiblemoves(); //System.out.println(test); } } } } public static void undomove(String moveinfo){ posx=Character.getNumericValue(moveinfo.charAt(0)); posy=Character.getNumericValue(moveinfo.charAt(1)); posxfinal=Character.getNumericValue(moveinfo.charAt(2)); posyfinal=Character.getNumericValue(moveinfo.charAt(3)); chess.pieces[posy][posx]=chess.pieces[posyfinal][posxfinal]; if (moveinfo.charAt(4)==' '){ Chess.pieces[posyfinal][posxfinal]=null; } else if (moveinfo.charAt(4)=='r'){ Chess.pieces[posyfinal][posxfinal]=new Rook(false, chess); } else if (moveinfo.charAt(4)=='R'){ Chess.pieces[posyfinal][posxfinal]=new Rook(true, chess); } else if (moveinfo.charAt(4)=='k'){ Chess.pieces[posyfinal][posxfinal]=new Knight(false, chess); } else if (moveinfo.charAt(4)=='K'){ Chess.pieces[posyfinal][posxfinal]=new Knight(true, chess); } else if (moveinfo.charAt(4)=='b'){ Chess.pieces[posyfinal][posxfinal]=new Bishop(false, chess); } else if (moveinfo.charAt(4)=='B'){ Chess.pieces[posyfinal][posxfinal]=new Bishop(true, chess); } else if (moveinfo.charAt(4)=='q'){ Chess.pieces[posyfinal][posxfinal]=new Queen(false, chess); } else if (moveinfo.charAt(4)=='Q'){ Chess.pieces[posyfinal][posxfinal]=new Queen(true, chess); } else if (moveinfo.charAt(4)=='k'){ Chess.pieces[posyfinal][posxfinal]=new King(false, chess); } else if (moveinfo.charAt(4)=='K'){ Chess.pieces[posyfinal][posxfinal]=new King(true, chess); } else if (moveinfo.charAt(4)=='p'){ Chess.pieces[posyfinal][posxfinal]=new Pawn(false, chess); } else if(moveinfo.charAt(4)=='P'){ Chess.pieces[posyfinal][posxfinal]=new Pawn(true, chess); } } public BoardMouseListener(Chess chess) { this.chess = chess; } public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent e) { //equates initial mouse/piece position with tile position on board posx = e.getX() / 62; posy = e.getY() / 62; } public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub //equates final mouse/piece position with tile position on board posxfinal = e.getX() / 62; posyfinal = e.getY() / 62; //conditional checking to see if it's the first turn so white moves first if (whiteturn == true) { //makes it so you can click and release on empty square without null pointer exception if (Math.abs(posxfinal - posx) != 0|| Math.abs(posyfinal - posy) != 0) { //checks to see if piece can move based on initial and final coordinates, this version also only allows white to move since it is the first turn if (chess.pieces[posy][posx].canMove(posx, posy, posxfinal,posyfinal)&& chess.pieces[posy][posx].isWhite == true) { //moves piece chess.pieces[posyfinal][posxfinal] = chess.pieces[posy][posx]; //conditional prevents user from deleteing piece of mouse is clicked and release on the same position if (posy != posyfinal || posx != posxfinal) { //deletes old piece position chess.pieces[posy][posx] = null; //ends first move/whites beginning turn whiteturn = false; } //repaints board with new piece positions chess.theboard.repaint(); String test= possiblemoves(); //System.out.println(test); /*for (int i=0; i<100; i++){ if (test[i]!=null){ System.out.println(test[i]); } }*/ //System.out.println(possiblemoves()); /*if (Math.abs(posxfinal - posx) != 0|| Math.abs(posyfinal - posy) != 0) { //checks if piece can move System.out.println(chess.pieces[posy][posx]); if (chess.pieces[posy][posx].canMove(posx, posy, posxfinal,posyfinal)) { //changes position chess.pieces[posyfinal][posxfinal] = chess.pieces[posy][posx]; //prevents user from accidentally deleting piece by clicking and releasing on same piece if (posy != posyfinal || posx != posxfinal) { //deletes old piece position chess.pieces[posy][posx] = null; } //repaints board chess.theboard.repaint(); //insert ai here //System.out.println(possiblemoves()); } }*/ } } } //conditionals for all turns after first turn else{ //makes it so user can click and release on empty square without null pointer exception if (Math.abs(posxfinal - posx) != 0|| Math.abs(posyfinal - posy) != 0) { //checks if piece can move if (chess.pieces[posy][posx].canMove(posx, posy, posxfinal,posyfinal)) { //changes position chess.pieces[posyfinal][posxfinal] = chess.pieces[posy][posx]; //prevents user from accidentally deleting piece by clicking and releasing on same piece if (posy != posyfinal || posx != posxfinal) { //deletes old piece position chess.pieces[posy][posx] = null; } //repaints boardå chess.theboard.repaint(); String test= possiblemoves(); //System.out.println(test); /*for (int i=0; i<100; i++){ if (test[i]!=null){ System.out.println(test[i]); } }*/ //insert ai here /*if (Math.abs(posxfinal - posx) != 0|| Math.abs(posyfinal - posy) != 0) { //checks if piece can move if (chess.pieces[posy][posx].canMove(posx, posy, posxfinal,posyfinal)) { //changes position chess.pieces[posyfinal][posxfinal] = chess.pieces[posy][posx]; //prevents user from accidentally deleting piece by clicking and releasing on same piece if (posy != posyfinal || posx != posxfinal) { //deletes old piece position chess.pieces[posy][posx] = null; } //repaints board chess.theboard.repaint(); } }*/ } } } System.out.println(alphaBeta(globaldepth,1000000,-1000000,"",0)); } public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } }
Ai kinda works now, not really
src/BoardMouseListener.java
Ai kinda works now, not really
<ide><path>rc/BoardMouseListener.java <ide> <ide> public static String alphaBeta(int depth, int beta, int alpha, String move, int player) { <ide> //return in the form of 1234b########## <del> //String list=posibleMoves(); <del> String list="1"; <add> String list=possiblemoves(); <add> //String list="1"; <ide> if (depth==0 || list.length()==0) { <del> return move+(rating()); <del> }//*(player*2-1));} <del> list=""; <del> System.out.print("How many moves are there: "); <del> Scanner sc=new Scanner(System.in); <del> int temp=sc.nextInt(); <del> for (int i=0;i<temp;i++) { <del> list+="1111b"; <del> } <add> return move+(rating()*(player*2-1)); <add> } <add> //list=""; <add> //System.out.print("How many moves are there: "); <add> //Scanner sc=new Scanner(System.in); <add> //int temp=sc.nextInt(); <add> //for (int i=0;i<temp;i++) { <add> // list+="1111b"; <add> //} <ide> //sort later <ide> player=1-player;//either 1 or 0 <ide> for (int i=0;i<list.length();i+=5) { <ide> for (int i=0; i<32; i++){ <ide> int r= i/8; <ide> int c= i%8; <add> System.out.println(r); <add> System.out.println(c); <ide> if (Character.isUpperCase(chess.pieces[c][r].pieceletter.charAt(0))) <ide> { <ide> temp=chess.pieces[c][r].pieceletter.toLowerCase(); <ide> } <ide> if (Character.isUpperCase(chess.pieces[7-c][7-r].pieceletter.charAt(0))) <ide> { <del> temp=chess.pieces[7-c][7-r].pieceletter.toLowerCase(); <add> chess.pieces[c][r].pieceletter=chess.pieces[7-c][7-r].pieceletter.toLowerCase(); <ide> } <ide> else{ <del> temp=chess.pieces[7-c][7-r].pieceletter.toUpperCase(); <add> chess.pieces[c][r].pieceletter=chess.pieces[7-c][7-r].pieceletter.toUpperCase(); <ide> } <ide> /*if (chess.pieces[c][r].pieceletter=="k" || chess.pieces[c][r].pieceletter=="K"){ <ide> int kingtempy=c; <ide> <ide> } <ide> public static void makemove(String moveinfo){ <del> <del> posx=moveinfo.charAt(0); <del> posy=moveinfo.charAt(1); <del> posxfinal=moveinfo.charAt(2); <del> posyfinal=moveinfo.charAt(3); <add> int posx=Character.getNumericValue(moveinfo.charAt(0)); <add> int posy=Character.getNumericValue(moveinfo.charAt(1)); <add> int posxfinal=Character.getNumericValue(moveinfo.charAt(2)); <add> int posyfinal=Character.getNumericValue(moveinfo.charAt(3)); <add> <ide> //conditional checking to see if it's the first turn so white moves first <ide> if (whiteturn == true) { <ide> //makes it so you can click and release on empty square without null pointer exception <ide> chess.theboard.repaint(); <ide> <ide> String test= possiblemoves(); <del> //System.out.println(test); <add> System.out.println(test); <ide> <ide> <ide> } <ide> //makes it so user can click and release on empty square without null pointer exception <ide> if (Math.abs(posxfinal - posx) != 0|| Math.abs(posyfinal - posy) != 0) { <ide> //checks if piece can move <add> <add> <ide> if (chess.pieces[posy][posx].canMove(posx, posy, posxfinal,posyfinal)) { <ide> //changes position <ide> chess.pieces[posyfinal][posxfinal] = chess.pieces[posy][posx]; <ide> } <ide> } <ide> <del> System.out.println(alphaBeta(globaldepth,1000000,-1000000,"",0)); <add> makemove(alphaBeta(globaldepth,1000000,-1000000,"",0)); <ide> <ide> } <ide>
Java
apache-2.0
error: pathspec 'sandbox/spring-security-config/src/test/java/org/acegisecurity/config/RememberMeServicesBeanDefinitionParserTests.java' did not match any file(s) known to git
5249befa25a541eba6e9e39a383e76546fa5b2a6
1
pwheel/spring-security,jmnarloch/spring-security,ollie314/spring-security,cyratech/spring-security,wkorando/spring-security,fhanik/spring-security,Xcorpio/spring-security,kazuki43zoo/spring-security,tekul/spring-security,SanjayUser/SpringSecurityPro,adairtaosy/spring-security,xingguang2013/spring-security,mdeinum/spring-security,Krasnyanskiy/spring-security,yinhe402/spring-security,zshift/spring-security,pkdevbox/spring-security,justinedelson/spring-security,chinazhaoht/spring-security,ractive/spring-security,spring-projects/spring-security,ajdinhedzic/spring-security,mounb/spring-security,adairtaosy/spring-security,spring-projects/spring-security,jmnarloch/spring-security,hippostar/spring-security,mdeinum/spring-security,dsyer/spring-security,vitorgv/spring-security,wilkinsona/spring-security,fhanik/spring-security,follow99/spring-security,kazuki43zoo/spring-security,mounb/spring-security,kazuki43zoo/spring-security,raindev/spring-security,wkorando/spring-security,Xcorpio/spring-security,Krasnyanskiy/spring-security,caiwenshu/spring-security,jgrandja/spring-security,spring-projects/spring-security,zgscwjm/spring-security,driftman/spring-security,panchenko/spring-security,Peter32/spring-security,olezhuravlev/spring-security,cyratech/spring-security,MatthiasWinzeler/spring-security,ollie314/spring-security,izeye/spring-security,thomasdarimont/spring-security,chinazhaoht/spring-security,forestqqqq/spring-security,yinhe402/spring-security,zshift/spring-security,thomasdarimont/spring-security,forestqqqq/spring-security,cyratech/spring-security,vitorgv/spring-security,likaiwalkman/spring-security,wilkinsona/spring-security,jgrandja/spring-security,pwheel/spring-security,chinazhaoht/spring-security,dsyer/spring-security,cyratech/spring-security,SanjayUser/SpringSecurityPro,SanjayUser/SpringSecurityPro,zgscwjm/spring-security,jmnarloch/spring-security,zhaoqin102/spring-security,zgscwjm/spring-security,xingguang2013/spring-security,hippostar/spring-security,mounb/spring-security,djechelon/spring-security,ollie314/spring-security,eddumelendez/spring-security,zshift/spring-security,diegofernandes/spring-security,mounb/spring-security,tekul/spring-security,diegofernandes/spring-security,ajdinhedzic/spring-security,pwheel/spring-security,zgscwjm/spring-security,raindev/spring-security,fhanik/spring-security,xingguang2013/spring-security,pkdevbox/spring-security,panchenko/spring-security,liuguohua/spring-security,zhaoqin102/spring-security,caiwenshu/spring-security,dsyer/spring-security,djechelon/spring-security,mrkingybc/spring-security,raindev/spring-security,izeye/spring-security,liuguohua/spring-security,spring-projects/spring-security,rwinch/spring-security,izeye/spring-security,spring-projects/spring-security,follow99/spring-security,forestqqqq/spring-security,pkdevbox/spring-security,spring-projects/spring-security,wilkinsona/spring-security,mdeinum/spring-security,mparaz/spring-security,zhaoqin102/spring-security,olezhuravlev/spring-security,eddumelendez/spring-security,olezhuravlev/spring-security,driftman/spring-security,rwinch/spring-security,mrkingybc/spring-security,ractive/spring-security,vitorgv/spring-security,follow99/spring-security,olezhuravlev/spring-security,mparaz/spring-security,likaiwalkman/spring-security,djechelon/spring-security,justinedelson/spring-security,eddumelendez/spring-security,mparaz/spring-security,rwinch/spring-security,Peter32/spring-security,ollie314/spring-security,wilkinsona/spring-security,caiwenshu/spring-security,mrkingybc/spring-security,pkdevbox/spring-security,kazuki43zoo/spring-security,rwinch/spring-security,tekul/spring-security,follow99/spring-security,MatthiasWinzeler/spring-security,mparaz/spring-security,Peter32/spring-security,ractive/spring-security,thomasdarimont/spring-security,pwheel/spring-security,Xcorpio/spring-security,hippostar/spring-security,fhanik/spring-security,kazuki43zoo/spring-security,ajdinhedzic/spring-security,ajdinhedzic/spring-security,xingguang2013/spring-security,Krasnyanskiy/spring-security,liuguohua/spring-security,pwheel/spring-security,panchenko/spring-security,Peter32/spring-security,zshift/spring-security,liuguohua/spring-security,zhaoqin102/spring-security,jgrandja/spring-security,diegofernandes/spring-security,ractive/spring-security,yinhe402/spring-security,Krasnyanskiy/spring-security,wkorando/spring-security,chinazhaoht/spring-security,caiwenshu/spring-security,fhanik/spring-security,forestqqqq/spring-security,justinedelson/spring-security,rwinch/spring-security,driftman/spring-security,rwinch/spring-security,thomasdarimont/spring-security,likaiwalkman/spring-security,izeye/spring-security,MatthiasWinzeler/spring-security,wkorando/spring-security,dsyer/spring-security,SanjayUser/SpringSecurityPro,jmnarloch/spring-security,jgrandja/spring-security,Xcorpio/spring-security,mrkingybc/spring-security,vitorgv/spring-security,SanjayUser/SpringSecurityPro,MatthiasWinzeler/spring-security,thomasdarimont/spring-security,justinedelson/spring-security,adairtaosy/spring-security,fhanik/spring-security,adairtaosy/spring-security,raindev/spring-security,mdeinum/spring-security,panchenko/spring-security,jgrandja/spring-security,hippostar/spring-security,likaiwalkman/spring-security,tekul/spring-security,olezhuravlev/spring-security,spring-projects/spring-security,diegofernandes/spring-security,driftman/spring-security,yinhe402/spring-security,djechelon/spring-security,jgrandja/spring-security,dsyer/spring-security,djechelon/spring-security,eddumelendez/spring-security,eddumelendez/spring-security
/** * */ package org.acegisecurity.config; import java.lang.reflect.Field; import java.util.Map; import junit.framework.TestCase; import org.acegisecurity.AuthenticationManager; import org.acegisecurity.ui.rememberme.RememberMeProcessingFilter; import org.acegisecurity.ui.rememberme.RememberMeServices; import org.acegisecurity.ui.rememberme.TokenBasedRememberMeServices; import org.acegisecurity.userdetails.UserDetailsService; import org.springframework.beans.PropertyValue; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.util.ReflectionUtils; /** * @author Vishal Puri * */ public class RememberMeServicesBeanDefinitionParserTests extends TestCase { public void testFilterConfiguration() { ApplicationContext context = new ClassPathXmlApplicationContext("org/acegisecurity/config/remember-me-defaults.xml"); ConfigurableListableBeanFactory bf = (ConfigurableListableBeanFactory)context.getAutowireCapableBeanFactory(); String[] names = bf.getBeanNamesForType(RememberMeProcessingFilter.class); assertEquals(1, names.length); RootBeanDefinition definition = (RootBeanDefinition)bf.getBeanDefinition(names[0]); assertEquals(definition.getBeanClass(), RememberMeProcessingFilter.class); } public void testRuntimeAutoDetectionOfDependencies() throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext("org/acegisecurity/config/remember-me-autodetect.xml"); ConfigurableListableBeanFactory factory = (ConfigurableListableBeanFactory) context.getAutowireCapableBeanFactory(); Map map = factory.getBeansOfType(RememberMeProcessingFilter.class); RememberMeProcessingFilter filter = (RememberMeProcessingFilter)map.values().iterator().next(); RememberMeServices services = filter.getRememberMeServices(); assertNotNull(services); TokenBasedRememberMeServices rememberMeServices = (TokenBasedRememberMeServices)services; UserDetailsService ud = rememberMeServices.getUserDetailsService(); assertNotNull(ud); Field field = filter.getClass().getDeclaredField("authenticationManager"); ReflectionUtils.makeAccessible(field); Object obj = field.get(filter); assertNotNull("authentication manager should not have been null", obj); assertTrue(obj instanceof AuthenticationManager); } }
sandbox/spring-security-config/src/test/java/org/acegisecurity/config/RememberMeServicesBeanDefinitionParserTests.java
SEC-271: tests for RememberMeServicesBeanDefinitionParser
sandbox/spring-security-config/src/test/java/org/acegisecurity/config/RememberMeServicesBeanDefinitionParserTests.java
SEC-271: tests for RememberMeServicesBeanDefinitionParser
<ide><path>andbox/spring-security-config/src/test/java/org/acegisecurity/config/RememberMeServicesBeanDefinitionParserTests.java <add>/** <add> * <add> */ <add>package org.acegisecurity.config; <add> <add>import java.lang.reflect.Field; <add>import java.util.Map; <add> <add>import junit.framework.TestCase; <add> <add>import org.acegisecurity.AuthenticationManager; <add>import org.acegisecurity.ui.rememberme.RememberMeProcessingFilter; <add>import org.acegisecurity.ui.rememberme.RememberMeServices; <add>import org.acegisecurity.ui.rememberme.TokenBasedRememberMeServices; <add>import org.acegisecurity.userdetails.UserDetailsService; <add>import org.springframework.beans.PropertyValue; <add>import org.springframework.beans.factory.config.BeanDefinition; <add>import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; <add>import org.springframework.beans.factory.support.RootBeanDefinition; <add>import org.springframework.context.ApplicationContext; <add>import org.springframework.context.support.ClassPathXmlApplicationContext; <add>import org.springframework.util.ReflectionUtils; <add> <add>/** <add> * @author Vishal Puri <add> * <add> */ <add>public class RememberMeServicesBeanDefinitionParserTests extends TestCase { <add> <add> public void testFilterConfiguration() { <add> ApplicationContext context = new ClassPathXmlApplicationContext("org/acegisecurity/config/remember-me-defaults.xml"); <add> ConfigurableListableBeanFactory bf = (ConfigurableListableBeanFactory)context.getAutowireCapableBeanFactory(); <add> String[] names = bf.getBeanNamesForType(RememberMeProcessingFilter.class); <add> assertEquals(1, names.length); <add> RootBeanDefinition definition = (RootBeanDefinition)bf.getBeanDefinition(names[0]); <add> assertEquals(definition.getBeanClass(), RememberMeProcessingFilter.class); <add> } <add> <add> public void testRuntimeAutoDetectionOfDependencies() throws Exception { <add> ApplicationContext context = new ClassPathXmlApplicationContext("org/acegisecurity/config/remember-me-autodetect.xml"); <add> ConfigurableListableBeanFactory factory = (ConfigurableListableBeanFactory) context.getAutowireCapableBeanFactory(); <add> Map map = factory.getBeansOfType(RememberMeProcessingFilter.class); <add> RememberMeProcessingFilter filter = (RememberMeProcessingFilter)map.values().iterator().next(); <add> RememberMeServices services = filter.getRememberMeServices(); <add> assertNotNull(services); <add> TokenBasedRememberMeServices rememberMeServices = (TokenBasedRememberMeServices)services; <add> UserDetailsService ud = rememberMeServices.getUserDetailsService(); <add> assertNotNull(ud); <add> Field field = filter.getClass().getDeclaredField("authenticationManager"); <add> ReflectionUtils.makeAccessible(field); <add> Object obj = field.get(filter); <add> assertNotNull("authentication manager should not have been null", obj); <add> assertTrue(obj instanceof AuthenticationManager); <add> } <add> <add>}
Java
apache-2.0
93dd925f7657f8a3f1146db9fdab2c0df6ffcfb7
0
OfflinePoker/Tournament,OfflinePoker/Tournament,OfflinePoker/Tournament,Thomas-Bergmann/Tournament,Thomas-Bergmann/Tournament,Thomas-Bergmann/Tournament
package de.hatoka.common.capi.resource; import java.text.MessageFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import de.hatoka.common.capi.app.xslt.Localizer; public class ResourceLocalizer implements Localizer { private final LocalizationBundle bundle; private final String dateFormat; public ResourceLocalizer(LocalizationBundle bundle) { this(bundle, "yyyy/MM/dd"); } public ResourceLocalizer(LocalizationBundle bundle, String dateFormat) { this.bundle = bundle; this.dateFormat = dateFormat; } @Override public String formatDate(String dateString) { if (dateString == null || dateString.isEmpty()) { return ""; } // convert xml format 2014-11-25T09:45:55.624+01:00 to target try { return new SimpleDateFormat(dateFormat).format(new SimpleDateFormat(LocalizationConstants.XML_DATEFORMAT).parse(dateString)); } catch(ParseException e) { throw new IllegalArgumentException("Illegal source date string: '" + dateString + "'", e); } } @Override public String getText(String key, String defaultText, Object... arguments) { String pattern = bundle.getText(key, null); if (pattern == null) { return defaultText; } MessageFormat messageFormat = new MessageFormat(pattern, bundle.getLocal()); return messageFormat.format(arguments, new StringBuffer(), null).toString(); } }
de.hatoka.common/src/main/java/de/hatoka/common/capi/resource/ResourceLocalizer.java
package de.hatoka.common.capi.resource; import java.text.MessageFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import de.hatoka.common.capi.app.xslt.Localizer; public class ResourceLocalizer implements Localizer { private final LocalizationBundle bundle; private final String dateFormat; public ResourceLocalizer(LocalizationBundle bundle) { this(bundle, "yyyy/MM/dd"); } public ResourceLocalizer(LocalizationBundle bundle, String dateFormat) { this.bundle = bundle; this.dateFormat = dateFormat; } @Override public String formatDate(String dateString) { // 2014-11-25T09:45:55.624+01:00 Date date; try { date = new SimpleDateFormat(LocalizationConstants.XML_DATEFORMAT).parse(dateString); } catch(ParseException e) { return dateString; } return new SimpleDateFormat(dateFormat).format(date); } @Override public String getText(String key, String defaultText, Object... arguments) { String pattern = bundle.getText(key, null); if (pattern == null) { return defaultText; } MessageFormat messageFormat = new MessageFormat(pattern, bundle.getLocal()); return messageFormat.format(arguments, new StringBuffer(), null).toString(); } }
throw exception in case of wrong format * return empty string for null date
de.hatoka.common/src/main/java/de/hatoka/common/capi/resource/ResourceLocalizer.java
throw exception in case of wrong format * return empty string for null date
<ide><path>e.hatoka.common/src/main/java/de/hatoka/common/capi/resource/ResourceLocalizer.java <ide> import java.text.MessageFormat; <ide> import java.text.ParseException; <ide> import java.text.SimpleDateFormat; <del>import java.util.Date; <ide> <ide> import de.hatoka.common.capi.app.xslt.Localizer; <ide> <ide> @Override <ide> public String formatDate(String dateString) <ide> { <del> // 2014-11-25T09:45:55.624+01:00 <del> Date date; <add> if (dateString == null || dateString.isEmpty()) <add> { <add> return ""; <add> } <add> // convert xml format 2014-11-25T09:45:55.624+01:00 to target <ide> try <ide> { <del> date = new SimpleDateFormat(LocalizationConstants.XML_DATEFORMAT).parse(dateString); <add> return new SimpleDateFormat(dateFormat).format(new SimpleDateFormat(LocalizationConstants.XML_DATEFORMAT).parse(dateString)); <ide> } <ide> catch(ParseException e) <ide> { <del> return dateString; <add> throw new IllegalArgumentException("Illegal source date string: '" + dateString + "'", e); <ide> } <del> return new SimpleDateFormat(dateFormat).format(date); <ide> } <ide> <ide> @Override
Java
apache-2.0
1abe4e08428841d402aaea2f2b13df58ffe8858c
0
Lekanich/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,signed/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,slisson/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,kool79/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,amith01994/intellij-community,supersven/intellij-community,adedayo/intellij-community,xfournet/intellij-community,caot/intellij-community,diorcety/intellij-community,retomerz/intellij-community,signed/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,adedayo/intellij-community,holmes/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,petteyg/intellij-community,da1z/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,izonder/intellij-community,consulo/consulo,xfournet/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,consulo/consulo,adedayo/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,ryano144/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,semonte/intellij-community,kool79/intellij-community,kdwink/intellij-community,supersven/intellij-community,jagguli/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,slisson/intellij-community,dslomov/intellij-community,diorcety/intellij-community,izonder/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,fnouama/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,vladmm/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,ernestp/consulo,holmes/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,holmes/intellij-community,allotria/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,ahb0327/intellij-community,caot/intellij-community,ryano144/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,FHannes/intellij-community,ryano144/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,caot/intellij-community,vladmm/intellij-community,dslomov/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,caot/intellij-community,signed/intellij-community,ibinti/intellij-community,blademainer/intellij-community,kool79/intellij-community,supersven/intellij-community,retomerz/intellij-community,retomerz/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,signed/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,clumsy/intellij-community,izonder/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,slisson/intellij-community,kdwink/intellij-community,samthor/intellij-community,blademainer/intellij-community,semonte/intellij-community,kool79/intellij-community,fitermay/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,asedunov/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,vladmm/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,clumsy/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,hurricup/intellij-community,kool79/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,consulo/consulo,holmes/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,samthor/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,holmes/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,caot/intellij-community,vladmm/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,xfournet/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,da1z/intellij-community,da1z/intellij-community,ernestp/consulo,adedayo/intellij-community,kool79/intellij-community,jagguli/intellij-community,robovm/robovm-studio,kdwink/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,izonder/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,supersven/intellij-community,ryano144/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,supersven/intellij-community,robovm/robovm-studio,ryano144/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,petteyg/intellij-community,apixandru/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,signed/intellij-community,kdwink/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,diorcety/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,samthor/intellij-community,ernestp/consulo,TangHao1987/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,ernestp/consulo,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,supersven/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,ernestp/consulo,ibinti/intellij-community,nicolargo/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,xfournet/intellij-community,fnouama/intellij-community,dslomov/intellij-community,amith01994/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,da1z/intellij-community,samthor/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,consulo/consulo,gnuhub/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,ryano144/intellij-community,semonte/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,FHannes/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,da1z/intellij-community,supersven/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,signed/intellij-community,signed/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,asedunov/intellij-community,petteyg/intellij-community,signed/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,consulo/consulo,ivan-fedorov/intellij-community,clumsy/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,slisson/intellij-community,ahb0327/intellij-community,caot/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,semonte/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,semonte/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,izonder/intellij-community,blademainer/intellij-community,blademainer/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,signed/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,allotria/intellij-community,izonder/intellij-community,vladmm/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,jagguli/intellij-community,slisson/intellij-community,fitermay/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,supersven/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,samthor/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,robovm/robovm-studio,supersven/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,holmes/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,diorcety/intellij-community,ryano144/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,diorcety/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,izonder/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,signed/intellij-community,gnuhub/intellij-community,da1z/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,consulo/consulo,slisson/intellij-community,samthor/intellij-community,asedunov/intellij-community,retomerz/intellij-community,ryano144/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,clumsy/intellij-community,diorcety/intellij-community,caot/intellij-community,da1z/intellij-community,robovm/robovm-studio,dslomov/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,ibinti/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,signed/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,da1z/intellij-community,asedunov/intellij-community,signed/intellij-community,slisson/intellij-community,izonder/intellij-community,dslomov/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,gnuhub/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,apixandru/intellij-community,clumsy/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,blademainer/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,allotria/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,jagguli/intellij-community,allotria/intellij-community,allotria/intellij-community,akosyakov/intellij-community,samthor/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,allotria/intellij-community,kdwink/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,ernestp/consulo,youdonghai/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,youdonghai/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,allotria/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,kool79/intellij-community,tmpgit/intellij-community,asedunov/intellij-community
/* * Copyright 2000-2009 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.codeInsight.generation; import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils; import com.intellij.lang.ASTNode; import com.intellij.lang.java.JavaLanguage; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.codeStyle.VariableKind; import com.intellij.psi.impl.light.LightMethodBuilder; import com.intellij.psi.impl.light.LightTypeElement; import com.intellij.psi.javadoc.PsiDocComment; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.psi.util.TypeConversionUtil; import com.intellij.refactoring.util.RefactoringUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.VisibilityUtil; import com.intellij.util.containers.HashMap; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; public class GenerateMembersUtil { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.generation.GenerateMembersUtil"); private GenerateMembersUtil() { } @NotNull public static <T extends GenerationInfo> List<T> insertMembersAtOffset(PsiFile file, int offset, @NotNull List<T> memberPrototypes) throws IncorrectOperationException { if (memberPrototypes.isEmpty()) return memberPrototypes; final PsiElement leaf = file.findElementAt(offset); if (leaf == null) return Collections.emptyList(); PsiClass aClass = findClassAtOffset(file, leaf); if (aClass == null) return Collections.emptyList(); PsiElement anchor = memberPrototypes.get(0).findInsertionAnchor(aClass, leaf); if (anchor instanceof PsiWhiteSpace) { final ASTNode spaceNode = anchor.getNode(); anchor = anchor.getNextSibling(); assert spaceNode != null; if (spaceNode.getStartOffset() <= offset && spaceNode.getStartOffset() + spaceNode.getTextLength() >= offset) { String whiteSpace = spaceNode.getText().substring(0, offset - spaceNode.getStartOffset()); if (!StringUtil.containsLineBreak(whiteSpace)) { // There is a possible case that the caret is located at the end of the line that already contains expression, say, we // want to override particular method while caret is located after the field. // Example - consider that we want to override toString() method at the class below: // class Test { // int i;<caret> // } // We want to add line feed then in order to avoid situation like below: // class Test { // int i;@Override String toString() { // super.toString(); // } // } whiteSpace += "\n"; } final PsiParserFacade parserFacade = PsiParserFacade.SERVICE.getInstance(file.getProject()); final ASTNode singleNewLineWhitespace = parserFacade.createWhiteSpaceFromText(whiteSpace).getNode(); if (singleNewLineWhitespace != null) { spaceNode.getTreeParent().replaceChild(spaceNode, singleNewLineWhitespace); // See http://jetbrains.net/jira/browse/IDEADEV-12837 } } } // Q: shouldn't it be somewhere in PSI? PsiElement element = anchor; while (true) { if (element == null) break; if (element instanceof PsiField || element instanceof PsiMethod || element instanceof PsiClassInitializer) break; element = element.getNextSibling(); } if (element instanceof PsiField) { PsiField field = (PsiField)element; PsiTypeElement typeElement = field.getTypeElement(); if (typeElement != null && !field.equals(typeElement.getParent())) { field.normalizeDeclaration(); anchor = field; } } return insertMembersBeforeAnchor(aClass, anchor, memberPrototypes); } @NotNull public static <T extends GenerationInfo> List<T> insertMembersBeforeAnchor(PsiClass aClass, @Nullable PsiElement anchor, @NotNull List<T> memberPrototypes) throws IncorrectOperationException { boolean before = true; for (T memberPrototype : memberPrototypes) { memberPrototype.insert(aClass, anchor, before); before = false; anchor = memberPrototype.getPsiMember(); } return memberPrototypes; } /** * @see GenerationInfo#positionCaret(com.intellij.openapi.editor.Editor, boolean) */ public static void positionCaret(@NotNull Editor editor, @NotNull PsiElement firstMember, boolean toEditMethodBody) { LOG.assertTrue(firstMember.isValid()); if (toEditMethodBody) { PsiMethod method = (PsiMethod)firstMember; PsiCodeBlock body = method.getBody(); if (body != null) { PsiElement l = body.getFirstBodyElement(); while (l instanceof PsiWhiteSpace) l = l.getNextSibling(); if (l == null) l = body; PsiElement r = body.getLastBodyElement(); while (r instanceof PsiWhiteSpace) r = r.getPrevSibling(); if (r == null) r = body; int start = l.getTextRange().getStartOffset(); int end = r.getTextRange().getEndOffset(); editor.getCaretModel().moveToOffset(Math.min(start, end)); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); if (start < end) { //Not an empty body editor.getSelectionModel().setSelection(start, end); } return; } } int offset; if (firstMember instanceof PsiMethod) { PsiMethod method = (PsiMethod)firstMember; PsiCodeBlock body = method.getBody(); if (body == null) { offset = method.getTextRange().getStartOffset(); } else { offset = body.getLBrace().getTextRange().getEndOffset(); } } else { offset = firstMember.getTextRange().getStartOffset(); } editor.getCaretModel().moveToOffset(offset); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); editor.getSelectionModel().removeSelection(); } public static PsiElement insert(@NotNull PsiClass aClass, @NotNull PsiMember member, @Nullable PsiElement anchor, boolean before) throws IncorrectOperationException { if (member instanceof PsiMethod) { if (!aClass.isInterface()) { final PsiParameter[] parameters = ((PsiMethod)member).getParameterList().getParameters(); final boolean generateFinals = CodeStyleSettingsManager.getSettings(aClass.getProject()).GENERATE_FINAL_PARAMETERS; for (final PsiParameter parameter : parameters) { final PsiModifierList modifierList = parameter.getModifierList(); assert modifierList != null; modifierList.setModifierProperty(PsiModifier.FINAL, generateFinals); } } } if (anchor != null) { return before ? aClass.addBefore(member, anchor) : aClass.addAfter(member, anchor); } else { return aClass.add(member); } } @Nullable private static PsiClass findClassAtOffset(PsiFile file, PsiElement leaf) { PsiElement element = leaf; while (element != null && !(element instanceof PsiFile)) { if (element instanceof PsiClass && !(element instanceof PsiTypeParameter)) { final PsiClass psiClass = (PsiClass)element; if (psiClass.isEnum()) { PsiElement lastChild = null; for (PsiElement child : psiClass.getChildren()) { if (child instanceof PsiJavaToken && ";".equals(child.getText())) { lastChild = child; break; } else if (child instanceof PsiJavaToken && ",".equals(child.getText()) || child instanceof PsiEnumConstant) { lastChild = child; } } if (lastChild != null) { int adjustedOffset = lastChild.getTextRange().getEndOffset(); if (leaf.getTextRange().getEndOffset() <= adjustedOffset) return findClassAtOffset(file, file.findElementAt(adjustedOffset)); } } return psiClass; } element = element.getParent(); } return null; } public static PsiMethod substituteGenericMethod(PsiMethod method, final PsiSubstitutor substitutor) { return substituteGenericMethod(method, substitutor, null); } public static PsiMethod substituteGenericMethod(@NotNull PsiMethod sourceMethod, @NotNull PsiSubstitutor substitutor, @Nullable PsiElement target) { final Project project = sourceMethod.getProject(); final JVMElementFactory factory = getFactory(sourceMethod, target); final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); final Module module = target != null ? ModuleUtil.findModuleForPsiElement(target) : null; final GlobalSearchScope moduleScope = module != null ? GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module) : null; try { final PsiMethod resultMethod = createMethod(factory, sourceMethod); copyDocComment(resultMethod, sourceMethod); copyModifiers(sourceMethod.getModifierList(), resultMethod.getModifierList()); final PsiSubstitutor collisionResolvedSubstitutor = substituteTypeParameters(factory, codeStyleManager, target, sourceMethod.getTypeParameterList(), resultMethod.getTypeParameterList(), substitutor); substituteReturnType(PsiManager.getInstance(project), resultMethod, sourceMethod.getReturnType(), collisionResolvedSubstitutor); substituteParameters(project, factory, codeStyleManager, moduleScope, sourceMethod.getParameterList(), resultMethod.getParameterList(), collisionResolvedSubstitutor); substituteThrows(factory, sourceMethod.getThrowsList(), resultMethod.getThrowsList(), collisionResolvedSubstitutor); return resultMethod; } catch (IncorrectOperationException e) { LOG.error(e); return sourceMethod; } } private static void copyModifiers(@NotNull PsiModifierList sourceModifierList, @NotNull PsiModifierList targetModifierList) { VisibilityUtil.setVisibility(targetModifierList, VisibilityUtil.getVisibilityModifier(sourceModifierList)); } @NotNull private static PsiSubstitutor substituteTypeParameters(@NotNull JVMElementFactory factory, @NotNull JavaCodeStyleManager codeStyleManager, @Nullable PsiElement target, @Nullable PsiTypeParameterList sourceTypeParameterList, @Nullable PsiTypeParameterList targetTypeParameterList, @NotNull PsiSubstitutor substitutor) { if (sourceTypeParameterList == null || targetTypeParameterList == null) { return substitutor; } final Map<PsiTypeParameter, PsiType> substitutionMap = new HashMap<PsiTypeParameter, PsiType>(substitutor.getSubstitutionMap()); for (PsiTypeParameter typeParam : sourceTypeParameterList.getTypeParameters()) { final PsiTypeParameter substitutedTypeParam = substituteTypeParameter(factory, typeParam, substitutor); final PsiTypeParameter resolvedTypeParam = resolveTypeParametersCollision(factory, sourceTypeParameterList, target, substitutedTypeParam, substitutor); targetTypeParameterList.add(resolvedTypeParam); if (substitutedTypeParam != resolvedTypeParam) { substitutionMap.put(typeParam, factory.createType(resolvedTypeParam)); } } return substitutionMap.isEmpty() ? substitutor : factory.createSubstitutor(substitutionMap); } @NotNull private static PsiTypeParameter resolveTypeParametersCollision(@NotNull JVMElementFactory factory, @NotNull PsiTypeParameterList sourceTypeParameterList, @Nullable PsiElement target, @NotNull PsiTypeParameter typeParam, @NotNull PsiSubstitutor substitutor) { for (PsiType type : substitutor.getSubstitutionMap().values()) { if (Comparing.equal(type.getCanonicalText(), typeParam.getName())) { final String newName = suggestUniqueTypeParameterName(typeParam.getName(), sourceTypeParameterList, PsiTreeUtil.getParentOfType(target, PsiClass.class,false)); final PsiTypeParameter newTypeParameter = factory.createTypeParameter(newName, typeParam.getSuperTypes()); substitutor.put(typeParam, factory.createType(newTypeParameter)); return newTypeParameter; } } return typeParam; } @NotNull private static String suggestUniqueTypeParameterName(@NonNls String baseName, @NotNull PsiTypeParameterList typeParameterList, @Nullable PsiClass targetClass) { String newName = baseName; int index = 0; while ((!checkUniqueTypeParameterName(newName, typeParameterList)) || (targetClass != null && !checkUniqueTypeParameterName(newName, targetClass.getTypeParameterList()))) { newName = baseName + ++index; } return newName; } private static boolean checkUniqueTypeParameterName(@NonNls @NotNull String baseName, @Nullable PsiTypeParameterList typeParameterList) { if (typeParameterList == null) return true; for (PsiTypeParameter typeParameter : typeParameterList.getTypeParameters()) { if (Comparing.equal(typeParameter.getName(), baseName)) { return false; } } return true; } @NotNull private static PsiTypeParameter substituteTypeParameter(final @NotNull JVMElementFactory factory, @NotNull PsiTypeParameter typeParameter, final @NotNull PsiSubstitutor substitutor) { final PsiElement copy = typeParameter.copy(); final Map<PsiElement, PsiElement> replacementMap = new HashMap<PsiElement, PsiElement>(); copy.accept(new JavaRecursiveElementVisitor() { @Override public void visitReferenceElement(PsiJavaCodeReferenceElement reference) { super.visitReferenceElement(reference); final PsiElement resolve = reference.resolve(); if (resolve instanceof PsiTypeParameter) { final PsiType type = factory.createType((PsiTypeParameter)resolve); replacementMap.put(reference, factory.createReferenceElementByType((PsiClassType)substituteType(substitutor, type))); } } }); return (PsiTypeParameter)RefactoringUtil.replaceElementsWithMap(copy, replacementMap); } private static void substituteParameters(@NotNull Project project, @NotNull JVMElementFactory factory, @NotNull JavaCodeStyleManager codeStyleManager, @Nullable GlobalSearchScope moduleScope, @NotNull PsiParameterList sourceParameterList, @NotNull PsiParameterList targetParameterList, @NotNull PsiSubstitutor substitutor) { PsiParameter[] parameters = sourceParameterList.getParameters(); Map<PsiType, Pair<String, Integer>> m = new HashMap<PsiType, Pair<String, Integer>>(); for (int i = 0; i < parameters.length; i++) { PsiParameter parameter = parameters[i]; final PsiType parameterType = parameter.getType(); final PsiType substituted = substituteType(substitutor, parameterType); @NonNls String paramName = parameter.getName(); boolean isBaseNameGenerated = true; final boolean isSubstituted = substituted.equals(parameterType); if (!isSubstituted && isBaseNameGenerated(codeStyleManager, TypeConversionUtil.erasure(parameterType), paramName)) { isBaseNameGenerated = false; } if (paramName == null || isBaseNameGenerated && !isSubstituted && isBaseNameGenerated(codeStyleManager, parameterType, paramName)) { Pair<String, Integer> pair = m.get(substituted); if (pair != null) { paramName = pair.first + pair.second; m.put(substituted, Pair.create(pair.first, pair.second.intValue() + 1)); } else { String[] names = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, substituted).names; if (names.length > 0) { paramName = names[0]; } else { paramName = "p" + i; } m.put(substituted, new Pair<String, Integer>(paramName, 1)); } } if (paramName == null) paramName = "p" + i; final PsiParameter newParameter = factory.createParameter(paramName, substituted); if (parameter.getLanguage() == newParameter.getLanguage()) { PsiModifierList modifierList = newParameter.getModifierList(); modifierList = (PsiModifierList)modifierList.replace(parameter.getModifierList()); if (parameter.getLanguage() == JavaLanguage.INSTANCE) { processAnnotations(project, modifierList, moduleScope); } } else { GenerateConstructorHandler.copyModifierList(factory, parameter, newParameter); } targetParameterList.add(newParameter); } } private static void substituteThrows(@NotNull JVMElementFactory factory, @NotNull PsiReferenceList sourceThrowsList, @NotNull PsiReferenceList targetThrowsList, @NotNull PsiSubstitutor substitutor) { for (PsiClassType thrownType : sourceThrowsList.getReferencedTypes()) { targetThrowsList.add(factory.createReferenceElementByType((PsiClassType)substituteType(substitutor, thrownType))); } } private static void copyDocComment(PsiMethod source, PsiMethod target) { final PsiElement navigationElement = source.getNavigationElement(); final PsiDocComment docComment = ((PsiDocCommentOwner)navigationElement).getDocComment(); if (docComment != null) { target.addAfter(docComment, null); } } @NotNull private static PsiMethod createMethod(@NotNull JVMElementFactory factory, @NotNull PsiMethod method) { if (method.isConstructor()) { return factory.createConstructor(method.getName()); } return factory.createMethod(method.getName(), PsiType.VOID); } private static void substituteReturnType(@NotNull PsiManager manager, @NotNull PsiMethod method, @NotNull PsiType returnType, @NotNull PsiSubstitutor substitutor) { final PsiTypeElement returnTypeElement = method.getReturnTypeElement(); if (returnTypeElement == null) { return; } final PsiType substitutedReturnType = substituteType(substitutor, returnType); returnTypeElement.replace(new LightTypeElement(manager, substitutedReturnType instanceof PsiWildcardType ? TypeConversionUtil.erasure(substitutedReturnType) : substitutedReturnType)); } @NotNull private static JVMElementFactory getFactory(@NotNull PsiMethod method, @Nullable PsiElement target) { if (target == null) { return JavaPsiFacade.getInstance(method.getProject()).getElementFactory(); } return JVMElementFactories.getFactory(target.getLanguage(), method.getProject()); } private static boolean isBaseNameGenerated(JavaCodeStyleManager codeStyleManager, PsiType parameterType, String paramName) { final String[] baseSuggestions = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, parameterType).names; boolean isBaseNameGenerated = false; for (String s : baseSuggestions) { if (s.equals(paramName)) { isBaseNameGenerated = true; break; } } return isBaseNameGenerated; } private static void processAnnotations(Project project, PsiModifierList modifierList, GlobalSearchScope moduleScope) { final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final Set<String> toRemove = new HashSet<String>(); for (PsiAnnotation annotation : modifierList.getAnnotations()) { final String qualifiedName = annotation.getQualifiedName(); for (OverrideImplementsAnnotationsHandler handler : Extensions.getExtensions(OverrideImplementsAnnotationsHandler.EP_NAME)) { final String[] annotations2Remove = handler.annotationsToRemove(project, qualifiedName); Collections.addAll(toRemove, annotations2Remove); if (moduleScope != null && psiFacade.findClass(qualifiedName, moduleScope) == null) { toRemove.add(qualifiedName); } } } for (String fqn : toRemove) { final PsiAnnotation psiAnnotation = modifierList.findAnnotation(fqn); if (psiAnnotation != null) { psiAnnotation.delete(); } } } private static PsiType substituteType(final PsiSubstitutor substitutor, final PsiType type) { final PsiType psiType = substitutor.substitute(type); if (psiType != null) return psiType; return TypeConversionUtil.erasure(type); } public static PsiSubstitutor correctSubstitutor(PsiMethod method, PsiSubstitutor substitutor) { PsiClass hisClass = method.getContainingClass(); PsiTypeParameter[] typeParameters = method.getTypeParameters(); if (typeParameters.length > 0) { if (PsiUtil.isRawSubstitutor(hisClass, substitutor)) { substitutor = JavaPsiFacade.getInstance(method.getProject()).getElementFactory().createRawSubstitutor(substitutor, typeParameters); } } return substitutor; } public static boolean isChildInRange(PsiElement child, PsiElement first, PsiElement last) { if (child.equals(first)) return true; while (true) { if (child.equals(first)) return false; // before first if (child.equals(last)) return true; child = child.getNextSibling(); if (child == null) return false; } } public static boolean shouldAddOverrideAnnotation(PsiElement context, boolean interfaceMethod) { CodeStyleSettings style = CodeStyleSettingsManager.getSettings(context.getProject()); if (!style.INSERT_OVERRIDE_ANNOTATION) return false; if (interfaceMethod) return PsiUtil.isLanguageLevel6OrHigher(context); return PsiUtil.isLanguageLevel5OrHigher(context); } public static void setupGeneratedMethod(PsiMethod method) { PsiClass base = method.getContainingClass().getSuperClass(); PsiMethod overridden = base == null ? null : base.findMethodBySignature(method, true); if (overridden == null) { CreateFromUsageUtils.setupMethodBody(method, method.getContainingClass()); return; } OverrideImplementUtil.setupMethodBody(method, overridden, method.getContainingClass()); OverrideImplementUtil.annotateOnOverrideImplement(method, base, overridden); } }
java/java-impl/src/com/intellij/codeInsight/generation/GenerateMembersUtil.java
/* * Copyright 2000-2009 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.codeInsight.generation; import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils; import com.intellij.lang.ASTNode; import com.intellij.lang.java.JavaLanguage; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.codeStyle.VariableKind; import com.intellij.psi.impl.light.LightMethodBuilder; import com.intellij.psi.javadoc.PsiDocComment; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiUtil; import com.intellij.psi.util.TypeConversionUtil; import com.intellij.refactoring.util.RefactoringUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.VisibilityUtil; import com.intellij.util.containers.HashMap; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; public class GenerateMembersUtil { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.generation.GenerateMembersUtil"); private GenerateMembersUtil() { } @NotNull public static <T extends GenerationInfo> List<T> insertMembersAtOffset(PsiFile file, int offset, @NotNull List<T> memberPrototypes) throws IncorrectOperationException { if (memberPrototypes.isEmpty()) return memberPrototypes; final PsiElement leaf = file.findElementAt(offset); if (leaf == null) return Collections.emptyList(); PsiClass aClass = findClassAtOffset(file, leaf); if (aClass == null) return Collections.emptyList(); PsiElement anchor = memberPrototypes.get(0).findInsertionAnchor(aClass, leaf); if (anchor instanceof PsiWhiteSpace) { final ASTNode spaceNode = anchor.getNode(); anchor = anchor.getNextSibling(); assert spaceNode != null; if (spaceNode.getStartOffset() <= offset && spaceNode.getStartOffset() + spaceNode.getTextLength() >= offset) { String whiteSpace = spaceNode.getText().substring(0, offset - spaceNode.getStartOffset()); if (!StringUtil.containsLineBreak(whiteSpace)) { // There is a possible case that the caret is located at the end of the line that already contains expression, say, we // want to override particular method while caret is located after the field. // Example - consider that we want to override toString() method at the class below: // class Test { // int i;<caret> // } // We want to add line feed then in order to avoid situation like below: // class Test { // int i;@Override String toString() { // super.toString(); // } // } whiteSpace += "\n"; } final PsiParserFacade parserFacade = PsiParserFacade.SERVICE.getInstance(file.getProject()); final ASTNode singleNewLineWhitespace = parserFacade.createWhiteSpaceFromText(whiteSpace).getNode(); if (singleNewLineWhitespace != null) { spaceNode.getTreeParent().replaceChild(spaceNode, singleNewLineWhitespace); // See http://jetbrains.net/jira/browse/IDEADEV-12837 } } } // Q: shouldn't it be somewhere in PSI? PsiElement element = anchor; while (true) { if (element == null) break; if (element instanceof PsiField || element instanceof PsiMethod || element instanceof PsiClassInitializer) break; element = element.getNextSibling(); } if (element instanceof PsiField) { PsiField field = (PsiField)element; PsiTypeElement typeElement = field.getTypeElement(); if (typeElement != null && !field.equals(typeElement.getParent())) { field.normalizeDeclaration(); anchor = field; } } return insertMembersBeforeAnchor(aClass, anchor, memberPrototypes); } @NotNull public static <T extends GenerationInfo> List<T> insertMembersBeforeAnchor(PsiClass aClass, @Nullable PsiElement anchor, @NotNull List<T> memberPrototypes) throws IncorrectOperationException { boolean before = true; for (T memberPrototype : memberPrototypes) { memberPrototype.insert(aClass, anchor, before); before = false; anchor = memberPrototype.getPsiMember(); } return memberPrototypes; } /** * @see GenerationInfo#positionCaret(com.intellij.openapi.editor.Editor, boolean) */ public static void positionCaret(@NotNull Editor editor, @NotNull PsiElement firstMember, boolean toEditMethodBody) { LOG.assertTrue(firstMember.isValid()); if (toEditMethodBody) { PsiMethod method = (PsiMethod)firstMember; PsiCodeBlock body = method.getBody(); if (body != null) { PsiElement l = body.getFirstBodyElement(); while (l instanceof PsiWhiteSpace) l = l.getNextSibling(); if (l == null) l = body; PsiElement r = body.getLastBodyElement(); while (r instanceof PsiWhiteSpace) r = r.getPrevSibling(); if (r == null) r = body; int start = l.getTextRange().getStartOffset(); int end = r.getTextRange().getEndOffset(); editor.getCaretModel().moveToOffset(Math.min(start, end)); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); if (start < end) { //Not an empty body editor.getSelectionModel().setSelection(start, end); } return; } } int offset; if (firstMember instanceof PsiMethod) { PsiMethod method = (PsiMethod)firstMember; PsiCodeBlock body = method.getBody(); if (body == null) { offset = method.getTextRange().getStartOffset(); } else { offset = body.getLBrace().getTextRange().getEndOffset(); } } else { offset = firstMember.getTextRange().getStartOffset(); } editor.getCaretModel().moveToOffset(offset); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); editor.getSelectionModel().removeSelection(); } public static PsiElement insert(@NotNull PsiClass aClass, @NotNull PsiMember member, @Nullable PsiElement anchor, boolean before) throws IncorrectOperationException { if (member instanceof PsiMethod) { if (!aClass.isInterface()) { final PsiParameter[] parameters = ((PsiMethod)member).getParameterList().getParameters(); final boolean generateFinals = CodeStyleSettingsManager.getSettings(aClass.getProject()).GENERATE_FINAL_PARAMETERS; for (final PsiParameter parameter : parameters) { final PsiModifierList modifierList = parameter.getModifierList(); assert modifierList != null; modifierList.setModifierProperty(PsiModifier.FINAL, generateFinals); } } } if (anchor != null) { return before ? aClass.addBefore(member, anchor) : aClass.addAfter(member, anchor); } else { return aClass.add(member); } } @Nullable private static PsiClass findClassAtOffset(PsiFile file, PsiElement leaf) { PsiElement element = leaf; while (element != null && !(element instanceof PsiFile)) { if (element instanceof PsiClass && !(element instanceof PsiTypeParameter)) { final PsiClass psiClass = (PsiClass)element; if (psiClass.isEnum()) { PsiElement lastChild = null; for (PsiElement child : psiClass.getChildren()) { if (child instanceof PsiJavaToken && ";".equals(child.getText())) { lastChild = child; break; } else if (child instanceof PsiJavaToken && ",".equals(child.getText()) || child instanceof PsiEnumConstant) { lastChild = child; } } if (lastChild != null) { int adjustedOffset = lastChild.getTextRange().getEndOffset(); if (leaf.getTextRange().getEndOffset() <= adjustedOffset) return findClassAtOffset(file, file.findElementAt(adjustedOffset)); } } return psiClass; } element = element.getParent(); } return null; } public static PsiMethod substituteGenericMethod(PsiMethod method, final PsiSubstitutor substitutor) { return substituteGenericMethod(method, substitutor, null); } public static PsiMethod substituteGenericMethod(@NotNull PsiMethod sourceMethod, @NotNull PsiSubstitutor substitutor, @Nullable PsiElement target) { final Project project = sourceMethod.getProject(); final JVMElementFactory factory = getFactory(sourceMethod, target); final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); final Module module = target != null ? ModuleUtil.findModuleForPsiElement(target) : null; final GlobalSearchScope moduleScope = module != null ? GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module) : null; try { //final LightMethodBuilder method = new LightMethodBuilder(PsiManager.getInstance(project),""); final PsiMethod resultMethod = createMethod(factory, sourceMethod, substitutor); copyDocComment(resultMethod, sourceMethod); copyModifiers(sourceMethod.getModifierList(), resultMethod.getModifierList()); final PsiSubstitutor collisionResolvedSubstitutor = substituteTypeParameters(factory, sourceMethod.getTypeParameterList(), resultMethod.getTypeParameterList(), substitutor); substituteParameters(project, factory, codeStyleManager, moduleScope, sourceMethod.getParameterList(), resultMethod.getParameterList(), collisionResolvedSubstitutor); substituteThrows(factory, sourceMethod.getThrowsList(), resultMethod.getThrowsList(), collisionResolvedSubstitutor); return resultMethod; } catch (IncorrectOperationException e) { LOG.error(e); return sourceMethod; } } private static void copyModifiers(@NotNull PsiModifierList sourceModifierList, @NotNull PsiModifierList targetModifierList) { VisibilityUtil.setVisibility(targetModifierList, VisibilityUtil.getVisibilityModifier(sourceModifierList)); } @NotNull private static PsiSubstitutor substituteTypeParameters(@NotNull JVMElementFactory factory, @Nullable PsiTypeParameterList sourceTypeParameterList, @Nullable PsiTypeParameterList targetTypeParameterList, @NotNull PsiSubstitutor substitutor) { if (sourceTypeParameterList == null || targetTypeParameterList == null) { return substitutor; } final Map<PsiTypeParameter, PsiType> substitutionMap = new HashMap<PsiTypeParameter, PsiType>(substitutor.getSubstitutionMap()); for (PsiTypeParameter typeParam : sourceTypeParameterList.getTypeParameters()) { final PsiTypeParameter substitutedTypeParam = substituteTypeParameter(factory, typeParam, substitutor); final PsiTypeParameter resolvedTypeParam = resolveTypeParametersCollision(factory,substitutedTypeParam,substitutor); targetTypeParameterList.add(resolvedTypeParam); if (substitutedTypeParam != resolvedTypeParam){ substitutionMap.put(typeParam, factory.createType(resolvedTypeParam)); } } return substitutionMap.isEmpty() ? substitutor : factory.createSubstitutor(substitutionMap); } @NotNull private static PsiTypeParameter resolveTypeParametersCollision(@NotNull JVMElementFactory factory, @NotNull PsiTypeParameter typeParam, @NotNull PsiSubstitutor substitutor) { for (PsiType type : substitutor.getSubstitutionMap().values()) { if (Comparing.equal(type.getCanonicalText(), typeParam.getName())) { final String newName = typeParam.getName() + "1"; final PsiTypeParameter newTypeParameter = factory.createTypeParameter(newName, typeParam.getSuperTypes()); substitutor.put(typeParam,factory.createType(newTypeParameter)); return newTypeParameter; } } return typeParam; } @NotNull private static PsiTypeParameter substituteTypeParameter(final @NotNull JVMElementFactory factory, @NotNull PsiTypeParameter typeParameter, final @NotNull PsiSubstitutor substitutor) { final PsiElement copy = typeParameter.copy(); final Map<PsiElement, PsiElement> replacementMap = new HashMap<PsiElement, PsiElement>(); copy.accept(new JavaRecursiveElementVisitor() { @Override public void visitReferenceElement(PsiJavaCodeReferenceElement reference) { super.visitReferenceElement(reference); final PsiElement resolve = reference.resolve(); if (resolve instanceof PsiTypeParameter) { final PsiType type = factory.createType((PsiTypeParameter)resolve); replacementMap.put(reference, factory.createReferenceElementByType((PsiClassType)substituteType(substitutor, type))); } } }); return (PsiTypeParameter)RefactoringUtil.replaceElementsWithMap(copy, replacementMap); } private static void substituteParameters(@NotNull Project project, @NotNull JVMElementFactory factory, @NotNull JavaCodeStyleManager codeStyleManager, @Nullable GlobalSearchScope moduleScope, @NotNull PsiParameterList sourceParameterList, @NotNull PsiParameterList targetParameterList, @NotNull PsiSubstitutor substitutor) { PsiParameter[] parameters = sourceParameterList.getParameters(); Map<PsiType, Pair<String, Integer>> m = new HashMap<PsiType, Pair<String, Integer>>(); for (int i = 0; i < parameters.length; i++) { PsiParameter parameter = parameters[i]; final PsiType parameterType = parameter.getType(); final PsiType substituted = substituteType(substitutor, parameterType); @NonNls String paramName = parameter.getName(); boolean isBaseNameGenerated = true; final boolean isSubstituted = substituted.equals(parameterType); if (!isSubstituted && isBaseNameGenerated(codeStyleManager, TypeConversionUtil.erasure(parameterType), paramName)) { isBaseNameGenerated = false; } if (paramName == null || isBaseNameGenerated && !isSubstituted && isBaseNameGenerated(codeStyleManager, parameterType, paramName)) { Pair<String, Integer> pair = m.get(substituted); if (pair != null) { paramName = pair.first + pair.second; m.put(substituted, Pair.create(pair.first, pair.second.intValue() + 1)); } else { String[] names = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, substituted).names; if (names.length > 0) { paramName = names[0]; } else { paramName = "p" + i; } m.put(substituted, new Pair<String, Integer>(paramName, 1)); } } if (paramName == null) paramName = "p" + i; final PsiParameter newParameter = factory.createParameter(paramName, substituted); if (parameter.getLanguage() == newParameter.getLanguage()) { PsiModifierList modifierList = newParameter.getModifierList(); modifierList = (PsiModifierList)modifierList.replace(parameter.getModifierList()); if (parameter.getLanguage() == JavaLanguage.INSTANCE) { processAnnotations(project, modifierList, moduleScope); } } else { GenerateConstructorHandler.copyModifierList(factory, parameter, newParameter); } targetParameterList.add(newParameter); } } private static void substituteThrows(@NotNull JVMElementFactory factory, @NotNull PsiReferenceList sourceThrowsList, @NotNull PsiReferenceList targetThrowsList, @NotNull PsiSubstitutor substitutor) { for (PsiClassType thrownType : sourceThrowsList.getReferencedTypes()) { targetThrowsList.add(factory.createReferenceElementByType((PsiClassType)substituteType(substitutor, thrownType))); } } private static void copyDocComment(PsiMethod source, PsiMethod target) { final PsiElement navigationElement = source.getNavigationElement(); final PsiDocComment docComment = ((PsiDocCommentOwner)navigationElement).getDocComment(); if (docComment != null) { target.addAfter(docComment, null); } } @NotNull private static PsiMethod createMethod(@NotNull JVMElementFactory factory, @NotNull PsiMethod method, @NotNull PsiSubstitutor substitutor) { if (method.isConstructor()) { return factory.createConstructor(method.getName()); } final PsiType substitutedReturnType = substituteType(substitutor, method.getReturnType()); return factory.createMethod(method.getName(), substitutedReturnType instanceof PsiWildcardType ? TypeConversionUtil.erasure(substitutedReturnType) : substitutedReturnType); } @NotNull private static JVMElementFactory getFactory(@NotNull PsiMethod method, @Nullable PsiElement target) { if (target == null) { return JavaPsiFacade.getInstance(method.getProject()).getElementFactory(); } return JVMElementFactories.getFactory(target.getLanguage(), method.getProject()); } private static boolean isBaseNameGenerated(JavaCodeStyleManager codeStyleManager, PsiType parameterType, String paramName) { final String[] baseSuggestions = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, parameterType).names; boolean isBaseNameGenerated = false; for (String s : baseSuggestions) { if (s.equals(paramName)) { isBaseNameGenerated = true; break; } } return isBaseNameGenerated; } private static void processAnnotations(Project project, PsiModifierList modifierList, GlobalSearchScope moduleScope) { final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final Set<String> toRemove = new HashSet<String>(); for (PsiAnnotation annotation : modifierList.getAnnotations()) { final String qualifiedName = annotation.getQualifiedName(); for (OverrideImplementsAnnotationsHandler handler : Extensions.getExtensions(OverrideImplementsAnnotationsHandler.EP_NAME)) { final String[] annotations2Remove = handler.annotationsToRemove(project, qualifiedName); Collections.addAll(toRemove, annotations2Remove); if (moduleScope != null && psiFacade.findClass(qualifiedName, moduleScope) == null) { toRemove.add(qualifiedName); } } } for (String fqn : toRemove) { final PsiAnnotation psiAnnotation = modifierList.findAnnotation(fqn); if (psiAnnotation != null) { psiAnnotation.delete(); } } } private static PsiType substituteType(final PsiSubstitutor substitutor, final PsiType type) { final PsiType psiType = substitutor.substitute(type); if (psiType != null) return psiType; return TypeConversionUtil.erasure(type); } public static PsiSubstitutor correctSubstitutor(PsiMethod method, PsiSubstitutor substitutor) { PsiClass hisClass = method.getContainingClass(); PsiTypeParameter[] typeParameters = method.getTypeParameters(); if (typeParameters.length > 0) { if (PsiUtil.isRawSubstitutor(hisClass, substitutor)) { substitutor = JavaPsiFacade.getInstance(method.getProject()).getElementFactory().createRawSubstitutor(substitutor, typeParameters); } } return substitutor; } public static boolean isChildInRange(PsiElement child, PsiElement first, PsiElement last) { if (child.equals(first)) return true; while (true) { if (child.equals(first)) return false; // before first if (child.equals(last)) return true; child = child.getNextSibling(); if (child == null) return false; } } public static boolean shouldAddOverrideAnnotation(PsiElement context, boolean interfaceMethod) { CodeStyleSettings style = CodeStyleSettingsManager.getSettings(context.getProject()); if (!style.INSERT_OVERRIDE_ANNOTATION) return false; if (interfaceMethod) return PsiUtil.isLanguageLevel6OrHigher(context); return PsiUtil.isLanguageLevel5OrHigher(context); } public static void setupGeneratedMethod(PsiMethod method) { PsiClass base = method.getContainingClass().getSuperClass(); PsiMethod overridden = base == null ? null : base.findMethodBySignature(method, true); if (overridden == null) { CreateFromUsageUtils.setupMethodBody(method, method.getContainingClass()); return; } OverrideImplementUtil.setupMethodBody(method, overridden, method.getContainingClass()); OverrideImplementUtil.annotateOnOverrideImplement(method, base, overridden); } }
IDEA-86405 fixed
java/java-impl/src/com/intellij/codeInsight/generation/GenerateMembersUtil.java
IDEA-86405 fixed
<ide><path>ava/java-impl/src/com/intellij/codeInsight/generation/GenerateMembersUtil.java <ide> import com.intellij.psi.codeStyle.JavaCodeStyleManager; <ide> import com.intellij.psi.codeStyle.VariableKind; <ide> import com.intellij.psi.impl.light.LightMethodBuilder; <add>import com.intellij.psi.impl.light.LightTypeElement; <ide> import com.intellij.psi.javadoc.PsiDocComment; <ide> import com.intellij.psi.search.GlobalSearchScope; <add>import com.intellij.psi.util.PsiTreeUtil; <ide> import com.intellij.psi.util.PsiUtil; <ide> import com.intellij.psi.util.TypeConversionUtil; <ide> import com.intellij.refactoring.util.RefactoringUtil; <ide> final GlobalSearchScope moduleScope = module != null ? GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module) : null; <ide> <ide> try { <del> //final LightMethodBuilder method = new LightMethodBuilder(PsiManager.getInstance(project),""); <del> <del> final PsiMethod resultMethod = createMethod(factory, sourceMethod, substitutor); <add> final PsiMethod resultMethod = createMethod(factory, sourceMethod); <ide> copyDocComment(resultMethod, sourceMethod); <ide> copyModifiers(sourceMethod.getModifierList(), resultMethod.getModifierList()); <del> final PsiSubstitutor collisionResolvedSubstitutor = substituteTypeParameters(factory, sourceMethod.getTypeParameterList(), resultMethod.getTypeParameterList(), substitutor); <add> final PsiSubstitutor collisionResolvedSubstitutor = <add> substituteTypeParameters(factory, codeStyleManager, target, sourceMethod.getTypeParameterList(), resultMethod.getTypeParameterList(), substitutor); <add> substituteReturnType(PsiManager.getInstance(project), resultMethod, sourceMethod.getReturnType(), collisionResolvedSubstitutor); <ide> substituteParameters(project, factory, codeStyleManager, moduleScope, sourceMethod.getParameterList(), resultMethod.getParameterList(), collisionResolvedSubstitutor); <ide> substituteThrows(factory, sourceMethod.getThrowsList(), resultMethod.getThrowsList(), collisionResolvedSubstitutor); <ide> return resultMethod; <ide> <ide> @NotNull <ide> private static PsiSubstitutor substituteTypeParameters(@NotNull JVMElementFactory factory, <add> @NotNull JavaCodeStyleManager codeStyleManager, <add> @Nullable PsiElement target, <ide> @Nullable PsiTypeParameterList sourceTypeParameterList, <ide> @Nullable PsiTypeParameterList targetTypeParameterList, <ide> @NotNull PsiSubstitutor substitutor) { <ide> for (PsiTypeParameter typeParam : sourceTypeParameterList.getTypeParameters()) { <ide> final PsiTypeParameter substitutedTypeParam = substituteTypeParameter(factory, typeParam, substitutor); <ide> <del> final PsiTypeParameter resolvedTypeParam = resolveTypeParametersCollision(factory,substitutedTypeParam,substitutor); <add> final PsiTypeParameter resolvedTypeParam = resolveTypeParametersCollision(factory, sourceTypeParameterList, target, substitutedTypeParam, substitutor); <ide> targetTypeParameterList.add(resolvedTypeParam); <del> if (substitutedTypeParam != resolvedTypeParam){ <add> if (substitutedTypeParam != resolvedTypeParam) { <ide> substitutionMap.put(typeParam, factory.createType(resolvedTypeParam)); <ide> } <ide> } <ide> <ide> @NotNull <ide> private static PsiTypeParameter resolveTypeParametersCollision(@NotNull JVMElementFactory factory, <add> @NotNull PsiTypeParameterList sourceTypeParameterList, <add> @Nullable PsiElement target, <ide> @NotNull PsiTypeParameter typeParam, <ide> @NotNull PsiSubstitutor substitutor) { <ide> for (PsiType type : substitutor.getSubstitutionMap().values()) { <ide> if (Comparing.equal(type.getCanonicalText(), typeParam.getName())) { <del> final String newName = typeParam.getName() + "1"; <add> final String newName = suggestUniqueTypeParameterName(typeParam.getName(), sourceTypeParameterList, PsiTreeUtil.getParentOfType(target, PsiClass.class,false)); <ide> final PsiTypeParameter newTypeParameter = factory.createTypeParameter(newName, typeParam.getSuperTypes()); <del> substitutor.put(typeParam,factory.createType(newTypeParameter)); <add> substitutor.put(typeParam, factory.createType(newTypeParameter)); <ide> return newTypeParameter; <ide> } <ide> } <ide> return typeParam; <ide> } <add> <add> @NotNull <add> private static String suggestUniqueTypeParameterName(@NonNls String baseName, @NotNull PsiTypeParameterList typeParameterList, @Nullable PsiClass targetClass) { <add> String newName = baseName; <add> int index = 0; <add> while ((!checkUniqueTypeParameterName(newName, typeParameterList)) || (targetClass != null && !checkUniqueTypeParameterName(newName, targetClass.getTypeParameterList()))) { <add> newName = baseName + ++index; <add> } <add> <add> return newName; <add> } <add> <add> <add> private static boolean checkUniqueTypeParameterName(@NonNls @NotNull String baseName, @Nullable PsiTypeParameterList typeParameterList) { <add> if (typeParameterList == null) return true; <add> <add> for (PsiTypeParameter typeParameter : typeParameterList.getTypeParameters()) { <add> if (Comparing.equal(typeParameter.getName(), baseName)) { <add> return false; <add> } <add> } <add> return true; <add> } <add> <ide> <ide> @NotNull <ide> private static PsiTypeParameter substituteTypeParameter(final @NotNull JVMElementFactory factory, <ide> <ide> @NotNull <ide> private static PsiMethod createMethod(@NotNull JVMElementFactory factory, <del> @NotNull PsiMethod method, <del> @NotNull PsiSubstitutor substitutor) { <add> @NotNull PsiMethod method) { <ide> if (method.isConstructor()) { <ide> return factory.createConstructor(method.getName()); <ide> } <del> final PsiType substitutedReturnType = substituteType(substitutor, method.getReturnType()); <del> return factory.createMethod(method.getName(), substitutedReturnType instanceof PsiWildcardType ? TypeConversionUtil.erasure(substitutedReturnType) : substitutedReturnType); <add> return factory.createMethod(method.getName(), PsiType.VOID); <add> } <add> <add> private static void substituteReturnType(@NotNull PsiManager manager, <add> @NotNull PsiMethod method, <add> @NotNull PsiType returnType, <add> @NotNull PsiSubstitutor substitutor) { <add> final PsiTypeElement returnTypeElement = method.getReturnTypeElement(); <add> if (returnTypeElement == null) { <add> return; <add> } <add> final PsiType substitutedReturnType = substituteType(substitutor, returnType); <add> <add> returnTypeElement.replace(new LightTypeElement(manager, substitutedReturnType instanceof PsiWildcardType ? TypeConversionUtil.erasure(substitutedReturnType) : substitutedReturnType)); <ide> } <ide> <ide> @NotNull
Java
apache-2.0
b3b5439cc63a27adc06e21cae9fc62c3341e30df
0
apache/tomcat,apache/tomcat,apache/tomcat,Nickname0806/Test_Q4,Nickname0806/Test_Q4,apache/tomcat,Nickname0806/Test_Q4,apache/tomcat,Nickname0806/Test_Q4
/* * 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.connector; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.catalina.Context; import org.apache.catalina.startup.SimpleHttpClient; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.startup.TomcatBaseTest; import org.apache.juli.logging.LogFactory; import org.apache.juli.logging.Log; public class TestMaxConnections extends TomcatBaseTest{ private static Log log = LogFactory.getLog(TestMaxConnections.class); static int soTimeout = 3000; static int connectTimeout = 1000; public void testConnector() throws Exception { init(); ConnectThread[] t = new ConnectThread[10]; int passcount = 0; int connectfail = 0; for (int i=0; i<t.length; i++) { t[i] = new ConnectThread(); t[i].setName("ConnectThread["+i+"]"); } for (int i=0; i<t.length; i++) { t[i].start(); } for (int i=0; i<t.length; i++) { t[i].join(); if (t[i].passed) passcount++; if (t[i].connectfailed) connectfail++; } assertTrue("The number of successful requests should have been 4-5, actual "+passcount,4==passcount || 5==passcount); } private class ConnectThread extends Thread { public boolean passed = true; public boolean connectfailed = false; public void run() { try { TestClient client = new TestClient(); client.doHttp10Request(); }catch (Exception x) { passed = false; log.error(Thread.currentThread().getName()+" Error:"+x.getMessage()); connectfailed = "connect timed out".equals(x.getMessage()) || "Connection refused: connect".equals(x.getMessage()); } } } private synchronized void init() throws Exception { Tomcat tomcat = getTomcatInstance(); Context root = tomcat.addContext("", SimpleHttpClient.TEMP_DIR); Tomcat.addServlet(root, "Simple", new SimpleServlet()); root.addServletMapping("/test", "Simple"); tomcat.getConnector().setProperty("maxKeepAliveRequests", "1"); tomcat.getConnector().setProperty("maxThreads", "10"); tomcat.getConnector().setProperty("soTimeout", "20000"); tomcat.getConnector().setProperty("keepAliveTimeout", "50000"); tomcat.getConnector().setProperty("port", "8080"); tomcat.getConnector().setProperty("maxConnections", "4"); tomcat.getConnector().setProperty("acceptCount", "1"); tomcat.start(); } private class TestClient extends SimpleHttpClient { private void doHttp10Request() throws Exception { long start = System.currentTimeMillis(); // Open connection connect(connectTimeout,soTimeout); // Send request in two parts String[] request = new String[1]; request[0] = "GET /test HTTP/1.0" + CRLF + CRLF; setRequest(request); boolean passed = false; processRequest(false); // blocks until response has been read long stop = System.currentTimeMillis(); log.info(Thread.currentThread().getName()+" Request complete:"+(stop-start)+" ms."); passed = (this.readLine()==null); // Close the connection disconnect(); reset(); assertTrue(passed); } @Override public boolean isResponseBodyOK() { return true; } } private static class SimpleServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { Thread.sleep(TestMaxConnections.soTimeout/2); }catch (InterruptedException x) { } resp.setContentLength(0); resp.flushBuffer(); } } }
test/org/apache/catalina/connector/TestMaxConnections.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.connector; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.catalina.Context; import org.apache.catalina.startup.SimpleHttpClient; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.startup.TomcatBaseTest; import org.apache.coyote.http11.Http11NioProtocol; import org.apache.coyote.http11.Http11Protocol; public class TestMaxConnections extends TomcatBaseTest{ static int soTimeout = 3000; static int connectTimeout = 1000; @Override public void setUp() throws Exception { //do nothing } public void testBio() throws Exception { init(Http11Protocol.class.getName()); ConnectThread[] t = new ConnectThread[10]; int passcount = 0; int connectfail = 0; for (int i=0; i<t.length; i++) { t[i] = new ConnectThread(); t[i].setName("ConnectThread["+i+"+]"); t[i].start(); } for (int i=0; i<t.length; i++) { t[i].join(); if (t[i].passed) passcount++; if (t[i].connectfailed) connectfail++; } assertEquals("The number of successful requests should have been 5.",5, passcount); assertEquals("The number of failed connects should have been 5.",5, connectfail); } public void testNio() throws Exception { init(Http11NioProtocol.class.getName()); ConnectThread[] t = new ConnectThread[10]; int passcount = 0; int connectfail = 0; for (int i=0; i<t.length; i++) { t[i] = new ConnectThread(); t[i].setName("ConnectThread["+i+"+]"); t[i].start(); } for (int i=0; i<t.length; i++) { t[i].join(); if (t[i].passed) passcount++; if (t[i].connectfailed) connectfail++; } assertTrue("The number of successful requests should have been 4-5, actual "+passcount,4==passcount || 5==passcount); } private class ConnectThread extends Thread { public boolean passed = true; public boolean connectfailed = false; public void run() { try { TestClient client = new TestClient(); client.doHttp10Request(); }catch (Exception x) { passed = false; System.err.println(Thread.currentThread().getName()+" Error:"+x.getMessage()); connectfailed = "connect timed out".equals(x.getMessage()) || "Connection refused: connect".equals(x.getMessage()); } } } private synchronized void init(String protocol) throws Exception { System.setProperty("tomcat.test.protocol", protocol); super.setUp(); Tomcat tomcat = getTomcatInstance(); Context root = tomcat.addContext("", SimpleHttpClient.TEMP_DIR); Tomcat.addServlet(root, "Simple", new SimpleServlet()); root.addServletMapping("/test", "Simple"); tomcat.getConnector().setProperty("maxKeepAliveRequests", "1"); tomcat.getConnector().setProperty("soTimeout", "20000"); tomcat.getConnector().setProperty("keepAliveTimeout", "50000"); tomcat.getConnector().setProperty("port", "8080"); tomcat.getConnector().setProperty("maxConnections", "4"); tomcat.getConnector().setProperty("acceptCount", "1"); tomcat.start(); Thread.sleep(5000); } private class TestClient extends SimpleHttpClient { private void doHttp10Request() throws Exception { long start = System.currentTimeMillis(); // Open connection connect(connectTimeout,soTimeout); // Send request in two parts String[] request = new String[1]; request[0] = "GET /test HTTP/1.0" + CRLF + CRLF; setRequest(request); boolean passed = false; processRequest(false); // blocks until response has been read long stop = System.currentTimeMillis(); System.out.println(Thread.currentThread().getName()+" Request complete:"+(stop-start)+" ms."); passed = (this.readLine()==null); // Close the connection disconnect(); reset(); assertTrue(passed); } @Override public boolean isResponseBodyOK() { return true; } } private static class SimpleServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { Thread.sleep(TestMaxConnections.soTimeout/2); }catch (InterruptedException x) { } resp.setContentLength(0); resp.flushBuffer(); } } }
Test can piggy back on the 'ant test' auto switch between connectors git-svn-id: 79cef5a5a257cc9dbe40a45ac190115b4780e2d0@1051335 13f79535-47bb-0310-9956-ffa450edef68
test/org/apache/catalina/connector/TestMaxConnections.java
Test can piggy back on the 'ant test' auto switch between connectors
<ide><path>est/org/apache/catalina/connector/TestMaxConnections.java <ide> import org.apache.catalina.startup.SimpleHttpClient; <ide> import org.apache.catalina.startup.Tomcat; <ide> import org.apache.catalina.startup.TomcatBaseTest; <del>import org.apache.coyote.http11.Http11NioProtocol; <del>import org.apache.coyote.http11.Http11Protocol; <add>import org.apache.juli.logging.LogFactory; <add>import org.apache.juli.logging.Log; <ide> <ide> public class TestMaxConnections extends TomcatBaseTest{ <del> <add> private static Log log = LogFactory.getLog(TestMaxConnections.class); <ide> static int soTimeout = 3000; <ide> static int connectTimeout = 1000; <ide> <del> @Override <del> public void setUp() throws Exception { <del> //do nothing <del> } <ide> <del> public void testBio() throws Exception { <del> init(Http11Protocol.class.getName()); <add> public void testConnector() throws Exception { <add> init(); <ide> ConnectThread[] t = new ConnectThread[10]; <ide> int passcount = 0; <ide> int connectfail = 0; <ide> for (int i=0; i<t.length; i++) { <ide> t[i] = new ConnectThread(); <del> t[i].setName("ConnectThread["+i+"+]"); <del> t[i].start(); <add> t[i].setName("ConnectThread["+i+"]"); <ide> } <ide> for (int i=0; i<t.length; i++) { <del> t[i].join(); <del> if (t[i].passed) passcount++; <del> if (t[i].connectfailed) connectfail++; <del> } <del> assertEquals("The number of successful requests should have been 5.",5, passcount); <del> assertEquals("The number of failed connects should have been 5.",5, connectfail); <del> } <del> <del> public void testNio() throws Exception { <del> init(Http11NioProtocol.class.getName()); <del> ConnectThread[] t = new ConnectThread[10]; <del> int passcount = 0; <del> int connectfail = 0; <del> for (int i=0; i<t.length; i++) { <del> t[i] = new ConnectThread(); <del> t[i].setName("ConnectThread["+i+"+]"); <ide> t[i].start(); <ide> } <ide> for (int i=0; i<t.length; i++) { <ide> client.doHttp10Request(); <ide> }catch (Exception x) { <ide> passed = false; <del> System.err.println(Thread.currentThread().getName()+" Error:"+x.getMessage()); <add> log.error(Thread.currentThread().getName()+" Error:"+x.getMessage()); <ide> connectfailed = "connect timed out".equals(x.getMessage()) || "Connection refused: connect".equals(x.getMessage()); <ide> } <ide> } <ide> } <ide> <ide> <del> private synchronized void init(String protocol) throws Exception { <del> System.setProperty("tomcat.test.protocol", protocol); <del> super.setUp(); <add> private synchronized void init() throws Exception { <ide> Tomcat tomcat = getTomcatInstance(); <ide> Context root = tomcat.addContext("", SimpleHttpClient.TEMP_DIR); <ide> Tomcat.addServlet(root, "Simple", new SimpleServlet()); <ide> root.addServletMapping("/test", "Simple"); <ide> tomcat.getConnector().setProperty("maxKeepAliveRequests", "1"); <add> tomcat.getConnector().setProperty("maxThreads", "10"); <ide> tomcat.getConnector().setProperty("soTimeout", "20000"); <ide> tomcat.getConnector().setProperty("keepAliveTimeout", "50000"); <ide> tomcat.getConnector().setProperty("port", "8080"); <ide> tomcat.getConnector().setProperty("maxConnections", "4"); <ide> tomcat.getConnector().setProperty("acceptCount", "1"); <ide> tomcat.start(); <del> Thread.sleep(5000); <ide> } <ide> <ide> private class TestClient extends SimpleHttpClient { <ide> boolean passed = false; <ide> processRequest(false); // blocks until response has been read <ide> long stop = System.currentTimeMillis(); <del> System.out.println(Thread.currentThread().getName()+" Request complete:"+(stop-start)+" ms."); <add> log.info(Thread.currentThread().getName()+" Request complete:"+(stop-start)+" ms."); <ide> passed = (this.readLine()==null); <ide> // Close the connection <ide> disconnect();
Java
mit
da5e150daa0bb0c70af6837d2d22f026830d1964
0
AzureAD/azure-activedirectory-library-for-android,iambmelt/azure-activedirectory-library-for-android,AzureAD/azure-activedirectory-library-for-android,thewulf7/adal-extended,w9jds/azure-activedirectory-library-for-android,iambmelt/azure-activedirectory-library-for-android,w9jds/azure-activedirectory-library-for-android,thewulf7/adal-extended
package com.microsoft.adal.testapp; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import android.app.Activity; import android.os.AsyncTask; import android.os.Handler; import android.os.Looper; import android.util.Log; import com.google.gson.Gson; import com.microsoft.adal.AuthenticationCallback; import com.microsoft.adal.AuthenticationContext; import com.microsoft.adal.AuthenticationResult; import com.microsoft.adal.HttpWebResponse; import com.microsoft.adal.PromptBehavior; import com.microsoft.adal.WebRequestHandler; public class TestScriptRunner { private static final String TAG = "TestScriptRunner"; private static final String TARGET_URL = "https://adal.azurewebsites.net/"; private Gson gson = new Gson(); private Activity mActivity; public TestScriptRunner(Activity activity) { mActivity = activity; } public void runRemoteScript() { new RetrieveTask(TARGET_URL + "WebRequest/GetTestScript", new ResponseListener() { @Override public void onResponse(TestScriptInfo script) { Log.v(TAG, "received test script"); TestResultInfo[] results = script.run(); Log.v(TAG, "executed test script"); postResults(results); } }); } public void processTestScript(String script) { // 1- json decode // 2- generate TestCommand object // 3- run test command Log.v(TAG, "received test script"); TestScriptInfo cacheItem = gson.fromJson(script, TestScriptInfo.class); TestResultInfo[] results = cacheItem.run(); Log.v(TAG, "executed test script"); postResults(results); } private void postResults(TestResultInfo[] results) { // TODO Auto-generated method stub new TestSubmitTask(TARGET_URL + "api/Values", gson.toJson(results)); } public String makeScript() { // to test it TestScriptInfo script = new TestScriptInfo(); TestCaseInfo test1 = new TestCaseInfo(); TestAction action1 = getAction("Enter", "resource", "resource-test"); test1.testActions = new TestAction[1]; test1.testActions[0] = action1; script.testCases = new TestCaseInfo[1]; script.testCases[0] = test1; String checkText = gson.toJson(script); return checkText; } class TestScriptInfo { TestCaseInfo[] testCases; TestResultInfo[] results; /** * Run all of the test cases */ public TestResultInfo[] run() { // run each test case and collect result if (testCases != null) { TestResultInfo[] results = new TestResultInfo[testCases.length]; for (int i = 0; i < testCases.length; i++) { try { results[i] = testCases[i].run(); } catch (Exception e) { results[i] = new TestResultInfo(testCases[i].testName); results[i].statusOk = false; results[i].testMsg = e.getMessage(); } } return results; } return null; } } class TestCaseInfo { String testName; TestAction[] testActions; public TestResultInfo run() throws InterruptedException { Log.v(TAG, "running test case:" + testName); TestResultInfo testResult = new TestResultInfo(testName); TestData testRunData = new TestData(); for (int i = 0; i < testActions.length; i++) { TestAction action = getAction(testActions[i].name, testActions[i].target, testActions[i].targetValue); Log.v(TAG, "running test case:" + testName + " action:" + action.name + " target:" + action.target); action.perform(testRunData); // call api directly if possible or do click actions on UI if (testRunData.mErrorInRun) { testResult.statusOk = false; testResult.testMsg = action.target + " failed"; break; } } return testResult; } } /** * rsult to submit back * * @author omercan */ class TestResultInfo { String testName; boolean statusOk = true; String testMsg; public TestResultInfo() { } public TestResultInfo(String name) { testName = name; } } private TestAction getAction(String name, String target, String value) { // add different actions related to the API here if (name.equals("AcquireToken")) { return new AcquireTokenAction(name, target, value); } else if (name.equals("ResetAllTokens")) { return new ResetAllTokensAction(name, target, value); } else if (name.equals("Enter")) { return new EnterAction(name, target, value); } else if (name.equals("Wait")) { return new WaitAction(name, target, value); } else if (name.equals("Verify")) { return new VerifyAction(name, target, value); } return null; } /** * target can be success or fail that is set at textbox * * @author omercan */ class VerifyAction extends TestAction { public VerifyAction() { } public VerifyAction(String name, String target, String value) { super(name, target, value); } public void perform(final TestData testRunData) throws InterruptedException { if (testRunData.mErrorInRun) return; // define factory method and subtypes for asserts if necessary if (target.equals("HasAccessToken")) { testRunData.mErrorInRun = testRunData.mResult == null || testRunData.mResult.getAccessToken().isEmpty(); } else if (target.equals("SameAsReferenceToken")) { testRunData.mErrorInRun = testRunData.mResult == null || testRunData.mResult.getAccessToken().equals( testRunData.referenceResult.getAccessToken()); } else if (target.equals("AccessTokenContains")) { testRunData.mErrorInRun = testRunData.mResult == null || testRunData.mResult.getAccessToken().contains(targetValue); } } } class EnterAction extends TestAction { public EnterAction() { } public EnterAction(String name, String target, String value) { super(name, target, value); } public void perform(final TestData data) throws InterruptedException { if (data.mErrorInRun) return; if (target.equals("resource")) { data.mResource = targetValue; } else if (target.equals("clientid")) { data.mClientId = targetValue; } else if (target.equals("authority")) { data.mAuthority = targetValue; } else if (target.equals("redirect")) { data.mRedirect = targetValue; } } } class WaitAction extends TestAction { public WaitAction() { } public WaitAction(String name, String target, String value) { super(name, target, value); } public void perform(final TestData data) throws InterruptedException { if (data.mErrorInRun) return; try { int sleeptime = Integer.parseInt(targetValue); Thread.sleep(sleeptime); } catch (Exception ex) { data.mErrorInRun = true; data.mErrorMessage = ex.getMessage(); } } } class ResetAllTokensAction extends TestAction { public ResetAllTokensAction() { } public ResetAllTokensAction(String name, String target, String value) { super(name, target, value); } public void perform(final TestData data) throws InterruptedException { if (data.mErrorInRun) return; if (data == null || data.mContext == null) { data.mErrorMessage = "Context is not initialized"; data.mErrorInRun = true; } else { data.mContext.getCache().removeAll(); } } } class AcquireTokenAction extends TestAction { private static final long CONTEXT_REQUEST_TIME_OUT = 30000; public AcquireTokenAction() { } public AcquireTokenAction(String name, String target, String value) { super(name, target, value); } public void perform(final TestData data) throws InterruptedException { if (data.mErrorInRun) return; if (data == null || data.mContext == null) { data.mErrorMessage = "Context is not initialized"; data.mErrorInRun = true; } else { // related api call needs to block until it finishes final CountDownLatch signal = new CountDownLatch(1); data.mContext.acquireToken(mActivity, data.mResource, data.mClientId, data.mRedirect, data.mLoginHint, PromptBehavior.valueOf(data.mPrompt), data.mExtraQuery, new AuthenticationCallback<AuthenticationResult>() { @Override public void onSuccess(AuthenticationResult result) { data.mResult = result; signal.countDown(); } @Override public void onError(Exception exc) { data.mErrorInRun = true; data.mErrorMessage = exc.getMessage(); signal.countDown(); } }); signal.await(CONTEXT_REQUEST_TIME_OUT, TimeUnit.MILLISECONDS); } } } class TestData { AuthenticationContext mContext; AuthenticationResult referenceResult; String mAuthority; String mResource; String mClientId; String mRedirect; String mLoginHint; String mExtraQuery; String mPrompt; CountDownLatch mSignal; AuthenticationResult mResult; boolean mErrorInRun; String mErrorMessage; } class TestAction { protected String name; protected String target; protected String targetValue; public TestAction() { name = "N/A"; targetValue = "N/A"; target = "N/A"; } public TestAction(String action_name, String action_target, String action_val) { name = action_name; target = action_target; targetValue = action_val; } public void perform(TestData data) throws InterruptedException { } } /** * Simple get request for test * * @author omercan */ class TestSubmitTask extends AsyncTask<Void, Void, Void> { private String mUrl; private String mData; public TestSubmitTask(String url, String data) { mUrl = url; mData = data; } @Override protected Void doInBackground(Void... empty) { WebRequestHandler request = new WebRequestHandler(); HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Accept", "application/json"); HttpWebResponse response = null; try { response = request.sendPost(new URL(mUrl), headers, mData.getBytes("UTF-8"), "application/json"); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } Log.v(TAG, "Send data status:" + response.getStatusCode()); return null; } } interface ResponseListener { void onResponse(TestScriptInfo script); } class RetrieveTask extends AsyncTask<Void, Void, TestScriptInfo> { private String mUrl; private ResponseListener mCallback; public RetrieveTask(String url, ResponseListener callback) { mUrl = url; mCallback = callback; } @Override protected TestScriptInfo doInBackground(Void... empty) { WebRequestHandler request = new WebRequestHandler(); HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Accept", "application/json"); HttpWebResponse response = null; try { response = request.sendGet(new URL(mUrl), headers); String body = new String(response.getBody(), "UTF-8"); TestScriptInfo scriptInfo = gson.fromJson(body, TestScriptInfo.class); return scriptInfo; } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } Log.v(TAG, "Send data status:" + response.getStatusCode()); return null; } @Override protected void onPostExecute(TestScriptInfo result) { super.onPostExecute(result); mCallback.onResponse(result); } } }
samples/testapp/src/com/microsoft/adal/testapp/TestScriptRunner.java
package com.microsoft.adal.testapp; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import android.app.Activity; import android.os.AsyncTask; import android.util.Log; import com.google.gson.Gson; import com.microsoft.adal.AuthenticationCallback; import com.microsoft.adal.AuthenticationContext; import com.microsoft.adal.AuthenticationResult; import com.microsoft.adal.HttpWebResponse; import com.microsoft.adal.PromptBehavior; import com.microsoft.adal.WebRequestHandler; public class TestScriptRunner { private static final String TAG = "TestScriptRunner"; private static final String TARGET_URL = "https://adal.azurewebsites.net/api/values"; private Gson gson = new Gson(); private Activity mActivity; public TestScriptRunner(Activity activity) { mActivity = activity; } public void processTestScript(String script) { // 1- json decode // 2- generate TestCommand object // 3- run test command Log.v(TAG, "received test script"); TestScriptInfo cacheItem = gson.fromJson(script, TestScriptInfo.class); TestResultInfo[] results = cacheItem.run(); Log.v(TAG, "executed test script"); postResults(results); } private void postResults(TestResultInfo[] results) { // TODO Auto-generated method stub new TestSubmitTask(TARGET_URL, gson.toJson(results)); } public String makeScript() { // to test it TestScriptInfo script = new TestScriptInfo(); TestCaseInfo test1 = new TestCaseInfo(); TestAction action1 = getAction("Enter", "resource", "resource-test"); test1.testActions = new TestAction[1]; test1.testActions[0] = action1; script.testCases = new TestCaseInfo[1]; script.testCases[0] = test1; String checkText = gson.toJson(script); return checkText; } class TestScriptInfo { TestCaseInfo[] testCases; TestResultInfo[] results; /** * Run all of the test cases */ public TestResultInfo[] run() { // run each test case and collect result if (testCases != null) { TestResultInfo[] results = new TestResultInfo[testCases.length]; for (int i = 0; i < testCases.length; i++) { try { results[i] = testCases[i].run(); } catch (Exception e) { results[i] = new TestResultInfo(testCases[i].testName); results[i].mStatusOk = false; results[i].mTestMsg = e.getMessage(); } } return results; } return null; } } class TestCaseInfo { String testName; TestAction[] testActions; AssertFlag[] testAsserts; public TestResultInfo run() throws InterruptedException { Log.v(TAG, "running test case:" + testName); TestResultInfo testResult = new TestResultInfo(testName); TestData testRunData = new TestData(); for (int i = 0; i < testActions.length; i++) { TestAction action = getAction(testActions[i].mName, testActions[i].mTarget, testActions[i].mValue); Log.v(TAG, "running test case:" + testName + " action:" + action.mName + " target:" + action.mTarget); action.perform(testRunData); // call api directly if possible or do click actions on UI } for (AssertFlag flagCheck : testAsserts) { Log.v(TAG, "verifying test case:" + testName + " flag:" + flagCheck.mTarget); flagCheck.perform(testRunData); if (!flagCheck.mValue) { testResult.mStatusOk = false; testResult.mTestMsg = flagCheck.mTarget + " failed"; break; } } return testResult; } } /** * rsult to submit back * * @author omercan */ class TestResultInfo { String mTestName; boolean mStatusOk = true; String mTestMsg; public TestResultInfo() { } public TestResultInfo(String name) { mTestName = name; } } /** * target can be success or fail that is set at textbox * * @author omercan */ class AssertFlag { private String mTarget; private boolean mValue; public void perform(TestData testRunData) { // define factory method and subtypes for asserts if necessary if (mTarget.equals("HasAccessToken")) { mValue = testRunData != null && testRunData.mResult != null && !testRunData.mResult.getAccessToken().isEmpty(); } } } private TestAction getAction(String name, String target, String value) { // add different actions related to the API here if (name.equals("AcquireToken")) { return new AcquireTokenAction(name, target, value); } else if (name.equals("ResetAllTokens")) { return new ResetAllTokensAction(name, target, value); } else if (name.equals("Enter")) { return new EnterAction(name, target, value); } return null; } class EnterAction extends TestAction { public EnterAction() { } public EnterAction(String name, String target, String value) { super(name, target, value); } public void perform(final TestData data) throws InterruptedException { if (data.mErrorInRun) return; if (mTarget.equals("resource")) { data.mResource = mValue; } } } class ResetAllTokensAction extends TestAction { public ResetAllTokensAction() { } public ResetAllTokensAction(String name, String target, String value) { super(name, target, value); } public void perform(final TestData data) throws InterruptedException { if (data.mErrorInRun) return; if (data == null || data.mContext == null) { data.mErrorMessage = "Context is not initialized"; data.mErrorInRun = true; } else { data.mContext.getCache().removeAll(); } } } class AcquireTokenAction extends TestAction { private static final long CONTEXT_REQUEST_TIME_OUT = 30000; public AcquireTokenAction() { } public AcquireTokenAction(String name, String target, String value) { super(name, target, value); } public void perform(final TestData data) throws InterruptedException { if (data.mErrorInRun) return; if (data == null || data.mContext == null) { data.mErrorMessage = "Context is not initialized"; data.mErrorInRun = true; } else { // related api call needs to block until it finishes final CountDownLatch signal = new CountDownLatch(1); data.mContext.acquireToken(mActivity, data.mResource, data.mClientId, data.mRedirect, data.mLoginHint, PromptBehavior.valueOf(data.mPrompt), data.mExtraQuery, new AuthenticationCallback<AuthenticationResult>() { @Override public void onSuccess(AuthenticationResult result) { data.mResult = result; signal.countDown(); } @Override public void onError(Exception exc) { data.mErrorInRun = true; data.mErrorMessage = exc.getMessage(); signal.countDown(); } }); signal.await(CONTEXT_REQUEST_TIME_OUT, TimeUnit.MILLISECONDS); } } } class TestData { AuthenticationContext mContext; String mAuthority; String mResource; String mClientId; String mRedirect; String mLoginHint; String mExtraQuery; String mPrompt; CountDownLatch mSignal; AuthenticationResult mResult; boolean mErrorInRun; String mErrorMessage; } class TestAction { protected String mName; protected String mTarget; protected String mValue; public TestAction() { mName = "N/A"; mValue = "N/A"; mTarget = "N/A"; } public TestAction(String name, String target, String val) { mName = name; mTarget = target; mValue = val; } public void perform(TestData data) throws InterruptedException { } } /** * Simple get request for test * * @author omercan */ class TestSubmitTask extends AsyncTask<Void, Void, Void> { private String mUrl; private String mData; public TestSubmitTask(String url, String data) { mUrl = url; mData = data; } @Override protected Void doInBackground(Void... empty) { WebRequestHandler request = new WebRequestHandler(); HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Accept", "application/json"); HttpWebResponse response = null; try { response = request.sendPost(new URL(mUrl), headers, mData.getBytes("UTF-8"), "application/json"); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } Log.v(TAG, "Send data status:" + response.getStatusCode()); return null; } } }
retrieve remote script and post
samples/testapp/src/com/microsoft/adal/testapp/TestScriptRunner.java
retrieve remote script and post
<ide><path>amples/testapp/src/com/microsoft/adal/testapp/TestScriptRunner.java <ide> <ide> import android.app.Activity; <ide> import android.os.AsyncTask; <add>import android.os.Handler; <add>import android.os.Looper; <ide> import android.util.Log; <ide> <ide> import com.google.gson.Gson; <ide> public class TestScriptRunner { <ide> private static final String TAG = "TestScriptRunner"; <ide> <del> private static final String TARGET_URL = "https://adal.azurewebsites.net/api/values"; <add> private static final String TARGET_URL = "https://adal.azurewebsites.net/"; <ide> <ide> private Gson gson = new Gson(); <ide> <ide> <ide> public TestScriptRunner(Activity activity) { <ide> mActivity = activity; <add> } <add> <add> public void runRemoteScript() { <add> new RetrieveTask(TARGET_URL + "WebRequest/GetTestScript", new ResponseListener() { <add> <add> @Override <add> public void onResponse(TestScriptInfo script) { <add> <add> Log.v(TAG, "received test script"); <add> TestResultInfo[] results = script.run(); <add> Log.v(TAG, "executed test script"); <add> postResults(results); <add> } <add> }); <ide> } <ide> <ide> public void processTestScript(String script) { <ide> <ide> private void postResults(TestResultInfo[] results) { <ide> // TODO Auto-generated method stub <del> new TestSubmitTask(TARGET_URL, gson.toJson(results)); <add> new TestSubmitTask(TARGET_URL + "api/Values", gson.toJson(results)); <ide> } <ide> <ide> public String makeScript() { <ide> results[i] = testCases[i].run(); <ide> } catch (Exception e) { <ide> results[i] = new TestResultInfo(testCases[i].testName); <del> results[i].mStatusOk = false; <del> results[i].mTestMsg = e.getMessage(); <add> results[i].statusOk = false; <add> results[i].testMsg = e.getMessage(); <ide> } <ide> } <ide> <ide> String testName; <ide> <ide> TestAction[] testActions; <del> <del> AssertFlag[] testAsserts; <ide> <ide> public TestResultInfo run() throws InterruptedException { <ide> Log.v(TAG, "running test case:" + testName); <ide> TestResultInfo testResult = new TestResultInfo(testName); <ide> TestData testRunData = new TestData(); <ide> for (int i = 0; i < testActions.length; i++) { <del> TestAction action = getAction(testActions[i].mName, testActions[i].mTarget, <del> testActions[i].mValue); <del> Log.v(TAG, "running test case:" + testName + " action:" + action.mName + " target:" <del> + action.mTarget); <add> TestAction action = getAction(testActions[i].name, testActions[i].target, <add> testActions[i].targetValue); <add> Log.v(TAG, "running test case:" + testName + " action:" + action.name + " target:" <add> + action.target); <ide> <ide> action.perform(testRunData); <ide> // call api directly if possible or do click actions on UI <del> } <del> <del> for (AssertFlag flagCheck : testAsserts) { <del> Log.v(TAG, "verifying test case:" + testName + " flag:" + flagCheck.mTarget); <del> flagCheck.perform(testRunData); <del> if (!flagCheck.mValue) { <del> testResult.mStatusOk = false; <del> testResult.mTestMsg = flagCheck.mTarget + " failed"; <add> if (testRunData.mErrorInRun) { <add> testResult.statusOk = false; <add> testResult.testMsg = action.target + " failed"; <ide> break; <ide> } <ide> } <ide> * @author omercan <ide> */ <ide> class TestResultInfo { <del> String mTestName; <del> <del> boolean mStatusOk = true; <del> <del> String mTestMsg; <add> String testName; <add> <add> boolean statusOk = true; <add> <add> String testMsg; <ide> <ide> public TestResultInfo() { <ide> } <ide> <ide> public TestResultInfo(String name) { <del> mTestName = name; <del> } <del> } <del> <del> /** <del> * target can be success or fail that is set at textbox <del> * <del> * @author omercan <del> */ <del> class AssertFlag { <del> private String mTarget; <del> <del> private boolean mValue; <del> <del> public void perform(TestData testRunData) { <del> // define factory method and subtypes for asserts if necessary <del> if (mTarget.equals("HasAccessToken")) { <del> mValue = testRunData != null && testRunData.mResult != null <del> && !testRunData.mResult.getAccessToken().isEmpty(); <del> } <add> testName = name; <ide> } <ide> } <ide> <ide> return new ResetAllTokensAction(name, target, value); <ide> } else if (name.equals("Enter")) { <ide> return new EnterAction(name, target, value); <add> } else if (name.equals("Wait")) { <add> return new WaitAction(name, target, value); <add> } else if (name.equals("Verify")) { <add> return new VerifyAction(name, target, value); <ide> } <ide> <ide> return null; <add> } <add> <add> /** <add> * target can be success or fail that is set at textbox <add> * <add> * @author omercan <add> */ <add> class VerifyAction extends TestAction { <add> public VerifyAction() { <add> } <add> <add> public VerifyAction(String name, String target, String value) { <add> super(name, target, value); <add> } <add> <add> public void perform(final TestData testRunData) throws InterruptedException { <add> if (testRunData.mErrorInRun) <add> return; <add> <add> // define factory method and subtypes for asserts if necessary <add> if (target.equals("HasAccessToken")) { <add> testRunData.mErrorInRun = testRunData.mResult == null <add> || testRunData.mResult.getAccessToken().isEmpty(); <add> } else if (target.equals("SameAsReferenceToken")) { <add> testRunData.mErrorInRun = testRunData.mResult == null <add> || testRunData.mResult.getAccessToken().equals( <add> testRunData.referenceResult.getAccessToken()); <add> } else if (target.equals("AccessTokenContains")) { <add> testRunData.mErrorInRun = testRunData.mResult == null <add> || testRunData.mResult.getAccessToken().contains(targetValue); <add> } <add> } <ide> } <ide> <ide> class EnterAction extends TestAction { <ide> if (data.mErrorInRun) <ide> return; <ide> <del> if (mTarget.equals("resource")) { <del> data.mResource = mValue; <del> } <del> } <add> if (target.equals("resource")) { <add> data.mResource = targetValue; <add> } else if (target.equals("clientid")) { <add> data.mClientId = targetValue; <add> } else if (target.equals("authority")) { <add> data.mAuthority = targetValue; <add> } else if (target.equals("redirect")) { <add> data.mRedirect = targetValue; <add> } <add> } <add> } <add> <add> class WaitAction extends TestAction { <add> public WaitAction() { <add> } <add> <add> public WaitAction(String name, String target, String value) { <add> super(name, target, value); <add> } <add> <add> public void perform(final TestData data) throws InterruptedException { <add> if (data.mErrorInRun) <add> return; <add> try { <add> int sleeptime = Integer.parseInt(targetValue); <add> <add> Thread.sleep(sleeptime); <add> } catch (Exception ex) { <add> data.mErrorInRun = true; <add> data.mErrorMessage = ex.getMessage(); <add> } <add> } <add> <ide> } <ide> <ide> class ResetAllTokensAction extends TestAction { <ide> class TestData { <ide> AuthenticationContext mContext; <ide> <add> AuthenticationResult referenceResult; <add> <ide> String mAuthority; <ide> <ide> String mResource; <ide> } <ide> <ide> class TestAction { <del> protected String mName; <del> <del> protected String mTarget; <del> <del> protected String mValue; <add> protected String name; <add> <add> protected String target; <add> <add> protected String targetValue; <ide> <ide> public TestAction() { <del> mName = "N/A"; <del> mValue = "N/A"; <del> mTarget = "N/A"; <del> } <del> <del> public TestAction(String name, String target, String val) { <del> mName = name; <del> mTarget = target; <del> mValue = val; <add> name = "N/A"; <add> targetValue = "N/A"; <add> target = "N/A"; <add> } <add> <add> public TestAction(String action_name, String action_target, String action_val) { <add> name = action_name; <add> target = action_target; <add> targetValue = action_val; <ide> } <ide> <ide> public void perform(TestData data) throws InterruptedException { <ide> <ide> } <del> <ide> } <ide> <ide> /** <ide> headers.put("Accept", "application/json"); <ide> HttpWebResponse response = null; <ide> try { <del> response = request.sendPost(new URL(mUrl), headers, <del> mData.getBytes("UTF-8"), "application/json"); <add> response = request.sendPost(new URL(mUrl), headers, mData.getBytes("UTF-8"), <add> "application/json"); <ide> } catch (MalformedURLException e) { <ide> // TODO Auto-generated catch block <ide> e.printStackTrace(); <ide> <ide> Log.v(TAG, "Send data status:" + response.getStatusCode()); <ide> return null; <del> <del> } <del> } <del> <add> } <add> } <add> <add> interface ResponseListener { <add> void onResponse(TestScriptInfo script); <add> <add> } <add> <add> class RetrieveTask extends AsyncTask<Void, Void, TestScriptInfo> { <add> <add> private String mUrl; <add> <add> private ResponseListener mCallback; <add> <add> public RetrieveTask(String url, ResponseListener callback) { <add> mUrl = url; <add> mCallback = callback; <add> } <add> <add> @Override <add> protected TestScriptInfo doInBackground(Void... empty) { <add> <add> WebRequestHandler request = new WebRequestHandler(); <add> HashMap<String, String> headers = new HashMap<String, String>(); <add> <add> headers.put("Accept", "application/json"); <add> HttpWebResponse response = null; <add> try { <add> response = request.sendGet(new URL(mUrl), headers); <add> String body = new String(response.getBody(), "UTF-8"); <add> TestScriptInfo scriptInfo = gson.fromJson(body, TestScriptInfo.class); <add> return scriptInfo; <add> } catch (MalformedURLException e) { <add> // TODO Auto-generated catch block <add> e.printStackTrace(); <add> } catch (UnsupportedEncodingException e) { <add> // TODO Auto-generated catch block <add> e.printStackTrace(); <add> } <add> <add> Log.v(TAG, "Send data status:" + response.getStatusCode()); <add> return null; <add> } <add> <add> @Override <add> protected void onPostExecute(TestScriptInfo result) { <add> super.onPostExecute(result); <add> mCallback.onResponse(result); <add> } <add> <add> } <ide> }
Java
apache-2.0
e9f0c3d713e4f75f6aaa94a488900d02522cb25c
0
xjodoin/torpedoquery
package org.torpedoquery.jpa.internal.utils; import java.io.Serializable; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import com.google.common.base.Throwables; public class SerializableMethod implements Serializable { private static final long serialVersionUID = 6005610965006048445L; private final Class<?> declaringClass; private final String methodName; private final Class<?>[] parameterTypes; private final Class<?> returnType; private final Class<?>[] exceptionTypes; private final boolean isVarArgs; private final boolean isAbstract; public SerializableMethod(Method method) { declaringClass = method.getDeclaringClass(); methodName = method.getName(); parameterTypes = method.getParameterTypes(); returnType = method.getReturnType(); exceptionTypes = method.getExceptionTypes(); isVarArgs = method.isVarArgs(); isAbstract = (method.getModifiers() & Modifier.ABSTRACT) != 0; } public String getName() { return methodName; } public Class<?> getReturnType() { return returnType; } public Class<?>[] getParameterTypes() { return parameterTypes; } public Class<?>[] getExceptionTypes() { return exceptionTypes; } public boolean isVarArgs() { return isVarArgs; } public boolean isAbstract() { return isAbstract; } public Method getJavaMethod() { try { return declaringClass.getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException | SecurityException e) { throw Throwables.propagate(e); } } @Override public int hashCode() { return 1; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SerializableMethod other = (SerializableMethod) obj; if (declaringClass == null) { if (other.declaringClass != null) return false; } else if (!declaringClass.equals(other.declaringClass)) return false; if (methodName == null) { if (other.methodName != null) return false; } else if (!methodName.equals(other.methodName)) return false; if (!Arrays.equals(parameterTypes, other.parameterTypes)) return false; if (returnType == null) { if (other.returnType != null) return false; } else if (!returnType.equals(other.returnType)) return false; return true; } }
src/main/java/org/torpedoquery/jpa/internal/utils/SerializableMethod.java
package org.torpedoquery.jpa.internal.utils; import java.io.Serializable; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import org.mockito.exceptions.base.MockitoException; public class SerializableMethod implements Serializable { private static final long serialVersionUID = 6005610965006048445L; private final Class<?> declaringClass; private final String methodName; private final Class<?>[] parameterTypes; private final Class<?> returnType; private final Class<?>[] exceptionTypes; private final boolean isVarArgs; private final boolean isAbstract; public SerializableMethod(Method method) { declaringClass = method.getDeclaringClass(); methodName = method.getName(); parameterTypes = method.getParameterTypes(); returnType = method.getReturnType(); exceptionTypes = method.getExceptionTypes(); isVarArgs = method.isVarArgs(); isAbstract = (method.getModifiers() & Modifier.ABSTRACT) != 0; } public String getName() { return methodName; } public Class<?> getReturnType() { return returnType; } public Class<?>[] getParameterTypes() { return parameterTypes; } public Class<?>[] getExceptionTypes() { return exceptionTypes; } public boolean isVarArgs() { return isVarArgs; } public boolean isAbstract() { return isAbstract; } public Method getJavaMethod() { try { return declaringClass.getDeclaredMethod(methodName, parameterTypes); } catch (SecurityException e) { String message = String.format( "The method %1$s.%2$s is probably private or protected and cannot be mocked.\n" + "Please report this as a defect with an example of how to reproduce it.", declaringClass, methodName); throw new MockitoException(message, e); } catch (NoSuchMethodException e) { String message = String.format( "The method %1$s.%2$s does not exists and you should not get to this point.\n" + "Please report this as a defect with an example of how to reproduce it.", declaringClass, methodName); throw new MockitoException(message, e); } } @Override public int hashCode() { return 1; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SerializableMethod other = (SerializableMethod) obj; if (declaringClass == null) { if (other.declaringClass != null) return false; } else if (!declaringClass.equals(other.declaringClass)) return false; if (methodName == null) { if (other.methodName != null) return false; } else if (!methodName.equals(other.methodName)) return false; if (!Arrays.equals(parameterTypes, other.parameterTypes)) return false; if (returnType == null) { if (other.returnType != null) return false; } else if (!returnType.equals(other.returnType)) return false; return true; } }
cleaup stuff
src/main/java/org/torpedoquery/jpa/internal/utils/SerializableMethod.java
cleaup stuff
<ide><path>rc/main/java/org/torpedoquery/jpa/internal/utils/SerializableMethod.java <ide> import java.lang.reflect.Modifier; <ide> import java.util.Arrays; <ide> <del>import org.mockito.exceptions.base.MockitoException; <add>import com.google.common.base.Throwables; <ide> <ide> public class SerializableMethod implements Serializable { <ide> <del> private static final long serialVersionUID = 6005610965006048445L; <add> private static final long serialVersionUID = 6005610965006048445L; <ide> <del> private final Class<?> declaringClass; <del> private final String methodName; <del> private final Class<?>[] parameterTypes; <del> private final Class<?> returnType; <del> private final Class<?>[] exceptionTypes; <del> private final boolean isVarArgs; <del> private final boolean isAbstract; <add> private final Class<?> declaringClass; <add> private final String methodName; <add> private final Class<?>[] parameterTypes; <add> private final Class<?> returnType; <add> private final Class<?>[] exceptionTypes; <add> private final boolean isVarArgs; <add> private final boolean isAbstract; <ide> <del> public SerializableMethod(Method method) { <del> declaringClass = method.getDeclaringClass(); <del> methodName = method.getName(); <del> parameterTypes = method.getParameterTypes(); <del> returnType = method.getReturnType(); <del> exceptionTypes = method.getExceptionTypes(); <del> isVarArgs = method.isVarArgs(); <del> isAbstract = (method.getModifiers() & Modifier.ABSTRACT) != 0; <del> } <add> public SerializableMethod(Method method) { <add> declaringClass = method.getDeclaringClass(); <add> methodName = method.getName(); <add> parameterTypes = method.getParameterTypes(); <add> returnType = method.getReturnType(); <add> exceptionTypes = method.getExceptionTypes(); <add> isVarArgs = method.isVarArgs(); <add> isAbstract = (method.getModifiers() & Modifier.ABSTRACT) != 0; <add> } <ide> <del> public String getName() { <del> return methodName; <del> } <add> public String getName() { <add> return methodName; <add> } <ide> <del> public Class<?> getReturnType() { <del> return returnType; <del> } <add> public Class<?> getReturnType() { <add> return returnType; <add> } <ide> <del> public Class<?>[] getParameterTypes() { <del> return parameterTypes; <del> } <add> public Class<?>[] getParameterTypes() { <add> return parameterTypes; <add> } <ide> <del> public Class<?>[] getExceptionTypes() { <del> return exceptionTypes; <del> } <add> public Class<?>[] getExceptionTypes() { <add> return exceptionTypes; <add> } <ide> <del> public boolean isVarArgs() { <del> return isVarArgs; <del> } <add> public boolean isVarArgs() { <add> return isVarArgs; <add> } <ide> <del> public boolean isAbstract() { <del> return isAbstract; <del> } <add> public boolean isAbstract() { <add> return isAbstract; <add> } <ide> <del> public Method getJavaMethod() { <del> try { <del> return declaringClass.getDeclaredMethod(methodName, parameterTypes); <del> } catch (SecurityException e) { <del> String message = String.format( <del> "The method %1$s.%2$s is probably private or protected and cannot be mocked.\n" + <del> "Please report this as a defect with an example of how to reproduce it.", declaringClass, methodName); <del> throw new MockitoException(message, e); <del> } catch (NoSuchMethodException e) { <del> String message = String.format( <del> "The method %1$s.%2$s does not exists and you should not get to this point.\n" + <del> "Please report this as a defect with an example of how to reproduce it.", declaringClass, methodName); <del> throw new MockitoException(message, e); <del> } <del> } <add> public Method getJavaMethod() { <add> try { <add> return declaringClass.getDeclaredMethod(methodName, parameterTypes); <add> } catch (NoSuchMethodException | SecurityException e) { <add> throw Throwables.propagate(e); <add> } <add> } <ide> <del> @Override <del> public int hashCode() { <del> return 1; <del> } <add> @Override <add> public int hashCode() { <add> return 1; <add> } <ide> <del> @Override <del> public boolean equals(Object obj) { <del> if (this == obj) <del> return true; <del> if (obj == null) <del> return false; <del> if (getClass() != obj.getClass()) <del> return false; <del> SerializableMethod other = (SerializableMethod) obj; <del> if (declaringClass == null) { <del> if (other.declaringClass != null) <del> return false; <del> } else if (!declaringClass.equals(other.declaringClass)) <del> return false; <del> if (methodName == null) { <del> if (other.methodName != null) <del> return false; <del> } else if (!methodName.equals(other.methodName)) <del> return false; <del> if (!Arrays.equals(parameterTypes, other.parameterTypes)) <del> return false; <del> if (returnType == null) { <del> if (other.returnType != null) <del> return false; <del> } else if (!returnType.equals(other.returnType)) <del> return false; <del> return true; <del> } <add> @Override <add> public boolean equals(Object obj) { <add> if (this == obj) <add> return true; <add> if (obj == null) <add> return false; <add> if (getClass() != obj.getClass()) <add> return false; <add> SerializableMethod other = (SerializableMethod) obj; <add> if (declaringClass == null) { <add> if (other.declaringClass != null) <add> return false; <add> } else if (!declaringClass.equals(other.declaringClass)) <add> return false; <add> if (methodName == null) { <add> if (other.methodName != null) <add> return false; <add> } else if (!methodName.equals(other.methodName)) <add> return false; <add> if (!Arrays.equals(parameterTypes, other.parameterTypes)) <add> return false; <add> if (returnType == null) { <add> if (other.returnType != null) <add> return false; <add> } else if (!returnType.equals(other.returnType)) <add> return false; <add> return true; <add> } <ide> }
Java
mpl-2.0
0c9d95574bf49754f0490bd4735994e1eb50067e
0
Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV
package org.helioviewer.jhv.camera.annotate; import javax.annotation.Nullable; import org.helioviewer.jhv.base.Colors; import org.helioviewer.jhv.camera.Camera; import org.helioviewer.jhv.camera.CameraHelper; import org.helioviewer.jhv.camera.Interaction; import org.helioviewer.jhv.display.Display; import org.helioviewer.jhv.display.Viewport; import org.helioviewer.jhv.math.Quat; import org.helioviewer.jhv.math.Vec2; import org.helioviewer.jhv.math.Vec3; import org.helioviewer.jhv.opengl.BufVertex; import org.helioviewer.jhv.opengl.GLHelper; import org.json.JSONObject; public class AnnotatePOS extends AbstractAnnotateable { private static final int SUBDIVISIONS = 2; private Quat posRotation; // plane-of-sky, should be saved public AnnotatePOS(JSONObject jo) { super(jo); } private static void drawLOS(Quat q, Viewport vp, Vec3 bp, BufVertex buf, byte[] color) { double delta = 2.5 * Math.PI / 180; Vec3 p1 = new Vec3(radius, bp.y + 4 * delta, bp.z); Vec3 p2 = new Vec3(radius, bp.y - 4 * delta, bp.z); Vec3 p3 = new Vec3(radius, bp.y, bp.z + delta); Vec3 p4 = new Vec3(radius, bp.y, bp.z - delta); interpolatedDraw(q, vp, p1, p2, buf, color, 4 * SUBDIVISIONS); interpolatedDraw(q, vp, p3, p4, buf, color, SUBDIVISIONS); } private static void interpolatedDraw(Quat q, Viewport vp, Vec3 p1s, Vec3 p2s, BufVertex buf, byte[] color, int subdivs) { Vec2 previous = null; for (int i = 0; i <= subdivs; i++) { Vec3 pc = interpolate(i / (double) subdivs, p1s, p2s); if (Display.mode == Display.DisplayMode.Orthographic) { if (i == 0) { buf.putVertex(pc, Colors.Null); } buf.putVertex(pc, color); if (i == subdivs) { buf.putVertex(pc, Colors.Null); } } else { pc.y = -pc.y; if (i == 0) { GLHelper.drawVertex(q, vp, pc, previous, buf, Colors.Null); } previous = GLHelper.drawVertex(q, vp, pc, previous, buf, color); if (i == subdivs) { GLHelper.drawVertex(q, vp, pc, previous, buf, Colors.Null); } } } } @Nullable public Quat getPOSRotation() { return posRotation; } @Override public void draw(Quat q, Viewport vp, boolean active, BufVertex buf) { if (startPoint == null) return; byte[] color = active ? activeColor : baseColor; drawLOS(q, vp, toSpherical(startPoint), buf, color); } @Override public void mousePressed(Camera camera, int x, int y) { Vec3 pt = computePoint(camera, x, y); if (pt != null) { startPoint = pt; Vec3 posPoint = CameraHelper.getVectorFromSphere(camera, Display.getActiveViewport(), x, y, Quat.ZERO, true); if (posPoint != null) { double lon = Math.atan2(posPoint.x, posPoint.z); posRotation = new Quat(0, Math.PI / 2 - lon); } } } @Override public void mouseDragged(Camera camera, int x, int y) { } @Override public void mouseReleased() { } @Override public boolean beingDragged() { return true; } @Override public boolean isDraggable() { return false; } @Override public String getType() { return Interaction.AnnotationMode.POS.toString(); } }
src/org/helioviewer/jhv/camera/annotate/AnnotatePOS.java
package org.helioviewer.jhv.camera.annotate; import javax.annotation.Nullable; import org.helioviewer.jhv.base.Colors; import org.helioviewer.jhv.camera.Camera; import org.helioviewer.jhv.camera.CameraHelper; import org.helioviewer.jhv.camera.Interaction; import org.helioviewer.jhv.display.Display; import org.helioviewer.jhv.display.Viewport; import org.helioviewer.jhv.math.Quat; import org.helioviewer.jhv.math.Vec2; import org.helioviewer.jhv.math.Vec3; import org.helioviewer.jhv.opengl.BufVertex; import org.helioviewer.jhv.opengl.GLHelper; import org.json.JSONObject; public class AnnotatePOS extends AbstractAnnotateable { private static final int SUBDIVISIONS = 2; private Quat posRotation; // plane-of-sky, should be saved public AnnotatePOS(JSONObject jo) { super(jo); } private static void drawLOS(Quat q, Viewport vp, Vec3 bp, BufVertex buf, byte[] color) { double delta = 2.5 * Math.PI / 180; Vec3 p1 = new Vec3(radius, bp.y + delta, bp.z); Vec3 p2 = new Vec3(radius, bp.y - delta, bp.z); Vec3 p3 = new Vec3(radius, bp.y, bp.z + delta); Vec3 p4 = new Vec3(radius, bp.y, bp.z - delta); interpolatedDraw(q, vp, p1, p2, buf, color); interpolatedDraw(q, vp, p3, p4, buf, color); } private static void interpolatedDraw(Quat q, Viewport vp, Vec3 p1s, Vec3 p2s, BufVertex buf, byte[] color) { Vec2 previous = null; for (int i = 0; i <= SUBDIVISIONS; i++) { Vec3 pc = interpolate(i / (double) SUBDIVISIONS, p1s, p2s); if (Display.mode == Display.DisplayMode.Orthographic) { if (i == 0) { buf.putVertex(pc, Colors.Null); } buf.putVertex(pc, color); if (i == SUBDIVISIONS) { buf.putVertex(pc, Colors.Null); } } else { pc.y = -pc.y; if (i == 0) { GLHelper.drawVertex(q, vp, pc, previous, buf, Colors.Null); } previous = GLHelper.drawVertex(q, vp, pc, previous, buf, color); if (i == SUBDIVISIONS) { GLHelper.drawVertex(q, vp, pc, previous, buf, Colors.Null); } } } } @Nullable public Quat getPOSRotation() { return posRotation; } @Override public void draw(Quat q, Viewport vp, boolean active, BufVertex buf) { if (startPoint == null) return; byte[] color = active ? activeColor : baseColor; drawLOS(q, vp, toSpherical(startPoint), buf, color); } @Override public void mousePressed(Camera camera, int x, int y) { Vec3 pt = computePoint(camera, x, y); if (pt != null) { startPoint = pt; Vec3 posPoint = CameraHelper.getVectorFromSphere(camera, Display.getActiveViewport(), x, y, Quat.ZERO, true); if (posPoint != null) { double lon = Math.atan2(posPoint.x, posPoint.z); posRotation = new Quat(0, Math.PI / 2 - lon); } } } @Override public void mouseDragged(Camera camera, int x, int y) { } @Override public void mouseReleased() { } @Override public boolean beingDragged() { return true; } @Override public boolean isDraggable() { return false; } @Override public String getType() { return Interaction.AnnotationMode.POS.toString(); } }
Extend POS meridian
src/org/helioviewer/jhv/camera/annotate/AnnotatePOS.java
Extend POS meridian
<ide><path>rc/org/helioviewer/jhv/camera/annotate/AnnotatePOS.java <ide> <ide> private static void drawLOS(Quat q, Viewport vp, Vec3 bp, BufVertex buf, byte[] color) { <ide> double delta = 2.5 * Math.PI / 180; <del> Vec3 p1 = new Vec3(radius, bp.y + delta, bp.z); <del> Vec3 p2 = new Vec3(radius, bp.y - delta, bp.z); <add> Vec3 p1 = new Vec3(radius, bp.y + 4 * delta, bp.z); <add> Vec3 p2 = new Vec3(radius, bp.y - 4 * delta, bp.z); <ide> Vec3 p3 = new Vec3(radius, bp.y, bp.z + delta); <ide> Vec3 p4 = new Vec3(radius, bp.y, bp.z - delta); <ide> <del> interpolatedDraw(q, vp, p1, p2, buf, color); <del> interpolatedDraw(q, vp, p3, p4, buf, color); <add> interpolatedDraw(q, vp, p1, p2, buf, color, 4 * SUBDIVISIONS); <add> interpolatedDraw(q, vp, p3, p4, buf, color, SUBDIVISIONS); <ide> } <ide> <del> private static void interpolatedDraw(Quat q, Viewport vp, Vec3 p1s, Vec3 p2s, BufVertex buf, byte[] color) { <add> private static void interpolatedDraw(Quat q, Viewport vp, Vec3 p1s, Vec3 p2s, BufVertex buf, byte[] color, int subdivs) { <ide> Vec2 previous = null; <del> for (int i = 0; i <= SUBDIVISIONS; i++) { <del> Vec3 pc = interpolate(i / (double) SUBDIVISIONS, p1s, p2s); <add> for (int i = 0; i <= subdivs; i++) { <add> Vec3 pc = interpolate(i / (double) subdivs, p1s, p2s); <ide> <ide> if (Display.mode == Display.DisplayMode.Orthographic) { <ide> if (i == 0) { <ide> buf.putVertex(pc, Colors.Null); <ide> } <ide> buf.putVertex(pc, color); <del> if (i == SUBDIVISIONS) { <add> if (i == subdivs) { <ide> buf.putVertex(pc, Colors.Null); <ide> } <ide> } else { <ide> GLHelper.drawVertex(q, vp, pc, previous, buf, Colors.Null); <ide> } <ide> previous = GLHelper.drawVertex(q, vp, pc, previous, buf, color); <del> if (i == SUBDIVISIONS) { <add> if (i == subdivs) { <ide> GLHelper.drawVertex(q, vp, pc, previous, buf, Colors.Null); <ide> } <ide> }
Java
apache-2.0
708f180f42f8195acbf69c9461fdcd6ca6ab7058
0
jasonwee/libgdx,bladecoder/libgdx,ricardorigodon/libgdx,yangweigbh/libgdx,josephknight/libgdx,ztv/libgdx,Deftwun/libgdx,collinsmith/libgdx,bladecoder/libgdx,MikkelTAndersen/libgdx,czyzby/libgdx,1yvT0s/libgdx,MetSystem/libgdx,zommuter/libgdx,saqsun/libgdx,FyiurAmron/libgdx,billgame/libgdx,sarkanyi/libgdx,azakhary/libgdx,zommuter/libgdx,haedri/libgdx-1,Gliby/libgdx,designcrumble/libgdx,FredGithub/libgdx,jberberick/libgdx,ya7lelkom/libgdx,noelsison2/libgdx,josephknight/libgdx,yangweigbh/libgdx,ThiagoGarciaAlves/libgdx,anserran/libgdx,GreenLightning/libgdx,gdos/libgdx,andyvand/libgdx,kagehak/libgdx,noelsison2/libgdx,andyvand/libgdx,MikkelTAndersen/libgdx,srwonka/libGdx,Deftwun/libgdx,nave966/libgdx,FyiurAmron/libgdx,ninoalma/libgdx,Zonglin-Li6565/libgdx,KrisLee/libgdx,KrisLee/libgdx,djom20/libgdx,jberberick/libgdx,josephknight/libgdx,toa5/libgdx,luischavez/libgdx,js78/libgdx,SidneyXu/libgdx,youprofit/libgdx,BlueRiverInteractive/libgdx,bsmr-java/libgdx,cypherdare/libgdx,djom20/libgdx,shiweihappy/libgdx,Zonglin-Li6565/libgdx,thepullman/libgdx,JFixby/libgdx,Badazdz/libgdx,fwolff/libgdx,libgdx/libgdx,tommycli/libgdx,EsikAntony/libgdx,del-sol/libgdx,ThiagoGarciaAlves/libgdx,xoppa/libgdx,JDReutt/libgdx,1yvT0s/libgdx,designcrumble/libgdx,jberberick/libgdx,MadcowD/libgdx,1yvT0s/libgdx,samskivert/libgdx,toloudis/libgdx,xranby/libgdx,BlueRiverInteractive/libgdx,FredGithub/libgdx,BlueRiverInteractive/libgdx,MadcowD/libgdx,noelsison2/libgdx,zommuter/libgdx,titovmaxim/libgdx,nooone/libgdx,gdos/libgdx,MikkelTAndersen/libgdx,saltares/libgdx,stinsonga/libgdx,TheAks999/libgdx,kagehak/libgdx,kotcrab/libgdx,davebaol/libgdx,gouessej/libgdx,BlueRiverInteractive/libgdx,tommycli/libgdx,realitix/libgdx,jsjolund/libgdx,nooone/libgdx,Wisienkas/libgdx,czyzby/libgdx,JFixby/libgdx,fiesensee/libgdx,MadcowD/libgdx,tell10glu/libgdx,Zonglin-Li6565/libgdx,sarkanyi/libgdx,luischavez/libgdx,czyzby/libgdx,ztv/libgdx,yangweigbh/libgdx,xpenatan/libgdx-LWJGL3,Wisienkas/libgdx,FyiurAmron/libgdx,GreenLightning/libgdx,titovmaxim/libgdx,djom20/libgdx,tell10glu/libgdx,Gliby/libgdx,designcrumble/libgdx,curtiszimmerman/libgdx,antag99/libgdx,xranby/libgdx,Senth/libgdx,bgroenks96/libgdx,flaiker/libgdx,ThiagoGarciaAlves/libgdx,cypherdare/libgdx,Thotep/libgdx,toa5/libgdx,fiesensee/libgdx,zhimaijoy/libgdx,hyvas/libgdx,SidneyXu/libgdx,junkdog/libgdx,Badazdz/libgdx,FredGithub/libgdx,tommycli/libgdx,EsikAntony/libgdx,MikkelTAndersen/libgdx,Badazdz/libgdx,ztv/libgdx,designcrumble/libgdx,titovmaxim/libgdx,alex-dorokhov/libgdx,ricardorigodon/libgdx,kotcrab/libgdx,saltares/libgdx,309746069/libgdx,TheAks999/libgdx,js78/libgdx,KrisLee/libgdx,youprofit/libgdx,JDReutt/libgdx,libgdx/libgdx,josephknight/libgdx,NathanSweet/libgdx,MovingBlocks/libgdx,TheAks999/libgdx,antag99/libgdx,stickyd/libgdx,antag99/libgdx,srwonka/libGdx,sarkanyi/libgdx,andyvand/libgdx,collinsmith/libgdx,nudelchef/libgdx,stinsonga/libgdx,sjosegarcia/libgdx,snovak/libgdx,Gliby/libgdx,azakhary/libgdx,katiepino/libgdx,Dzamir/libgdx,309746069/libgdx,stinsonga/libgdx,yangweigbh/libgdx,copystudy/libgdx,cypherdare/libgdx,Wisienkas/libgdx,antag99/libgdx,xpenatan/libgdx-LWJGL3,katiepino/libgdx,antag99/libgdx,Xhanim/libgdx,alex-dorokhov/libgdx,FyiurAmron/libgdx,junkdog/libgdx,toa5/libgdx,SidneyXu/libgdx,titovmaxim/libgdx,shiweihappy/libgdx,ya7lelkom/libgdx,firefly2442/libgdx,jsjolund/libgdx,saltares/libgdx,kagehak/libgdx,alireza-hosseini/libgdx,zhimaijoy/libgdx,designcrumble/libgdx,hyvas/libgdx,309746069/libgdx,revo09/libgdx,Zonglin-Li6565/libgdx,del-sol/libgdx,zhimaijoy/libgdx,fwolff/libgdx,andyvand/libgdx,jberberick/libgdx,billgame/libgdx,andyvand/libgdx,MadcowD/libgdx,MikkelTAndersen/libgdx,Heart2009/libgdx,alex-dorokhov/libgdx,xranby/libgdx,fiesensee/libgdx,firefly2442/libgdx,revo09/libgdx,JDReutt/libgdx,haedri/libgdx-1,thepullman/libgdx,MikkelTAndersen/libgdx,firefly2442/libgdx,petugez/libgdx,tell10glu/libgdx,Gliby/libgdx,1yvT0s/libgdx,nelsonsilva/libgdx,samskivert/libgdx,copystudy/libgdx,gf11speed/libgdx,mumer92/libgdx,js78/libgdx,xranby/libgdx,josephknight/libgdx,Dzamir/libgdx,billgame/libgdx,Gliby/libgdx,MetSystem/libgdx,flaiker/libgdx,FyiurAmron/libgdx,realitix/libgdx,ricardorigodon/libgdx,Heart2009/libgdx,hyvas/libgdx,Heart2009/libgdx,bgroenks96/libgdx,ThiagoGarciaAlves/libgdx,thepullman/libgdx,gdos/libgdx,Senth/libgdx,fwolff/libgdx,tommyettinger/libgdx,sarkanyi/libgdx,srwonka/libGdx,djom20/libgdx,kotcrab/libgdx,snovak/libgdx,ztv/libgdx,petugez/libgdx,nooone/libgdx,snovak/libgdx,haedri/libgdx-1,copystudy/libgdx,KrisLee/libgdx,thepullman/libgdx,fwolff/libgdx,MovingBlocks/libgdx,Senth/libgdx,hyvas/libgdx,copystudy/libgdx,KrisLee/libgdx,hyvas/libgdx,petugez/libgdx,zhimaijoy/libgdx,firefly2442/libgdx,PedroRomanoBarbosa/libgdx,EsikAntony/libgdx,saqsun/libgdx,antag99/libgdx,MetSystem/libgdx,nrallakis/libgdx,youprofit/libgdx,hyvas/libgdx,BlueRiverInteractive/libgdx,junkdog/libgdx,kotcrab/libgdx,ztv/libgdx,libgdx/libgdx,Gliby/libgdx,Badazdz/libgdx,snovak/libgdx,kotcrab/libgdx,toloudis/libgdx,Wisienkas/libgdx,nudelchef/libgdx,sarkanyi/libgdx,ya7lelkom/libgdx,ricardorigodon/libgdx,BlueRiverInteractive/libgdx,bgroenks96/libgdx,bsmr-java/libgdx,libgdx/libgdx,shiweihappy/libgdx,Badazdz/libgdx,mumer92/libgdx,nelsonsilva/libgdx,FyiurAmron/libgdx,nudelchef/libgdx,davebaol/libgdx,billgame/libgdx,samskivert/libgdx,ninoalma/libgdx,js78/libgdx,tell10glu/libgdx,haedri/libgdx-1,bsmr-java/libgdx,sjosegarcia/libgdx,309746069/libgdx,Xhanim/libgdx,ttencate/libgdx,tell10glu/libgdx,junkdog/libgdx,kotcrab/libgdx,codepoke/libgdx,PedroRomanoBarbosa/libgdx,js78/libgdx,snovak/libgdx,Heart2009/libgdx,saqsun/libgdx,ztv/libgdx,czyzby/libgdx,saqsun/libgdx,nelsonsilva/libgdx,curtiszimmerman/libgdx,codepoke/libgdx,KrisLee/libgdx,gouessej/libgdx,sjosegarcia/libgdx,MetSystem/libgdx,revo09/libgdx,Senth/libgdx,SidneyXu/libgdx,toa5/libgdx,Senth/libgdx,GreenLightning/libgdx,cypherdare/libgdx,junkdog/libgdx,realitix/libgdx,Deftwun/libgdx,del-sol/libgdx,del-sol/libgdx,petugez/libgdx,gouessej/libgdx,mumer92/libgdx,gdos/libgdx,tommyettinger/libgdx,del-sol/libgdx,Wisienkas/libgdx,fwolff/libgdx,anserran/libgdx,noelsison2/libgdx,stinsonga/libgdx,TheAks999/libgdx,toa5/libgdx,petugez/libgdx,UnluckyNinja/libgdx,tommycli/libgdx,mumer92/libgdx,davebaol/libgdx,xoppa/libgdx,samskivert/libgdx,Badazdz/libgdx,stickyd/libgdx,collinsmith/libgdx,ya7lelkom/libgdx,bsmr-java/libgdx,haedri/libgdx-1,jberberick/libgdx,billgame/libgdx,kagehak/libgdx,xranby/libgdx,andyvand/libgdx,jasonwee/libgdx,saqsun/libgdx,FredGithub/libgdx,del-sol/libgdx,ThiagoGarciaAlves/libgdx,alireza-hosseini/libgdx,MetSystem/libgdx,EsikAntony/libgdx,ya7lelkom/libgdx,bsmr-java/libgdx,NathanSweet/libgdx,fwolff/libgdx,JDReutt/libgdx,Wisienkas/libgdx,yangweigbh/libgdx,Deftwun/libgdx,309746069/libgdx,gouessej/libgdx,xpenatan/libgdx-LWJGL3,collinsmith/libgdx,alex-dorokhov/libgdx,tommycli/libgdx,js78/libgdx,fiesensee/libgdx,xpenatan/libgdx-LWJGL3,gf11speed/libgdx,Heart2009/libgdx,xoppa/libgdx,toloudis/libgdx,del-sol/libgdx,djom20/libgdx,PedroRomanoBarbosa/libgdx,kagehak/libgdx,codepoke/libgdx,bgroenks96/libgdx,nelsonsilva/libgdx,ninoalma/libgdx,firefly2442/libgdx,NathanSweet/libgdx,saqsun/libgdx,czyzby/libgdx,andyvand/libgdx,jsjolund/libgdx,Badazdz/libgdx,Thotep/libgdx,gdos/libgdx,thepullman/libgdx,basherone/libgdxcn,alireza-hosseini/libgdx,Zonglin-Li6565/libgdx,gf11speed/libgdx,nooone/libgdx,andyvand/libgdx,katiepino/libgdx,TheAks999/libgdx,mumer92/libgdx,jasonwee/libgdx,billgame/libgdx,basherone/libgdxcn,FredGithub/libgdx,libgdx/libgdx,srwonka/libGdx,fiesensee/libgdx,JFixby/libgdx,flaiker/libgdx,JDReutt/libgdx,thepullman/libgdx,yangweigbh/libgdx,gdos/libgdx,Deftwun/libgdx,nooone/libgdx,gouessej/libgdx,luischavez/libgdx,bsmr-java/libgdx,collinsmith/libgdx,Xhanim/libgdx,nave966/libgdx,shiweihappy/libgdx,Xhanim/libgdx,EsikAntony/libgdx,basherone/libgdxcn,flaiker/libgdx,Xhanim/libgdx,MetSystem/libgdx,thepullman/libgdx,junkdog/libgdx,MovingBlocks/libgdx,jberberick/libgdx,jsjolund/libgdx,nudelchef/libgdx,Thotep/libgdx,toloudis/libgdx,copystudy/libgdx,thepullman/libgdx,FredGithub/libgdx,czyzby/libgdx,yangweigbh/libgdx,gouessej/libgdx,MadcowD/libgdx,saltares/libgdx,nrallakis/libgdx,curtiszimmerman/libgdx,Badazdz/libgdx,xpenatan/libgdx-LWJGL3,GreenLightning/libgdx,ztv/libgdx,tell10glu/libgdx,sjosegarcia/libgdx,kotcrab/libgdx,SidneyXu/libgdx,PedroRomanoBarbosa/libgdx,Zonglin-Li6565/libgdx,toa5/libgdx,PedroRomanoBarbosa/libgdx,samskivert/libgdx,1yvT0s/libgdx,luischavez/libgdx,Zomby2D/libgdx,BlueRiverInteractive/libgdx,titovmaxim/libgdx,davebaol/libgdx,ThiagoGarciaAlves/libgdx,Thotep/libgdx,JFixby/libgdx,UnluckyNinja/libgdx,Senth/libgdx,snovak/libgdx,sarkanyi/libgdx,toloudis/libgdx,djom20/libgdx,jsjolund/libgdx,nudelchef/libgdx,noelsison2/libgdx,bsmr-java/libgdx,xranby/libgdx,Heart2009/libgdx,srwonka/libGdx,nave966/libgdx,Zomby2D/libgdx,firefly2442/libgdx,anserran/libgdx,mumer92/libgdx,ninoalma/libgdx,MikkelTAndersen/libgdx,PedroRomanoBarbosa/libgdx,Zomby2D/libgdx,bladecoder/libgdx,firefly2442/libgdx,kagehak/libgdx,revo09/libgdx,revo09/libgdx,davebaol/libgdx,sjosegarcia/libgdx,GreenLightning/libgdx,toloudis/libgdx,fiesensee/libgdx,stickyd/libgdx,JDReutt/libgdx,309746069/libgdx,realitix/libgdx,czyzby/libgdx,codepoke/libgdx,bgroenks96/libgdx,youprofit/libgdx,309746069/libgdx,samskivert/libgdx,js78/libgdx,nelsonsilva/libgdx,luischavez/libgdx,sjosegarcia/libgdx,mumer92/libgdx,ttencate/libgdx,GreenLightning/libgdx,EsikAntony/libgdx,zhimaijoy/libgdx,alex-dorokhov/libgdx,realitix/libgdx,stickyd/libgdx,haedri/libgdx-1,Zonglin-Li6565/libgdx,1yvT0s/libgdx,curtiszimmerman/libgdx,titovmaxim/libgdx,petugez/libgdx,jasonwee/libgdx,azakhary/libgdx,Wisienkas/libgdx,MovingBlocks/libgdx,alex-dorokhov/libgdx,Deftwun/libgdx,Dzamir/libgdx,UnluckyNinja/libgdx,nrallakis/libgdx,zhimaijoy/libgdx,youprofit/libgdx,shiweihappy/libgdx,fwolff/libgdx,tommyettinger/libgdx,EsikAntony/libgdx,ThiagoGarciaAlves/libgdx,1yvT0s/libgdx,zommuter/libgdx,gf11speed/libgdx,noelsison2/libgdx,copystudy/libgdx,Deftwun/libgdx,flaiker/libgdx,revo09/libgdx,1yvT0s/libgdx,MovingBlocks/libgdx,katiepino/libgdx,basherone/libgdxcn,ttencate/libgdx,xoppa/libgdx,zommuter/libgdx,collinsmith/libgdx,ya7lelkom/libgdx,jasonwee/libgdx,alireza-hosseini/libgdx,FyiurAmron/libgdx,anserran/libgdx,Dzamir/libgdx,JFixby/libgdx,luischavez/libgdx,kagehak/libgdx,copystudy/libgdx,shiweihappy/libgdx,alex-dorokhov/libgdx,stinsonga/libgdx,jsjolund/libgdx,kagehak/libgdx,nave966/libgdx,codepoke/libgdx,basherone/libgdxcn,designcrumble/libgdx,saqsun/libgdx,nrallakis/libgdx,flaiker/libgdx,Xhanim/libgdx,stickyd/libgdx,ninoalma/libgdx,JFixby/libgdx,Gliby/libgdx,xpenatan/libgdx-LWJGL3,gdos/libgdx,noelsison2/libgdx,MovingBlocks/libgdx,KrisLee/libgdx,Wisienkas/libgdx,Thotep/libgdx,josephknight/libgdx,MetSystem/libgdx,jasonwee/libgdx,MadcowD/libgdx,ttencate/libgdx,snovak/libgdx,zhimaijoy/libgdx,nave966/libgdx,BlueRiverInteractive/libgdx,curtiszimmerman/libgdx,fiesensee/libgdx,nooone/libgdx,bladecoder/libgdx,Dzamir/libgdx,codepoke/libgdx,SidneyXu/libgdx,haedri/libgdx-1,Heart2009/libgdx,xranby/libgdx,codepoke/libgdx,sarkanyi/libgdx,junkdog/libgdx,JFixby/libgdx,stickyd/libgdx,djom20/libgdx,flaiker/libgdx,katiepino/libgdx,jasonwee/libgdx,Heart2009/libgdx,nave966/libgdx,azakhary/libgdx,jberberick/libgdx,nudelchef/libgdx,Thotep/libgdx,FredGithub/libgdx,haedri/libgdx-1,luischavez/libgdx,ninoalma/libgdx,ttencate/libgdx,xpenatan/libgdx-LWJGL3,katiepino/libgdx,JDReutt/libgdx,NathanSweet/libgdx,PedroRomanoBarbosa/libgdx,youprofit/libgdx,anserran/libgdx,revo09/libgdx,junkdog/libgdx,firefly2442/libgdx,czyzby/libgdx,samskivert/libgdx,kotcrab/libgdx,SidneyXu/libgdx,nave966/libgdx,fiesensee/libgdx,alireza-hosseini/libgdx,jberberick/libgdx,ya7lelkom/libgdx,titovmaxim/libgdx,jsjolund/libgdx,Gliby/libgdx,sjosegarcia/libgdx,xoppa/libgdx,ricardorigodon/libgdx,bgroenks96/libgdx,toloudis/libgdx,hyvas/libgdx,UnluckyNinja/libgdx,bgroenks96/libgdx,ninoalma/libgdx,tell10glu/libgdx,NathanSweet/libgdx,PedroRomanoBarbosa/libgdx,FyiurAmron/libgdx,GreenLightning/libgdx,tommycli/libgdx,nudelchef/libgdx,MovingBlocks/libgdx,saltares/libgdx,GreenLightning/libgdx,srwonka/libGdx,Senth/libgdx,bsmr-java/libgdx,Dzamir/libgdx,nrallakis/libgdx,realitix/libgdx,gf11speed/libgdx,snovak/libgdx,katiepino/libgdx,xoppa/libgdx,flaiker/libgdx,gf11speed/libgdx,zommuter/libgdx,stickyd/libgdx,Xhanim/libgdx,JFixby/libgdx,toloudis/libgdx,Thotep/libgdx,Dzamir/libgdx,djom20/libgdx,Senth/libgdx,TheAks999/libgdx,zommuter/libgdx,srwonka/libGdx,realitix/libgdx,SidneyXu/libgdx,MadcowD/libgdx,davebaol/libgdx,nelsonsilva/libgdx,ninoalma/libgdx,alireza-hosseini/libgdx,codepoke/libgdx,saqsun/libgdx,gf11speed/libgdx,petugez/libgdx,antag99/libgdx,curtiszimmerman/libgdx,yangweigbh/libgdx,del-sol/libgdx,gouessej/libgdx,UnluckyNinja/libgdx,curtiszimmerman/libgdx,FredGithub/libgdx,Thotep/libgdx,petugez/libgdx,billgame/libgdx,xranby/libgdx,collinsmith/libgdx,josephknight/libgdx,gouessej/libgdx,UnluckyNinja/libgdx,TheAks999/libgdx,nrallakis/libgdx,anserran/libgdx,jsjolund/libgdx,KrisLee/libgdx,ttencate/libgdx,zhimaijoy/libgdx,Xhanim/libgdx,ztv/libgdx,UnluckyNinja/libgdx,copystudy/libgdx,ttencate/libgdx,katiepino/libgdx,ricardorigodon/libgdx,ricardorigodon/libgdx,nave966/libgdx,billgame/libgdx,ricardorigodon/libgdx,anserran/libgdx,Deftwun/libgdx,jasonwee/libgdx,toa5/libgdx,TheAks999/libgdx,samskivert/libgdx,nrallakis/libgdx,tell10glu/libgdx,srwonka/libGdx,js78/libgdx,shiweihappy/libgdx,toa5/libgdx,shiweihappy/libgdx,UnluckyNinja/libgdx,saltares/libgdx,Zonglin-Li6565/libgdx,gdos/libgdx,309746069/libgdx,fwolff/libgdx,realitix/libgdx,xpenatan/libgdx-LWJGL3,ttencate/libgdx,Dzamir/libgdx,tommycli/libgdx,zommuter/libgdx,revo09/libgdx,antag99/libgdx,azakhary/libgdx,Zomby2D/libgdx,noelsison2/libgdx,cypherdare/libgdx,saltares/libgdx,Zomby2D/libgdx,alex-dorokhov/libgdx,MovingBlocks/libgdx,sarkanyi/libgdx,tommyettinger/libgdx,youprofit/libgdx,alireza-hosseini/libgdx,MadcowD/libgdx,MikkelTAndersen/libgdx,gf11speed/libgdx,saltares/libgdx,nudelchef/libgdx,ya7lelkom/libgdx,anserran/libgdx,sjosegarcia/libgdx,stickyd/libgdx,mumer92/libgdx,EsikAntony/libgdx,titovmaxim/libgdx,xoppa/libgdx,bgroenks96/libgdx,azakhary/libgdx,tommyettinger/libgdx,josephknight/libgdx,collinsmith/libgdx,bladecoder/libgdx,nrallakis/libgdx,MetSystem/libgdx,alireza-hosseini/libgdx,ThiagoGarciaAlves/libgdx,hyvas/libgdx,designcrumble/libgdx,basherone/libgdxcn,JDReutt/libgdx,curtiszimmerman/libgdx,luischavez/libgdx,xoppa/libgdx,tommycli/libgdx,youprofit/libgdx,designcrumble/libgdx
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx; /** <p> * An <code>ApplicationListener</code> is called when the {@link Application} is created, resumed, rendering, paused or destroyed. * All methods are called in a thread that has the OpenGL context current. You can thus safely create and manipulate graphics * resources. * </p> * * <p> * The <code>ApplicationListener</code> interface follows the standard Android activity life-cycle and is emulated on the desktop * accordingly. * </p> * * @author mzechner */ public interface ApplicationListener { /** Called when the {@link Application} is first created. */ public void create (); /** Called when the {@link Application} is resized. This can happen at any point during a non-paused state but will never happen * before a call to {@link #create()}. * * @param width the new width in pixels * @param height the new height in pixels */ public void resize (int width, int height); /** Called when the {@link Application} should render itself. */ public void render (); /** Called when the {@link Application} is paused, usually when it's not active or visible on screen. An Application is also * paused before it is destroyed. */ public void pause (); /** Called when the {@link Application} is resumed from a paused state, usually when it regains focus. */ public void resume (); /** Called when the {@link Application} is destroyed. Preceded by a call to {@link #pause()}. */ public void dispose (); }
gdx/src/com/badlogic/gdx/ApplicationListener.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx; /** <p> * An <code>ApplicationListener</code> is called when the {@link Application} is created, resumed, rendering, paused or destroyed. * All methods are called in a thread that has the OpenGL context current. You can thus safely create and manipulate graphics * resources. * </p> * * <p> * The <code>ApplicationListener</code> interface follows the standard Android activity life-cycle and is emulated on the desktop * accordingly. * </p> * * @author mzechner */ public interface ApplicationListener { /** Called when the {@link Application} is first created. */ public void create (); /** Called when the {@link Application} is resized. This can happen at any point during a non-paused state but will never happen * before a call to {@link #create()}. * * @param width the new width in pixels * @param height the new height in pixels */ public void resize (int width, int height); /** Called when the {@link Application} should render itself. */ public void render (); /** Called when the {@link Application} is paused. An Application is paused before it is destroyed, when a user pressed the Home * button on Android or an incoming call happened. On the desktop this will only be called immediately before {@link #dispose()} * is called. */ public void pause (); /** Called when the {@link Application} is resumed from a paused state. On Android this happens when the activity gets focus * again. On the desktop this method will never be called. */ public void resume (); /** Called when the {@link Application} is destroyed. Preceded by a call to {@link #pause()}. */ public void dispose (); }
Update Javadoc for pause/resume
gdx/src/com/badlogic/gdx/ApplicationListener.java
Update Javadoc for pause/resume
<ide><path>dx/src/com/badlogic/gdx/ApplicationListener.java <ide> /** Called when the {@link Application} should render itself. */ <ide> public void render (); <ide> <del> /** Called when the {@link Application} is paused. An Application is paused before it is destroyed, when a user pressed the Home <del> * button on Android or an incoming call happened. On the desktop this will only be called immediately before {@link #dispose()} <del> * is called. */ <add> /** Called when the {@link Application} is paused, usually when it's not active or visible on screen. An Application is also <add> * paused before it is destroyed. */ <ide> public void pause (); <ide> <del> /** Called when the {@link Application} is resumed from a paused state. On Android this happens when the activity gets focus <del> * again. On the desktop this method will never be called. */ <add> /** Called when the {@link Application} is resumed from a paused state, usually when it regains focus. */ <ide> public void resume (); <ide> <ide> /** Called when the {@link Application} is destroyed. Preceded by a call to {@link #pause()}. */
JavaScript
agpl-3.0
2e62836b4d37d8af1cb7ee53d4f59f261900a029
0
ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs
"use strict"; function FileHandler() { this.get = function ( file ) { if ( AscBrowser.isAppleDevices ) { var downloadWindow = window.open( file, "_parent", "", false ); downloadWindow.document.title = "Downloading..."; window.focus(); } else { var frmWindow = getIFrameWindow( file ); var frm = frmWindow.document.getElementById( "frmFile" ); frm.submit(); // frmWindow.focus(); } } var getIFrameWindow = function ( file ) { var ifr = document.getElementById( "fileFrame" ); if ( null != ifr ) document.body.removeChild( ifr ); createFrame( file ); var wnd = window.frames["fileFrame"]; return wnd; } var createFrame = function ( file ) { var frame = document.createElement( "iframe" ); frame.name = "fileFrame"; frame.id = "fileFrame"; document.body.appendChild( frame ); generateIFrameContent( file ); frame.style.width = "0px"; frame.style.height = "0px"; frame.style.border = "0px"; frame.style.display = "none"; } var generateIFrameContent = function ( file ) { var frameWindow = window.frames["fileFrame"]; var content = "<form id='frmFile' method='post' enctype='application/data' action='" + file + "'></form>"; frameWindow.document.open(); frameWindow.document.write( content ); frameWindow.document.close(); } } function getFile( filePath ) { var fh = new FileHandler(); fh.get( filePath ); }
Common/downloaderfiles.js
"use strict"; function FileHandler() { this.get = function ( file ) { if ( AscBrowser.isAppleDevices ) { var downloadWindow = window.open( file, "_parent", "", false ); downloadWindow.document.title = "Downloading..."; window.focus(); } else { var frmWindow = getIFrameWindow( file ); var frm = frmWindow.document.getElementById( "frmFile" ); frm.submit(); frmWindow.focus(); } } var getIFrameWindow = function ( file ) { var ifr = document.getElementById( "fileFrame" ); if ( null != ifr ) document.body.removeChild( ifr ); createFrame( file ); var wnd = window.frames["fileFrame"]; return wnd; } var createFrame = function ( file ) { var frame = document.createElement( "iframe" ); frame.name = "fileFrame"; frame.id = "fileFrame"; document.body.appendChild( frame ); generateIFrameContent( file ); frame.style.width = "0px"; frame.style.height = "0px"; frame.style.border = "0px"; frame.style.display = "none"; } var generateIFrameContent = function ( file ) { var frameWindow = window.frames["fileFrame"]; var content = "<form id='frmFile' method='post' enctype='application/data' action='" + file + "'></form>"; frameWindow.document.open(); frameWindow.document.write( content ); frameWindow.document.close(); } } function getFile( filePath ) { var fh = new FileHandler(); fh.get( filePath ); }
fixed: Bug 25958 - Фокус не возвращается в рабочую область после нажатия кнопки печати документа (Print) Bug 24479 - После печати документа не работает ввод данных в canvas git-svn-id: 9db5f3bf534fda1ae49cdb5ebc7e13fb9e7e48c1@57816 954022d7-b5bf-4e40-9824-e11837661b57
Common/downloaderfiles.js
fixed: Bug 25958 - Фокус не возвращается в рабочую область после нажатия кнопки печати документа (Print) Bug 24479 - После печати документа не работает ввод данных в canvas
<ide><path>ommon/downloaderfiles.js <ide> var frmWindow = getIFrameWindow( file ); <ide> var frm = frmWindow.document.getElementById( "frmFile" ); <ide> frm.submit(); <del> frmWindow.focus(); <add>// frmWindow.focus(); <ide> } <ide> } <ide> var getIFrameWindow = function ( file ) {
JavaScript
mit
857afb3e750b9ea6f28ee9b26899a82e8b3ec93c
0
jbaicoianu/elation-engine
elation.require([ // "engine.external.three.ColladaLoader", //"engine.external.three.JSONLoader" //"engine.external.three.glTFLoader-combined" //"engine.things.trigger" "utils.proxy" ], function() { elation.component.add("engine.things.generic", function() { this.init = function() { this._proxies = {}; this._thingdef = { properties: {}, events: {}, actions: {} }; this.parentname = this.args.parentname || ''; this.name = this.args.name || ''; this.type = this.args.type || 'generic'; this.engine = this.args.engine; this.client = this.args.client; this.properties = {}; this.objects = {}; this.parts = {}; this.triggers = {}; this.parttypes = {}; this.children = {}; this.tags = []; this.sounds = {}; this.animations = false; this.skeleton = false; this.tmpvec = new THREE.Vector3(); this.interp = { rate: 20, lastTime: 0, time: 0, endpoint: new THREE.Vector3(), spline: [], active: false, fn: this.applyInterp }; //elation.events.add(this, 'thing_create', this); elation.events.add(this, 'thing_use_activate', this); this.defineActions({ 'spawn': this.spawn, 'move': this.move }); this.defineProperties({ 'position': { type: 'vector3', default: [0, 0, 0], comment: 'Object position, relative to parent' }, 'orientation': { type: 'quaternion', default: [0, 0, 0, 1], comment: 'Object orientation, relative to parent' }, 'scale': { type: 'vector3', default: [1, 1, 1], comment: 'Object scale, relative to parent' }, 'velocity': { type: 'vector3', default: [0, 0, 0], comment: 'Object velocity (m/s)' }, 'acceleration': { type: 'vector3', default: [0, 0, 0], comment: 'Object acceleration (m/s^2)' }, 'angular': { type: 'vector3', default: [0, 0, 0], comment: 'Object angular velocity (radians/sec)' }, 'angularacceleration': { type: 'vector3', default: [0, 0, 0], comment: 'Object angular acceleration (radians/sec^2)' }, 'mass': { type: 'float', default: 0.0, comment: 'Object mass (kg)' }, 'exists': { type: 'bool', default: true, comment: 'Exists' }, 'visible': { type: 'bool', default: true, comment: 'Is visible' }, 'physical': { type: 'bool', default: true, comment: 'Simulate physically' }, 'collidable': { type: 'bool', default: true, comment: 'Can crash into other things' }, //'fog': { type: 'bool', default: true, comment: 'Affected by fog' }, 'shadow': { type: 'bool', default: true, refreshMaterial: true, comment: 'Casts and receives shadows' }, 'wireframe': { type: 'bool', default: false, refreshMaterial: true, comment: 'Render this object as a wireframe' }, 'forcereload': { type: 'bool', default: false, refreshGeometry: true, refreshMaterial: true, comment: 'Force a full reload of all files' }, 'mouseevents': { type: 'bool', default: true, comment: 'Respond to mouse/touch events' }, 'persist': { type: 'bool', default: false, comment: 'Continues existing across world saves' }, 'pickable': { type: 'bool', default: true, comment: 'Selectable via mouse/touch events' }, 'render.mesh': { type: 'string', refreshGeometry: true, comment: 'URL for JSON model file' }, 'render.meshname':{ type: 'string', refreshGeometry: true }, 'render.scene': { type: 'string', refreshGeometry: true, comment: 'URL for JSON scene file' }, 'render.collada': { type: 'string', refreshGeometry: true, comment: 'URL for Collada scene file' }, 'render.model': { type: 'string', refreshGeometry: true, comment: 'Name of model asset' }, 'render.gltf': { type: 'string', refreshGeometry: true, comment: 'URL for glTF file' }, 'render.materialname': { type: 'string', refreshMaterial: true, comment: 'Material library name' }, 'render.texturepath': { type: 'string', refreshMaterial: true, comment: 'Texture location' }, 'player_id': { type: 'float', default: null, comment: 'Network id of the creator' }, 'tags': { type: 'string', comment: 'Default tags to add to this object' } }); this.defineEvents({ 'thing_create': [], 'thing_add': ['child'], 'thing_load': ['mesh'], 'thing_remove': [], 'thing_destroy': [], 'thing_tick': ['delta'], 'thing_think': ['delta'], 'thing_move': [], 'mouseover': ['clientX', 'clientY', 'position'], 'mouseout': [], 'mousedown': [], 'mouseup': [], 'click': [] }); if (typeof this.preinit == 'function') { this.preinit(); } if (typeof this.postinit == 'function') { this.postinit(); } this.init3D(); this.initDOM(); this.initPhysics(); setTimeout(elation.bind(this, function() { // Fire create event next frame this.createChildren(); this.refresh(); elation.events.fire({type: 'thing_create', element: this}); }), 0); } this.preinit = function() { } this.postinit = function() { } this.initProperties = function() { if (!this.properties) { this.properties = {}; } for (var propname in this._thingdef.properties) { var prop = this._thingdef.properties[propname]; if (!this.hasOwnProperty(propname)) { this.defineProperty(propname, prop); } } } this.getPropertyValue = function(type, value) { if (value === null) { return; } switch (type) { case 'vector2': if (elation.utils.isArray(value)) { value = new THREE.Vector2(+value[0], +value[1]); } else if (elation.utils.isString(value)) { var split = value.split((value.indexOf(' ') != -1 ? ' ' : ',')); value = new THREE.Vector2(+split[0], +split[1]); } break; case 'vector3': if (elation.utils.isArray(value)) { value = new THREE.Vector3(+value[0], +value[1], +value[2]); } else if (elation.utils.isString(value)) { var split = value.split((value.indexOf(' ') != -1 ? ' ' : ',')); value = new THREE.Vector3(+split[0], +split[1], +split[2]); } break; case 'euler': if (elation.utils.isArray(value)) { value = new THREE.Euler(+value[0], +value[1], +value[2]); } else if (elation.utils.isString(value)) { var split = value.split((value.indexOf(' ') != -1 ? ' ' : ',')); value = new THREE.Euler(+split[0], +split[1], +split[2]); } break; case 'quaternion': if (elation.utils.isArray(value)) { value = new THREE.Quaternion(+value[0], +value[1], +value[2], +value[3]); } else if (elation.utils.isString(value)) { var split = value.split((value.indexOf(' ') != -1 ? ' ' : ',')); value = new THREE.Quaternion(+split[0], +split[1], +split[2], +split[3]); } break; case 'color': var clamp = elation.utils.math.clamp; if (value instanceof THREE.Vector3) { value = new THREE.Color(clamp(value.x, 0, 1), clamp(value.y, 0, 1), clamp(value.z, 0, 1)); } else if (value instanceof THREE.Vector4) { this.opacity = clamp(value.w, 0, 1); value = new THREE.Color(clamp(value.x, 0, 1), clamp(value.y, 0, 1), clamp(value.z, 0, 1)); } else if (elation.utils.isString(value)) { var splitpos = value.indexOf(' '); if (splitpos == -1) splitpos = value.indexOf(','); if (splitpos == -1) { value = new THREE.Color(value); } else { var split = value.split((value.indexOf(' ') != -1 ? ' ' : ',')); value = new THREE.Color(clamp(split[0], 0, 1), clamp(split[1], 0, 1), clamp(split[2], 0, 1)); if (split.length > 3) { this.opacity = clamp(split[3], 0, 1); } } } else if (elation.utils.isArray(value)) { value = new THREE.Color(+value[0], +value[1], +value[2]); } else if (!(value instanceof THREE.Color)) { value = new THREE.Color(value); } break; case 'bool': case 'boolean': value = !(value === false || (elation.utils.isString(value) && value.toLowerCase() === 'false') || value === 0 || value === '0' || value === '' || value === null || typeof value == 'undefined'); break; case 'float': value = +value; break; case 'int': value = value | 0; break; case 'texture': if (value !== false) { value = (value instanceof THREE.Texture ? value : elation.engine.materials.getTexture(value)); } break; case 'json': if (value !== false) { value = (elation.utils.isString(value) ? JSON.parse(value) : value); } break; case 'component': if (value) { var component = elation.component.fetch(value[0], value[1]); if (component) { value = component; } } break; } return value; } this.defineProperties = function(properties) { elation.utils.merge(properties, this._thingdef.properties); this.initProperties(); } this.defineProperty = function(propname, prop) { var propval = elation.utils.arrayget(this.properties, propname, null); Object.defineProperty(this, propname, { configurable: true, enumerable: true, get: function() { var proxy = this._proxies[propname]; if (proxy) { return proxy; } return elation.utils.arrayget(this.properties, propname); }, set: function(v) { this.set(propname, v, prop.refreshGeometry); //this.refresh(); //console.log('set ' + propname + ' to ', v); } }); if (propval === null) { if (!elation.utils.isNull(this.args.properties[propname])) { propval = this.args.properties[propname] } else if (!elation.utils.isNull(prop.default)) { propval = prop.default; } this.set(propname, propval); } if (prop.type == 'vector2' || prop.type == 'vector3' || prop.type == 'quaternion' || prop.type == 'color') { if (propval && !this._proxies[propname]) { // Create proxy objects for these special types var proxydef = { x: ['property', 'x'], y: ['property', 'y'], z: ['property', 'z'], }; if (prop.type == 'quaternion') { proxydef.w = ['property', 'w']; } else if (prop.type == 'color') { // We want to support color.xyz as well as color.rgb proxydef.r = ['property', 'r']; proxydef.g = ['property', 'g']; proxydef.b = ['property', 'b']; proxydef.x = ['property', 'r']; proxydef.y = ['property', 'g']; proxydef.z = ['property', 'b']; } var propval = elation.utils.arrayget(this.properties, propname, null); if (propval) { this._proxies[propname] = new elation.proxy( propval, proxydef, true ); /* // FIXME - listening for proxy_change events would let us respond to changes for individual vector elements, but it gets expensive elation.events.add(propval, 'proxy_change', elation.bind(this, function(ev) { //this.refresh(); //this.set('exists', this.properties.exists, prop.refreshGeometry); //this[propname] = this[propname]; })); */ } } } } this.defineActions = function(actions) { elation.utils.merge(actions, this._thingdef.actions); } this.defineEvents = function(events) { elation.utils.merge(events, this._thingdef.events); } this.set = function(property, value, forcerefresh) { var propdef = this._thingdef.properties[property]; if (!propdef) { console.warn('Tried to set unknown property', property, value, this); return; } var changed = false var propval = this.getPropertyValue(propdef.type, value); var currval = this.get(property); //if (currval !== null) { switch (propdef.type) { case 'vector2': case 'vector3': case 'vector4': case 'quaternion': case 'color': if (currval === null) { elation.utils.arrayset(this.properties, property, propval); changed = true; } else { if (!currval.equals(propval)) { currval.copy(propval); changed = true } } break; case 'texture': //console.log('TRY TO SET NEW TEX', property, value, forcerefresh); default: if (currval !== propval) { elation.utils.arrayset(this.properties, property, propval); changed = true; } } //} else { // elation.utils.arrayset(this.properties, property, propval); //} if (changed) { if (propdef.set) { propdef.set.apply(this, [property, propval]); } if (forcerefresh && this.objects['3d']) { var oldobj = this.objects['3d'], parent = oldobj.parent, newobj = this.createObject3D(); this.objects['3d'] = newobj; this.objects['3d'].bindPosition(this.properties.position); this.objects['3d'].bindQuaternion(this.properties.orientation); this.objects['3d'].bindScale(this.properties.scale); this.objects['3d'].userData.thing = this; if (parent) { parent.remove(oldobj); parent.add(newobj); } } if (this.objects.dynamics) { if (false && forcerefresh) { this.removeDynamics(); this.initPhysics(); } else { this.objects.dynamics.mass = this.properties.mass; this.objects.dynamics.updateState(); if (this.objects.dynamics.collider) { this.objects.dynamics.collider.getInertialMoment(); } } } this.refresh(); } } this.setProperties = function(properties, interpolate) { for (var prop in properties) { if (prop == 'position' && interpolate == true ) { if ( this.tmpvec.fromArray(properties[prop]).distanceToSquared(this.get('position')) > 1 ) { // call interpolate function // TODO: fix magic number 0.001 this.interpolateTo(properties[prop]); } } else { this.set(prop, properties[prop], false); } } this.refresh(); } this.interpolateTo = function(newPos) { this.interp.time = 0; this.interp.endpoint.fromArray(newPos); this.interp.spline = new THREE.SplineCurve3([this.get('position'), this.interp.endpoint]).getPoints(10); // console.log(this.interp.spline); elation.events.add(this.engine, 'engine_frame', elation.bind(this, this.applyInterp)); } this.applyInterp = function(ev) { this.interp.time += ev.data.delta * this.engine.systems.physics.timescale; if (this.interp.time >= this.interp.rate) { elation.events.remove(this, 'engine_frame', elation.bind(this, this.applyInterp)); return; } console.log("DEBUG: interpolating, time:", this.interp.time); if (this.interp.time - this.interp.lastTime >= 2) { this.set('position', this.interp.spline[Math.floor((this.interp.time * 10) / this.interp.rate)], false); this.refresh(); } }; this.get = function(property, defval) { if (typeof defval == 'undefined') defval = null; return elation.utils.arrayget(this.properties, property, defval); } this.init3D = function() { if (this.objects['3d']) { if (this.objects['3d'].parent) { this.objects['3d'].parent.remove(this.objects['3d']); } } if (this.properties.tags) { var tags = this.properties.tags.split(','); for (var i = 0; i < tags.length; i++) { this.addTag(tags[i].trim()); } } this.objects['3d'] = this.createObject3D(); if (this.objects['3d']) { this.objects['3d'].bindPosition(this.properties.position); this.objects['3d'].bindQuaternion(this.properties.orientation); this.objects['3d'].bindScale(this.properties.scale); //this.objects['3d'].useQuaternion = true; this.objects['3d'].userData.thing = this; } if (!this.colliders) { this.colliders = new THREE.Object3D(); this.colliders.bindPosition(this.properties.position); this.colliders.bindQuaternion(this.properties.orientation); this.colliders.bindScale(this.properties.scale); //this.colliders.scale.set(1/this.properties.scale.x, 1/this.properties.scale.y, 1/this.properties.scale.z); this.colliders.userData.thing = this; } var childkeys = Object.keys(this.children); if (childkeys.length > 0) { // Things were added during initialization, so make sure they're added to the scene for (var i = 0; i < childkeys.length; i++) { var k = childkeys[i]; if (this.children[k].objects['3d']) { this.objects['3d'].add(this.children[k].objects['3d']); } } } if (!this.properties.visible) { this.hide(); } elation.events.fire({type: 'thing_init3d', element: this}); this.refresh(); } this.initDOM = function() { if (ENV_IS_BROWSER) { this.objects['dom'] = this.createObjectDOM(); elation.html.addclass(this.container, "space.thing"); elation.html.addclass(this.container, "space.things." + this.type); //this.updateDOM(); } } this.initPhysics = function() { if (this.properties.physical) { this.createDynamics(); this.createForces(); } } this.createObject3D = function() { // if (this.properties.exists === false || !ENV_IS_BROWSER) return; if (this.properties.exists === false) return; var object = null, geometry = null, material = null; var cachebust = ''; if (this.properties.forcereload) cachebust = '?n=' + (Math.floor(Math.random() * 10000)); if (this.properties.render) { if (this.properties.render.scene) { this.loadJSONScene(this.properties.render.scene, this.properties.render.texturepath + cachebust); } else if (this.properties.render.mesh) { this.loadJSON(this.properties.render.mesh, this.properties.render.texturepath + cachebust); } else if (this.properties.render.collada) { this.loadCollada(this.properties.render.collada + cachebust); } else if (this.properties.render.model) { object = elation.engine.assets.find('model', this.properties.render.model); } else if (this.properties.render.gltf) { this.loadglTF(this.properties.render.gltf + cachebust); } else if (this.properties.render.meshname) { object = new THREE.Object3D(); setTimeout(elation.bind(this, this.loadMeshName, this.properties.render.meshname), 0); } } var geomparams = elation.utils.arrayget(this.properties, "generic.geometry") || {}; switch (geomparams.type) { case 'sphere': geometry = new THREE.SphereGeometry(geomparams.radius || geomparams.size, geomparams.segmentsWidth, geomparams.segmentsHeight); break; case 'cube': geometry = new THREE.BoxGeometry( geomparams.width || geomparams.size, geomparams.height || geomparams.size, geomparams.depth || geomparams.size, geomparams.segmentsWidth || 1, geomparams.segmentsHeight || 1, geomparams.segmentsDepth || 1); break; case 'cylinder': geometry = new THREE.CylinderGeometry( geomparams.radiusTop || geomparams.radius, geomparams.radiusBottom || geomparams.radius, geomparams.height, geomparams.segmentsRadius, geomparams.segmentsHeight, geomparams.openEnded); break; case 'torus': geometry = new THREE.TorusGeometry(geomparams.radius, geomparams.tube, geomparams.segmentsR, geomparams.segmentsT, geomparams.arc); break; } if (geometry) { var materialparams = elation.utils.arrayget(this.properties, "generic.material") || {}; if (materialparams instanceof THREE.Material) { material = materialparams; } else { switch (materialparams.type) { case 'phong': material = new THREE.MeshPhongMaterial(materialparams); break; case 'lambert': material = new THREE.MeshLambertMaterial(materialparams); break; case 'depth': material = new THREE.MeshDepthMaterial(); break; case 'normal': material = new THREE.MeshNormalMaterial(); break; case 'basic': default: material = new THREE.MeshBasicMaterial(materialparams); } } } if (!geometry && !material) { //geometry = new THREE.BoxGeometry(1, 1, 1); //material = new THREE.MeshPhongMaterial({color: 0xcccccc, opacity: .2, emissive: 0x333333, transparent: true}); //console.log('made placeholder thing', geometry, material); } if (!object) { object = (geometry && material ? new THREE.Mesh(geometry, material) : new THREE.Object3D()); } if (geometry && material) { if (geomparams.flipSided) material.side = THREE.BackSide; if (geomparams.doubleSided) material.side = THREE.DoubleSide; } this.objects['3d'] = object; //this.spawn('gridhelper', {persist: false}); return object; } this.createObjectDOM = function() { return; } this.createChildren = function() { return; } this.add = function(thing) { if (!this.children[thing.id]) { this.children[thing.id] = thing; thing.parent = this; if (this.objects && thing.objects && this.objects['3d'] && thing.objects['3d']) { this.objects['3d'].add(thing.objects['3d']); } else if (thing instanceof THREE.Object3D) { this.objects['3d'].add(thing); } if (this.objects && thing.objects && this.objects['dynamics'] && thing.objects['dynamics']) { this.objects['dynamics'].add(thing.objects['dynamics']); } if (this.container && thing.container) { this.container.appendChild(thing.container); } if (this.colliders && thing.colliders) { this.colliders.add(thing.colliders); } elation.events.fire({type: 'thing_add', element: this, data: {thing: thing}}); return true; } else { console.log("Couldn't add ", thing.name, " already exists in ", this.name); } return false; } this.remove = function(thing) { if (thing && this.children[thing.id]) { if (this.objects['3d'] && thing.objects['3d']) { this.objects['3d'].remove(thing.objects['3d']); } if (thing.container && thing.container.parentNode) { thing.container.parentNode.removeChild(thing.container); } if (thing.objects['dynamics'] && thing.objects['dynamics'].parent) { thing.objects['dynamics'].parent.remove(thing.objects['dynamics']); } if (this.colliders && thing.colliders) { this.colliders.remove(thing.colliders); } if (thing.colliderhelper) { //this.engine.systems.world.scene['colliders'].remove(thing.colliderhelper); } elation.events.fire({type: 'thing_remove', element: this, data: {thing: thing}}); delete this.children[thing.id]; thing.parent = false; } else { console.log("Couldn't remove ", thing.name, " doesn't exist in ", this.name); } } this.reparent = function(newparent) { if (newparent) { if (this.parent) { newparent.worldToLocal(this.parent.localToWorld(this.properties.position)); this.properties.orientation.copy(newparent.worldToLocalOrientation(this.parent.localToWorldOrientation())); this.parent.remove(this); //newparent.worldToLocalDir(this.parent.localToWorldDir(this.properties.orientation)); } var success = newparent.add(this); this.refresh(); return success; } return false; } this.show = function() { this.objects['3d'].visible = true; if (this.colliderhelper) this.colliderhelper.visible = true; } this.hide = function() { this.objects['3d'].visible = false; if (this.colliderhelper) this.colliderhelper.visible = false; } this.createDynamics = function() { if (!this.objects['dynamics'] && this.engine.systems.physics) { this.objects['dynamics'] = new elation.physics.rigidbody({ position: this.properties.position, orientation: this.properties.orientation, mass: this.properties.mass, velocity: this.properties.velocity, acceleration: this.properties.acceleration, angular: this.properties.angular, angularacceleration: this.properties.angularacceleration, object: this }); //this.engine.systems.physics.add(this.objects['dynamics']); if ((this.properties.collidable || this.properties.pickable) && this.objects['3d'] && this.objects['3d'].geometry) { setTimeout(elation.bind(this, this.updateColliderFromGeometry), 0); } elation.events.add(this.objects['dynamics'], "physics_update,physics_collide", this); elation.events.add(this.objects['dynamics'], "physics_update", elation.bind(this, this.refresh)); } } this.removeDynamics = function() { if (this.objects.dynamics) { if (this.objects.dynamics.parent) { this.objects.dynamics.parent.remove(this.objects.dynamics); } else { this.engine.systems.physics.remove(this.objects.dynamics); } delete this.objects.dynamics; } } this.createForces = function() { } this.addForce = function(type, args) { return this.objects.dynamics.addForce(type, args); } this.removeForce = function(force) { return this.objects.dynamics.removeForce(force); } this.updateColliderFromGeometry = function(geom) { if (!geom) geom = this.objects['3d'].geometry; var collidergeom = false; // Determine appropriate collider for the geometry associated with this thing var dyn = this.objects['dynamics']; if (geom && dyn) { if (geom instanceof THREE.SphereGeometry || geom instanceof THREE.SphereBufferGeometry) { if (!geom.boundingSphere) geom.computeBoundingSphere(); this.setCollider('sphere', {radius: geom.boundingSphere.radius}); } else if (geom instanceof THREE.PlaneGeometry || geom instanceof THREE.PlaneBufferGeometry) { if (!geom.boundingBox) geom.computeBoundingBox(); var size = new THREE.Vector3().subVectors(geom.boundingBox.max, geom.boundingBox.min); // Ensure minimum size if (size.x < 1e-6) size.x = .25; if (size.y < 1e-6) size.y = .25; if (size.z < 1e-6) size.z = .25; this.setCollider('box', geom.boundingBox); } else if (geom instanceof THREE.CylinderGeometry) { if (geom.radiusTop == geom.radiusBottom) { this.setCollider('cylinder', {height: geom.height, radius: geom.radiusTop}); } else { console.log('FIXME - cylinder collider only supports uniform cylinders for now'); } } else if (!dyn.collider) { if (!geom.boundingBox) geom.computeBoundingBox(); this.setCollider('box', geom.boundingBox); } } } this.setCollider = function(type, args, rigidbody, reuseMesh) { //console.log('set collider', type, args, rigidbody, this.collidable); if (!rigidbody) rigidbody = this.objects['dynamics']; if (this.properties.collidable) { rigidbody.setCollider(type, args); } if (this.properties.collidable || this.properties.pickable) { var collidergeom = false; if (type == 'sphere') { collidergeom = elation.engine.geometries.generate('sphere', { radius: args.radius / this.properties.scale.x }); } else if (type == 'box') { var size = new THREE.Vector3().subVectors(args.max, args.min); size.x /= this.scale.x; size.y /= this.scale.y; size.z /= this.scale.z; var offset = new THREE.Vector3().addVectors(args.max, args.min).multiplyScalar(.5); collidergeom = elation.engine.geometries.generate('box', { size: size, offset: offset }); } else if (type == 'cylinder') { collidergeom = elation.engine.geometries.generate('cylinder', { radius: args.radius, height: args.height, radialSegments: 12 }); if (args.offset) { collidergeom.applyMatrix(new THREE.Matrix4().makeTranslation(args.offset.x, args.offset.y, args.offset.z)); } } else if (type == 'capsule') { collidergeom = elation.engine.geometries.generate('capsule', { radius: args.radius, length: args.length, radialSegments: 8, offset: args.offset, }); } else if (type == 'threejs') { // TODO - stub for compound mesh colliders } /* if (this.collidermesh) { this.colliders.remove(this.collidermesh); this.engine.systems.world.scene['colliders'].remove(this.colliderhelper); this.collidermesh = false; } */ if (collidergeom) { var collidermat = new THREE.MeshLambertMaterial({color: 0x999900, opacity: .2, transparent: true, emissive: 0x444400, alphaTest: .1, depthTest: false, depthWrite: false, side: THREE.DoubleSide}); if (reuseMesh && this.collidermesh) { var collidermesh = this.collidermesh; collidermesh.geometry = collidergeom; } else { var collidermesh = this.collidermesh = new THREE.Mesh(collidergeom, collidermat); if (rigidbody.position !== this.properties.position) { collidermesh.bindPosition(rigidbody.position); collidermesh.bindQuaternion(rigidbody.orientation); //collidermesh.bindScale(this.properties.scale); } collidermesh.userData.thing = this; this.colliders.add(collidermesh); } collidermesh.updateMatrixWorld(); var colliderhelper = this.colliderhelper; if (!colliderhelper) { //colliderhelper = this.colliderhelper = new THREE.EdgesHelper(collidermesh, 0x999900); //colliderhelper.matrix = collidermesh.matrix; //this.colliders.add(colliderhelper); } else { //THREE.EdgesHelper.call(colliderhelper, collidermesh, 0x990099); } //this.engine.systems.world.scene['colliders'].add(colliderhelper); // TODO - integrate this with the physics debug system /* elation.events.add(rigidbody, 'physics_collide', function() { collidermat.color.setHex(0x990000); colliderhelper.material.color.setHex(0x990000); setTimeout(function() { collidermat.color.setHex(0x999900); colliderhelper.material.color.setHex(0x999900); }, 100); }); elation.events.add(this, 'mouseover,mouseout', elation.bind(this, function(ev) { var color = 0xffff00; if (ev.type == 'mouseover' && ev.data.object === collidermesh) { color = 0x00ff00; } collidermat.color.setHex(0xffff00); colliderhelper.material.color.setHex(color); this.refresh(); })); */ } } } this.physics_collide = function(ev) { var obj1 = ev.data.bodies[0].object, obj2 = ev.data.bodies[1].object; elation.events.fire({type: 'collide', element: this, data: { other: (obj1 == this ? obj2 : obj1), collision: ev.data } }); } this.loadJSON = function(url, texturepath) { if (typeof texturepath == 'undefined') { texturepath = '/media/space/textures/'; } var loader = new THREE.JSONLoader(); loader.load(url, elation.bind(this, this.processJSON), texturepath); } this.processJSON = function(geometry, materials) { geometry.computeFaceNormals(); geometry.computeVertexNormals(); var mesh = new THREE.Mesh(geometry, materials); mesh.doubleSided = false; mesh.castShadow = false; mesh.receiveShadow = false; //this.objects['3d'].updateCollisionSize(); elation.events.fire({type: "thing_load", element: this, data: mesh}); this.objects['3d'].add(mesh); this.refresh(); } this.loadJSONScene = function(url, texturepath) { if (typeof texturepath == 'undefined') { texturepath = '/media/space/textures'; } var loader = new THREE.ObjectLoader(); loader.load(url, elation.bind(this, this.processJSONScene, url)); } this.processJSONScene = function(url, scene) { this.extractEntities(scene); this.objects['3d'].add(scene); this.extractColliders(scene); var textures = this.extractTextures(scene, true); this.loadTextures(textures); elation.events.fire({ type: 'resource_load_finish', element: this, data: { type: 'model', url: url } }); this.extractAnimations(scene); this.refresh(); } this.loadCollada = function(url) { if (!THREE.ColladaLoader) { // If the loader hasn't been initialized yet, fetch it! elation.require('engine.external.three.ColladaLoader', elation.bind(this, this.loadCollada, url)); } else { var loader = new THREE.ColladaLoader(); loader.options.convertUpAxis = true; var xhr = loader.load(url, elation.bind(this, this.processCollada, url)); elation.events.fire({ type: 'resource_load_start', element: this, data: { type: 'model', url: url } }); } } this.processCollada = function(url, collada) { //collada.scene.rotation.x = -Math.PI / 2; //collada.scene.rotation.z = Math.PI; this.extractEntities(collada.scene); /* collada.scene.computeBoundingSphere(); collada.scene.computeBoundingBox(); //this.updateCollisionSize(); */ this.objects['3d'].add(collada.scene); this.extractColliders(collada.scene, true); var textures = this.extractTextures(collada.scene, true); this.loadTextures(textures); elation.events.fire({ type: 'resource_load_finish', element: this, data: { type: 'model', url: url } }); this.refresh(); } this.loadglTF = function(url) { if (!THREE.glTFLoader) { // If the loader hasn't been initialized yet, fetch it! elation.require('engine.external.three.glTFLoader-combined', elation.bind(this, this.loadglTF, url)); } else { var loader = new THREE.glTFLoader(); loader.useBufferGeometry = true; loader.load(url, elation.bind(this, this.processglTF, url)); elation.events.fire({ type: 'resource_load_start', data: { type: 'model', url: url } }); } } this.processglTF = function(url, scenedata) { this.extractEntities(scenedata.scene); //this.updateCollisionSize(); //this.objects['3d'].add(scenedata.scene); var parent = this.objects['3d'].parent; parent.remove(this.objects['3d']); this.objects['3d'] = new THREE.Object3D(); this.objects['3d'].bindPosition(this.properties.position); this.objects['3d'].bindQuaternion(this.properties.orientation); this.objects['3d'].bindScale(this.properties.scale); this.objects['3d'].userData.thing = this; // Correct coordinate space from various modelling programs // FIXME - hardcoded for blender's settings for now, this should come from a property var scene = scenedata.scene; scene.rotation.x = -Math.PI/2; // FIXME - enable shadows for all non-transparent materials. This should be coming from the model file... scene.traverse(function(n) { if (n instanceof THREE.Mesh) { if (n.material && !(n.material.transparent || n.material.opacity < 1.0)) { n.castShadow = true; n.receiveShadow = true; } else { n.castShadow = false; n.receiveShadow = false; } } }); /* while (scenedata.scene.children.length > 0) { var obj = scenedata.scene.children[0]; scenedata.scene.remove(obj); coordspace.add(obj); } this.objects['3d'].add(coordspace); */ this.objects['3d'].add(scene); //this.objects['3d'].quaternion.setFromEuler(scenedata.scene.rotation); var textures = this.extractTextures(scene, true); this.loadTextures(textures); parent.add(this.objects['3d']); // If no pending textures, we're already loaded, so fire the event if (this.pendingtextures == 0) { elation.events.fire({type: "thing_load", element: this, data: scenedata.scene}); } elation.events.fire({ type: 'resource_load_finish', data: { type: 'model', url: url } }); this.refresh(); } this.loadMeshName = function(meshname) { var subobj = elation.engine.geometries.getMesh(meshname); subobj.rotation.x = -Math.PI/2; subobj.rotation.y = 0; subobj.rotation.z = Math.PI; this.extractEntities(subobj); this.objects['3d'].add(subobj); this.extractColliders(subobj); elation.events.add(null, 'resource_load_complete', elation.bind(this, this.extractColliders, subobj)); if (ENV_IS_BROWSER){ var textures = this.extractTextures(subobj, true); this.loadTextures(textures); } } this.extractEntities = function(scene) { this.cameras = []; this.parts = {}; scene.traverse(elation.bind(this, function ( node ) { if ( node instanceof THREE.Camera ) { this.cameras.push(node); //} else if (node instanceof THREE.Mesh) { } else if (node.name !== '') { this.parts[node.name] = node; node.castShadow = this.properties.shadow; node.receiveShadow = this.properties.shadow; } if (node.material) { node.material.fog = this.properties.fog; node.material.wireframe = this.properties.wireframe; } })); //console.log('Collada loaded: ', this.parts, this.cameras, this); if (this.cameras.length > 0) { this.camera = this.cameras[0]; } //this.updateCollisionSize(); } this.extractColliders = function(obj, useParentPosition) { if (!(this.properties.collidable || this.properties.pickable)) return; var meshes = []; if (!obj) obj = this.objects['3d']; var re = new RegExp(/^[_\*](collider|trigger)-(.*)$/); obj.traverse(function(n) { if (n instanceof THREE.Mesh && n.material) { var materials = n.material; if (!elation.utils.isArray(n.material)) { materials = [n.material]; } for (var i = 0; i < materials.length; i++) { var m = materials[i]; if (m.name && m.name.match(re)) { n.geometry.computeBoundingBox(); n.geometry.computeBoundingSphere(); meshes.push(n); break; } } } }); // FIXME - hack to make demo work //this.colliders.bindPosition(this.localToWorld(new THREE.Vector3())); //var flip = new THREE.Quaternion().setFromEuler(new THREE.Euler(0, Math.PI, 0)); var flip = new THREE.Quaternion(); var root = new elation.physics.rigidbody({orientation: flip, object: this});// orientation: obj.quaternion.clone() }); //root.orientation.multiply(flip); for (var i = 0; i < meshes.length; i++) { var m = meshes[i].material.name.match(re), type = m[1], shape = m[2]; var rigid = new elation.physics.rigidbody({object: this}); var min = meshes[i].geometry.boundingBox.min, max = meshes[i].geometry.boundingBox.max; //console.log('type is', type, shape, min, max); var position = meshes[i].position, orientation = meshes[i].quaternion; if (useParentPosition) { position = meshes[i].parent.position; orientation = meshes[i].parent.quaternion; } rigid.position.copy(position); rigid.orientation.copy(orientation); min.x *= this.properties.scale.x; min.y *= this.properties.scale.y; min.z *= this.properties.scale.z; max.x *= this.properties.scale.x; max.y *= this.properties.scale.y; max.z *= this.properties.scale.z; rigid.position.x *= this.properties.scale.x; rigid.position.y *= this.properties.scale.y; rigid.position.z *= this.properties.scale.z; if (shape == 'box') { this.setCollider('box', {min: min, max: max}, rigid); } else if (shape == 'sphere') { this.setCollider('sphere', {radius: Math.max(max.x, max.y, max.z)}, rigid); } else if (shape == 'cylinder') { var radius = Math.max(max.x - min.x, max.z - min.z) / 2, height = max.y - min.y; this.setCollider('cylinder', {radius: radius, height: height}, rigid); // FIXME - rotate everything by 90 degrees on x axis to match default orientation var rot = new THREE.Quaternion().setFromEuler(new THREE.Euler(0, -Math.PI/2, 0)); rigid.orientation.multiply(rot); } if (type == 'collider') { //console.log('add collider:', rigid, rigid.position.toArray(), rigid.orientation.toArray()); root.add(rigid); } else if (type == 'trigger') { var triggername = meshes[i].parent.name; var size = new THREE.Vector3().subVectors(max, min); /* size.x /= this.properties.scale.x; size.y /= this.properties.scale.y; size.z /= this.properties.scale.z; */ var quat = new THREE.Quaternion().multiplyQuaternions(obj.quaternion, rigid.orientation); var pos = rigid.position.clone().applyQuaternion(quat); /* pos.x /= this.properties.scale.x; pos.y /= this.properties.scale.y; pos.z /= this.properties.scale.z; */ this.triggers[triggername] = this.spawn('trigger', 'trigger_' + this.name + '_' + triggername, { position: pos, orientation: quat, shape: shape, size: size, scale: new THREE.Vector3(1 / this.properties.scale.x, 1 / this.properties.scale.y, 1 / this.properties.scale.z) }); } meshes[i].parent.remove(meshes[i]); meshes[i].bindPosition(rigid.position); meshes[i].bindQuaternion(rigid.orientation); //meshes[i].bindScale(this.properties.scale); meshes[i].userData.thing = this; meshes[i].updateMatrixWorld(); //meshes[i].material = new THREE.MeshPhongMaterial({color: 0x999900, emissive: 0x666666, opacity: .5, transparent: true}); this.colliders.add(meshes[i]); meshes[i].material = new THREE.MeshLambertMaterial({color: 0x999900, opacity: .2, transparent: true, emissive: 0x444400, alphaTest: .1, depthTest: false, depthWrite: false}); /* this.colliderhelper = new THREE.EdgesHelper(meshes[i], 0x00ff00); this.colliders.add(this.colliderhelper); this.engine.systems.world.scene['colliders'].add(this.colliderhelper); meshes[i].updateMatrixWorld(); */ } if (this.objects.dynamics) { this.objects.dynamics.add(root); } /* new3d.scale.copy(obj.scale); new3d.position.copy(obj.position); new3d.quaternion.copy(obj.quaternion); this.objects['3d'].add(new3d); */ //this.colliders.bindScale(this.properties.scale); //this.colliders.updateMatrixWorld(); return this.colliders; } this.extractTextures = function(object, useloadhandler) { if (!object) object = this.objects['3d']; // Extract the unique texture images out of the specified object var unique = {}; var ret = []; var mapnames = ['map', 'lightMap', 'bumpMap', 'normalMap', 'specularMap', 'envMap']; object.traverse(function(n) { if (n instanceof THREE.Mesh) { var materials = n.material; if (!elation.utils.isArray(n.material)) { materials = [n.material]; } for (var materialidx = 0; materialidx < materials.length; materialidx++) { var m = materials[materialidx]; for (var mapidx = 0; mapidx < mapnames.length; mapidx++) { var tex = m[mapnames[mapidx]]; if (tex) { if (tex.image && !unique[tex.image.src]) { unique[tex.image.src] = true; ret.push(tex); } else if (!tex.image && tex.sourceFile != '') { if (!unique[tex.sourceFile]) { unique[tex.sourceFile] = true; ret.push(tex); } } else if (!tex.image) { ret.push(tex); } } } } } }); return ret; } this.extractAnimations = function(scene) { var animations = [], actions = {}, skeleton = false, meshes = [], num = 0; scene.traverse(function(n) { if (n.animations) { //animations[n.name] = n; animations.push.apply(animations, n.animations); num++; } if (n.skeleton) { skeleton = n.skeleton; } if (n instanceof THREE.SkinnedMesh) { meshes.push(n); } }); if (skeleton) { this.skeleton = skeleton; /* scene.traverse(function(n) { n.skeleton = skeleton; }); */ if (true) { //meshes.length > 0) { var mixer = this.animationmixer = new THREE.AnimationMixer(meshes[0]); var skeletons = [skeleton]; for (var i = 0; i < meshes.length; i++) { //meshes[i].bind(this.skeleton); skeletons.push(meshes[i].skeleton); } // FIXME - shouldn't be hardcoded! var then = performance.now(); setInterval(elation.bind(this, function() { var now = performance.now(), diff = now - then; then = now; this.animationmixer.update(diff / 1000); for (var i = 0; i < skeletons.length; i++) { skeletons[i].update(); } }), 16); } } if (num > 0) { this.animations = animations; for (var i = 0; i < animations.length; i++) { var anim = animations[i]; actions[anim.name] = mixer.clipAction(anim); } this.animationactions = actions; } if (this.skeletonhelper && this.skeletonhelper.parent) { this.skeletonhelper.parent.remove(this.skeletonhelper); } this.skeletonhelper = new THREE.SkeletonHelper(this.objects['3d']); //this.engine.systems.world.scene['world-3d'].add(this.skeletonhelper); } this.rebindAnimations = function() { var rootobject = this.objects['3d']; if (this.animationmixer) { // Reset to t-pose before rebinding skeleton this.animationmixer.stopAllAction(); this.animationmixer.update(0); } rootobject.traverse(function(n) { if (n instanceof THREE.SkinnedMesh) { n.rebindByName(rootobject); } }); } this.loadTextures = function(textures) { this.pendingtextures = 0; for (var i = 0; i < textures.length; i++) { if (textures[i].image) { if (!textures[i].image.complete) { elation.events.fire({ type: 'resource_load_start', data: { type: 'image', image: textures[i].image } }); this.pendingtextures++; elation.events.add(textures[i].image, 'load', elation.bind(this, this.textureLoadComplete)); } } } // Everything was already loaded, so fire the event immediately if (this.pendingtextures === 0) { this.refresh(); elation.events.fire({type: "thing_load", element: this, data: this.objects['3d']}); } } this.textureLoadComplete = function(ev) { this.refresh(); if (--this.pendingtextures == 0) { // Fire the thing_load event once all textures are loaded elation.events.fire({type: "thing_load", element: this, data: this.objects['3d']}); } } this.spawn = function(type, name, spawnargs, orphan) { var newspawn = this.engine.systems.world.spawn(type, name, spawnargs, (orphan ? null : this)); return newspawn; } this.die = function() { this.removeDynamics(); if (this.parent) { this.parent.remove(this); } if (this.children) { var keys = Object.keys(this.children); for (var i = 0; i < keys.length; i++) { this.children[keys[i]].die(); } } elation.events.fire({element: this, type: 'thing_destroy'}); this.destroy(); } this.refresh = function() { elation.events.fire({type: 'thing_change_queued', element: this}); } this.applyChanges = function() { var s = this.scale; if (s && this.objects['3d']) { this.objects['3d'].visible = this.visible && !(s.x == 0 || s.y == 0 || s.z == 0); } elation.events.fire({type: 'thing_change', element: this}); } this.reload = function() { this.set('forcereload', true, true); } this.worldToLocal = function(worldpos, clone) { if (this.objects['3d'].matrixWorldNeedsUpdate) this.objects['3d'].updateMatrixWorld(); if (clone) worldpos = worldpos.clone(); return this.objects['3d'].worldToLocal(worldpos); } this.localToWorld = function(localpos, clone) { if (this.objects['3d'].matrixWorldNeedsUpdate) this.objects['3d'].updateMatrixWorld(); if (clone) localpos = localpos.clone(); return this.objects['3d'].localToWorld(localpos); } this.worldToParent = function(worldpos, clone) { if (this.objects['3d'].matrixWorldNeedsUpdate) this.objects['3d'].updateMatrixWorld(); if (clone) worldpos = worldpos.clone(); return this.objects['3d'].parent.worldToLocal(worldpos); } this.localToParent = function(localpos, clone) { if (this.objects['3d'].matrixWorldNeedsUpdate) this.objects['3d'].updateMatrixWorld(); if (clone) localpos = localpos.clone(); return localpos.applyMatrix4(this.objects['3d'].matrix); } this.localToWorldOrientation = function(orient) { if (!orient) orient = new THREE.Quaternion(); var n = this; while (n && n.properties) { orient.multiply(n.properties.orientation); n = n.parent; } return orient; } this.worldToLocalOrientation = function(orient) { if (!orient) orient = new THREE.Quaternion(); /* var n = this.parent; var worldorient = new THREE.Quaternion(); while (n && n.properties) { worldorient.multiply(inverse.copy(n.properties.orientation).inverse()); n = n.parent; } return orient.multiply(worldorient); */ // FIXME - this is cheating! var tmpquat = new THREE.Quaternion(); return orient.multiply(tmpquat.copy(this.objects.dynamics.orientationWorld).inverse()); } this.lookAt = function(other, up) { if (!up) up = new THREE.Vector3(0,1,0); var otherpos = false; if (other.properties && other.properties.position) { otherpos = other.localToWorld(new THREE.Vector3()); } else if (other instanceof THREE.Vector3) { otherpos = other.clone(); } var thispos = this.localToWorld(new THREE.Vector3()); if (otherpos) { var dir = thispos.clone().sub(otherpos).normalize(); var axis = new THREE.Vector3().crossVectors(up, dir); var angle = dir.dot(up); //this.properties.orientation.setFromAxisAngle(axis, -angle); console.log(thispos.toArray(), otherpos.toArray(), dir.toArray(), axis.toArray(), angle, this.properties.orientation.toArray()); } } this.serialize = function(serializeAll) { var ret = { name: this.name, parentname: this.parentname, type: this.type, properties: {}, things: {} }; var numprops = 0, numthings = 0; for (var k in this._thingdef.properties) { var propdef = this._thingdef.properties[k]; var propval = this.get(k); if (propval !== null) { switch (propdef.type) { case 'vector2': case 'vector3': case 'vector4': propval = propval.toArray(); for (var i = 0; i < propval.length; i++) propval[i] = +propval[i]; // FIXME - force to float break; case 'quaternion': propval = [propval.x, propval.y, propval.z, propval.w]; break; case 'texture': propval = propval.sourceFile; break; /* case 'color': propval = propval.getHexString(); break; */ case 'component': var ref = propval; propval = [ ref.type, ref.id ]; break; } try { if (propval !== null && !elation.utils.isIdentical(propval, propdef.default)) { //elation.utils.arrayset(ret.properties, k, propval); ret.properties[k] = propval; numprops++; } } catch (e) { console.log("Error serializing property: " + k, this, e); } } } if (numprops == 0) delete ret.properties; for (var k in this.children) { if (this.children[k].properties) { if (!serializeAll) { if (this.children[k].properties.persist) { ret.things[k] = this.children[k].serialize(); numthings++; } } else { ret.things[k] = this.children[k].serialize(); numthings++; } } else { console.log('huh what', k, this.children[k]); } } if (numthings == 0) delete ret.things; return ret; } //this.thing_add = function(ev) { // elation.events.fire({type: 'thing_add', element: this, data: ev.data}); //} /* this.createCamera = function(offset, rotation) { //var viewsize = this.engine.systems.render.views['main'].size; var viewsize = [640, 480]; // FIXME - hardcoded hack! this.cameras.push(new THREE.PerspectiveCamera(50, viewsize[0] / viewsize[1], .01, 1e15)); this.camera = this.cameras[this.cameras.length-1]; if (offset) { this.camera.position.copy(offset) } if (rotation) { //this.camera.eulerOrder = "YZX"; this.camera.rotation.copy(rotation); } this.objects['3d'].add(this.camera); } */ // Sound functions this.playSound = function(sound, volume, position, velocity) { if (this.sounds[sound] && this.engine.systems.sound.enabled) { this.updateSound(sound, volume, position, velocity); this.sounds[sound].play(); } } this.stopSound = function(sound) { if (this.sounds[sound] && this.sounds[sound].playing) { this.sounds[sound].stop(); } } this.updateSound = function(sound, volume, position, velocity) { if (this.sounds[sound]) { if (!volume) volume = 100; this.sounds[sound].setVolume(volume); if (position) { this.sounds[sound].setPan([position.x, position.y, position.z], (velocity ? [velocity.x, velocity.y, velocity.z] : [0,0,0])); } } } this.addTag = function(tag) { if (!this.hasTag(tag)) { this.tags.push(tag); return true; } return false; } this.hasTag = function(tag) { return (this.tags.indexOf(tag) !== -1); } this.removeTag = function(tag) { var idx = this.tags.indexOf(tag); if (idx !== -1) { this.tags.splice(idx, 1); return true; } return false; } this.getPlayer = function() { console.log('player id:', this.get('player_id')); return this.get('player_id'); } this.addPart = function(name, part) { if (this.parts[name] === undefined) { this.parts[name] = part; var type = part.componentname; if (this.parttypes[type] === undefined) { this.parttypes[type] = []; } this.parttypes[type].push(part); return true; } return false; } this.hasPart = function(name) { return (this.parts[name] !== undefined); } this.hasPartOfType = function(type) { return (this.parttypes[type] !== undefined && this.parttypes[type].length > 0); } this.getPart = function(name) { return this.parts[name]; } this.getPartsByType = function(type) { return this.parttypes[type] || []; } this.getThingByObject = function(obj) { while (obj) { if (obj.userData.thing) return obj.userData.thing; obj = obj.parent; } return null; } this.getObjectsByTag = function(tag) { } this.getChildren = function(collection) { if (typeof collection == 'undefined') collection = []; for (var k in this.children) { collection.push(this.children[k]); this.children[k].getChildren(collection); } return collection; } this.getChildrenByProperty = function(key, value, collection) { if (typeof collection == 'undefined') collection = []; for (var k in this.children) { if (this.children[k][key] === value) { collection.push(this.children[k]); } this.children[k].getChildrenByProperty(key, value, collection); } return collection; } this.getChildrenByPlayer = function(player, collection) { if (typeof collection == 'undefined') collection = []; for (var k in this.children) { if (this.children[k].getPlayer() == player) { collection.push(this.children[k]); } this.children[k].getChildrenByPlayer(player, collection); } return collection; } this.getChildrenByTag = function(tag, collection) { if (typeof collection == 'undefined') collection = []; for (var k in this.children) { if (this.children[k].hasTag(tag)) { collection.push(this.children[k]); } this.children[k].getChildrenByTag(tag, collection); } return collection; } this.getChildrenByType = function(type, collection) { if (typeof collection == 'undefined') collection = []; for (var k in this.children) { if (this.children[k].type == type) { collection.push(this.children[k]); } this.children[k].getChildrenByType(type, collection); } return collection; } this.distanceTo = (function() { // closure scratch variables var _v1 = new THREE.Vector3(), _v2 = new THREE.Vector3(); return function(obj) { var mypos = this.localToWorld(_v1.set(0,0,0)); if (obj && obj.localToWorld) { return mypos.distanceTo(obj.localToWorld(_v2.set(0,0,0))); } else if (obj instanceof THREE.Vector3) { return mypos.distanceTo(obj); } return Infinity; } })(); this.canUse = function(object) { return false; } this.thing_use_activate = function(ev) { var player = ev.data; var canuse = this.canUse(player); if (canuse && canuse.action) { canuse.action(player); } } this.getBoundingSphere = function() { // Iterate over all children and expand our bounding sphere to encompass them. // This gives us the total size of the whole thing var bounds = new THREE.Sphere(); var worldpos = this.localToWorld(new THREE.Vector3()); var childworldpos = new THREE.Vector3(); this.objects['3d'].traverse(function(n) { childworldpos.set(0,0,0).applyMatrix4(n.matrixWorld); if (n.boundingSphere) { var newradius = worldpos.distanceTo(childworldpos) + n.boundingSphere.radius; if (newradius > bounds.radius) { bounds.radius = newradius; } } }); return bounds; } this.getBoundingBox = function() { // Iterate over all children and expand our bounding box to encompass them. // This gives us the total size of the whole thing var bounds = new THREE.Box3(); bounds.setFromObject(this.objects['3d']); for (var k in this.children) { var childbounds = this.children[k].getBoundingBox(); bounds.expandByPoint(bounds.min); bounds.expandByPoint(bounds.max); } return bounds; } }); });
scripts/things/generic.js
elation.require([ // "engine.external.three.ColladaLoader", //"engine.external.three.JSONLoader" //"engine.external.three.glTFLoader-combined" //"engine.things.trigger" "utils.proxy" ], function() { elation.component.add("engine.things.generic", function() { this.init = function() { this._proxies = {}; this._thingdef = { properties: {}, events: {}, actions: {} }; this.parentname = this.args.parentname || ''; this.name = this.args.name || ''; this.type = this.args.type || 'generic'; this.engine = this.args.engine; this.client = this.args.client; this.properties = {}; this.objects = {}; this.parts = {}; this.triggers = {}; this.parttypes = {}; this.children = {}; this.tags = []; this.sounds = {}; this.animations = false; this.skeleton = false; this.tmpvec = new THREE.Vector3(); this.interp = { rate: 20, lastTime: 0, time: 0, endpoint: new THREE.Vector3(), spline: [], active: false, fn: this.applyInterp }; //elation.events.add(this, 'thing_create', this); elation.events.add(this, 'thing_use_activate', this); this.defineActions({ 'spawn': this.spawn, 'move': this.move }); this.defineProperties({ 'position': { type: 'vector3', default: [0, 0, 0], comment: 'Object position, relative to parent' }, 'orientation': { type: 'quaternion', default: [0, 0, 0, 1], comment: 'Object orientation, relative to parent' }, 'scale': { type: 'vector3', default: [1, 1, 1], comment: 'Object scale, relative to parent' }, 'velocity': { type: 'vector3', default: [0, 0, 0], comment: 'Object velocity (m/s)' }, 'acceleration': { type: 'vector3', default: [0, 0, 0], comment: 'Object acceleration (m/s^2)' }, 'angular': { type: 'vector3', default: [0, 0, 0], comment: 'Object angular velocity (radians/sec)' }, 'angularacceleration': { type: 'vector3', default: [0, 0, 0], comment: 'Object angular acceleration (radians/sec^2)' }, 'mass': { type: 'float', default: 0.0, comment: 'Object mass (kg)' }, 'exists': { type: 'bool', default: true, comment: 'Exists' }, 'visible': { type: 'bool', default: true, comment: 'Is visible' }, 'physical': { type: 'bool', default: true, comment: 'Simulate physically' }, 'collidable': { type: 'bool', default: true, comment: 'Can crash into other things' }, //'fog': { type: 'bool', default: true, comment: 'Affected by fog' }, 'shadow': { type: 'bool', default: true, refreshMaterial: true, comment: 'Casts and receives shadows' }, 'wireframe': { type: 'bool', default: false, refreshMaterial: true, comment: 'Render this object as a wireframe' }, 'forcereload': { type: 'bool', default: false, refreshGeometry: true, refreshMaterial: true, comment: 'Force a full reload of all files' }, 'mouseevents': { type: 'bool', default: true, comment: 'Respond to mouse/touch events' }, 'persist': { type: 'bool', default: false, comment: 'Continues existing across world saves' }, 'pickable': { type: 'bool', default: true, comment: 'Selectable via mouse/touch events' }, 'render.mesh': { type: 'string', refreshGeometry: true, comment: 'URL for JSON model file' }, 'render.meshname':{ type: 'string', refreshGeometry: true }, 'render.scene': { type: 'string', refreshGeometry: true, comment: 'URL for JSON scene file' }, 'render.collada': { type: 'string', refreshGeometry: true, comment: 'URL for Collada scene file' }, 'render.model': { type: 'string', refreshGeometry: true, comment: 'Name of model asset' }, 'render.gltf': { type: 'string', refreshGeometry: true, comment: 'URL for glTF file' }, 'render.materialname': { type: 'string', refreshMaterial: true, comment: 'Material library name' }, 'render.texturepath': { type: 'string', refreshMaterial: true, comment: 'Texture location' }, 'player_id': { type: 'float', default: null, comment: 'Network id of the creator' }, 'tags': { type: 'string', comment: 'Default tags to add to this object' } }); this.defineEvents({ 'thing_create': [], 'thing_add': ['child'], 'thing_load': ['mesh'], 'thing_remove': [], 'thing_destroy': [], 'thing_tick': ['delta'], 'thing_think': ['delta'], 'thing_move': [], 'mouseover': ['clientX', 'clientY', 'position'], 'mouseout': [], 'mousedown': [], 'mouseup': [], 'click': [] }); if (typeof this.preinit == 'function') { this.preinit(); } if (typeof this.postinit == 'function') { this.postinit(); } this.init3D(); this.initDOM(); this.initPhysics(); setTimeout(elation.bind(this, function() { // Fire create event next frame this.createChildren(); this.refresh(); elation.events.fire({type: 'thing_create', element: this}); }), 0); } this.preinit = function() { } this.postinit = function() { } this.initProperties = function() { if (!this.properties) { this.properties = {}; } for (var propname in this._thingdef.properties) { var prop = this._thingdef.properties[propname]; if (!this.hasOwnProperty(propname)) { this.defineProperty(propname, prop); } } } this.getPropertyValue = function(type, value) { if (value === null) { return; } switch (type) { case 'vector2': if (elation.utils.isArray(value)) { value = new THREE.Vector2(+value[0], +value[1]); } else if (elation.utils.isString(value)) { var split = value.split((value.indexOf(' ') != -1 ? ' ' : ',')); value = new THREE.Vector2(+split[0], +split[1]); } break; case 'vector3': if (elation.utils.isArray(value)) { value = new THREE.Vector3(+value[0], +value[1], +value[2]); } else if (elation.utils.isString(value)) { var split = value.split((value.indexOf(' ') != -1 ? ' ' : ',')); value = new THREE.Vector3(+split[0], +split[1], +split[2]); } break; case 'euler': if (elation.utils.isArray(value)) { value = new THREE.Euler(+value[0], +value[1], +value[2]); } else if (elation.utils.isString(value)) { var split = value.split((value.indexOf(' ') != -1 ? ' ' : ',')); value = new THREE.Euler(+split[0], +split[1], +split[2]); } break; case 'quaternion': if (elation.utils.isArray(value)) { value = new THREE.Quaternion(+value[0], +value[1], +value[2], +value[3]); } else if (elation.utils.isString(value)) { var split = value.split((value.indexOf(' ') != -1 ? ' ' : ',')); value = new THREE.Quaternion(+split[0], +split[1], +split[2], +split[3]); } break; case 'color': var clamp = elation.utils.math.clamp; if (value instanceof THREE.Vector3) { value = new THREE.Color(clamp(value.x, 0, 1), clamp(value.y, 0, 1), clamp(value.z, 0, 1)); } else if (value instanceof THREE.Vector4) { this.opacity = clamp(value.w, 0, 1); value = new THREE.Color(clamp(value.x, 0, 1), clamp(value.y, 0, 1), clamp(value.z, 0, 1)); } else if (elation.utils.isString(value)) { var splitpos = value.indexOf(' '); if (splitpos == -1) splitpos = value.indexOf(','); if (splitpos == -1) { value = new THREE.Color(value); } else { var split = value.split((value.indexOf(' ') != -1 ? ' ' : ',')); value = new THREE.Color(clamp(split[0], 0, 1), clamp(split[1], 0, 1), clamp(split[2], 0, 1)); if (split.length > 3) { this.opacity = clamp(split[3], 0, 1); } } } else if (elation.utils.isArray(value)) { value = new THREE.Color(+value[0], +value[1], +value[2]); } else if (!(value instanceof THREE.Color)) { value = new THREE.Color(value); } break; case 'bool': case 'boolean': value = !(value === false || (elation.utils.isString(value) && value.toLowerCase() === 'false') || value === 0 || value === '0' || value === '' || value === null || typeof value == 'undefined'); break; case 'float': value = +value; break; case 'int': value = value | 0; break; case 'texture': if (value !== false) { value = (value instanceof THREE.Texture ? value : elation.engine.materials.getTexture(value)); } break; case 'json': if (value !== false) { value = (elation.utils.isString(value) ? JSON.parse(value) : value); } break; case 'component': if (value) { var component = elation.component.fetch(value[0], value[1]); if (component) { value = component; } } break; } return value; } this.defineProperties = function(properties) { elation.utils.merge(properties, this._thingdef.properties); this.initProperties(); } this.defineProperty = function(propname, prop) { var propval = elation.utils.arrayget(this.properties, propname, null); Object.defineProperty(this, propname, { configurable: true, enumerable: true, get: function() { var proxy = this._proxies[propname]; if (proxy) { return proxy; } return elation.utils.arrayget(this.properties, propname); }, set: function(v) { this.set(propname, v, prop.refreshGeometry); //this.refresh(); //console.log('set ' + propname + ' to ', v); } }); if (propval === null) { if (!elation.utils.isNull(this.args.properties[propname])) { propval = this.args.properties[propname] } else if (!elation.utils.isNull(prop.default)) { propval = prop.default; } this.set(propname, propval); } if (prop.type == 'vector2' || prop.type == 'vector3' || prop.type == 'quaternion' || prop.type == 'color') { if (propval && !this._proxies[propname]) { // Create proxy objects for these special types var proxydef = { x: ['property', 'x'], y: ['property', 'y'], z: ['property', 'z'], }; if (prop.type == 'quaternion') { proxydef.w = ['property', 'w']; } else if (prop.type == 'color') { // We want to support color.xyz as well as color.rgb proxydef.r = ['property', 'r']; proxydef.g = ['property', 'g']; proxydef.b = ['property', 'b']; proxydef.x = ['property', 'r']; proxydef.y = ['property', 'g']; proxydef.z = ['property', 'b']; } var propval = elation.utils.arrayget(this.properties, propname, null); if (propval) { this._proxies[propname] = new elation.proxy( propval, proxydef, true ); /* // FIXME - listening for proxy_change events would let us respond to changes for individual vector elements, but it gets expensive elation.events.add(propval, 'proxy_change', elation.bind(this, function(ev) { //this.refresh(); //this.set('exists', this.properties.exists, prop.refreshGeometry); //this[propname] = this[propname]; })); */ } } } } this.defineActions = function(actions) { elation.utils.merge(actions, this._thingdef.actions); } this.defineEvents = function(events) { elation.utils.merge(events, this._thingdef.events); } this.set = function(property, value, forcerefresh) { var propdef = this._thingdef.properties[property]; if (!propdef) { console.warn('Tried to set unknown property', property, value, this); return; } var changed = false var propval = this.getPropertyValue(propdef.type, value); var currval = this.get(property); //if (currval !== null) { switch (propdef.type) { case 'vector2': case 'vector3': case 'vector4': case 'quaternion': case 'color': if (currval === null) { elation.utils.arrayset(this.properties, property, propval); changed = true; } else { if (!currval.equals(propval)) { currval.copy(propval); changed = true } } break; case 'texture': //console.log('TRY TO SET NEW TEX', property, value, forcerefresh); default: if (currval !== propval) { elation.utils.arrayset(this.properties, property, propval); changed = true; } } //} else { // elation.utils.arrayset(this.properties, property, propval); //} if (changed) { if (propdef.set) { propdef.set.apply(this, [property, propval]); } if (forcerefresh && this.objects['3d']) { var oldobj = this.objects['3d'], parent = oldobj.parent, newobj = this.createObject3D(); this.objects['3d'] = newobj; this.objects['3d'].bindPosition(this.properties.position); this.objects['3d'].bindQuaternion(this.properties.orientation); this.objects['3d'].bindScale(this.properties.scale); this.objects['3d'].userData.thing = this; if (parent) { parent.remove(oldobj); parent.add(newobj); } } if (this.objects.dynamics) { if (false && forcerefresh) { this.removeDynamics(); this.initPhysics(); } else { this.objects.dynamics.mass = this.properties.mass; this.objects.dynamics.updateState(); if (this.objects.dynamics.collider) { this.objects.dynamics.collider.getInertialMoment(); } } } this.refresh(); } } this.setProperties = function(properties, interpolate) { for (var prop in properties) { if (prop == 'position' && interpolate == true ) { if ( this.tmpvec.fromArray(properties[prop]).distanceToSquared(this.get('position')) > 1 ) { // call interpolate function // TODO: fix magic number 0.001 this.interpolateTo(properties[prop]); } } else { this.set(prop, properties[prop], false); } } this.refresh(); } this.interpolateTo = function(newPos) { this.interp.time = 0; this.interp.endpoint.fromArray(newPos); this.interp.spline = new THREE.SplineCurve3([this.get('position'), this.interp.endpoint]).getPoints(10); // console.log(this.interp.spline); elation.events.add(this.engine, 'engine_frame', elation.bind(this, this.applyInterp)); } this.applyInterp = function(ev) { this.interp.time += ev.data.delta * this.engine.systems.physics.timescale; if (this.interp.time >= this.interp.rate) { elation.events.remove(this, 'engine_frame', elation.bind(this, this.applyInterp)); return; } console.log("DEBUG: interpolating, time:", this.interp.time); if (this.interp.time - this.interp.lastTime >= 2) { this.set('position', this.interp.spline[Math.floor((this.interp.time * 10) / this.interp.rate)], false); this.refresh(); } }; this.get = function(property, defval) { if (typeof defval == 'undefined') defval = null; return elation.utils.arrayget(this.properties, property, defval); } this.init3D = function() { if (this.objects['3d']) { if (this.objects['3d'].parent) { this.objects['3d'].parent.remove(this.objects['3d']); } } if (this.properties.tags) { var tags = this.properties.tags.split(','); for (var i = 0; i < tags.length; i++) { this.addTag(tags[i].trim()); } } this.objects['3d'] = this.createObject3D(); if (this.objects['3d']) { this.objects['3d'].bindPosition(this.properties.position); this.objects['3d'].bindQuaternion(this.properties.orientation); this.objects['3d'].bindScale(this.properties.scale); //this.objects['3d'].useQuaternion = true; this.objects['3d'].userData.thing = this; } if (!this.colliders) { this.colliders = new THREE.Object3D(); this.colliders.bindPosition(this.properties.position); this.colliders.bindQuaternion(this.properties.orientation); this.colliders.bindScale(this.properties.scale); //this.colliders.scale.set(1/this.properties.scale.x, 1/this.properties.scale.y, 1/this.properties.scale.z); this.colliders.userData.thing = this; } var childkeys = Object.keys(this.children); if (childkeys.length > 0) { // Things were added during initialization, so make sure they're added to the scene for (var i = 0; i < childkeys.length; i++) { var k = childkeys[i]; if (this.children[k].objects['3d']) { this.objects['3d'].add(this.children[k].objects['3d']); } } } if (!this.properties.visible) { this.hide(); } elation.events.fire({type: 'thing_init3d', element: this}); this.refresh(); } this.initDOM = function() { if (ENV_IS_BROWSER) { this.objects['dom'] = this.createObjectDOM(); elation.html.addclass(this.container, "space.thing"); elation.html.addclass(this.container, "space.things." + this.type); //this.updateDOM(); } } this.initPhysics = function() { if (this.properties.physical) { this.createDynamics(); this.createForces(); } } this.createObject3D = function() { // if (this.properties.exists === false || !ENV_IS_BROWSER) return; if (this.properties.exists === false) return; var object = null, geometry = null, material = null; var cachebust = ''; if (this.properties.forcereload) cachebust = '?n=' + (Math.floor(Math.random() * 10000)); if (this.properties.render) { if (this.properties.render.scene) { this.loadJSONScene(this.properties.render.scene, this.properties.render.texturepath + cachebust); } else if (this.properties.render.mesh) { this.loadJSON(this.properties.render.mesh, this.properties.render.texturepath + cachebust); } else if (this.properties.render.collada) { this.loadCollada(this.properties.render.collada + cachebust); } else if (this.properties.render.model) { object = elation.engine.assets.find('model', this.properties.render.model); } else if (this.properties.render.gltf) { this.loadglTF(this.properties.render.gltf + cachebust); } else if (this.properties.render.meshname) { object = new THREE.Object3D(); setTimeout(elation.bind(this, this.loadMeshName, this.properties.render.meshname), 0); } } var geomparams = elation.utils.arrayget(this.properties, "generic.geometry") || {}; switch (geomparams.type) { case 'sphere': geometry = new THREE.SphereGeometry(geomparams.radius || geomparams.size, geomparams.segmentsWidth, geomparams.segmentsHeight); break; case 'cube': geometry = new THREE.BoxGeometry( geomparams.width || geomparams.size, geomparams.height || geomparams.size, geomparams.depth || geomparams.size, geomparams.segmentsWidth || 1, geomparams.segmentsHeight || 1, geomparams.segmentsDepth || 1); break; case 'cylinder': geometry = new THREE.CylinderGeometry( geomparams.radiusTop || geomparams.radius, geomparams.radiusBottom || geomparams.radius, geomparams.height, geomparams.segmentsRadius, geomparams.segmentsHeight, geomparams.openEnded); break; case 'torus': geometry = new THREE.TorusGeometry(geomparams.radius, geomparams.tube, geomparams.segmentsR, geomparams.segmentsT, geomparams.arc); break; } if (geometry) { var materialparams = elation.utils.arrayget(this.properties, "generic.material") || {}; if (materialparams instanceof THREE.Material) { material = materialparams; } else { switch (materialparams.type) { case 'phong': material = new THREE.MeshPhongMaterial(materialparams); break; case 'lambert': material = new THREE.MeshLambertMaterial(materialparams); break; case 'face': material = new THREE.MeshFaceMaterial(); break; case 'depth': material = new THREE.MeshDepthMaterial(); break; case 'normal': material = new THREE.MeshNormalMaterial(); break; case 'basic': default: material = new THREE.MeshBasicMaterial(materialparams); } } } if (!geometry && !material) { //geometry = new THREE.BoxGeometry(1, 1, 1); //material = new THREE.MeshPhongMaterial({color: 0xcccccc, opacity: .2, emissive: 0x333333, transparent: true}); //console.log('made placeholder thing', geometry, material); } if (!object) { object = (geometry && material ? new THREE.Mesh(geometry, material) : new THREE.Object3D()); } if (geometry && material) { if (geomparams.flipSided) material.side = THREE.BackSide; if (geomparams.doubleSided) material.side = THREE.DoubleSide; } this.objects['3d'] = object; //this.spawn('gridhelper', {persist: false}); return object; } this.createObjectDOM = function() { return; } this.createChildren = function() { return; } this.add = function(thing) { if (!this.children[thing.id]) { this.children[thing.id] = thing; thing.parent = this; if (this.objects && thing.objects && this.objects['3d'] && thing.objects['3d']) { this.objects['3d'].add(thing.objects['3d']); } else if (thing instanceof THREE.Object3D) { this.objects['3d'].add(thing); } if (this.objects && thing.objects && this.objects['dynamics'] && thing.objects['dynamics']) { this.objects['dynamics'].add(thing.objects['dynamics']); } if (this.container && thing.container) { this.container.appendChild(thing.container); } if (this.colliders && thing.colliders) { this.colliders.add(thing.colliders); } elation.events.fire({type: 'thing_add', element: this, data: {thing: thing}}); return true; } else { console.log("Couldn't add ", thing.name, " already exists in ", this.name); } return false; } this.remove = function(thing) { if (thing && this.children[thing.id]) { if (this.objects['3d'] && thing.objects['3d']) { this.objects['3d'].remove(thing.objects['3d']); } if (thing.container && thing.container.parentNode) { thing.container.parentNode.removeChild(thing.container); } if (thing.objects['dynamics'] && thing.objects['dynamics'].parent) { thing.objects['dynamics'].parent.remove(thing.objects['dynamics']); } if (this.colliders && thing.colliders) { this.colliders.remove(thing.colliders); } if (thing.colliderhelper) { //this.engine.systems.world.scene['colliders'].remove(thing.colliderhelper); } elation.events.fire({type: 'thing_remove', element: this, data: {thing: thing}}); delete this.children[thing.id]; thing.parent = false; } else { console.log("Couldn't remove ", thing.name, " doesn't exist in ", this.name); } } this.reparent = function(newparent) { if (newparent) { if (this.parent) { newparent.worldToLocal(this.parent.localToWorld(this.properties.position)); this.properties.orientation.copy(newparent.worldToLocalOrientation(this.parent.localToWorldOrientation())); this.parent.remove(this); //newparent.worldToLocalDir(this.parent.localToWorldDir(this.properties.orientation)); } var success = newparent.add(this); this.refresh(); return success; } return false; } this.show = function() { this.objects['3d'].visible = true; if (this.colliderhelper) this.colliderhelper.visible = true; } this.hide = function() { this.objects['3d'].visible = false; if (this.colliderhelper) this.colliderhelper.visible = false; } this.createDynamics = function() { if (!this.objects['dynamics'] && this.engine.systems.physics) { this.objects['dynamics'] = new elation.physics.rigidbody({ position: this.properties.position, orientation: this.properties.orientation, mass: this.properties.mass, velocity: this.properties.velocity, acceleration: this.properties.acceleration, angular: this.properties.angular, angularacceleration: this.properties.angularacceleration, object: this }); //this.engine.systems.physics.add(this.objects['dynamics']); if ((this.properties.collidable || this.properties.pickable) && this.objects['3d'] && this.objects['3d'].geometry) { setTimeout(elation.bind(this, this.updateColliderFromGeometry), 0); } elation.events.add(this.objects['dynamics'], "physics_update,physics_collide", this); elation.events.add(this.objects['dynamics'], "physics_update", elation.bind(this, this.refresh)); } } this.removeDynamics = function() { if (this.objects.dynamics) { if (this.objects.dynamics.parent) { this.objects.dynamics.parent.remove(this.objects.dynamics); } else { this.engine.systems.physics.remove(this.objects.dynamics); } delete this.objects.dynamics; } } this.createForces = function() { } this.addForce = function(type, args) { return this.objects.dynamics.addForce(type, args); } this.removeForce = function(force) { return this.objects.dynamics.removeForce(force); } this.updateColliderFromGeometry = function(geom) { if (!geom) geom = this.objects['3d'].geometry; var collidergeom = false; // Determine appropriate collider for the geometry associated with this thing var dyn = this.objects['dynamics']; if (geom && dyn) { if (geom instanceof THREE.SphereGeometry || geom instanceof THREE.SphereBufferGeometry) { if (!geom.boundingSphere) geom.computeBoundingSphere(); this.setCollider('sphere', {radius: geom.boundingSphere.radius}); } else if (geom instanceof THREE.PlaneGeometry || geom instanceof THREE.PlaneBufferGeometry) { if (!geom.boundingBox) geom.computeBoundingBox(); var size = new THREE.Vector3().subVectors(geom.boundingBox.max, geom.boundingBox.min); // Ensure minimum size if (size.x < 1e-6) size.x = .25; if (size.y < 1e-6) size.y = .25; if (size.z < 1e-6) size.z = .25; this.setCollider('box', geom.boundingBox); } else if (geom instanceof THREE.CylinderGeometry) { if (geom.radiusTop == geom.radiusBottom) { this.setCollider('cylinder', {height: geom.height, radius: geom.radiusTop}); } else { console.log('FIXME - cylinder collider only supports uniform cylinders for now'); } } else if (!dyn.collider) { if (!geom.boundingBox) geom.computeBoundingBox(); this.setCollider('box', geom.boundingBox); } } } this.setCollider = function(type, args, rigidbody, reuseMesh) { //console.log('set collider', type, args, rigidbody, this.collidable); if (!rigidbody) rigidbody = this.objects['dynamics']; if (this.properties.collidable) { rigidbody.setCollider(type, args); } if (this.properties.collidable || this.properties.pickable) { var collidergeom = false; if (type == 'sphere') { collidergeom = elation.engine.geometries.generate('sphere', { radius: args.radius / this.properties.scale.x }); } else if (type == 'box') { var size = new THREE.Vector3().subVectors(args.max, args.min); size.x /= this.scale.x; size.y /= this.scale.y; size.z /= this.scale.z; var offset = new THREE.Vector3().addVectors(args.max, args.min).multiplyScalar(.5); collidergeom = elation.engine.geometries.generate('box', { size: size, offset: offset }); } else if (type == 'cylinder') { collidergeom = elation.engine.geometries.generate('cylinder', { radius: args.radius, height: args.height, radialSegments: 12 }); if (args.offset) { collidergeom.applyMatrix(new THREE.Matrix4().makeTranslation(args.offset.x, args.offset.y, args.offset.z)); } } else if (type == 'capsule') { collidergeom = elation.engine.geometries.generate('capsule', { radius: args.radius, length: args.length, radialSegments: 8, offset: args.offset, }); } else if (type == 'threejs') { // TODO - stub for compound mesh colliders } /* if (this.collidermesh) { this.colliders.remove(this.collidermesh); this.engine.systems.world.scene['colliders'].remove(this.colliderhelper); this.collidermesh = false; } */ if (collidergeom) { var collidermat = new THREE.MeshLambertMaterial({color: 0x999900, opacity: .2, transparent: true, emissive: 0x444400, alphaTest: .1, depthTest: false, depthWrite: false, side: THREE.DoubleSide}); if (reuseMesh && this.collidermesh) { var collidermesh = this.collidermesh; collidermesh.geometry = collidergeom; } else { var collidermesh = this.collidermesh = new THREE.Mesh(collidergeom, collidermat); if (rigidbody.position !== this.properties.position) { collidermesh.bindPosition(rigidbody.position); collidermesh.bindQuaternion(rigidbody.orientation); //collidermesh.bindScale(this.properties.scale); } collidermesh.userData.thing = this; this.colliders.add(collidermesh); } collidermesh.updateMatrixWorld(); var colliderhelper = this.colliderhelper; if (!colliderhelper) { //colliderhelper = this.colliderhelper = new THREE.EdgesHelper(collidermesh, 0x999900); //colliderhelper.matrix = collidermesh.matrix; //this.colliders.add(colliderhelper); } else { //THREE.EdgesHelper.call(colliderhelper, collidermesh, 0x990099); } //this.engine.systems.world.scene['colliders'].add(colliderhelper); // TODO - integrate this with the physics debug system /* elation.events.add(rigidbody, 'physics_collide', function() { collidermat.color.setHex(0x990000); colliderhelper.material.color.setHex(0x990000); setTimeout(function() { collidermat.color.setHex(0x999900); colliderhelper.material.color.setHex(0x999900); }, 100); }); elation.events.add(this, 'mouseover,mouseout', elation.bind(this, function(ev) { var color = 0xffff00; if (ev.type == 'mouseover' && ev.data.object === collidermesh) { color = 0x00ff00; } collidermat.color.setHex(0xffff00); colliderhelper.material.color.setHex(color); this.refresh(); })); */ } } } this.physics_collide = function(ev) { var obj1 = ev.data.bodies[0].object, obj2 = ev.data.bodies[1].object; elation.events.fire({type: 'collide', element: this, data: { other: (obj1 == this ? obj2 : obj1), collision: ev.data } }); } this.loadJSON = function(url, texturepath) { if (typeof texturepath == 'undefined') { texturepath = '/media/space/textures/'; } var loader = new THREE.JSONLoader(); loader.load(url, elation.bind(this, this.processJSON), texturepath); } this.processJSON = function(geometry, materials) { geometry.computeFaceNormals(); geometry.computeVertexNormals(); var mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials)); mesh.doubleSided = false; mesh.castShadow = false; mesh.receiveShadow = false; //this.objects['3d'].updateCollisionSize(); elation.events.fire({type: "thing_load", element: this, data: mesh}); this.objects['3d'].add(mesh); this.refresh(); } this.loadJSONScene = function(url, texturepath) { if (typeof texturepath == 'undefined') { texturepath = '/media/space/textures'; } var loader = new THREE.ObjectLoader(); loader.load(url, elation.bind(this, this.processJSONScene, url)); } this.processJSONScene = function(url, scene) { this.extractEntities(scene); this.objects['3d'].add(scene); this.extractColliders(scene); var textures = this.extractTextures(scene, true); this.loadTextures(textures); elation.events.fire({ type: 'resource_load_finish', element: this, data: { type: 'model', url: url } }); this.extractAnimations(scene); this.refresh(); } this.loadCollada = function(url) { if (!THREE.ColladaLoader) { // If the loader hasn't been initialized yet, fetch it! elation.require('engine.external.three.ColladaLoader', elation.bind(this, this.loadCollada, url)); } else { var loader = new THREE.ColladaLoader(); loader.options.convertUpAxis = true; var xhr = loader.load(url, elation.bind(this, this.processCollada, url)); elation.events.fire({ type: 'resource_load_start', element: this, data: { type: 'model', url: url } }); } } this.processCollada = function(url, collada) { //collada.scene.rotation.x = -Math.PI / 2; //collada.scene.rotation.z = Math.PI; this.extractEntities(collada.scene); /* collada.scene.computeBoundingSphere(); collada.scene.computeBoundingBox(); //this.updateCollisionSize(); */ this.objects['3d'].add(collada.scene); this.extractColliders(collada.scene, true); var textures = this.extractTextures(collada.scene, true); this.loadTextures(textures); elation.events.fire({ type: 'resource_load_finish', element: this, data: { type: 'model', url: url } }); this.refresh(); } this.loadglTF = function(url) { if (!THREE.glTFLoader) { // If the loader hasn't been initialized yet, fetch it! elation.require('engine.external.three.glTFLoader-combined', elation.bind(this, this.loadglTF, url)); } else { var loader = new THREE.glTFLoader(); loader.useBufferGeometry = true; loader.load(url, elation.bind(this, this.processglTF, url)); elation.events.fire({ type: 'resource_load_start', data: { type: 'model', url: url } }); } } this.processglTF = function(url, scenedata) { this.extractEntities(scenedata.scene); //this.updateCollisionSize(); //this.objects['3d'].add(scenedata.scene); var parent = this.objects['3d'].parent; parent.remove(this.objects['3d']); this.objects['3d'] = new THREE.Object3D(); this.objects['3d'].bindPosition(this.properties.position); this.objects['3d'].bindQuaternion(this.properties.orientation); this.objects['3d'].bindScale(this.properties.scale); this.objects['3d'].userData.thing = this; // Correct coordinate space from various modelling programs // FIXME - hardcoded for blender's settings for now, this should come from a property var scene = scenedata.scene; scene.rotation.x = -Math.PI/2; // FIXME - enable shadows for all non-transparent materials. This should be coming from the model file... scene.traverse(function(n) { if (n instanceof THREE.Mesh) { if (n.material && !(n.material.transparent || n.material.opacity < 1.0)) { n.castShadow = true; n.receiveShadow = true; } else { n.castShadow = false; n.receiveShadow = false; } } }); /* while (scenedata.scene.children.length > 0) { var obj = scenedata.scene.children[0]; scenedata.scene.remove(obj); coordspace.add(obj); } this.objects['3d'].add(coordspace); */ this.objects['3d'].add(scene); //this.objects['3d'].quaternion.setFromEuler(scenedata.scene.rotation); var textures = this.extractTextures(scene, true); this.loadTextures(textures); parent.add(this.objects['3d']); // If no pending textures, we're already loaded, so fire the event if (this.pendingtextures == 0) { elation.events.fire({type: "thing_load", element: this, data: scenedata.scene}); } elation.events.fire({ type: 'resource_load_finish', data: { type: 'model', url: url } }); this.refresh(); } this.loadMeshName = function(meshname) { var subobj = elation.engine.geometries.getMesh(meshname); subobj.rotation.x = -Math.PI/2; subobj.rotation.y = 0; subobj.rotation.z = Math.PI; this.extractEntities(subobj); this.objects['3d'].add(subobj); this.extractColliders(subobj); elation.events.add(null, 'resource_load_complete', elation.bind(this, this.extractColliders, subobj)); if (ENV_IS_BROWSER){ var textures = this.extractTextures(subobj, true); this.loadTextures(textures); } } this.extractEntities = function(scene) { this.cameras = []; this.parts = {}; scene.traverse(elation.bind(this, function ( node ) { if ( node instanceof THREE.Camera ) { this.cameras.push(node); //} else if (node instanceof THREE.Mesh) { } else if (node.name !== '') { this.parts[node.name] = node; node.castShadow = this.properties.shadow; node.receiveShadow = this.properties.shadow; } if (node.material) { node.material.fog = this.properties.fog; node.material.wireframe = this.properties.wireframe; } })); //console.log('Collada loaded: ', this.parts, this.cameras, this); if (this.cameras.length > 0) { this.camera = this.cameras[0]; } //this.updateCollisionSize(); } this.extractColliders = function(obj, useParentPosition) { if (!(this.properties.collidable || this.properties.pickable)) return; var meshes = []; if (!obj) obj = this.objects['3d']; var re = new RegExp(/^[_\*](collider|trigger)-(.*)$/); obj.traverse(function(n) { if (n instanceof THREE.Mesh && n.material) { var materials = n.material; if (!elation.utils.isArray(n.material)) { materials = [n.material]; } for (var i = 0; i < materials.length; i++) { var m = materials[i]; if (m.name && m.name.match(re)) { n.geometry.computeBoundingBox(); n.geometry.computeBoundingSphere(); meshes.push(n); break; } } } }); // FIXME - hack to make demo work //this.colliders.bindPosition(this.localToWorld(new THREE.Vector3())); //var flip = new THREE.Quaternion().setFromEuler(new THREE.Euler(0, Math.PI, 0)); var flip = new THREE.Quaternion(); var root = new elation.physics.rigidbody({orientation: flip, object: this});// orientation: obj.quaternion.clone() }); //root.orientation.multiply(flip); for (var i = 0; i < meshes.length; i++) { var m = meshes[i].material.name.match(re), type = m[1], shape = m[2]; var rigid = new elation.physics.rigidbody({object: this}); var min = meshes[i].geometry.boundingBox.min, max = meshes[i].geometry.boundingBox.max; //console.log('type is', type, shape, min, max); var position = meshes[i].position, orientation = meshes[i].quaternion; if (useParentPosition) { position = meshes[i].parent.position; orientation = meshes[i].parent.quaternion; } rigid.position.copy(position); rigid.orientation.copy(orientation); min.x *= this.properties.scale.x; min.y *= this.properties.scale.y; min.z *= this.properties.scale.z; max.x *= this.properties.scale.x; max.y *= this.properties.scale.y; max.z *= this.properties.scale.z; rigid.position.x *= this.properties.scale.x; rigid.position.y *= this.properties.scale.y; rigid.position.z *= this.properties.scale.z; if (shape == 'box') { this.setCollider('box', {min: min, max: max}, rigid); } else if (shape == 'sphere') { this.setCollider('sphere', {radius: Math.max(max.x, max.y, max.z)}, rigid); } else if (shape == 'cylinder') { var radius = Math.max(max.x - min.x, max.z - min.z) / 2, height = max.y - min.y; this.setCollider('cylinder', {radius: radius, height: height}, rigid); // FIXME - rotate everything by 90 degrees on x axis to match default orientation var rot = new THREE.Quaternion().setFromEuler(new THREE.Euler(0, -Math.PI/2, 0)); rigid.orientation.multiply(rot); } if (type == 'collider') { //console.log('add collider:', rigid, rigid.position.toArray(), rigid.orientation.toArray()); root.add(rigid); } else if (type == 'trigger') { var triggername = meshes[i].parent.name; var size = new THREE.Vector3().subVectors(max, min); /* size.x /= this.properties.scale.x; size.y /= this.properties.scale.y; size.z /= this.properties.scale.z; */ var quat = new THREE.Quaternion().multiplyQuaternions(obj.quaternion, rigid.orientation); var pos = rigid.position.clone().applyQuaternion(quat); /* pos.x /= this.properties.scale.x; pos.y /= this.properties.scale.y; pos.z /= this.properties.scale.z; */ this.triggers[triggername] = this.spawn('trigger', 'trigger_' + this.name + '_' + triggername, { position: pos, orientation: quat, shape: shape, size: size, scale: new THREE.Vector3(1 / this.properties.scale.x, 1 / this.properties.scale.y, 1 / this.properties.scale.z) }); } meshes[i].parent.remove(meshes[i]); meshes[i].bindPosition(rigid.position); meshes[i].bindQuaternion(rigid.orientation); //meshes[i].bindScale(this.properties.scale); meshes[i].userData.thing = this; meshes[i].updateMatrixWorld(); //meshes[i].material = new THREE.MeshPhongMaterial({color: 0x999900, emissive: 0x666666, opacity: .5, transparent: true}); this.colliders.add(meshes[i]); meshes[i].material = new THREE.MeshLambertMaterial({color: 0x999900, opacity: .2, transparent: true, emissive: 0x444400, alphaTest: .1, depthTest: false, depthWrite: false}); /* this.colliderhelper = new THREE.EdgesHelper(meshes[i], 0x00ff00); this.colliders.add(this.colliderhelper); this.engine.systems.world.scene['colliders'].add(this.colliderhelper); meshes[i].updateMatrixWorld(); */ } if (this.objects.dynamics) { this.objects.dynamics.add(root); } /* new3d.scale.copy(obj.scale); new3d.position.copy(obj.position); new3d.quaternion.copy(obj.quaternion); this.objects['3d'].add(new3d); */ //this.colliders.bindScale(this.properties.scale); //this.colliders.updateMatrixWorld(); return this.colliders; } this.extractTextures = function(object, useloadhandler) { if (!object) object = this.objects['3d']; // Extract the unique texture images out of the specified object var unique = {}; var ret = []; var mapnames = ['map', 'lightMap', 'bumpMap', 'normalMap', 'specularMap', 'envMap']; object.traverse(function(n) { if (n instanceof THREE.Mesh) { var materials = [n.material]; if (n.material instanceof THREE.MeshFaceMaterial) { materials = n.material.materials; } for (var materialidx = 0; materialidx < materials.length; materialidx++) { var m = materials[materialidx]; for (var mapidx = 0; mapidx < mapnames.length; mapidx++) { var tex = m[mapnames[mapidx]]; if (tex) { if (tex.image && !unique[tex.image.src]) { unique[tex.image.src] = true; ret.push(tex); } else if (!tex.image && tex.sourceFile != '') { if (!unique[tex.sourceFile]) { unique[tex.sourceFile] = true; ret.push(tex); } } else if (!tex.image) { ret.push(tex); } } } } } }); return ret; } this.extractAnimations = function(scene) { var animations = [], actions = {}, skeleton = false, meshes = [], num = 0; scene.traverse(function(n) { if (n.animations) { //animations[n.name] = n; animations.push.apply(animations, n.animations); num++; } if (n.skeleton) { skeleton = n.skeleton; } if (n instanceof THREE.SkinnedMesh) { meshes.push(n); } }); if (skeleton) { this.skeleton = skeleton; /* scene.traverse(function(n) { n.skeleton = skeleton; }); */ if (true) { //meshes.length > 0) { var mixer = this.animationmixer = new THREE.AnimationMixer(meshes[0]); var skeletons = [skeleton]; for (var i = 0; i < meshes.length; i++) { //meshes[i].bind(this.skeleton); skeletons.push(meshes[i].skeleton); } // FIXME - shouldn't be hardcoded! var then = performance.now(); setInterval(elation.bind(this, function() { var now = performance.now(), diff = now - then; then = now; this.animationmixer.update(diff / 1000); for (var i = 0; i < skeletons.length; i++) { skeletons[i].update(); } }), 16); } } if (num > 0) { this.animations = animations; for (var i = 0; i < animations.length; i++) { var anim = animations[i]; actions[anim.name] = mixer.clipAction(anim); } this.animationactions = actions; } if (this.skeletonhelper && this.skeletonhelper.parent) { this.skeletonhelper.parent.remove(this.skeletonhelper); } this.skeletonhelper = new THREE.SkeletonHelper(this.objects['3d']); //this.engine.systems.world.scene['world-3d'].add(this.skeletonhelper); } this.rebindAnimations = function() { var rootobject = this.objects['3d']; if (this.animationmixer) { // Reset to t-pose before rebinding skeleton this.animationmixer.stopAllAction(); this.animationmixer.update(0); } rootobject.traverse(function(n) { if (n instanceof THREE.SkinnedMesh) { n.rebindByName(rootobject); } }); } this.loadTextures = function(textures) { this.pendingtextures = 0; for (var i = 0; i < textures.length; i++) { if (textures[i].image) { if (!textures[i].image.complete) { elation.events.fire({ type: 'resource_load_start', data: { type: 'image', image: textures[i].image } }); this.pendingtextures++; elation.events.add(textures[i].image, 'load', elation.bind(this, this.textureLoadComplete)); } } } // Everything was already loaded, so fire the event immediately if (this.pendingtextures === 0) { this.refresh(); elation.events.fire({type: "thing_load", element: this, data: this.objects['3d']}); } } this.textureLoadComplete = function(ev) { this.refresh(); if (--this.pendingtextures == 0) { // Fire the thing_load event once all textures are loaded elation.events.fire({type: "thing_load", element: this, data: this.objects['3d']}); } } this.spawn = function(type, name, spawnargs, orphan) { var newspawn = this.engine.systems.world.spawn(type, name, spawnargs, (orphan ? null : this)); return newspawn; } this.die = function() { this.removeDynamics(); if (this.parent) { this.parent.remove(this); } if (this.children) { var keys = Object.keys(this.children); for (var i = 0; i < keys.length; i++) { this.children[keys[i]].die(); } } elation.events.fire({element: this, type: 'thing_destroy'}); this.destroy(); } this.refresh = function() { elation.events.fire({type: 'thing_change_queued', element: this}); } this.applyChanges = function() { var s = this.scale; if (s && this.objects['3d']) { this.objects['3d'].visible = this.visible && !(s.x == 0 || s.y == 0 || s.z == 0); } elation.events.fire({type: 'thing_change', element: this}); } this.reload = function() { this.set('forcereload', true, true); } this.worldToLocal = function(worldpos, clone) { if (this.objects['3d'].matrixWorldNeedsUpdate) this.objects['3d'].updateMatrixWorld(); if (clone) worldpos = worldpos.clone(); return this.objects['3d'].worldToLocal(worldpos); } this.localToWorld = function(localpos, clone) { if (this.objects['3d'].matrixWorldNeedsUpdate) this.objects['3d'].updateMatrixWorld(); if (clone) localpos = localpos.clone(); return this.objects['3d'].localToWorld(localpos); } this.worldToParent = function(worldpos, clone) { if (this.objects['3d'].matrixWorldNeedsUpdate) this.objects['3d'].updateMatrixWorld(); if (clone) worldpos = worldpos.clone(); return this.objects['3d'].parent.worldToLocal(worldpos); } this.localToParent = function(localpos, clone) { if (this.objects['3d'].matrixWorldNeedsUpdate) this.objects['3d'].updateMatrixWorld(); if (clone) localpos = localpos.clone(); return localpos.applyMatrix4(this.objects['3d'].matrix); } this.localToWorldOrientation = function(orient) { if (!orient) orient = new THREE.Quaternion(); var n = this; while (n && n.properties) { orient.multiply(n.properties.orientation); n = n.parent; } return orient; } this.worldToLocalOrientation = function(orient) { if (!orient) orient = new THREE.Quaternion(); /* var n = this.parent; var worldorient = new THREE.Quaternion(); while (n && n.properties) { worldorient.multiply(inverse.copy(n.properties.orientation).inverse()); n = n.parent; } return orient.multiply(worldorient); */ // FIXME - this is cheating! var tmpquat = new THREE.Quaternion(); return orient.multiply(tmpquat.copy(this.objects.dynamics.orientationWorld).inverse()); } this.lookAt = function(other, up) { if (!up) up = new THREE.Vector3(0,1,0); var otherpos = false; if (other.properties && other.properties.position) { otherpos = other.localToWorld(new THREE.Vector3()); } else if (other instanceof THREE.Vector3) { otherpos = other.clone(); } var thispos = this.localToWorld(new THREE.Vector3()); if (otherpos) { var dir = thispos.clone().sub(otherpos).normalize(); var axis = new THREE.Vector3().crossVectors(up, dir); var angle = dir.dot(up); //this.properties.orientation.setFromAxisAngle(axis, -angle); console.log(thispos.toArray(), otherpos.toArray(), dir.toArray(), axis.toArray(), angle, this.properties.orientation.toArray()); } } this.serialize = function(serializeAll) { var ret = { name: this.name, parentname: this.parentname, type: this.type, properties: {}, things: {} }; var numprops = 0, numthings = 0; for (var k in this._thingdef.properties) { var propdef = this._thingdef.properties[k]; var propval = this.get(k); if (propval !== null) { switch (propdef.type) { case 'vector2': case 'vector3': case 'vector4': propval = propval.toArray(); for (var i = 0; i < propval.length; i++) propval[i] = +propval[i]; // FIXME - force to float break; case 'quaternion': propval = [propval.x, propval.y, propval.z, propval.w]; break; case 'texture': propval = propval.sourceFile; break; /* case 'color': propval = propval.getHexString(); break; */ case 'component': var ref = propval; propval = [ ref.type, ref.id ]; break; } try { if (propval !== null && !elation.utils.isIdentical(propval, propdef.default)) { //elation.utils.arrayset(ret.properties, k, propval); ret.properties[k] = propval; numprops++; } } catch (e) { console.log("Error serializing property: " + k, this, e); } } } if (numprops == 0) delete ret.properties; for (var k in this.children) { if (this.children[k].properties) { if (!serializeAll) { if (this.children[k].properties.persist) { ret.things[k] = this.children[k].serialize(); numthings++; } } else { ret.things[k] = this.children[k].serialize(); numthings++; } } else { console.log('huh what', k, this.children[k]); } } if (numthings == 0) delete ret.things; return ret; } //this.thing_add = function(ev) { // elation.events.fire({type: 'thing_add', element: this, data: ev.data}); //} /* this.createCamera = function(offset, rotation) { //var viewsize = this.engine.systems.render.views['main'].size; var viewsize = [640, 480]; // FIXME - hardcoded hack! this.cameras.push(new THREE.PerspectiveCamera(50, viewsize[0] / viewsize[1], .01, 1e15)); this.camera = this.cameras[this.cameras.length-1]; if (offset) { this.camera.position.copy(offset) } if (rotation) { //this.camera.eulerOrder = "YZX"; this.camera.rotation.copy(rotation); } this.objects['3d'].add(this.camera); } */ // Sound functions this.playSound = function(sound, volume, position, velocity) { if (this.sounds[sound] && this.engine.systems.sound.enabled) { this.updateSound(sound, volume, position, velocity); this.sounds[sound].play(); } } this.stopSound = function(sound) { if (this.sounds[sound] && this.sounds[sound].playing) { this.sounds[sound].stop(); } } this.updateSound = function(sound, volume, position, velocity) { if (this.sounds[sound]) { if (!volume) volume = 100; this.sounds[sound].setVolume(volume); if (position) { this.sounds[sound].setPan([position.x, position.y, position.z], (velocity ? [velocity.x, velocity.y, velocity.z] : [0,0,0])); } } } this.addTag = function(tag) { if (!this.hasTag(tag)) { this.tags.push(tag); return true; } return false; } this.hasTag = function(tag) { return (this.tags.indexOf(tag) !== -1); } this.removeTag = function(tag) { var idx = this.tags.indexOf(tag); if (idx !== -1) { this.tags.splice(idx, 1); return true; } return false; } this.getPlayer = function() { console.log('player id:', this.get('player_id')); return this.get('player_id'); } this.addPart = function(name, part) { if (this.parts[name] === undefined) { this.parts[name] = part; var type = part.componentname; if (this.parttypes[type] === undefined) { this.parttypes[type] = []; } this.parttypes[type].push(part); return true; } return false; } this.hasPart = function(name) { return (this.parts[name] !== undefined); } this.hasPartOfType = function(type) { return (this.parttypes[type] !== undefined && this.parttypes[type].length > 0); } this.getPart = function(name) { return this.parts[name]; } this.getPartsByType = function(type) { return this.parttypes[type] || []; } this.getThingByObject = function(obj) { while (obj) { if (obj.userData.thing) return obj.userData.thing; obj = obj.parent; } return null; } this.getObjectsByTag = function(tag) { } this.getChildren = function(collection) { if (typeof collection == 'undefined') collection = []; for (var k in this.children) { collection.push(this.children[k]); this.children[k].getChildren(collection); } return collection; } this.getChildrenByProperty = function(key, value, collection) { if (typeof collection == 'undefined') collection = []; for (var k in this.children) { if (this.children[k][key] === value) { collection.push(this.children[k]); } this.children[k].getChildrenByProperty(key, value, collection); } return collection; } this.getChildrenByPlayer = function(player, collection) { if (typeof collection == 'undefined') collection = []; for (var k in this.children) { if (this.children[k].getPlayer() == player) { collection.push(this.children[k]); } this.children[k].getChildrenByPlayer(player, collection); } return collection; } this.getChildrenByTag = function(tag, collection) { if (typeof collection == 'undefined') collection = []; for (var k in this.children) { if (this.children[k].hasTag(tag)) { collection.push(this.children[k]); } this.children[k].getChildrenByTag(tag, collection); } return collection; } this.getChildrenByType = function(type, collection) { if (typeof collection == 'undefined') collection = []; for (var k in this.children) { if (this.children[k].type == type) { collection.push(this.children[k]); } this.children[k].getChildrenByType(type, collection); } return collection; } this.distanceTo = (function() { // closure scratch variables var _v1 = new THREE.Vector3(), _v2 = new THREE.Vector3(); return function(obj) { var mypos = this.localToWorld(_v1.set(0,0,0)); if (obj && obj.localToWorld) { return mypos.distanceTo(obj.localToWorld(_v2.set(0,0,0))); } else if (obj instanceof THREE.Vector3) { return mypos.distanceTo(obj); } return Infinity; } })(); this.canUse = function(object) { return false; } this.thing_use_activate = function(ev) { var player = ev.data; var canuse = this.canUse(player); if (canuse && canuse.action) { canuse.action(player); } } this.getBoundingSphere = function() { // Iterate over all children and expand our bounding sphere to encompass them. // This gives us the total size of the whole thing var bounds = new THREE.Sphere(); var worldpos = this.localToWorld(new THREE.Vector3()); var childworldpos = new THREE.Vector3(); this.objects['3d'].traverse(function(n) { childworldpos.set(0,0,0).applyMatrix4(n.matrixWorld); if (n.boundingSphere) { var newradius = worldpos.distanceTo(childworldpos) + n.boundingSphere.radius; if (newradius > bounds.radius) { bounds.radius = newradius; } } }); return bounds; } this.getBoundingBox = function() { // Iterate over all children and expand our bounding box to encompass them. // This gives us the total size of the whole thing var bounds = new THREE.Box3(); bounds.setFromObject(this.objects['3d']); for (var k in this.children) { var childbounds = this.children[k].getBoundingBox(); bounds.expandByPoint(bounds.min); bounds.expandByPoint(bounds.max); } return bounds; } }); });
Removed MeshFaceMaterial references
scripts/things/generic.js
Removed MeshFaceMaterial references
<ide><path>cripts/things/generic.js <ide> case 'lambert': <ide> material = new THREE.MeshLambertMaterial(materialparams); <ide> break; <del> case 'face': <del> material = new THREE.MeshFaceMaterial(); <del> break; <ide> case 'depth': <ide> material = new THREE.MeshDepthMaterial(); <ide> break; <ide> this.processJSON = function(geometry, materials) { <ide> geometry.computeFaceNormals(); <ide> geometry.computeVertexNormals(); <del> var mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials)); <add> var mesh = new THREE.Mesh(geometry, materials); <ide> mesh.doubleSided = false; <ide> mesh.castShadow = false; <ide> mesh.receiveShadow = false; <ide> var mapnames = ['map', 'lightMap', 'bumpMap', 'normalMap', 'specularMap', 'envMap']; <ide> object.traverse(function(n) { <ide> if (n instanceof THREE.Mesh) { <del> var materials = [n.material]; <del> if (n.material instanceof THREE.MeshFaceMaterial) { <del> materials = n.material.materials; <add> var materials = n.material; <add> if (!elation.utils.isArray(n.material)) { <add> materials = [n.material]; <ide> } <ide> <ide> for (var materialidx = 0; materialidx < materials.length; materialidx++) {
Java
mit
c7419ccbdbdf504e45dee8a2c4bf2a0f8234b8e9
0
TakWolf/GB2260.java
package com.takwolf.gb2260; import java.util.regex.Pattern; /** * 五级划分对应的英文分别为: * 省 Province,市 Prefecture,县 County,乡 Township,村 Village */ public final class Division { public enum Level { PROVINCE(1), PREFECTURE(2), COUNTY(3); private final int value; Level(int value) { this.value = value; } protected int getValue() { return value; } } private final GB2260 gb2260; private final String code; private final String name; private final Level level; protected Division(GB2260 gb2260, String code, String name) { this.gb2260 = gb2260; this.code = code; this.name = name; if (Pattern.matches("^\\d{2}0{4}$", code)) { level = Level.PROVINCE; } else if (Pattern.matches("^\\d{4}0{2}$", code)) { level = Level.PREFECTURE; } else { level = Level.COUNTY; } } public String getCode() { return code; } public String getName() { return name; } public Revision getRevision() { return gb2260.getRevision(); } public Level getLevel() { return level; } public boolean isProvince() { return level == Level.PROVINCE; } public boolean isPrefecture() { return level == Level.PREFECTURE; } public boolean isCounty() { return level == Level.COUNTY; } public Division getProvince() { if (level.getValue() > Level.PROVINCE.getValue()) { return gb2260.getDivision(code.substring(0, 2) + "0000"); } else { return null; } } public Division getPrefecture() { if (level.getValue() > Level.PREFECTURE.getValue()) { return gb2260.getDivision(code.substring(0, 4) + "00"); } else { return null; } } public Division getParent() { switch (level) { case COUNTY: return getPrefecture(); case PREFECTURE: return getProvince(); default: return null; } } }
gb2260/src/main/java/com/takwolf/gb2260/Division.java
package com.takwolf.gb2260; import java.util.regex.Pattern; /** * 五级划分对应的英文分别为: * 省 Province,市 Prefecture,县 County,乡 Township,村 Village */ public final class Division { public enum Level { PROVINCE, PREFECTURE, COUNTY } private final GB2260 gb2260; private final String code; private final String name; private final Level level; protected Division(GB2260 gb2260, String code, String name) { this.gb2260 = gb2260; this.code = code; this.name = name; if (Pattern.matches("^\\d{2}0{4}$", code)) { level = Level.PROVINCE; } else if (Pattern.matches("^\\d{4}0{2}$", code)) { level = Level.PREFECTURE; } else { level = Level.COUNTY; } } public String getCode() { return code; } public String getName() { return name; } public Revision getRevision() { return gb2260.getRevision(); } public Level getLevel() { return level; } public boolean isProvince() { return level == Level.PROVINCE; } public boolean isPrefecture() { return level == Level.PREFECTURE; } public boolean isCounty() { return level == Level.COUNTY; } }
添加获取父类结点接口
gb2260/src/main/java/com/takwolf/gb2260/Division.java
添加获取父类结点接口
<ide><path>b2260/src/main/java/com/takwolf/gb2260/Division.java <ide> public final class Division { <ide> <ide> public enum Level { <del> PROVINCE, PREFECTURE, COUNTY <add> <add> PROVINCE(1), <add> <add> PREFECTURE(2), <add> <add> COUNTY(3); <add> <add> private final int value; <add> <add> Level(int value) { <add> this.value = value; <add> } <add> <add> protected int getValue() { <add> return value; <add> } <add> <ide> } <ide> <ide> private final GB2260 gb2260; <ide> return level == Level.COUNTY; <ide> } <ide> <add> public Division getProvince() { <add> if (level.getValue() > Level.PROVINCE.getValue()) { <add> return gb2260.getDivision(code.substring(0, 2) + "0000"); <add> } else { <add> return null; <add> } <add> } <add> <add> public Division getPrefecture() { <add> if (level.getValue() > Level.PREFECTURE.getValue()) { <add> return gb2260.getDivision(code.substring(0, 4) + "00"); <add> } else { <add> return null; <add> } <add> } <add> <add> public Division getParent() { <add> switch (level) { <add> case COUNTY: <add> return getPrefecture(); <add> case PREFECTURE: <add> return getProvince(); <add> default: <add> return null; <add> } <add> } <add> <ide> }
Java
bsd-3-clause
96b2bd62845d93f4ee7fb6a1aaa63294afad4a30
0
nka11/jintn3270
package com.sf.jintn3270; import javax.swing.event.EventListenerList; import com.sf.jintn3270.event.TerminalEvent; import com.sf.jintn3270.event.TerminalEventListener; /** * A TerminalModel is where telnet stream data goes to be rendered by a view. * A model maintains a list of listeners, which are notified when changes to the * buffer occur. It also tracks a CursorPosition, which is used when printing * data into the buffer. */ public abstract class TerminalModel { TerminalCharacter[][] buffer; CharacterFactory charFact; CursorPosition cursor; protected EventListenerList listenerList = new EventListenerList(); /** * Constructs a TerminalModel with the given number of rows and cols. * The model will use the given CharacterFactory to render print() * invocations into the Buffer. */ protected TerminalModel(int rows, int cols, CharacterFactory charFact) { this.charFact = charFact; cursor = new CursorPosition(); initializeBuffer(rows, cols); } /** * Initializes the buffer by allocate a new buffer array, then filling * the array with the character mapped to byte 0x00 */ protected void initializeBuffer(int rows, int cols) { buffer = new TerminalCharacter[rows][cols]; cursor.row = 0; cursor.column = 0; byte b = 0; for (int row = 0; row < buffer.length; row++) { for (int col = 0; col < buffer[row].length; col++) { buffer[row][col] = charFact.get(b); } } fire(new TerminalEvent(this, TerminalEvent.BUFFER_CHANGED)); } /** * Adds the given Listener */ public void addTerminalEventListener(TerminalEventListener listener) { listenerList.add(TerminalEventListener.class, listener); } /** * Removes the given Listener */ public void removeTerminalEventListener(TerminalEventListener listener) { listenerList.remove(TerminalEventListener.class, listener); } /** * Erase the last character printed. This moved the cursor to the left, * THEN sets the character to 0x00. * * This would be like a 'backspace'. */ public void eraseChar() { CursorPosition before = (CursorPosition)cursor.clone(); cursor.left(); buffer[cursor.row()][cursor.column()] = charFact.get((byte)0); fire(TerminalEvent.BUFFER_UPDATE, (CursorPosition)cursor.clone(), before); } /** * Erases the last line printed (Based on cursor position). This sets the * entire line to 0x00, then moves the cursor to column 0. */ public void eraseLine() { CursorPosition before = (CursorPosition)cursor.clone(); before.column = buffer[0].length - 1; for (int col = 0; col < buffer[cursor.row()].length; col++) { buffer[cursor.row()][col] = charFact.get((byte)0); } cursor.column = 0; fire(TerminalEvent.BUFFER_UPDATE, (CursorPosition)cursor.clone(), before); } /** * Gets the current CursorPosition used by this TerminalModel. */ public CursorPosition getCursor() { return cursor; } /** * Method that sets the buffer data at the current cursor position, then * advances the cursor position (by calling cursor.right()) one position. */ protected void print(TerminalCharacter ch) { boolean display = true; if (ch.getDisplay() == '\n') { cursor.down(); display = false; } if (ch.getDisplay() == '\r') { cursor.column = 0; display = false; } if (display) { buffer[cursor.row()][cursor.column()] = ch; cursor.right(); } } /** * Prints the given byte at the current cursor location. */ public void print(byte b) { CursorPosition before = (CursorPosition)cursor.clone(); print(charFact.get(b)); fire(TerminalEvent.BUFFER_UPDATE, before, cursor); } /** * Prints the given array of bytes, starting at offset, up to length, at * the current cursor location. */ public void print(byte[] bytes, int offset, int length) { CursorPosition before = (CursorPosition)cursor.clone(); for (int pos = offset; pos < (offset + length); pos++) { print(charFact.get(bytes[pos])); } fire(TerminalEvent.BUFFER_UPDATE, before, cursor); } /** * Prints the given array of bytes at the current cursor location. */ public void print(byte[] bytes) { print(bytes, 0, bytes.length); } /** * Fire the given TerminalEvent to all registered listeners */ protected void fire(TerminalEvent evt) { Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == TerminalEventListener.class) { ((TerminalEventListener)listeners[i + 1]).terminalChanged(evt); } } } /** * Create and fire a new TerminalEvent to all registered listeners */ protected void fire(int id, CursorPosition start, CursorPosition end) { this.fire(new TerminalEvent(this, id, start, end)); } /** * CursorPosition is closely tied to the buffer. */ public class CursorPosition implements Cloneable { private int row; private int column; public CursorPosition() { this.row = 0; this.column = 0; } // Copy Constructor CursorPosition(int row, int column) { this.row = row; this.column = column; } public void moveTo(int row, int column) { CursorPosition before = new CursorPosition(row, column); this.row = row; this.column = column; fire(TerminalEvent.CURSOR_MOVED, before, this); } public int row() { return row; } public int column() { return column; } /** * Gets the position as if it were being used to index a linear buffer. */ public int getPosition() { return (row * buffer[0].length) + column; } public void left() { column--; if (column < 0) { column = buffer[0].length - 1; up(); } } public void up() { row--; if (row < 0) { row = buffer.length - 1; } } public void right() { column++; if (column >= buffer[0].length) { column = 0; down(); } } public void down() { row++; if (row > buffer.length) { row = 0; } } /** * Implements cloneable. */ public Object clone() { return new CursorPosition(row, column); } } }
src/com/sf/jintn3270/TerminalModel.java
package com.sf.jintn3270; import javax.swing.event.EventListenerList; import com.sf.jintn3270.event.TerminalEvent; import com.sf.jintn3270.event.TerminalEventListener; /** * A TerminalModel is where telnet stream data goes to be rendered by a view. * A model maintains a list of listeners, which are notified when changes to the * buffer occur. It also tracks a CursorPosition, which is used when printing * data into the buffer. */ public abstract class TerminalModel { TerminalCharacter[][] buffer; CharacterFactory charFact; CursorPosition cursor; protected EventListenerList listenerList = new EventListenerList(); /** * Constructs a TerminalModel with the given number of rows and cols. * The model will use the given CharacterFactory to render print() * invocations into the Buffer. */ protected TerminalModel(int rows, int cols, CharacterFactory charFact) { this.charFact = charFact; cursor = new CursorPosition(); initializeBuffer(rows, cols); } /** * Initializes the buffer by allocate a new buffer array, then filling * the array with the character mapped to byte 0x00 */ protected void initializeBuffer(int rows, int cols) { buffer = new TerminalCharacter[rows][cols]; cursor.row = 0; cursor.column = 0; byte b = 0; for (int row = 0; row < buffer.length; row++) { for (int col = 0; col < buffer[row].length; col++) { buffer[row][col] = charFact.get(b); } } fire(new TerminalEvent(this, TerminalEvent.BUFFER_CHANGED)); } /** * Adds the given Listener */ public void addTerminalEventListener(TerminalEventListener listener) { listenerList.add(TerminalEventListener.class, listener); } /** * Removes the given Listener */ public void removeTerminalEventListener(TerminalEventListener listener) { listenerList.remove(TerminalEventListener.class, listener); } /** * Erase the last character printed. This moved the cursor to the left, * THEN sets the character to 0x00. * * This would be like a 'backspace'. */ public void eraseChar() { CursorPosition before = (CursorPosition)cursor.clone(); cursor.left(); buffer[cursor.row()][cursor.column()] = charFact.get((byte)0); fire(TerminalEvent.BUFFER_UPDATE, (CursorPosition)cursor.clone(), before); } /** * Erases the last line printed (Based on cursor position). This sets the * entire line to 0x00, then moves the cursor to column 0. */ public void eraseLine() { CursorPosition before = (CursorPosition)cursor.clone(); before.column = buffer[0].length - 1; for (int col = 0; col < buffer[cursor.row()].length; col++) { buffer[cursor.row()][col] = charFact.get((byte)0); } cursor.column = 0; fire(TerminalEvent.BUFFER_UPDATE, (CursorPosition)cursor.clone(), before); } /** * Gets the current CursorPosition used by this TerminalModel. */ public CursorPosition getCursor() { return cursor; } /** * Method that sets the buffer data at the current cursor position, then * advances the cursor position (by calling cursor.right()) one position. */ protected void print(TerminalCharacter ch) { boolean display = true; if (ch.getDisplay() == '\n') { cursor.down(); display = false; } if (ch.getDisplay() == '\r') { cursor.column = 0; display = false; } if (display) { buffer[cursor.row()][cursor.column()] = ch; cursor.right(); } } /** * Prints the given byte at the current cursor location. */ public void print(byte b) { CursorPosition before = (CursorPosition)cursor.clone(); print(charFact.get(b)); fire(TerminalEvent.BUFFER_UPDATE, before, cursor); } /** * Prints the given array of bytes, starting at offset, up to length, at * the current cursor location. */ public void print(byte[] bytes, int offset, int length) { CursorPosition before = (CursorPosition)cursor.clone(); for (int pos = offset; pos < (offset + length); pos++) { print(charFact.get(bytes[pos])); } fire(TerminalEvent.BUFFER_UPDATE, before, cursor); } /** * Prints the given array of bytes at the current cursor location. */ public void print(byte[] bytes) { print(bytes, 0, bytes.length); } protected void fire(TerminalEvent evt) { // TODO: Actually fire the event! Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == TerminalEventListener.class) { ((TerminalEventListener)listeners[i + 1]).terminalChanged(evt); } } } protected void fire(int id, CursorPosition start, CursorPosition end) { this.fire(new TerminalEvent(this, id, start, end)); } /** * CursorPosition is closely tied to the buffer. */ public class CursorPosition implements Cloneable { private int row; private int column; public CursorPosition() { this.row = 0; this.column = 0; } // Copy Constructor CursorPosition(int row, int column) { this.row = row; this.column = column; } public void moveTo(int row, int column) { CursorPosition before = new CursorPosition(row, column); this.row = row; this.column = column; fire(TerminalEvent.CURSOR_MOVED, before, this); } public int row() { return row; } public int column() { return column; } /** * Gets the position as if it were being used to index a linear buffer. */ public int getPosition() { return (row * buffer[0].length) + column; } public void left() { column--; if (column < 0) { column = buffer[0].length - 1; up(); } } public void up() { row--; if (row < 0) { row = buffer.length - 1; } } public void right() { column++; if (column >= buffer[0].length) { column = 0; down(); } } public void down() { row++; if (row > buffer.length) { row = 0; } } /** * Implements cloneable. */ public Object clone() { return new CursorPosition(row, column); } } }
Minor clean-up. git-svn-id: f76f0d361b8045537d852970971daaa7b3f7adae@35 d6bd4e80-8031-4e1d-bd39-93c407d940fc
src/com/sf/jintn3270/TerminalModel.java
Minor clean-up.
<ide><path>rc/com/sf/jintn3270/TerminalModel.java <ide> } <ide> <ide> <add> /** <add> * Fire the given TerminalEvent to all registered listeners <add> */ <ide> protected void fire(TerminalEvent evt) { <del> // TODO: Actually fire the event! <ide> Object[] listeners = listenerList.getListenerList(); <ide> for (int i = listeners.length - 2; i >= 0; i -= 2) { <ide> if (listeners[i] == TerminalEventListener.class) { <ide> } <ide> } <ide> <add> /** <add> * Create and fire a new TerminalEvent to all registered listeners <add> */ <ide> protected void fire(int id, CursorPosition start, CursorPosition end) { <ide> this.fire(new TerminalEvent(this, id, start, end)); <ide> }
JavaScript
mit
041f7fe301331a2fde9913b1c58cca513357558e
0
janoside/btc-rpc-explorer
#!/usr/bin/env node "use strict"; const os = require('os'); const path = require('path'); const dotenv = require("dotenv"); const fs = require('fs'); const debug = require("debug"); // start with this, we will update after loading any .env files const debugDefaultCategories = "btcexp:app,btcexp:error,btcexp:errorVerbose"; debug.enable(debugDefaultCategories); const debugLog = debug("btcexp:app"); const debugErrorLog = debug("btcexp:error"); const debugPerfLog = debug("btcexp:actionPerformace"); const debugAccessLog = debug("btcexp:access"); const configPaths = [ path.join(os.homedir(), ".config", "btc-rpc-explorer.env"), path.join("/etc", "btc-rpc-explorer", ".env"), path.join(process.cwd(), ".env"), ]; debugLog("Searching for config files..."); let configFileLoaded = false; configPaths.forEach(path => { if (fs.existsSync(path)) { debugLog(`Config file found at ${path}, loading...`); // this does not override any existing env vars dotenv.config({ path }); // we manually set env.DEBUG above (so that app-launch log output is good), // so if it's defined in the .env file, we need to manually override const config = dotenv.parse(fs.readFileSync(path)); if (config.DEBUG) { process.env.DEBUG = config.DEBUG; } configFileLoaded = true; } else { debugLog(`Config file not found at ${path}, continuing...`); } }); if (!configFileLoaded) { debugLog("No config files found. Using all defaults."); if (!process.env.NODE_ENV) { process.env.NODE_ENV = "production"; } } // debug module is already loaded by the time we do dotenv.config // so refresh the status of DEBUG env var debug.enable(process.env.DEBUG || debugDefaultCategories); global.cacheStats = {}; const express = require('express'); const favicon = require('serve-favicon'); const logger = require('morgan'); const cookieParser = require('cookie-parser'); const bodyParser = require('body-parser'); const session = require("express-session"); const csurf = require("csurf"); const config = require("./app/config.js"); const simpleGit = require('simple-git'); const utils = require("./app/utils.js"); const moment = require("moment"); const Decimal = require('decimal.js'); const bitcoinCore = require("btc-rpc-client"); const pug = require("pug"); const momentDurationFormat = require("moment-duration-format"); const coreApi = require("./app/api/coreApi.js"); const rpcApi = require("./app/api/rpcApi.js"); const coins = require("./app/coins.js"); const axios = require("axios"); const qrcode = require("qrcode"); const addressApi = require("./app/api/addressApi.js"); const electrumAddressApi = require("./app/api/electrumAddressApi.js"); const appStats = require("./app/appStats.js"); const btcQuotes = require("./app/coins/btcQuotes.js"); const btcHolidays = require("./app/coins/btcHolidays.js"); const auth = require('./app/auth.js'); const sso = require('./app/sso.js'); const markdown = require("markdown-it")(); const v8 = require("v8"); var compression = require("compression"); const appUtils = require("@janoside/app-utils"); const s3Utils = appUtils.s3Utils; let cdnS3Bucket = null; if (config.cdn.active) { cdnS3Bucket = s3Utils.createBucket(config.cdn.s3Bucket, config.cdn.s3BucketPath); } require("./app/currencies.js"); const package_json = require('./package.json'); global.appVersion = package_json.version; global.cacheId = global.appVersion; debugLog(`Default cacheId '${global.cacheId}'`); global.btcNodeSemver = "0.0.0"; const baseActionsRouter = require('./routes/baseRouter.js'); const internalApiActionsRouter = require('./routes/internalApiRouter.js'); const apiActionsRouter = require('./routes/apiRouter.js'); const snippetActionsRouter = require('./routes/snippetRouter.js'); const adminActionsRouter = require('./routes/adminRouter.js'); const testActionsRouter = require('./routes/testRouter.js'); const expressApp = express(); const statTracker = require("./app/statTracker.js"); const statsProcessFunction = (name, stats) => { appStats.trackAppStats(name, stats); if (process.env.STATS_API_URL) { const data = Object.assign({}, stats); data.name = name; axios.post(process.env.STATS_API_URL, data) .then(res => { /*console.log(res.data);*/ }) .catch(error => { utils.logError("38974wrg9w7dsgfe", error); }); } }; const processStatsInterval = setInterval(() => { statTracker.processAndReset( statsProcessFunction, statsProcessFunction, statsProcessFunction); }, process.env.STATS_PROCESS_INTERVAL || (5 * 60 * 1000)); // Don't keep Node.js process up processStatsInterval.unref(); const systemMonitor = require("./app/systemMonitor.js"); const normalizeActions = require("./app/normalizeActions.js"); expressApp.use(require("./app/actionPerformanceMonitor.js")(statTracker, { ignoredEndsWithActions: /\.js|\.css|\.svg|\.png|\.woff2/, ignoredStartsWithActions: `${config.baseUrl}snippet`, normalizeAction: (action) => { return normalizeActions(config.baseUrl, action); }, })); // view engine setup expressApp.set('views', path.join(__dirname, 'views')); // ref: https://blog.stigok.com/post/disable-pug-debug-output-with-expressjs-web-app expressApp.engine('pug', (path, options, fn) => { options.debug = false; return pug.__express.call(null, path, options, fn); }); expressApp.set('view engine', 'pug'); if (process.env.NODE_ENV != "local") { // enable view cache regardless of env (development/production) // ref: https://pugjs.org/api/express.html debugLog("Enabling view caching (performance will be improved but template edits will not be reflected)") expressApp.enable('view cache'); } expressApp.use(cookieParser()); expressApp.disable('x-powered-by'); if (process.env.BTCEXP_BASIC_AUTH_PASSWORD) { // basic http authentication expressApp.use(auth(process.env.BTCEXP_BASIC_AUTH_PASSWORD)); } else if (process.env.BTCEXP_SSO_TOKEN_FILE) { // sso authentication expressApp.use(sso(process.env.BTCEXP_SSO_TOKEN_FILE, process.env.BTCEXP_SSO_LOGIN_REDIRECT_URL)); } // uncomment after placing your favicon in /public //expressApp.use(favicon(__dirname + '/public/favicon.ico')); //expressApp.use(logger('dev')); expressApp.use(bodyParser.json()); expressApp.use(bodyParser.urlencoded({ extended: false })); expressApp.use(session({ secret: config.cookieSecret, resave: false, saveUninitialized: false })); expressApp.use(compression()); expressApp.use(config.baseUrl, express.static(path.join(__dirname, 'public'), { maxAge: 30 * 24 * 60 * 60 * 1000 })); if (config.baseUrl != '/') { expressApp.get('/', (req, res) => res.redirect(config.baseUrl)); } // if a CDN is configured, these assets will be uploaded at launch, then referenced from there const cdnItems = [ [`style/dark.css`, `text/css`, "utf8"], [`style/light.css`, `text/css`, "utf8"], [`style/highlight.min.css`, `text/css`, "utf8"], [`style/dataTables.bootstrap4.min.css`, `text/css`, "utf8"], [`style/bootstrap-icons.css`, `text/css`, "utf8"], [`js/bootstrap.bundle.min.js`, `text/javascript`, "utf8"], [`js/chart.min.js`, `text/javascript`, "utf8"], [`js/jquery.min.js`, `text/javascript`, "utf8"], [`js/site.js`, `text/javascript`, "utf8"], [`js/highlight.pack.js`, `text/javascript`, "utf8"], [`js/chartjs-adapter-moment.min.js`, `text/javascript`, "utf8"], [`js/jquery.dataTables.min.js`, `text/javascript`, "utf8"], [`js/dataTables.bootstrap4.min.js`, `text/javascript`, "utf8"], [`js/moment.min.js`, `text/javascript`, "utf8"], [`js/sentry.min.js`, `text/javascript`, "utf8"], [`js/decimal.js`, `text/javascript`, "utf8"], [`img/network-mainnet/logo.svg`, `image/svg+xml`, "utf8"], [`img/network-mainnet/coin-icon.svg`, `image/svg+xml`, "utf8"], [`img/network-mainnet/apple-touch-icon.png`, `image/png`, "binary"], [`img/network-mainnet/favicon-16x16.png`, `image/png`, "binary"], [`img/network-mainnet/favicon-32x32.png`, `image/png`, "binary"], [`img/network-testnet/logo.svg`, `image/svg+xml`, "utf8"], [`img/network-testnet/coin-icon.svg`, `image/svg+xml`, "utf8"], [`img/network-signet/logo.svg`, `image/svg+xml`, "utf8"], [`img/network-signet/coin-icon.svg`, `image/svg+xml`, "utf8"], [`img/network-regtest/logo.svg`, `image/svg+xml`, "utf8"], [`img/network-regtest/coin-icon.svg`, `image/svg+xml`, "utf8"], [`img/network-mainnet/favicon.ico`, `image/x-icon`, "binary"], [`img/network-testnet/favicon.ico`, `image/x-icon`, "binary"], [`img/network-signet/favicon.ico`, `image/x-icon`, "binary"], [`img/network-regtest/favicon.ico`, `image/x-icon`, "binary"], [`font/bootstrap-icons.woff`, `font/woff`, "binary"], [`font/bootstrap-icons.woff2`, `font/woff2`, "binary"], [`leaflet/leaflet.js`, `text/javascript`, "utf8"], [`leaflet/leaflet.css`, `text/css`, "utf8"], ]; const cdnFilepathMap = {}; cdnItems.forEach(item => { cdnFilepathMap[item[0]] = true; }); process.on("unhandledRejection", (reason, p) => { debugLog("Unhandled Rejection at: Promise", p, "reason:", reason, "stack:", (reason != null ? reason.stack : "null")); }); function loadMiningPoolConfigs() { debugLog("Loading mining pools config"); global.miningPoolsConfigs = []; var miningPoolsConfigDir = path.join(__dirname, "public", "txt", "mining-pools-configs", global.coinConfig.ticker); fs.readdir(miningPoolsConfigDir, function(err, files) { if (err) { utils.logError("3ufhwehe", err, {configDir:miningPoolsConfigDir, desc:"Unable to scan directory"}); return; } files.forEach(function(file) { var filepath = path.join(miningPoolsConfigDir, file); var contents = fs.readFileSync(filepath, 'utf8'); global.miningPoolsConfigs.push(JSON.parse(contents)); }); for (var i = 0; i < global.miningPoolsConfigs.length; i++) { for (var x in global.miningPoolsConfigs[i].payout_addresses) { if (global.miningPoolsConfigs[i].payout_addresses.hasOwnProperty(x)) { global.specialAddresses[x] = {type:"minerPayout", minerInfo:global.miningPoolsConfigs[i].payout_addresses[x]}; } } } }); } async function getSourcecodeProjectMetadata() { var options = { url: "https://api.github.com/repos/janoside/btc-rpc-explorer", headers: { 'User-Agent': 'request' } }; try { const response = await axios(options); global.sourcecodeProjectMetadata = response.data; } catch (err) { utils.logError("3208fh3ew7eghfg", err); } } function loadChangelog() { var filename = "CHANGELOG.md"; fs.readFile(path.join(__dirname, filename), 'utf8', function(err, data) { if (err) { utils.logError("2379gsd7sgd334", err); } else { global.changelogMarkdown = data; } }); var filename = "CHANGELOG-API.md"; fs.readFile(path.join(__dirname, filename), 'utf8', function(err, data) { if (err) { utils.logError("ouqhuwey723", err); } else { global.apiChangelogMarkdown = data; } }); } function loadHistoricalDataForChain(chain) { debugLog(`Loading historical data for chain=${chain}`); if (global.coinConfig.historicalData) { global.coinConfig.historicalData.forEach(function(item) { if (item.chain == chain) { if (item.type == "blockheight") { global.specialBlocks[item.blockHash] = item; } else if (item.type == "tx") { global.specialTransactions[item.txid] = item; } else if (item.type == "address" || item.address) { global.specialAddresses[item.address] = {type:"fun", addressInfo:item}; } } }); } } function loadHolidays(chain) { debugLog(`Loading holiday data`); global.btcHolidays = btcHolidays; global.btcHolidays.byDay = {}; global.btcHolidays.sortedDays = []; global.btcHolidays.sortedItems = [...btcHolidays.items]; global.btcHolidays.sortedItems.sort((a, b) => a.date.localeCompare(b.date)); global.btcHolidays.items.forEach(function(item) { let day = item.date.substring(5); if (!global.btcHolidays.sortedDays.includes(day)) { global.btcHolidays.sortedDays.push(day); global.btcHolidays.sortedDays.sort(); } if (global.btcHolidays.byDay[day] == undefined) { global.btcHolidays.byDay[day] = []; } global.btcHolidays.byDay[day].push(item); }); } function verifyRpcConnection() { if (!global.activeBlockchain) { debugLog(`Verifying RPC connection...`); // normally in application code we target coreApi, but here we're trying to // verify the RPC connection so we target rpcApi directly and include // the second parameter "verifyingConnection=true", to bypass a // fail-if-were-not-connected check Promise.all([ rpcApi.getRpcData("getnetworkinfo", true), rpcApi.getRpcData("getblockchaininfo", true), ]).then(([ getnetworkinfo, getblockchaininfo ]) => { global.activeBlockchain = getblockchaininfo.chain; // we've verified rpc connection, no need to keep trying clearInterval(global.verifyRpcConnectionIntervalId); onRpcConnectionVerified(getnetworkinfo, getblockchaininfo); }).catch(function(err) { utils.logError("32ugegdfsde", err); }); } } async function onRpcConnectionVerified(getnetworkinfo, getblockchaininfo) { // localservicenames introduced in 0.19 var services = getnetworkinfo.localservicesnames ? ("[" + getnetworkinfo.localservicesnames.join(", ") + "]") : getnetworkinfo.localservices; global.rpcConnected = true; global.getnetworkinfo = getnetworkinfo; if (getblockchaininfo.pruned) { global.prunedBlockchain = true; global.pruneHeight = getblockchaininfo.pruneheight; } var bitcoinCoreVersionRegex = /^.*\/Satoshi\:(.*)\/.*$/; var match = bitcoinCoreVersionRegex.exec(getnetworkinfo.subversion); if (match) { global.btcNodeVersion = match[1]; var semver4PartRegex = /^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/; var semver4PartMatch = semver4PartRegex.exec(global.btcNodeVersion); if (semver4PartMatch) { var p0 = semver4PartMatch[1]; var p1 = semver4PartMatch[2]; var p2 = semver4PartMatch[3]; var p3 = semver4PartMatch[4]; // drop last segment, which usually indicates a bug fix release which is (hopefully) irrelevant for RPC API versioning concerns global.btcNodeSemver = `${p0}.${p1}.${p2}`; } else { var semver3PartRegex = /^([0-9]+)\.([0-9]+)\.([0-9]+)$/; var semver3PartMatch = semver3PartRegex.exec(global.btcNodeVersion); if (semver3PartMatch) { var p0 = semver3PartMatch[1]; var p1 = semver3PartMatch[2]; var p2 = semver3PartMatch[3]; global.btcNodeSemver = `${p0}.${p1}.${p2}`; } else { // short-circuit: force all RPC calls to pass their version checks - this will likely lead to errors / instability / unexpected results global.btcNodeSemver = "1000.1000.0" } } } else { // short-circuit: force all RPC calls to pass their version checks - this will likely lead to errors / instability / unexpected results global.btcNodeSemver = "1000.1000.0" debugErrorLog(`Unable to parse node version string: ${getnetworkinfo.subversion} - RPC versioning will likely be unreliable. Is your node a version of Bitcoin Core?`); } debugLog(`RPC Connected: version=${getnetworkinfo.version} subversion=${getnetworkinfo.subversion}, parsedVersion(used for RPC versioning)=${global.btcNodeSemver}, protocolversion=${getnetworkinfo.protocolversion}, chain=${getblockchaininfo.chain}, services=${services}`); // load historical/fun items for this chain loadHistoricalDataForChain(global.activeBlockchain); loadHolidays(); if (global.activeBlockchain == "main") { loadDifficultyHistory(getblockchaininfo.blocks); // refresh difficulty history periodically // TODO: refresh difficulty history when there's a new block and height % 2016 == 0 setInterval(loadDifficultyHistory, 15 * 60 * 1000); if (global.exchangeRates == null) { utils.refreshExchangeRates(); } // refresh exchange rate periodically setInterval(utils.refreshExchangeRates, 1800000); } // 1d / 7d volume refreshNetworkVolumes(); setInterval(refreshNetworkVolumes, 30 * 60 * 1000); await assessTxindexAvailability(); // UTXO pull refreshUtxoSetSummary(); setInterval(refreshUtxoSetSummary, 30 * 60 * 1000); if (false) { var zmq = require("zeromq"); var sock = zmq.socket("sub"); sock.connect("tcp://192.168.1.1:28333"); console.log("Worker connected to port 28333"); sock.on("message", function(topic, message) { console.log(Buffer.from(topic).toString("ascii") + " - " + Buffer.from(message).toString("hex")); }); //sock.subscribe('rawtx'); } } async function loadDifficultyHistory(tipBlockHeight=null) { if (!tipBlockHeight) { let getblockchaininfo = await coreApi.getBlockchainInfo(); tipBlockHeight = getblockchaininfo.blocks; } if (config.slowDeviceMode) { debugLog("Skipping performance-intensive task: load difficulty history. This is skipped due to the flag 'slowDeviceMode' which defaults to 'true' to protect slow nodes. Set this flag to 'false' to enjoy difficulty history details."); return; } let height = 0; let heights = []; while (height <= tipBlockHeight) { heights.push(height); height += global.coinConfig.difficultyAdjustmentBlockCount; } global.difficultyHistory = await coreApi.getDifficultyByBlockHeights(heights); global.athDifficulty = 0; for (let i = 0; i < heights.length; i++) { if (global.difficultyHistory[`${heights[i]}`].difficulty > global.athDifficulty) { global.athDifficulty = global.difficultyHistory[heights[i]].difficulty; } } debugLog("ATH difficulty: " + global.athDifficulty); } var txindexCheckCount = 0; async function assessTxindexAvailability() { // Here we try to call getindexinfo to assess availability of txindex // However, getindexinfo RPC is only available in v0.21+, so the call // may return an "unsupported" error. If/when it does, we will fall back // to assessing txindex availability by querying a known txid debugLog("txindex check: trying getindexinfo"); try { global.getindexinfo = await coreApi.getIndexInfo(); debugLog(`txindex check: getindexinfo=${JSON.stringify(global.getindexinfo)}`); if (global.getindexinfo.txindex) { // getindexinfo was available, and txindex is also available...easy street global.txindexAvailable = true; debugLog("txindex check: available!"); } else if (global.getindexinfo.minRpcVersionNeeded) { // here we find out that getindexinfo is unavailable on our node because // we're running pre-v0.21, so we fall back to querying a known txid // to assess txindex availability debugLog("txindex check: getindexinfo unavailable, trying txid lookup"); try { // lookup a known TXID as a test for whether txindex is available let knownTx = await coreApi.getRawTransaction(coinConfig.knownTransactionsByNetwork[global.activeBlockchain]); // if we get here without an error being thrown, we know we're able to look up by txid // thus, txindex is available global.txindexAvailable = true; debugLog("txindex check: available! (pre-v0.21)"); } catch (e) { // here we were unable to query by txid, so we believe txindex is unavailable global.txindexAvailable = false; debugLog("txindex check: unavailable"); } } else { // here getindexinfo is available (i.e. we're on v0.21+), but txindex is NOT available global.txindexAvailable = false; debugLog("txindex check: unavailable"); } } catch (e) { utils.logError("o2328ryw8wsde", e); var retryTime = parseInt(Math.min(15 * 60 * 1000, 1000 * 10 * Math.pow(2, txindexCheckCount))); txindexCheckCount++; debugLog(`txindex check: error in rpc getindexinfo; will try again in ${retryTime}ms`); // try again in 5 mins setTimeout(assessTxindexAvailability, retryTime); } } async function refreshUtxoSetSummary() { if (config.slowDeviceMode) { if (!global.getindexinfo || !global.getindexinfo.coinstatsindex) { global.utxoSetSummary = null; global.utxoSetSummaryPending = false; debugLog("Skipping performance-intensive task: fetch UTXO set summary. This is skipped due to the flag 'slowDeviceMode' which defaults to 'true' to protect slow nodes. Set this flag to 'false' to enjoy UTXO set summary details."); return; } } // flag that we're working on calculating UTXO details (to differentiate cases where we don't have the details and we're not going to try computing them) global.utxoSetSummaryPending = true; global.utxoSetSummary = await coreApi.getUtxoSetSummary(true, false); debugLog("Refreshed utxo summary: " + JSON.stringify(global.utxoSetSummary)); } function refreshNetworkVolumes() { if (config.slowDeviceMode) { debugLog("Skipping performance-intensive task: fetch last 24 hrs of blockstats to calculate transaction volume. This is skipped due to the flag 'slowDeviceMode' which defaults to 'true' to protect slow nodes. Set this flag to 'false' to enjoy UTXO set summary details."); return; } var cutoff1d = new Date().getTime() - (60 * 60 * 24 * 1000); var cutoff7d = new Date().getTime() - (60 * 60 * 24 * 7 * 1000); coreApi.getBlockchainInfo().then(function(result) { var promises = []; var blocksPerDay = 144 + 20; // 20 block padding for (var i = 0; i < (blocksPerDay * 1); i++) { if (result.blocks - i >= 0) { promises.push(coreApi.getBlockStatsByHeight(result.blocks - i)); } } var startBlock = result.blocks; var endBlock1d = result.blocks; var endBlock7d = result.blocks; var endBlockTime1d = 0; var endBlockTime7d = 0; Promise.all(promises).then(function(results) { var volume1d = new Decimal(0); var volume7d = new Decimal(0); var blocks1d = 0; var blocks7d = 0; if (results && results.length > 0 && results[0] != null) { for (var i = 0; i < results.length; i++) { if (results[i].time * 1000 > cutoff1d) { volume1d = volume1d.plus(new Decimal(results[i].total_out)); volume1d = volume1d.plus(new Decimal(results[i].subsidy)); volume1d = volume1d.plus(new Decimal(results[i].totalfee)); blocks1d++; endBlock1d = results[i].height; endBlockTime1d = results[i].time; } if (results[i].time * 1000 > cutoff7d) { volume7d = volume7d.plus(new Decimal(results[i].total_out)); volume7d = volume7d.plus(new Decimal(results[i].subsidy)); volume7d = volume7d.plus(new Decimal(results[i].totalfee)); blocks7d++; endBlock7d = results[i].height; endBlockTime7d = results[i].time; } } volume1d = volume1d.dividedBy(coinConfig.baseCurrencyUnit.multiplier); volume7d = volume7d.dividedBy(coinConfig.baseCurrencyUnit.multiplier); global.networkVolume = {d1:{amt:volume1d, blocks:blocks1d, startBlock:startBlock, endBlock:endBlock1d, startTime:results[0].time, endTime:endBlockTime1d}}; debugLog(`Network volume: ${JSON.stringify(global.networkVolume)}`); } else { debugLog("Unable to load network volume, likely due to bitcoind version older than 0.17.0 (the first version to support getblockstats)."); } }); }); } expressApp.onStartup = async () => { global.appStartTime = new Date().getTime(); global.config = config; global.coinConfig = coins[config.coin]; global.coinConfigs = coins; global.specialTransactions = {}; global.specialBlocks = {}; global.specialAddresses = {}; loadChangelog(); global.nodeVersion = process.version; debugLog(`Environment(${expressApp.get("env")}) - Node: ${process.version}, Platform: ${process.platform}, Versions: ${JSON.stringify(process.versions)}`); // dump "startup" heap after 5sec if (false) { (function () { var callback = function() { debugLog("Waited 5 sec after startup, now dumping 'startup' heap..."); const filename = `./heapDumpAtStartup-${Date.now()}.heapsnapshot`; const heapdumpStream = v8.getHeapSnapshot(); const fileStream = fs.createWriteStream(filename); heapdumpStream.pipe(fileStream); debugLog("Heap dump at startup written to", filename); }; setTimeout(callback, 5000); })(); } if (global.sourcecodeVersion == null && fs.existsSync('.git')) { try { let log = await simpleGit(".").log(["-n 1"]); global.sourcecodeVersion = log.all[0].hash.substring(0, 10); global.sourcecodeDate = log.all[0].date.substring(0, "0000-00-00".length); global.cacheId = `${global.sourcecodeDate}-${global.sourcecodeVersion}`; debugLog(`Using sourcecode metadata as cacheId: '${global.cacheId}'`); debugLog(`Starting ${global.coinConfig.ticker} RPC Explorer, v${global.appVersion} (commit: '${global.sourcecodeVersion}', date: ${global.sourcecodeDate}) at http://${config.host}:${config.port}${config.baseUrl}`); } catch (err) { utils.logError("3fehge9ee", err, {desc:"Error accessing git repo"}); global.cacheId = global.appVersion; debugLog(`Error getting sourcecode version, continuing to use default cacheId '${global.cacheId}'`); debugLog(`Starting ${global.coinConfig.ticker} RPC Explorer, v${global.appVersion} (code: unknown commit) at http://${config.host}:${config.port}${config.baseUrl}`); } expressApp.continueStartup(); } else { global.cacheId = global.appVersion; debugLog(`No sourcecode version available, continuing to use default cacheId '${global.cacheId}'`); debugLog(`Starting ${global.coinConfig.ticker} RPC Explorer, v${global.appVersion} at http://${config.host}:${config.port}${config.baseUrl}`); expressApp.continueStartup(); } if (config.cdn.active && config.cdn.s3Bucket) { debugLog(`Configuring CDN assets; uploading ${cdnItems.length} assets to S3...`); const s3Path = (filepath) => { return `${global.cacheId}/${filepath}`; } const uploadedItems = []; const existingItems = []; const errorItems = []; const uploadAssetIfNeeded = async (filepath, contentType, encoding) => { try { let absoluteFilepath = path.join(process.cwd(), "public", filepath); let s3path = s3Path(filepath); const existingAsset = await cdnS3Bucket.get(s3path); if (existingAsset) { existingItems.push(filepath); //debugLog(`Asset ${filepath} already in S3, skipping upload.`); } else { let fileData = fs.readFileSync(absoluteFilepath, {encoding: encoding, flag:'r'}); let fileBuffer = Buffer.from(fileData, encoding); let options = { "ContentType": contentType, "CacheControl": "max-age=315360000" }; await cdnS3Bucket.put(fileBuffer, s3path, options); uploadedItems.push(filepath); //debugLog(`Uploaded ${filepath} to S3.`); } } catch (e) { errorItems.push(filepath); debugErrorLog(`Error uploading asset to S3: ${JSON.stringify(filepath)}`, e); } }; const promises = []; for (let i = 0; i < cdnItems.length; i++) { let item = cdnItems[i]; let filepath = item[0]; let contentType = item[1]; let encoding = item[2]; promises.push(uploadAssetIfNeeded(filepath, contentType, encoding)); } await utils.awaitPromises(promises); debugLog(`Done uploading assets to S3:\n\tAlready present: ${existingItems.length}\n\tNewly uploaded: ${uploadedItems.length}\n\tError items: ${errorItems.length}`); } } expressApp.continueStartup = function() { var rpcCred = config.credentials.rpc; debugLog(`Connecting to RPC node at ${rpcCred.host}:${rpcCred.port}`); var rpcClientProperties = { host: rpcCred.host, port: rpcCred.port, username: rpcCred.username, password: rpcCred.password, timeout: rpcCred.timeout }; global.rpcClient = new bitcoinCore(rpcClientProperties); var rpcClientNoTimeoutProperties = { host: rpcCred.host, port: rpcCred.port, username: rpcCred.username, password: rpcCred.password, timeout: 0 }; global.rpcClientNoTimeout = new bitcoinCore(rpcClientNoTimeoutProperties); // default values - after we connect via RPC, we update these global.txindexAvailable = false; global.prunedBlockchain = false; global.pruneHeight = -1; // keep trying to verify rpc connection until we succeed // note: see verifyRpcConnection() for associated clearInterval() after success verifyRpcConnection(); global.verifyRpcConnectionIntervalId = setInterval(verifyRpcConnection, 30000); if (config.addressApi) { var supportedAddressApis = addressApi.getSupportedAddressApis(); if (!supportedAddressApis.includes(config.addressApi)) { utils.logError("32907ghsd0ge", `Unrecognized value for BTCEXP_ADDRESS_API: '${config.addressApi}'. Valid options are: ${supportedAddressApis}`); } if (config.addressApi == "electrum" || config.addressApi == "electrumx") { if (config.electrumServers && config.electrumServers.length > 0) { electrumAddressApi.connectToServers().then(function() { global.electrumAddressApi = electrumAddressApi; }).catch(function(err) { utils.logError("31207ugf4e0fed", err, {electrumServers:config.electrumServers}); }); } else { utils.logError("327hs0gde", "You must set the 'BTCEXP_ELECTRUM_SERVERS' environment variable when BTCEXP_ADDRESS_API=electrum."); } } } loadMiningPoolConfigs(); if (config.demoSite) { getSourcecodeProjectMetadata(); setInterval(getSourcecodeProjectMetadata, 3600000); } utils.logMemoryUsage(); setInterval(utils.logMemoryUsage, 5000); }; expressApp.use(function(req, res, next) { req.startTime = Date.now(); next(); }); expressApp.use(function(req, res, next) { // make session available in templates res.locals.session = req.session; if (config.credentials.rpc && req.session.host == null) { req.session.host = config.credentials.rpc.host; req.session.port = config.credentials.rpc.port; req.session.username = config.credentials.rpc.username; } var userAgent = req.headers['user-agent']; var crawler = utils.getCrawlerFromUserAgentString(userAgent); if (crawler) { res.locals.crawlerBot = true; } // make a bunch of globals available to templates res.locals.config = global.config; res.locals.coinConfig = global.coinConfig; res.locals.activeBlockchain = global.activeBlockchain; res.locals.exchangeRates = global.exchangeRates; res.locals.utxoSetSummary = global.utxoSetSummary; res.locals.utxoSetSummaryPending = global.utxoSetSummaryPending; res.locals.networkVolume = global.networkVolume; res.locals.host = req.session.host; res.locals.port = req.session.port; res.locals.genesisBlockHash = coreApi.getGenesisBlockHash(); res.locals.genesisCoinbaseTransactionId = coreApi.getGenesisCoinbaseTransactionId(); res.locals.pageErrors = []; if (!req.session.userSettings) { req.session.userSettings = Object.create(null); const cookieSettings = JSON.parse(req.cookies["user-settings"] || "{}"); for (const [key, value] of Object.entries(cookieSettings)) { req.session.userSettings[key] = value; } } const userSettings = req.session.userSettings; res.locals.userSettings = userSettings; // set defaults userSettings.displayCurrency = (userSettings.displayCurrency || config.displayDefaults.displayCurrency); userSettings.localCurrency = (userSettings.localCurrency || config.displayDefaults.localCurrency); userSettings.uiTimezone = (userSettings.uiTimezone || config.displayDefaults.timezone); userSettings.uiTheme = (userSettings.uiTheme || config.displayDefaults.theme); // make available in templates res.locals.displayCurrency = userSettings.displayCurrency; res.locals.localCurrency = userSettings.localCurrency; res.locals.uiTimezone = userSettings.uiTimezone; res.locals.uiTheme = userSettings.uiTheme; res.locals.userTzOffset = userSettings.userTzOffset || "unset"; res.locals.browserTzOffset = userSettings.browserTzOffset || "0"; if (!["/", "/connect"].includes(req.originalUrl)) { if (utils.redirectToConnectPageIfNeeded(req, res)) { return; } } if (req.session.userMessage) { res.locals.userMessage = req.session.userMessage; if (req.session.userMessageType) { res.locals.userMessageType = req.session.userMessageType; } else { res.locals.userMessageType = "warning"; } req.session.userMessage = null; req.session.userMessageType = null; } if (req.session.query) { res.locals.query = req.session.query; req.session.query = null; } if (!global.rpcConnected) { res.status(500); res.render('error', { errorType: "noRpcConnection" }); return; } // make some var available to all request // ex: req.cheeseStr = "cheese"; next(); }); expressApp.use(csurf(), (req, res, next) => { res.locals.csrfToken = req.csrfToken(); next(); }); expressApp.use(config.baseUrl, baseActionsRouter); expressApp.use(config.baseUrl + 'internal-api/', internalApiActionsRouter); expressApp.use(config.baseUrl + 'api/', apiActionsRouter); expressApp.use(config.baseUrl + 'snippet/', snippetActionsRouter); expressApp.use(config.baseUrl + 'admin/', adminActionsRouter); if (expressApp.get("env") === "local") { expressApp.use(config.baseUrl + 'test/', testActionsRouter); } expressApp.use(function(req, res, next) { var time = Date.now() - req.startTime; var userAgent = req.headers['user-agent']; var crawler = utils.getCrawlerFromUserAgentString(userAgent); let ip = (req.headers['x-forwarded-for'] || req.connection.remoteAddress || '').split(',')[0].trim(); if (crawler) { debugAccessLog(`Finished action '${req.path}' (${res.statusCode}) in ${time}ms for crawler '${crawler}' / '${userAgent}', ip=${ip}`); } else { debugAccessLog(`Finished action '${req.path}' (${res.statusCode}) in ${time}ms for UA '${userAgent}', ip=${ip}`); } if (!res.headersSent) { next(); } }); /// catch 404 and forwarding to error handler expressApp.use(function(req, res, next) { var err = new Error(`Not Found: ${req ? req.url : 'unknown url'}`); err.status = 404; next(err); }); /// error handlers const sharedErrorHandler = (req, err) => { if (err && err.message && err.message.includes("Not Found")) { const path = err.toString().substring(err.toString().lastIndexOf(" ") + 1); const userAgent = req.headers['user-agent']; const crawler = utils.getCrawlerFromUserAgentString(userAgent); const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress; const attributes = { path:path }; if (crawler) { attributes.crawler = crawler; } debugErrorLog(`404 NotFound: path=${path}, ip=${ip}, userAgent=${userAgent} (crawler=${(crawler != null)}${crawler ? crawler : ""})`); utils.logError(`NotFound`, err, attributes, false); } else { utils.logError("ExpressUncaughtError", err); } }; // development error handler // will print stacktrace if (expressApp.get("env") === "development" || expressApp.get("env") === "local") { expressApp.use(function(err, req, res, next) { if (err) { sharedErrorHandler(req, err); } res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user expressApp.use(function(err, req, res, next) { if (err) { sharedErrorHandler(req, err); } res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); expressApp.locals.moment = moment; expressApp.locals.Decimal = Decimal; expressApp.locals.utils = utils; expressApp.locals.markdown = src => markdown.render(src); expressApp.locals.assetUrl = (path) => { // trim off leading "./" let normalizedPath = path.substring(2); //console.log("assetUrl: " + path + " -> " + normalizedPath); if (config.cdn.active && cdnFilepathMap[normalizedPath]) { return `${config.cdn.baseUrl}/${global.cacheId}/${normalizedPath}`; } else { return `${path}?v=${global.cacheId}`; } }; // debug setting to skip js/css integrity checks const skipIntegrityChecks = false; const resourceIntegrityHashes = JSON.parse(fs.readFileSync(path.join(process.cwd(), "public/txt/resource-integrity.json"))); expressApp.locals.assetIntegrity = (filename) => { if (!skipIntegrityChecks && resourceIntegrityHashes[filename]) { return resourceIntegrityHashes[filename]; } else { return ""; } }; module.exports = expressApp;
app.js
#!/usr/bin/env node "use strict"; const os = require('os'); const path = require('path'); const dotenv = require("dotenv"); const fs = require('fs'); const debug = require("debug"); // start with this, we will update after loading any .env files const debugDefaultCategories = "btcexp:app,btcexp:error,btcexp:errorVerbose"; debug.enable(debugDefaultCategories); const debugLog = debug("btcexp:app"); const debugErrorLog = debug("btcexp:error"); const debugPerfLog = debug("btcexp:actionPerformace"); const debugAccessLog = debug("btcexp:access"); const configPaths = [ path.join(os.homedir(), ".config", "btc-rpc-explorer.env"), path.join("/etc", "btc-rpc-explorer", ".env"), path.join(process.cwd(), ".env"), ]; debugLog("Searching for config files..."); let configFileLoaded = false; configPaths.forEach(path => { if (fs.existsSync(path)) { debugLog(`Config file found at ${path}, loading...`); // this does not override any existing env vars dotenv.config({ path }); // we manually set env.DEBUG above (so that app-launch log output is good), // so if it's defined in the .env file, we need to manually override const config = dotenv.parse(fs.readFileSync(path)); if (config.DEBUG) { process.env.DEBUG = config.DEBUG; } configFileLoaded = true; } else { debugLog(`Config file not found at ${path}, continuing...`); } }); if (!configFileLoaded) { debugLog("No config files found. Using all defaults."); if (!process.env.NODE_ENV) { process.env.NODE_ENV = "production"; } } // debug module is already loaded by the time we do dotenv.config // so refresh the status of DEBUG env var debug.enable(process.env.DEBUG || debugDefaultCategories); global.cacheStats = {}; const express = require('express'); const favicon = require('serve-favicon'); const logger = require('morgan'); const cookieParser = require('cookie-parser'); const bodyParser = require('body-parser'); const session = require("express-session"); const csurf = require("csurf"); const config = require("./app/config.js"); const simpleGit = require('simple-git'); const utils = require("./app/utils.js"); const moment = require("moment"); const Decimal = require('decimal.js'); const bitcoinCore = require("btc-rpc-client"); const pug = require("pug"); const momentDurationFormat = require("moment-duration-format"); const coreApi = require("./app/api/coreApi.js"); const rpcApi = require("./app/api/rpcApi.js"); const coins = require("./app/coins.js"); const axios = require("axios"); const qrcode = require("qrcode"); const addressApi = require("./app/api/addressApi.js"); const electrumAddressApi = require("./app/api/electrumAddressApi.js"); const appStats = require("./app/appStats.js"); const btcQuotes = require("./app/coins/btcQuotes.js"); const btcHolidays = require("./app/coins/btcHolidays.js"); const auth = require('./app/auth.js'); const sso = require('./app/sso.js'); const markdown = require("markdown-it")(); const v8 = require("v8"); var compression = require("compression"); const appUtils = require("@janoside/app-utils"); const s3Utils = appUtils.s3Utils; let cdnS3Bucket = null; if (config.cdn.active) { cdnS3Bucket = s3Utils.createBucket(config.cdn.s3Bucket, config.cdn.s3BucketPath); } require("./app/currencies.js"); const package_json = require('./package.json'); global.appVersion = package_json.version; global.cacheId = global.appVersion; debugLog(`Default cacheId '${global.cacheId}'`); global.btcNodeSemver = "0.0.0"; const baseActionsRouter = require('./routes/baseRouter.js'); const internalApiActionsRouter = require('./routes/internalApiRouter.js'); const apiActionsRouter = require('./routes/apiRouter.js'); const snippetActionsRouter = require('./routes/snippetRouter.js'); const adminActionsRouter = require('./routes/adminRouter.js'); const testActionsRouter = require('./routes/testRouter.js'); const expressApp = express(); const statTracker = require("./app/statTracker.js"); const statsProcessFunction = (name, stats) => { appStats.trackAppStats(name, stats); if (process.env.STATS_API_URL) { const data = Object.assign({}, stats); data.name = name; axios.post(process.env.STATS_API_URL, data) .then(res => { /*console.log(res.data);*/ }) .catch(error => { utils.logError("38974wrg9w7dsgfe", error); }); } }; const processStatsInterval = setInterval(() => { statTracker.processAndReset( statsProcessFunction, statsProcessFunction, statsProcessFunction); }, process.env.STATS_PROCESS_INTERVAL || (5 * 60 * 1000)); // Don't keep Node.js process up processStatsInterval.unref(); const systemMonitor = require("./app/systemMonitor.js"); const normalizeActions = require("./app/normalizeActions.js"); expressApp.use(require("./app/actionPerformanceMonitor.js")(statTracker, { ignoredEndsWithActions: "\.js|\.css|\.svg|\.png|\.woff2", ignoredStartsWithActions: `${config.baseUrl}snippet`, normalizeAction: (action) => { return normalizeActions(config.baseUrl, action); }, })); // view engine setup expressApp.set('views', path.join(__dirname, 'views')); // ref: https://blog.stigok.com/post/disable-pug-debug-output-with-expressjs-web-app expressApp.engine('pug', (path, options, fn) => { options.debug = false; return pug.__express.call(null, path, options, fn); }); expressApp.set('view engine', 'pug'); if (process.env.NODE_ENV != "local") { // enable view cache regardless of env (development/production) // ref: https://pugjs.org/api/express.html debugLog("Enabling view caching (performance will be improved but template edits will not be reflected)") expressApp.enable('view cache'); } expressApp.use(cookieParser()); expressApp.disable('x-powered-by'); if (process.env.BTCEXP_BASIC_AUTH_PASSWORD) { // basic http authentication expressApp.use(auth(process.env.BTCEXP_BASIC_AUTH_PASSWORD)); } else if (process.env.BTCEXP_SSO_TOKEN_FILE) { // sso authentication expressApp.use(sso(process.env.BTCEXP_SSO_TOKEN_FILE, process.env.BTCEXP_SSO_LOGIN_REDIRECT_URL)); } // uncomment after placing your favicon in /public //expressApp.use(favicon(__dirname + '/public/favicon.ico')); //expressApp.use(logger('dev')); expressApp.use(bodyParser.json()); expressApp.use(bodyParser.urlencoded({ extended: false })); expressApp.use(session({ secret: config.cookieSecret, resave: false, saveUninitialized: false })); expressApp.use(compression()); expressApp.use(config.baseUrl, express.static(path.join(__dirname, 'public'), { maxAge: 30 * 24 * 60 * 60 * 1000 })); if (config.baseUrl != '/') { expressApp.get('/', (req, res) => res.redirect(config.baseUrl)); } // if a CDN is configured, these assets will be uploaded at launch, then referenced from there const cdnItems = [ [`style/dark.css`, `text/css`, "utf8"], [`style/light.css`, `text/css`, "utf8"], [`style/highlight.min.css`, `text/css`, "utf8"], [`style/dataTables.bootstrap4.min.css`, `text/css`, "utf8"], [`style/bootstrap-icons.css`, `text/css`, "utf8"], [`js/bootstrap.bundle.min.js`, `text/javascript`, "utf8"], [`js/chart.min.js`, `text/javascript`, "utf8"], [`js/jquery.min.js`, `text/javascript`, "utf8"], [`js/site.js`, `text/javascript`, "utf8"], [`js/highlight.pack.js`, `text/javascript`, "utf8"], [`js/chartjs-adapter-moment.min.js`, `text/javascript`, "utf8"], [`js/jquery.dataTables.min.js`, `text/javascript`, "utf8"], [`js/dataTables.bootstrap4.min.js`, `text/javascript`, "utf8"], [`js/moment.min.js`, `text/javascript`, "utf8"], [`js/sentry.min.js`, `text/javascript`, "utf8"], [`js/decimal.js`, `text/javascript`, "utf8"], [`img/network-mainnet/logo.svg`, `image/svg+xml`, "utf8"], [`img/network-mainnet/coin-icon.svg`, `image/svg+xml`, "utf8"], [`img/network-mainnet/apple-touch-icon.png`, `image/png`, "binary"], [`img/network-mainnet/favicon-16x16.png`, `image/png`, "binary"], [`img/network-mainnet/favicon-32x32.png`, `image/png`, "binary"], [`img/network-testnet/logo.svg`, `image/svg+xml`, "utf8"], [`img/network-testnet/coin-icon.svg`, `image/svg+xml`, "utf8"], [`img/network-signet/logo.svg`, `image/svg+xml`, "utf8"], [`img/network-signet/coin-icon.svg`, `image/svg+xml`, "utf8"], [`img/network-regtest/logo.svg`, `image/svg+xml`, "utf8"], [`img/network-regtest/coin-icon.svg`, `image/svg+xml`, "utf8"], [`img/network-mainnet/favicon.ico`, `image/x-icon`, "binary"], [`img/network-testnet/favicon.ico`, `image/x-icon`, "binary"], [`img/network-signet/favicon.ico`, `image/x-icon`, "binary"], [`img/network-regtest/favicon.ico`, `image/x-icon`, "binary"], [`font/bootstrap-icons.woff`, `font/woff`, "binary"], [`font/bootstrap-icons.woff2`, `font/woff2`, "binary"], [`leaflet/leaflet.js`, `text/javascript`, "utf8"], [`leaflet/leaflet.css`, `text/css`, "utf8"], ]; const cdnFilepathMap = {}; cdnItems.forEach(item => { cdnFilepathMap[item[0]] = true; }); process.on("unhandledRejection", (reason, p) => { debugLog("Unhandled Rejection at: Promise", p, "reason:", reason, "stack:", (reason != null ? reason.stack : "null")); }); function loadMiningPoolConfigs() { debugLog("Loading mining pools config"); global.miningPoolsConfigs = []; var miningPoolsConfigDir = path.join(__dirname, "public", "txt", "mining-pools-configs", global.coinConfig.ticker); fs.readdir(miningPoolsConfigDir, function(err, files) { if (err) { utils.logError("3ufhwehe", err, {configDir:miningPoolsConfigDir, desc:"Unable to scan directory"}); return; } files.forEach(function(file) { var filepath = path.join(miningPoolsConfigDir, file); var contents = fs.readFileSync(filepath, 'utf8'); global.miningPoolsConfigs.push(JSON.parse(contents)); }); for (var i = 0; i < global.miningPoolsConfigs.length; i++) { for (var x in global.miningPoolsConfigs[i].payout_addresses) { if (global.miningPoolsConfigs[i].payout_addresses.hasOwnProperty(x)) { global.specialAddresses[x] = {type:"minerPayout", minerInfo:global.miningPoolsConfigs[i].payout_addresses[x]}; } } } }); } async function getSourcecodeProjectMetadata() { var options = { url: "https://api.github.com/repos/janoside/btc-rpc-explorer", headers: { 'User-Agent': 'request' } }; try { const response = await axios(options); global.sourcecodeProjectMetadata = response.data; } catch (err) { utils.logError("3208fh3ew7eghfg", err); } } function loadChangelog() { var filename = "CHANGELOG.md"; fs.readFile(path.join(__dirname, filename), 'utf8', function(err, data) { if (err) { utils.logError("2379gsd7sgd334", err); } else { global.changelogMarkdown = data; } }); var filename = "CHANGELOG-API.md"; fs.readFile(path.join(__dirname, filename), 'utf8', function(err, data) { if (err) { utils.logError("ouqhuwey723", err); } else { global.apiChangelogMarkdown = data; } }); } function loadHistoricalDataForChain(chain) { debugLog(`Loading historical data for chain=${chain}`); if (global.coinConfig.historicalData) { global.coinConfig.historicalData.forEach(function(item) { if (item.chain == chain) { if (item.type == "blockheight") { global.specialBlocks[item.blockHash] = item; } else if (item.type == "tx") { global.specialTransactions[item.txid] = item; } else if (item.type == "address" || item.address) { global.specialAddresses[item.address] = {type:"fun", addressInfo:item}; } } }); } } function loadHolidays(chain) { debugLog(`Loading holiday data`); global.btcHolidays = btcHolidays; global.btcHolidays.byDay = {}; global.btcHolidays.sortedDays = []; global.btcHolidays.sortedItems = [...btcHolidays.items]; global.btcHolidays.sortedItems.sort((a, b) => a.date.localeCompare(b.date)); global.btcHolidays.items.forEach(function(item) { let day = item.date.substring(5); if (!global.btcHolidays.sortedDays.includes(day)) { global.btcHolidays.sortedDays.push(day); global.btcHolidays.sortedDays.sort(); } if (global.btcHolidays.byDay[day] == undefined) { global.btcHolidays.byDay[day] = []; } global.btcHolidays.byDay[day].push(item); }); } function verifyRpcConnection() { if (!global.activeBlockchain) { debugLog(`Verifying RPC connection...`); // normally in application code we target coreApi, but here we're trying to // verify the RPC connection so we target rpcApi directly and include // the second parameter "verifyingConnection=true", to bypass a // fail-if-were-not-connected check Promise.all([ rpcApi.getRpcData("getnetworkinfo", true), rpcApi.getRpcData("getblockchaininfo", true), ]).then(([ getnetworkinfo, getblockchaininfo ]) => { global.activeBlockchain = getblockchaininfo.chain; // we've verified rpc connection, no need to keep trying clearInterval(global.verifyRpcConnectionIntervalId); onRpcConnectionVerified(getnetworkinfo, getblockchaininfo); }).catch(function(err) { utils.logError("32ugegdfsde", err); }); } } async function onRpcConnectionVerified(getnetworkinfo, getblockchaininfo) { // localservicenames introduced in 0.19 var services = getnetworkinfo.localservicesnames ? ("[" + getnetworkinfo.localservicesnames.join(", ") + "]") : getnetworkinfo.localservices; global.rpcConnected = true; global.getnetworkinfo = getnetworkinfo; if (getblockchaininfo.pruned) { global.prunedBlockchain = true; global.pruneHeight = getblockchaininfo.pruneheight; } var bitcoinCoreVersionRegex = /^.*\/Satoshi\:(.*)\/.*$/; var match = bitcoinCoreVersionRegex.exec(getnetworkinfo.subversion); if (match) { global.btcNodeVersion = match[1]; var semver4PartRegex = /^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/; var semver4PartMatch = semver4PartRegex.exec(global.btcNodeVersion); if (semver4PartMatch) { var p0 = semver4PartMatch[1]; var p1 = semver4PartMatch[2]; var p2 = semver4PartMatch[3]; var p3 = semver4PartMatch[4]; // drop last segment, which usually indicates a bug fix release which is (hopefully) irrelevant for RPC API versioning concerns global.btcNodeSemver = `${p0}.${p1}.${p2}`; } else { var semver3PartRegex = /^([0-9]+)\.([0-9]+)\.([0-9]+)$/; var semver3PartMatch = semver3PartRegex.exec(global.btcNodeVersion); if (semver3PartMatch) { var p0 = semver3PartMatch[1]; var p1 = semver3PartMatch[2]; var p2 = semver3PartMatch[3]; global.btcNodeSemver = `${p0}.${p1}.${p2}`; } else { // short-circuit: force all RPC calls to pass their version checks - this will likely lead to errors / instability / unexpected results global.btcNodeSemver = "1000.1000.0" } } } else { // short-circuit: force all RPC calls to pass their version checks - this will likely lead to errors / instability / unexpected results global.btcNodeSemver = "1000.1000.0" debugErrorLog(`Unable to parse node version string: ${getnetworkinfo.subversion} - RPC versioning will likely be unreliable. Is your node a version of Bitcoin Core?`); } debugLog(`RPC Connected: version=${getnetworkinfo.version} subversion=${getnetworkinfo.subversion}, parsedVersion(used for RPC versioning)=${global.btcNodeSemver}, protocolversion=${getnetworkinfo.protocolversion}, chain=${getblockchaininfo.chain}, services=${services}`); // load historical/fun items for this chain loadHistoricalDataForChain(global.activeBlockchain); loadHolidays(); if (global.activeBlockchain == "main") { loadDifficultyHistory(getblockchaininfo.blocks); // refresh difficulty history periodically // TODO: refresh difficulty history when there's a new block and height % 2016 == 0 setInterval(loadDifficultyHistory, 15 * 60 * 1000); if (global.exchangeRates == null) { utils.refreshExchangeRates(); } // refresh exchange rate periodically setInterval(utils.refreshExchangeRates, 1800000); } // 1d / 7d volume refreshNetworkVolumes(); setInterval(refreshNetworkVolumes, 30 * 60 * 1000); await assessTxindexAvailability(); // UTXO pull refreshUtxoSetSummary(); setInterval(refreshUtxoSetSummary, 30 * 60 * 1000); if (false) { var zmq = require("zeromq"); var sock = zmq.socket("sub"); sock.connect("tcp://192.168.1.1:28333"); console.log("Worker connected to port 28333"); sock.on("message", function(topic, message) { console.log(Buffer.from(topic).toString("ascii") + " - " + Buffer.from(message).toString("hex")); }); //sock.subscribe('rawtx'); } } async function loadDifficultyHistory(tipBlockHeight=null) { if (!tipBlockHeight) { let getblockchaininfo = await coreApi.getBlockchainInfo(); tipBlockHeight = getblockchaininfo.blocks; } if (config.slowDeviceMode) { debugLog("Skipping performance-intensive task: load difficulty history. This is skipped due to the flag 'slowDeviceMode' which defaults to 'true' to protect slow nodes. Set this flag to 'false' to enjoy difficulty history details."); return; } let height = 0; let heights = []; while (height <= tipBlockHeight) { heights.push(height); height += global.coinConfig.difficultyAdjustmentBlockCount; } global.difficultyHistory = await coreApi.getDifficultyByBlockHeights(heights); global.athDifficulty = 0; for (let i = 0; i < heights.length; i++) { if (global.difficultyHistory[`${heights[i]}`].difficulty > global.athDifficulty) { global.athDifficulty = global.difficultyHistory[heights[i]].difficulty; } } debugLog("ATH difficulty: " + global.athDifficulty); } var txindexCheckCount = 0; async function assessTxindexAvailability() { // Here we try to call getindexinfo to assess availability of txindex // However, getindexinfo RPC is only available in v0.21+, so the call // may return an "unsupported" error. If/when it does, we will fall back // to assessing txindex availability by querying a known txid debugLog("txindex check: trying getindexinfo"); try { global.getindexinfo = await coreApi.getIndexInfo(); debugLog(`txindex check: getindexinfo=${JSON.stringify(global.getindexinfo)}`); if (global.getindexinfo.txindex) { // getindexinfo was available, and txindex is also available...easy street global.txindexAvailable = true; debugLog("txindex check: available!"); } else if (global.getindexinfo.minRpcVersionNeeded) { // here we find out that getindexinfo is unavailable on our node because // we're running pre-v0.21, so we fall back to querying a known txid // to assess txindex availability debugLog("txindex check: getindexinfo unavailable, trying txid lookup"); try { // lookup a known TXID as a test for whether txindex is available let knownTx = await coreApi.getRawTransaction(coinConfig.knownTransactionsByNetwork[global.activeBlockchain]); // if we get here without an error being thrown, we know we're able to look up by txid // thus, txindex is available global.txindexAvailable = true; debugLog("txindex check: available! (pre-v0.21)"); } catch (e) { // here we were unable to query by txid, so we believe txindex is unavailable global.txindexAvailable = false; debugLog("txindex check: unavailable"); } } else { // here getindexinfo is available (i.e. we're on v0.21+), but txindex is NOT available global.txindexAvailable = false; debugLog("txindex check: unavailable"); } } catch (e) { utils.logError("o2328ryw8wsde", e); var retryTime = parseInt(Math.min(15 * 60 * 1000, 1000 * 10 * Math.pow(2, txindexCheckCount))); txindexCheckCount++; debugLog(`txindex check: error in rpc getindexinfo; will try again in ${retryTime}ms`); // try again in 5 mins setTimeout(assessTxindexAvailability, retryTime); } } async function refreshUtxoSetSummary() { if (config.slowDeviceMode) { if (!global.getindexinfo || !global.getindexinfo.coinstatsindex) { global.utxoSetSummary = null; global.utxoSetSummaryPending = false; debugLog("Skipping performance-intensive task: fetch UTXO set summary. This is skipped due to the flag 'slowDeviceMode' which defaults to 'true' to protect slow nodes. Set this flag to 'false' to enjoy UTXO set summary details."); return; } } // flag that we're working on calculating UTXO details (to differentiate cases where we don't have the details and we're not going to try computing them) global.utxoSetSummaryPending = true; global.utxoSetSummary = await coreApi.getUtxoSetSummary(true, false); debugLog("Refreshed utxo summary: " + JSON.stringify(global.utxoSetSummary)); } function refreshNetworkVolumes() { if (config.slowDeviceMode) { debugLog("Skipping performance-intensive task: fetch last 24 hrs of blockstats to calculate transaction volume. This is skipped due to the flag 'slowDeviceMode' which defaults to 'true' to protect slow nodes. Set this flag to 'false' to enjoy UTXO set summary details."); return; } var cutoff1d = new Date().getTime() - (60 * 60 * 24 * 1000); var cutoff7d = new Date().getTime() - (60 * 60 * 24 * 7 * 1000); coreApi.getBlockchainInfo().then(function(result) { var promises = []; var blocksPerDay = 144 + 20; // 20 block padding for (var i = 0; i < (blocksPerDay * 1); i++) { if (result.blocks - i >= 0) { promises.push(coreApi.getBlockStatsByHeight(result.blocks - i)); } } var startBlock = result.blocks; var endBlock1d = result.blocks; var endBlock7d = result.blocks; var endBlockTime1d = 0; var endBlockTime7d = 0; Promise.all(promises).then(function(results) { var volume1d = new Decimal(0); var volume7d = new Decimal(0); var blocks1d = 0; var blocks7d = 0; if (results && results.length > 0 && results[0] != null) { for (var i = 0; i < results.length; i++) { if (results[i].time * 1000 > cutoff1d) { volume1d = volume1d.plus(new Decimal(results[i].total_out)); volume1d = volume1d.plus(new Decimal(results[i].subsidy)); volume1d = volume1d.plus(new Decimal(results[i].totalfee)); blocks1d++; endBlock1d = results[i].height; endBlockTime1d = results[i].time; } if (results[i].time * 1000 > cutoff7d) { volume7d = volume7d.plus(new Decimal(results[i].total_out)); volume7d = volume7d.plus(new Decimal(results[i].subsidy)); volume7d = volume7d.plus(new Decimal(results[i].totalfee)); blocks7d++; endBlock7d = results[i].height; endBlockTime7d = results[i].time; } } volume1d = volume1d.dividedBy(coinConfig.baseCurrencyUnit.multiplier); volume7d = volume7d.dividedBy(coinConfig.baseCurrencyUnit.multiplier); global.networkVolume = {d1:{amt:volume1d, blocks:blocks1d, startBlock:startBlock, endBlock:endBlock1d, startTime:results[0].time, endTime:endBlockTime1d}}; debugLog(`Network volume: ${JSON.stringify(global.networkVolume)}`); } else { debugLog("Unable to load network volume, likely due to bitcoind version older than 0.17.0 (the first version to support getblockstats)."); } }); }); } expressApp.onStartup = async () => { global.appStartTime = new Date().getTime(); global.config = config; global.coinConfig = coins[config.coin]; global.coinConfigs = coins; global.specialTransactions = {}; global.specialBlocks = {}; global.specialAddresses = {}; loadChangelog(); global.nodeVersion = process.version; debugLog(`Environment(${expressApp.get("env")}) - Node: ${process.version}, Platform: ${process.platform}, Versions: ${JSON.stringify(process.versions)}`); // dump "startup" heap after 5sec if (false) { (function () { var callback = function() { debugLog("Waited 5 sec after startup, now dumping 'startup' heap..."); const filename = `./heapDumpAtStartup-${Date.now()}.heapsnapshot`; const heapdumpStream = v8.getHeapSnapshot(); const fileStream = fs.createWriteStream(filename); heapdumpStream.pipe(fileStream); debugLog("Heap dump at startup written to", filename); }; setTimeout(callback, 5000); })(); } if (global.sourcecodeVersion == null && fs.existsSync('.git')) { try { let log = await simpleGit(".").log(["-n 1"]); global.sourcecodeVersion = log.all[0].hash.substring(0, 10); global.sourcecodeDate = log.all[0].date.substring(0, "0000-00-00".length); global.cacheId = `${global.sourcecodeDate}-${global.sourcecodeVersion}`; debugLog(`Using sourcecode metadata as cacheId: '${global.cacheId}'`); debugLog(`Starting ${global.coinConfig.ticker} RPC Explorer, v${global.appVersion} (commit: '${global.sourcecodeVersion}', date: ${global.sourcecodeDate}) at http://${config.host}:${config.port}${config.baseUrl}`); } catch (err) { utils.logError("3fehge9ee", err, {desc:"Error accessing git repo"}); global.cacheId = global.appVersion; debugLog(`Error getting sourcecode version, continuing to use default cacheId '${global.cacheId}'`); debugLog(`Starting ${global.coinConfig.ticker} RPC Explorer, v${global.appVersion} (code: unknown commit) at http://${config.host}:${config.port}${config.baseUrl}`); } expressApp.continueStartup(); } else { global.cacheId = global.appVersion; debugLog(`No sourcecode version available, continuing to use default cacheId '${global.cacheId}'`); debugLog(`Starting ${global.coinConfig.ticker} RPC Explorer, v${global.appVersion} at http://${config.host}:${config.port}${config.baseUrl}`); expressApp.continueStartup(); } if (config.cdn.active && config.cdn.s3Bucket) { debugLog(`Configuring CDN assets; uploading ${cdnItems.length} assets to S3...`); const s3Path = (filepath) => { return `${global.cacheId}/${filepath}`; } const uploadedItems = []; const existingItems = []; const errorItems = []; const uploadAssetIfNeeded = async (filepath, contentType, encoding) => { try { let absoluteFilepath = path.join(process.cwd(), "public", filepath); let s3path = s3Path(filepath); const existingAsset = await cdnS3Bucket.get(s3path); if (existingAsset) { existingItems.push(filepath); //debugLog(`Asset ${filepath} already in S3, skipping upload.`); } else { let fileData = fs.readFileSync(absoluteFilepath, {encoding: encoding, flag:'r'}); let fileBuffer = Buffer.from(fileData, encoding); let options = { "ContentType": contentType, "CacheControl": "max-age=315360000" }; await cdnS3Bucket.put(fileBuffer, s3path, options); uploadedItems.push(filepath); //debugLog(`Uploaded ${filepath} to S3.`); } } catch (e) { errorItems.push(filepath); debugErrorLog(`Error uploading asset to S3: ${JSON.stringify(filepath)}`, e); } }; const promises = []; for (let i = 0; i < cdnItems.length; i++) { let item = cdnItems[i]; let filepath = item[0]; let contentType = item[1]; let encoding = item[2]; promises.push(uploadAssetIfNeeded(filepath, contentType, encoding)); } await utils.awaitPromises(promises); debugLog(`Done uploading assets to S3:\n\tAlready present: ${existingItems.length}\n\tNewly uploaded: ${uploadedItems.length}\n\tError items: ${errorItems.length}`); } } expressApp.continueStartup = function() { var rpcCred = config.credentials.rpc; debugLog(`Connecting to RPC node at ${rpcCred.host}:${rpcCred.port}`); var rpcClientProperties = { host: rpcCred.host, port: rpcCred.port, username: rpcCred.username, password: rpcCred.password, timeout: rpcCred.timeout }; global.rpcClient = new bitcoinCore(rpcClientProperties); var rpcClientNoTimeoutProperties = { host: rpcCred.host, port: rpcCred.port, username: rpcCred.username, password: rpcCred.password, timeout: 0 }; global.rpcClientNoTimeout = new bitcoinCore(rpcClientNoTimeoutProperties); // default values - after we connect via RPC, we update these global.txindexAvailable = false; global.prunedBlockchain = false; global.pruneHeight = -1; // keep trying to verify rpc connection until we succeed // note: see verifyRpcConnection() for associated clearInterval() after success verifyRpcConnection(); global.verifyRpcConnectionIntervalId = setInterval(verifyRpcConnection, 30000); if (config.addressApi) { var supportedAddressApis = addressApi.getSupportedAddressApis(); if (!supportedAddressApis.includes(config.addressApi)) { utils.logError("32907ghsd0ge", `Unrecognized value for BTCEXP_ADDRESS_API: '${config.addressApi}'. Valid options are: ${supportedAddressApis}`); } if (config.addressApi == "electrum" || config.addressApi == "electrumx") { if (config.electrumServers && config.electrumServers.length > 0) { electrumAddressApi.connectToServers().then(function() { global.electrumAddressApi = electrumAddressApi; }).catch(function(err) { utils.logError("31207ugf4e0fed", err, {electrumServers:config.electrumServers}); }); } else { utils.logError("327hs0gde", "You must set the 'BTCEXP_ELECTRUM_SERVERS' environment variable when BTCEXP_ADDRESS_API=electrum."); } } } loadMiningPoolConfigs(); if (config.demoSite) { getSourcecodeProjectMetadata(); setInterval(getSourcecodeProjectMetadata, 3600000); } utils.logMemoryUsage(); setInterval(utils.logMemoryUsage, 5000); }; expressApp.use(function(req, res, next) { req.startTime = Date.now(); next(); }); expressApp.use(function(req, res, next) { // make session available in templates res.locals.session = req.session; if (config.credentials.rpc && req.session.host == null) { req.session.host = config.credentials.rpc.host; req.session.port = config.credentials.rpc.port; req.session.username = config.credentials.rpc.username; } var userAgent = req.headers['user-agent']; var crawler = utils.getCrawlerFromUserAgentString(userAgent); if (crawler) { res.locals.crawlerBot = true; } // make a bunch of globals available to templates res.locals.config = global.config; res.locals.coinConfig = global.coinConfig; res.locals.activeBlockchain = global.activeBlockchain; res.locals.exchangeRates = global.exchangeRates; res.locals.utxoSetSummary = global.utxoSetSummary; res.locals.utxoSetSummaryPending = global.utxoSetSummaryPending; res.locals.networkVolume = global.networkVolume; res.locals.host = req.session.host; res.locals.port = req.session.port; res.locals.genesisBlockHash = coreApi.getGenesisBlockHash(); res.locals.genesisCoinbaseTransactionId = coreApi.getGenesisCoinbaseTransactionId(); res.locals.pageErrors = []; if (!req.session.userSettings) { req.session.userSettings = Object.create(null); const cookieSettings = JSON.parse(req.cookies["user-settings"] || "{}"); for (const [key, value] of Object.entries(cookieSettings)) { req.session.userSettings[key] = value; } } const userSettings = req.session.userSettings; res.locals.userSettings = userSettings; // set defaults userSettings.displayCurrency = (userSettings.displayCurrency || config.displayDefaults.displayCurrency); userSettings.localCurrency = (userSettings.localCurrency || config.displayDefaults.localCurrency); userSettings.uiTimezone = (userSettings.uiTimezone || config.displayDefaults.timezone); userSettings.uiTheme = (userSettings.uiTheme || config.displayDefaults.theme); // make available in templates res.locals.displayCurrency = userSettings.displayCurrency; res.locals.localCurrency = userSettings.localCurrency; res.locals.uiTimezone = userSettings.uiTimezone; res.locals.uiTheme = userSettings.uiTheme; res.locals.userTzOffset = userSettings.userTzOffset || "unset"; res.locals.browserTzOffset = userSettings.browserTzOffset || "0"; if (!["/", "/connect"].includes(req.originalUrl)) { if (utils.redirectToConnectPageIfNeeded(req, res)) { return; } } if (req.session.userMessage) { res.locals.userMessage = req.session.userMessage; if (req.session.userMessageType) { res.locals.userMessageType = req.session.userMessageType; } else { res.locals.userMessageType = "warning"; } req.session.userMessage = null; req.session.userMessageType = null; } if (req.session.query) { res.locals.query = req.session.query; req.session.query = null; } if (!global.rpcConnected) { res.status(500); res.render('error', { errorType: "noRpcConnection" }); return; } // make some var available to all request // ex: req.cheeseStr = "cheese"; next(); }); expressApp.use(csurf(), (req, res, next) => { res.locals.csrfToken = req.csrfToken(); next(); }); expressApp.use(config.baseUrl, baseActionsRouter); expressApp.use(config.baseUrl + 'internal-api/', internalApiActionsRouter); expressApp.use(config.baseUrl + 'api/', apiActionsRouter); expressApp.use(config.baseUrl + 'snippet/', snippetActionsRouter); expressApp.use(config.baseUrl + 'admin/', adminActionsRouter); if (expressApp.get("env") === "local") { expressApp.use(config.baseUrl + 'test/', testActionsRouter); } expressApp.use(function(req, res, next) { var time = Date.now() - req.startTime; var userAgent = req.headers['user-agent']; var crawler = utils.getCrawlerFromUserAgentString(userAgent); let ip = (req.headers['x-forwarded-for'] || req.connection.remoteAddress || '').split(',')[0].trim(); if (crawler) { debugAccessLog(`Finished action '${req.path}' (${res.statusCode}) in ${time}ms for crawler '${crawler}' / '${userAgent}', ip=${ip}`); } else { debugAccessLog(`Finished action '${req.path}' (${res.statusCode}) in ${time}ms for UA '${userAgent}', ip=${ip}`); } if (!res.headersSent) { next(); } }); /// catch 404 and forwarding to error handler expressApp.use(function(req, res, next) { var err = new Error(`Not Found: ${req ? req.url : 'unknown url'}`); err.status = 404; next(err); }); /// error handlers const sharedErrorHandler = (req, err) => { if (err && err.message && err.message.includes("Not Found")) { const path = err.toString().substring(err.toString().lastIndexOf(" ") + 1); const userAgent = req.headers['user-agent']; const crawler = utils.getCrawlerFromUserAgentString(userAgent); const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress; const attributes = { path:path }; if (crawler) { attributes.crawler = crawler; } debugErrorLog(`404 NotFound: path=${path}, ip=${ip}, userAgent=${userAgent} (crawler=${(crawler != null)}${crawler ? crawler : ""})`); utils.logError(`NotFound`, err, attributes, false); } else { utils.logError("ExpressUncaughtError", err); } }; // development error handler // will print stacktrace if (expressApp.get("env") === "development" || expressApp.get("env") === "local") { expressApp.use(function(err, req, res, next) { if (err) { sharedErrorHandler(req, err); } res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user expressApp.use(function(err, req, res, next) { if (err) { sharedErrorHandler(req, err); } res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); expressApp.locals.moment = moment; expressApp.locals.Decimal = Decimal; expressApp.locals.utils = utils; expressApp.locals.markdown = src => markdown.render(src); expressApp.locals.assetUrl = (path) => { // trim off leading "./" let normalizedPath = path.substring(2); //console.log("assetUrl: " + path + " -> " + normalizedPath); if (config.cdn.active && cdnFilepathMap[normalizedPath]) { return `${config.cdn.baseUrl}/${global.cacheId}/${normalizedPath}`; } else { return `${path}?v=${global.cacheId}`; } }; // debug setting to skip js/css integrity checks const skipIntegrityChecks = false; const resourceIntegrityHashes = JSON.parse(fs.readFileSync(path.join(process.cwd(), "public/txt/resource-integrity.json"))); expressApp.locals.assetIntegrity = (filename) => { if (!skipIntegrityChecks && resourceIntegrityHashes[filename]) { return resourceIntegrityHashes[filename]; } else { return ""; } }; module.exports = expressApp;
more regex cleanup
app.js
more regex cleanup
<ide><path>pp.js <ide> <ide> const normalizeActions = require("./app/normalizeActions.js"); <ide> expressApp.use(require("./app/actionPerformanceMonitor.js")(statTracker, { <del> ignoredEndsWithActions: "\.js|\.css|\.svg|\.png|\.woff2", <add> ignoredEndsWithActions: /\.js|\.css|\.svg|\.png|\.woff2/, <ide> ignoredStartsWithActions: `${config.baseUrl}snippet`, <ide> normalizeAction: (action) => { <ide> return normalizeActions(config.baseUrl, action);
Java
apache-2.0
4b32425a09fa38a0eebe57ddbfc2d882d22261ab
0
apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
/* * 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.shardingsphere.shardingjdbc.spring.namespace.handler; import org.apache.shardingsphere.shardingjdbc.spring.namespace.constants.EncryptDataSourceBeanDefinitionParserTag; import org.apache.shardingsphere.shardingjdbc.spring.namespace.parser.EncryptDataSourceBeanDefinitionParser; import org.springframework.beans.factory.xml.NamespaceHandlerSupport; /** * Spring namespace handler for encrypt. * * @author panjuan */ public final class EncryptNamespaceHandler extends NamespaceHandlerSupport { @Override public void init() { registerBeanDefinitionParser(EncryptDataSourceBeanDefinitionParserTag.ROOT_TAG, new EncryptDataSourceBeanDefinitionParser()); } }
sharding-spring/sharding-jdbc-spring/sharding-jdbc-spring-namespace/src/main/java/org/apache/shardingsphere/shardingjdbc/spring/namespace/handler/EncryptNamespaceHandler.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.shardingsphere.shardingjdbc.spring.namespace.handler; import org.apache.shardingsphere.shardingjdbc.spring.namespace.constants.EncryptDataSourceBeanDefinitionParserTag; import org.apache.shardingsphere.shardingjdbc.spring.namespace.parser.EncryptDataSourceBeanDefinitionParser; import org.apache.shardingsphere.shardingjdbc.spring.namespace.parser.EncryptorRuleBeanDefinitionParser; import org.springframework.beans.factory.xml.NamespaceHandlerSupport; /** * Spring namespace handler for encrypt. * * @author panjuan */ public final class EncryptNamespaceHandler extends NamespaceHandlerSupport { @Override public void init() { registerBeanDefinitionParser(EncryptDataSourceBeanDefinitionParserTag.ENCRYPT_RULE_CONFIG_TAG, new EncryptorRuleBeanDefinitionParser()); registerBeanDefinitionParser(EncryptDataSourceBeanDefinitionParserTag.ROOT_TAG, new EncryptDataSourceBeanDefinitionParser()); } }
delete EncryptorRuleBeanDefinitionParser
sharding-spring/sharding-jdbc-spring/sharding-jdbc-spring-namespace/src/main/java/org/apache/shardingsphere/shardingjdbc/spring/namespace/handler/EncryptNamespaceHandler.java
delete EncryptorRuleBeanDefinitionParser
<ide><path>harding-spring/sharding-jdbc-spring/sharding-jdbc-spring-namespace/src/main/java/org/apache/shardingsphere/shardingjdbc/spring/namespace/handler/EncryptNamespaceHandler.java <ide> <ide> import org.apache.shardingsphere.shardingjdbc.spring.namespace.constants.EncryptDataSourceBeanDefinitionParserTag; <ide> import org.apache.shardingsphere.shardingjdbc.spring.namespace.parser.EncryptDataSourceBeanDefinitionParser; <del>import org.apache.shardingsphere.shardingjdbc.spring.namespace.parser.EncryptorRuleBeanDefinitionParser; <ide> import org.springframework.beans.factory.xml.NamespaceHandlerSupport; <ide> <ide> /** <ide> <ide> @Override <ide> public void init() { <del> registerBeanDefinitionParser(EncryptDataSourceBeanDefinitionParserTag.ENCRYPT_RULE_CONFIG_TAG, new EncryptorRuleBeanDefinitionParser()); <ide> registerBeanDefinitionParser(EncryptDataSourceBeanDefinitionParserTag.ROOT_TAG, new EncryptDataSourceBeanDefinitionParser()); <ide> } <ide> }
Java
apache-2.0
6e849e91e751439c79bd44a614ded9aaf43ce094
0
sekikn/ambari,sekikn/ambari,sekikn/ambari,sekikn/ambari,sekikn/ambari,sekikn/ambari,sekikn/ambari,sekikn/ambari,sekikn/ambari
/* * 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.ambari.server; import org.apache.ambari.server.events.STOMPEvent; @SuppressWarnings("serial") public class MessageDestinationIsNotDefinedException extends ObjectNotFoundException { public MessageDestinationIsNotDefinedException(STOMPEvent.Type eventType) { super(String.format("No destination defined for message with %s type", eventType)); } }
ambari-server/src/main/java/org/apache/ambari/server/MessageDestinationIsNotDefinedException.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.ambari.server; import org.apache.ambari.server.events.STOMPEvent; @SuppressWarnings("serial") public class MessageDestinationIsNotDefinedException extends ObjectNotFoundException { public MessageDestinationIsNotDefinedException(STOMPEvent.Type eventType) { super(String.format("No destination defined for message with {} type", eventType)); } }
AMBARI-22734. Wrong placeholder in format string (#1436)
ambari-server/src/main/java/org/apache/ambari/server/MessageDestinationIsNotDefinedException.java
AMBARI-22734. Wrong placeholder in format string (#1436)
<ide><path>mbari-server/src/main/java/org/apache/ambari/server/MessageDestinationIsNotDefinedException.java <ide> public class MessageDestinationIsNotDefinedException extends ObjectNotFoundException { <ide> <ide> public MessageDestinationIsNotDefinedException(STOMPEvent.Type eventType) { <del> super(String.format("No destination defined for message with {} type", eventType)); <add> super(String.format("No destination defined for message with %s type", eventType)); <ide> } <ide> }
Java
apache-2.0
1e413cf9403bffa125373e7eeb2b635b4c4b7d89
0
evgenymatveev/Task
package ru.ematveev.stratigypattern; import ru.ematveev.model.IPrinter; /** * Class Paint this StratigyClient. * * @author Matveev Evgeny. * @version 1.0. * @since 18.01.17. */ public class Paint { /** * Iprinter for output to console. */ private IPrinter iPrinter; /** * Constructor. * @param iPrinter iPrinter. */ public Paint(IPrinter iPrinter) { this.iPrinter = iPrinter; } /** * Method output to console the figures. * @param shape shape. */ public void draw(Shape shape) { iPrinter.println(shape.pic()); } }
chapter_002/src/main/java/ru/ematveev/stratigypattern/Paint.java
package ru.ematveev.stratigypattern; import ru.ematveev.model.IPrinter; /** * Class Paint this StratigyClient. * * @author Matveev Evgeny. * @version 1.0. * @since 18.01.17. */ public class Paint { /** * Iprinter for output to console. */ private IPrinter iPrinter; /** * Constructor. * @param iPrinter iPrinter. */ public Paint(IPrinter iPrinter) { this.iPrinter = iPrinter; } /** * Method output to console the figures. * @param shape shape. */ public void draw(Shape shape) { iPrinter.println(shape.pic()); } /** * Method start the program. * @param args args. */ public static void main(String[] args) { IPrinter iPrinter = text -> System.out.println(text); Shape shape = new QuadreShape(7); Shape shape1 = new TriangleShape(7); Paint paint = new Paint(iPrinter); paint.draw(shape); paint.draw(shape1); } }
Paint - delete method main
chapter_002/src/main/java/ru/ematveev/stratigypattern/Paint.java
Paint - delete method main
<ide><path>hapter_002/src/main/java/ru/ematveev/stratigypattern/Paint.java <ide> public void draw(Shape shape) { <ide> iPrinter.println(shape.pic()); <ide> } <del> <del> /** <del> * Method start the program. <del> * @param args args. <del> */ <del> <del> public static void main(String[] args) { <del> IPrinter iPrinter = text -> System.out.println(text); <del> Shape shape = new QuadreShape(7); <del> Shape shape1 = new TriangleShape(7); <del> Paint paint = new Paint(iPrinter); <del> <del> paint.draw(shape); <del> paint.draw(shape1); <del> } <ide> }
Java
agpl-3.0
7a74c11d0596790ce722293c94a1f607b57bdb0c
0
jpmml/jpmml-evaluator
/* * Copyright (c) 2013 KNIME.com AG, Zurich, Switzerland * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder 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 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.jpmml.evaluator.nearest_neighbor; import java.util.ArrayList; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import com.google.common.base.Function; import com.google.common.cache.Cache; import com.google.common.collect.Collections2; import com.google.common.collect.HashBasedTable; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Iterables; import com.google.common.collect.LinkedHashMultiset; import com.google.common.collect.Maps; import com.google.common.collect.Multiset; import com.google.common.collect.Ordering; import com.google.common.collect.Table; import org.dmg.pmml.ComparisonMeasure; import org.dmg.pmml.DataField; import org.dmg.pmml.DataType; import org.dmg.pmml.DerivedField; import org.dmg.pmml.FieldName; import org.dmg.pmml.InlineTable; import org.dmg.pmml.MathContext; import org.dmg.pmml.Measure; import org.dmg.pmml.MiningField; import org.dmg.pmml.MiningFunction; import org.dmg.pmml.OpType; import org.dmg.pmml.PMML; import org.dmg.pmml.TypeDefinitionField; import org.dmg.pmml.nearest_neighbor.InstanceField; import org.dmg.pmml.nearest_neighbor.InstanceFields; import org.dmg.pmml.nearest_neighbor.KNNInput; import org.dmg.pmml.nearest_neighbor.KNNInputs; import org.dmg.pmml.nearest_neighbor.NearestNeighborModel; import org.dmg.pmml.nearest_neighbor.TrainingInstances; import org.jpmml.evaluator.AffinityDistribution; import org.jpmml.evaluator.CacheUtil; import org.jpmml.evaluator.Classification; import org.jpmml.evaluator.EvaluationContext; import org.jpmml.evaluator.EvaluationException; import org.jpmml.evaluator.ExpressionUtil; import org.jpmml.evaluator.FieldValue; import org.jpmml.evaluator.FieldValueUtil; import org.jpmml.evaluator.InlineTableUtil; import org.jpmml.evaluator.InvalidFeatureException; import org.jpmml.evaluator.InvalidResultException; import org.jpmml.evaluator.MeasureUtil; import org.jpmml.evaluator.MissingFieldException; import org.jpmml.evaluator.MissingValueException; import org.jpmml.evaluator.ModelEvaluationContext; import org.jpmml.evaluator.ModelEvaluator; import org.jpmml.evaluator.OutputUtil; import org.jpmml.evaluator.TargetField; import org.jpmml.evaluator.TypeUtil; import org.jpmml.evaluator.UnsupportedFeatureException; import org.jpmml.evaluator.Value; import org.jpmml.evaluator.ValueAggregator; import org.jpmml.evaluator.ValueFactory; import org.jpmml.evaluator.VoteAggregator; public class NearestNeighborModelEvaluator extends ModelEvaluator<NearestNeighborModel> { transient private Table<Integer, FieldName, FieldValue> trainingInstances = null; transient private Map<Integer, BitSet> instanceFlags = null; transient private Map<Integer, List<FieldValue>> instanceValues = null; public NearestNeighborModelEvaluator(PMML pmml){ this(pmml, selectModel(pmml, NearestNeighborModel.class)); } public NearestNeighborModelEvaluator(PMML pmml, NearestNeighborModel nearestNeighborModel){ super(pmml, nearestNeighborModel); ComparisonMeasure comparisoonMeasure = nearestNeighborModel.getComparisonMeasure(); if(comparisoonMeasure == null){ throw new InvalidFeatureException(nearestNeighborModel); } TrainingInstances trainingInstances = nearestNeighborModel.getTrainingInstances(); if(trainingInstances == null){ throw new InvalidFeatureException(nearestNeighborModel); } InstanceFields instanceFields = trainingInstances.getInstanceFields(); if(instanceFields == null){ throw new InvalidFeatureException(trainingInstances); } // End if if(!instanceFields.hasInstanceFields()){ throw new InvalidFeatureException(instanceFields); } KNNInputs knnInputs = nearestNeighborModel.getKNNInputs(); if(knnInputs == null){ throw new InvalidFeatureException(nearestNeighborModel); } // End if if(!knnInputs.hasKNNInputs()){ throw new InvalidFeatureException(knnInputs); } } @Override public String getSummary(){ return "k-Nearest neighbors model"; } @Override protected DataField getDataField(){ MiningFunction miningFunction = getMiningFunction(); switch(miningFunction){ case REGRESSION: case CLASSIFICATION: case MIXED: return null; default: return super.getDataField(); } } @Override public Map<FieldName, ?> evaluate(ModelEvaluationContext context){ NearestNeighborModel nearestNeighborModel = getModel(); if(!nearestNeighborModel.isScorable()){ throw new InvalidResultException(nearestNeighborModel); } ValueFactory<?> valueFactory; MathContext mathContext = nearestNeighborModel.getMathContext(); switch(mathContext){ case FLOAT: case DOUBLE: valueFactory = getValueFactory(); break; default: throw new UnsupportedFeatureException(nearestNeighborModel, mathContext); } Map<FieldName, ? extends AffinityDistribution<?>> predictions; MiningFunction miningFunction = nearestNeighborModel.getMiningFunction(); switch(miningFunction){ // The model contains one or more continuous and/or categorical target(s) case REGRESSION: case CLASSIFICATION: case MIXED: predictions = evaluateMixed(valueFactory, context); break; // The model does not contain targets case CLUSTERING: predictions = evaluateClustering(valueFactory, context); break; default: throw new UnsupportedFeatureException(nearestNeighborModel, miningFunction); } return OutputUtil.evaluate(predictions, context); } private <V extends Number> Map<FieldName, AffinityDistribution<V>> evaluateMixed(ValueFactory<V> valueFactory, EvaluationContext context){ NearestNeighborModel nearestNeighborModel = getModel(); Table<Integer, FieldName, FieldValue> table = getTrainingInstances(); List<InstanceResult<V>> instanceResults = evaluateInstanceRows(valueFactory, context); Ordering<InstanceResult<V>> ordering = (Ordering.natural()).reverse(); List<InstanceResult<V>> nearestInstanceResults = ordering.sortedCopy(instanceResults); nearestInstanceResults = nearestInstanceResults.subList(0, nearestNeighborModel.getNumberOfNeighbors()); Function<Integer, String> function = new Function<Integer, String>(){ @Override public String apply(Integer row){ return row.toString(); } }; FieldName instanceIdVariable = nearestNeighborModel.getInstanceIdVariable(); if(instanceIdVariable != null){ function = createIdentifierResolver(instanceIdVariable, table); } Map<FieldName, AffinityDistribution<V>> result = new LinkedHashMap<>(); List<TargetField> targetFields = getTargetFields(); for(TargetField targetField : targetFields){ FieldName name = targetField.getName(); DataField dataField = targetField.getDataField(); Object value; OpType opType = dataField.getOpType(); switch(opType){ case CONTINUOUS: value = calculateContinuousTarget(valueFactory, name, nearestInstanceResults, table); break; case CATEGORICAL: value = calculateCategoricalTarget(valueFactory, name, nearestInstanceResults, table); break; default: throw new UnsupportedFeatureException(dataField, opType); } value = TypeUtil.parseOrCast(dataField.getDataType(), value); result.put(name, createAffinityDistribution(instanceResults, function, value)); } return result; } private <V extends Number> Map<FieldName, AffinityDistribution<V>> evaluateClustering(ValueFactory<V> valueFactory, EvaluationContext context){ NearestNeighborModel nearestNeighborModel = getModel(); Table<Integer, FieldName, FieldValue> table = getTrainingInstances(); List<InstanceResult<V>> instanceResults = evaluateInstanceRows(valueFactory, context); FieldName instanceIdVariable = nearestNeighborModel.getInstanceIdVariable(); if(instanceIdVariable == null){ throw new InvalidFeatureException(nearestNeighborModel); } Function<Integer, String> function = createIdentifierResolver(instanceIdVariable, table); return Collections.singletonMap(getTargetFieldName(), createAffinityDistribution(instanceResults, function, null)); } private <V extends Number> List<InstanceResult<V>> evaluateInstanceRows(ValueFactory<V> valueFactory, EvaluationContext context){ NearestNeighborModel nearestNeighborModel = getModel(); ComparisonMeasure comparisonMeasure = nearestNeighborModel.getComparisonMeasure(); List<FieldValue> values = new ArrayList<>(); KNNInputs knnInputs = nearestNeighborModel.getKNNInputs(); for(KNNInput knnInput : knnInputs){ FieldValue value = context.evaluate(knnInput.getField()); values.add(value); } Measure measure = comparisonMeasure.getMeasure(); if(MeasureUtil.isSimilarity(measure)){ return evaluateSimilarity(valueFactory, comparisonMeasure, knnInputs.getKNNInputs(), values); } else if(MeasureUtil.isDistance(measure)){ return evaluateDistance(valueFactory, comparisonMeasure, knnInputs.getKNNInputs(), values); } else { throw new UnsupportedFeatureException(measure); } } private <V extends Number> List<InstanceResult<V>> evaluateSimilarity(ValueFactory<V> valueFactory, ComparisonMeasure comparisonMeasure, List<KNNInput> knnInputs, List<FieldValue> values){ BitSet flags = MeasureUtil.toBitSet(values); Map<Integer, BitSet> flagMap = getInstanceFlags(); List<InstanceResult<V>> result = new ArrayList<>(flagMap.size()); Set<Integer> rowKeys = flagMap.keySet(); for(Integer rowKey : rowKeys){ BitSet instanceFlags = flagMap.get(rowKey); Value<V> similarity = MeasureUtil.evaluateSimilarity(valueFactory, comparisonMeasure, knnInputs, flags, instanceFlags); result.add(new InstanceResult.Similarity<>(rowKey, similarity)); } return result; } private <V extends Number> List<InstanceResult<V>> evaluateDistance(ValueFactory<V> valueFactory, ComparisonMeasure comparisonMeasure, List<KNNInput> knnInputs, List<FieldValue> values){ Map<Integer, List<FieldValue>> valueMap = getInstanceValues(); List<InstanceResult<V>> result = new ArrayList<>(valueMap.size()); Value<V> adjustment = MeasureUtil.calculateAdjustment(valueFactory, values); Set<Integer> rowKeys = valueMap.keySet(); for(Integer rowKey : rowKeys){ List<FieldValue> instanceValues = valueMap.get(rowKey); Value<V> distance = MeasureUtil.evaluateDistance(valueFactory, comparisonMeasure, knnInputs, values, instanceValues, adjustment); result.add(new InstanceResult.Distance<>(rowKey, distance)); } return result; } private <V extends Number> V calculateContinuousTarget(final ValueFactory<V> valueFactory, FieldName name, List<InstanceResult<V>> instanceResults, Table<Integer, FieldName, FieldValue> table){ NearestNeighborModel nearestNeighborModel = getModel(); NearestNeighborModel.ContinuousScoringMethod continuousScoringMethod = nearestNeighborModel.getContinuousScoringMethod(); ValueAggregator<V> aggregator; switch(continuousScoringMethod){ case AVERAGE: aggregator = new ValueAggregator<>(valueFactory.newVector(0)); break; case WEIGHTED_AVERAGE: aggregator = new ValueAggregator<>(valueFactory.newVector(0), valueFactory.newVector(0), valueFactory.newVector(0)); break; case MEDIAN: aggregator = new ValueAggregator<>(valueFactory.newVector(instanceResults.size())); break; default: throw new UnsupportedFeatureException(nearestNeighborModel, continuousScoringMethod); } for(InstanceResult<V> instanceResult : instanceResults){ FieldValue value = table.get(instanceResult.getId(), name); if(value == null){ throw new MissingValueException(name); } Number number = value.asNumber(); switch(continuousScoringMethod){ case AVERAGE: case MEDIAN: aggregator.add(number); break; case WEIGHTED_AVERAGE: Value<V> weight = instanceResult.getWeight(nearestNeighborModel.getThreshold()); aggregator.add(number, weight.doubleValue()); break; default: throw new UnsupportedFeatureException(nearestNeighborModel, continuousScoringMethod); } } switch(continuousScoringMethod){ case AVERAGE: return (aggregator.average()).getValue(); case WEIGHTED_AVERAGE: return (aggregator.weightedAverage()).getValue(); case MEDIAN: return (aggregator.median()).getValue(); default: throw new UnsupportedFeatureException(nearestNeighborModel, continuousScoringMethod); } } @SuppressWarnings ( value = {"rawtypes", "unchecked"} ) private <V extends Number> Object calculateCategoricalTarget(final ValueFactory<V> valueFactory, FieldName name, List<InstanceResult<V>> instanceResults, Table<Integer, FieldName, FieldValue> table){ NearestNeighborModel nearestNeighborModel = getModel(); VoteAggregator<Object, V> aggregator = new VoteAggregator<Object, V>(){ @Override public ValueFactory<V> getValueFactory(){ return valueFactory; } }; NearestNeighborModel.CategoricalScoringMethod categoricalScoringMethod = nearestNeighborModel.getCategoricalScoringMethod(); for(InstanceResult<V> instanceResult : instanceResults){ FieldValue value = table.get(instanceResult.getId(), name); if(value == null){ throw new MissingValueException(name); } Object object = value.getValue(); switch(categoricalScoringMethod){ case MAJORITY_VOTE: aggregator.add(object); break; case WEIGHTED_MAJORITY_VOTE: Value<V> weight = instanceResult.getWeight(nearestNeighborModel.getThreshold()); aggregator.add(object, weight.doubleValue()); break; default: throw new UnsupportedFeatureException(nearestNeighborModel, categoricalScoringMethod); } } Set<Object> winners = aggregator.getWinners(); // "In case of a tie, the category with the largest number of cases in the training data is the winner" if(winners.size() > 1){ Multiset<Object> multiset = LinkedHashMultiset.create(); Map<Integer, FieldValue> column = table.column(name); Function<FieldValue, Object> function = new Function<FieldValue, Object>(){ @Override public Object apply(FieldValue value){ return value.getValue(); } }; multiset.addAll(Collections2.transform(column.values(), function)); aggregator.clear(); for(Object winner : winners){ aggregator.add(winner, multiset.count(winner)); } winners = aggregator.getWinners(); // "If multiple categories are tied on the largest number of cases in the training data, then the category with the smallest data value (in lexical order) among the tied categories is the winner" if(winners.size() > 1){ return Collections.min((Collection)winners); } } return Iterables.getFirst(winners, null); } private Function<Integer, String> createIdentifierResolver(final FieldName name, final Table<Integer, FieldName, FieldValue> table){ Function<Integer, String> function = new Function<Integer, String>(){ @Override public String apply(Integer row){ FieldValue value = table.get(row, name); if(value == null){ throw new MissingValueException(name); } return value.asString(); } }; return function; } private <V extends Number> AffinityDistribution<V> createAffinityDistribution(List<InstanceResult<V>> instanceResults, Function<Integer, String> function, Object value){ NearestNeighborModel nearestNeighborModel = getModel(); ComparisonMeasure comparisonMeasure = nearestNeighborModel.getComparisonMeasure(); AffinityDistribution<V> result; Measure measure = comparisonMeasure.getMeasure(); if(MeasureUtil.isSimilarity(measure)){ result = new AffinityDistribution<>(Classification.Type.SIMILARITY, value); } else if(MeasureUtil.isDistance(measure)){ result = new AffinityDistribution<>(Classification.Type.DISTANCE, value); } else { throw new UnsupportedFeatureException(measure); } for(InstanceResult<V> instanceResult : instanceResults){ result.put(function.apply(instanceResult.getId()), instanceResult.getValue()); } return result; } private Table<Integer, FieldName, FieldValue> getTrainingInstances(){ if(this.trainingInstances == null){ this.trainingInstances = getValue(NearestNeighborModelEvaluator.trainingInstanceCache, createTrainingInstanceLoader(this)); } return this.trainingInstances; } static private Callable<Table<Integer, FieldName, FieldValue>> createTrainingInstanceLoader(final NearestNeighborModelEvaluator modelEvaluator){ return new Callable<Table<Integer, FieldName, FieldValue>>(){ @Override public Table<Integer, FieldName, FieldValue> call(){ return parseTrainingInstances(modelEvaluator); } }; } static private Table<Integer, FieldName, FieldValue> parseTrainingInstances(NearestNeighborModelEvaluator modelEvaluator){ NearestNeighborModel nearestNeighborModel = modelEvaluator.getModel(); FieldName instanceIdVariable = nearestNeighborModel.getInstanceIdVariable(); TrainingInstances trainingInstances = nearestNeighborModel.getTrainingInstances(); List<FieldLoader> fieldLoaders = new ArrayList<>(); InstanceFields instanceFields = trainingInstances.getInstanceFields(); for(InstanceField instanceField : instanceFields){ FieldName name = instanceField.getField(); String column = instanceField.getColumn(); if(instanceIdVariable != null && (instanceIdVariable).equals(name)){ fieldLoaders.add(new IdentifierLoader(name, column)); continue; } TypeDefinitionField field = modelEvaluator.resolveField(name); if(field == null){ throw new MissingFieldException(name, instanceField); } // End if if(field instanceof DataField){ DataField dataField = (DataField)field; MiningField miningField = modelEvaluator.getMiningField(name); fieldLoaders.add(new DataFieldLoader(name, column, dataField, miningField)); } else if(field instanceof DerivedField){ DerivedField derivedField = (DerivedField)field; fieldLoaders.add(new DerivedFieldLoader(name, column, derivedField)); } else { throw new InvalidFeatureException(instanceField); } } Table<Integer, FieldName, FieldValue> result = HashBasedTable.create(); InlineTable inlineTable = InlineTableUtil.getInlineTable(trainingInstances); if(inlineTable != null){ Table<Integer, String, String> table = InlineTableUtil.getContent(inlineTable); Set<Integer> rowKeys = table.rowKeySet(); for(Integer rowKey : rowKeys){ Map<String, String> rowValues = table.row(rowKey); for(FieldLoader fieldLoader : fieldLoaders){ result.put(rowKey, fieldLoader.getName(), fieldLoader.load(rowValues)); } } } KNNInputs knnInputs = nearestNeighborModel.getKNNInputs(); for(KNNInput knnInput : knnInputs){ FieldName name = knnInput.getField(); DerivedField derivedField = modelEvaluator.resolveDerivedField(name); if(derivedField == null){ continue; } Set<Integer> rowKeys = result.rowKeySet(); for(Integer rowKey : rowKeys){ Map<FieldName, FieldValue> rowValues = result.row(rowKey); if(rowValues.containsKey(name)){ continue; } ModelEvaluationContext context = new ModelEvaluationContext(null, modelEvaluator); context.declareAll(rowValues); result.put(rowKey, name, ExpressionUtil.evaluate(derivedField, context)); } } return result; } private Map<Integer, BitSet> getInstanceFlags(){ if(this.instanceFlags == null){ this.instanceFlags = getValue(NearestNeighborModelEvaluator.instanceFlagCache, createInstanceFlagLoader(this)); } return this.instanceFlags; } static private Callable<Map<Integer, BitSet>> createInstanceFlagLoader(final NearestNeighborModelEvaluator modelEvaluator){ return new Callable<Map<Integer, BitSet>>(){ @Override public Map<Integer, BitSet> call(){ return loadInstanceFlags(modelEvaluator); } }; } static private Map<Integer, BitSet> loadInstanceFlags(NearestNeighborModelEvaluator modelEvaluator){ Map<Integer, BitSet> result = new LinkedHashMap<>(); Map<Integer, List<FieldValue>> valueMap = modelEvaluator.getValue(NearestNeighborModelEvaluator.instanceValueCache, createInstanceValueLoader(modelEvaluator)); Maps.EntryTransformer<Integer, List<FieldValue>, BitSet> transformer = new Maps.EntryTransformer<Integer, List<FieldValue>, BitSet>(){ @Override public BitSet transformEntry(Integer key, List<FieldValue> value){ return MeasureUtil.toBitSet(value); } }; result.putAll(Maps.transformEntries(valueMap, transformer)); return result; } private Map<Integer, List<FieldValue>> getInstanceValues(){ if(this.instanceValues == null){ this.instanceValues = getValue(NearestNeighborModelEvaluator.instanceValueCache, createInstanceValueLoader(this)); } return this.instanceValues; } static private Callable<Map<Integer, List<FieldValue>>> createInstanceValueLoader(final NearestNeighborModelEvaluator modelEvaluator){ return new Callable<Map<Integer, List<FieldValue>>>(){ @Override public Map<Integer, List<FieldValue>> call(){ return loadInstanceValues(modelEvaluator); } }; } static private Map<Integer, List<FieldValue>> loadInstanceValues(NearestNeighborModelEvaluator modelEvaluator){ NearestNeighborModel nearestNeighborModel = modelEvaluator.getModel(); Map<Integer, List<FieldValue>> result = new LinkedHashMap<>(); Table<Integer, FieldName, FieldValue> table = modelEvaluator.getValue(NearestNeighborModelEvaluator.trainingInstanceCache, createTrainingInstanceLoader(modelEvaluator)); KNNInputs knnInputs = nearestNeighborModel.getKNNInputs(); Set<Integer> rowKeys = ImmutableSortedSet.copyOf(table.rowKeySet()); for(Integer rowKey : rowKeys){ List<FieldValue> values = new ArrayList<>(); Map<FieldName, FieldValue> rowValues = table.row(rowKey); for(KNNInput knnInput : knnInputs){ FieldValue value = rowValues.get(knnInput.getField()); values.add(value); } result.put(rowKey, values); } return result; } static abstract private class FieldLoader { private FieldName name = null; private String column = null; private FieldLoader(FieldName name, String column){ setName(name); setColumn(column); } abstract public FieldValue prepare(String value); public FieldValue load(Map<String, String> values){ String value = values.get(getColumn()); return prepare(value); } public FieldName getName(){ return this.name; } private void setName(FieldName name){ this.name = name; } public String getColumn(){ return this.column; } private void setColumn(String column){ this.column = column; } } static private class IdentifierLoader extends FieldLoader { private IdentifierLoader(FieldName name, String column){ super(name, column); } @Override public FieldValue prepare(String value){ return FieldValueUtil.create(DataType.STRING, OpType.CATEGORICAL, value); } } static private class DataFieldLoader extends FieldLoader { private DataField dataField = null; private MiningField miningField = null; private DataFieldLoader(FieldName name, String column, DataField dataField, MiningField miningField){ super(name, column); setDataField(dataField); setMiningField(miningField); } @Override public FieldValue prepare(String value){ return FieldValueUtil.prepareInputValue(getDataField(), getMiningField(), value); } public DataField getDataField(){ return this.dataField; } private void setDataField(DataField dataField){ this.dataField = dataField; } public MiningField getMiningField(){ return this.miningField; } private void setMiningField(MiningField miningField){ this.miningField = miningField; } } static private class DerivedFieldLoader extends FieldLoader { private DerivedField derivedField = null; private DerivedFieldLoader(FieldName name, String column, DerivedField derivedField){ super(name, column); setDerivedField(derivedField); } @Override public FieldValue prepare(String value){ return FieldValueUtil.create(getDerivedField(), value); } public DerivedField getDerivedField(){ return this.derivedField; } private void setDerivedField(DerivedField derivedField){ this.derivedField = derivedField; } } static abstract private class InstanceResult<V extends Number> implements Comparable<InstanceResult<V>> { private Integer id = null; private Value<V> value = null; private InstanceResult(Integer id, Value<V> value){ setId(id); setValue(value); } abstract public Value<V> getWeight(double threshold); public Integer getId(){ return this.id; } private void setId(Integer id){ this.id = id; } public Value<V> getValue(){ return this.value; } private void setValue(Value<V> value){ this.value = value; } static private class Similarity<V extends Number> extends InstanceResult<V> { private Similarity(Integer id, Value<V> value){ super(id, value); } @Override public int compareTo(InstanceResult<V> that){ if(that instanceof Similarity){ return Classification.Type.SIMILARITY.compareValues(this.getValue(), that.getValue()); } throw new ClassCastException(); } @Override public Value<V> getWeight(double threshold){ throw new EvaluationException(); } } static private class Distance<V extends Number> extends InstanceResult<V> { private Distance(Integer id, Value<V> value){ super(id, value); } @Override public int compareTo(InstanceResult<V> that){ if(that instanceof Distance){ return Classification.Type.DISTANCE.compareValues(this.getValue(), that.getValue()); } throw new ClassCastException(); } @Override public Value<V> getWeight(double threshold){ Value<V> value = getValue(); value = value.copy(); if(threshold != 0d){ value.add(threshold); } return value.reciprocal(); } } } private static final Cache<NearestNeighborModel, Table<Integer, FieldName, FieldValue>> trainingInstanceCache = CacheUtil.buildCache(); private static final Cache<NearestNeighborModel, Map<Integer, BitSet>> instanceFlagCache = CacheUtil.buildCache(); private static final Cache<NearestNeighborModel, Map<Integer, List<FieldValue>>> instanceValueCache = CacheUtil.buildCache(); }
pmml-evaluator/src/main/java/org/jpmml/evaluator/nearest_neighbor/NearestNeighborModelEvaluator.java
/* * Copyright (c) 2013 KNIME.com AG, Zurich, Switzerland * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder 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 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.jpmml.evaluator.nearest_neighbor; import java.util.ArrayList; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import com.google.common.base.Function; import com.google.common.cache.Cache; import com.google.common.collect.Collections2; import com.google.common.collect.HashBasedTable; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Iterables; import com.google.common.collect.LinkedHashMultiset; import com.google.common.collect.Maps; import com.google.common.collect.Multiset; import com.google.common.collect.Ordering; import com.google.common.collect.Table; import org.dmg.pmml.ComparisonMeasure; import org.dmg.pmml.DataField; import org.dmg.pmml.DataType; import org.dmg.pmml.DerivedField; import org.dmg.pmml.FieldName; import org.dmg.pmml.InlineTable; import org.dmg.pmml.MathContext; import org.dmg.pmml.Measure; import org.dmg.pmml.MiningField; import org.dmg.pmml.MiningFunction; import org.dmg.pmml.OpType; import org.dmg.pmml.PMML; import org.dmg.pmml.TypeDefinitionField; import org.dmg.pmml.nearest_neighbor.InstanceField; import org.dmg.pmml.nearest_neighbor.InstanceFields; import org.dmg.pmml.nearest_neighbor.KNNInput; import org.dmg.pmml.nearest_neighbor.KNNInputs; import org.dmg.pmml.nearest_neighbor.NearestNeighborModel; import org.dmg.pmml.nearest_neighbor.TrainingInstances; import org.jpmml.evaluator.AffinityDistribution; import org.jpmml.evaluator.CacheUtil; import org.jpmml.evaluator.Classification; import org.jpmml.evaluator.ComplexDoubleVector; import org.jpmml.evaluator.EvaluationContext; import org.jpmml.evaluator.EvaluationException; import org.jpmml.evaluator.ExpressionUtil; import org.jpmml.evaluator.FieldValue; import org.jpmml.evaluator.FieldValueUtil; import org.jpmml.evaluator.InlineTableUtil; import org.jpmml.evaluator.InvalidFeatureException; import org.jpmml.evaluator.InvalidResultException; import org.jpmml.evaluator.MeasureUtil; import org.jpmml.evaluator.MissingFieldException; import org.jpmml.evaluator.MissingValueException; import org.jpmml.evaluator.ModelEvaluationContext; import org.jpmml.evaluator.ModelEvaluator; import org.jpmml.evaluator.OutputUtil; import org.jpmml.evaluator.SimpleDoubleVector; import org.jpmml.evaluator.TargetField; import org.jpmml.evaluator.TypeUtil; import org.jpmml.evaluator.UnsupportedFeatureException; import org.jpmml.evaluator.Value; import org.jpmml.evaluator.ValueAggregator; import org.jpmml.evaluator.ValueFactory; import org.jpmml.evaluator.VoteAggregator; public class NearestNeighborModelEvaluator extends ModelEvaluator<NearestNeighborModel> { transient private Table<Integer, FieldName, FieldValue> trainingInstances = null; transient private Map<Integer, BitSet> instanceFlags = null; transient private Map<Integer, List<FieldValue>> instanceValues = null; public NearestNeighborModelEvaluator(PMML pmml){ this(pmml, selectModel(pmml, NearestNeighborModel.class)); } public NearestNeighborModelEvaluator(PMML pmml, NearestNeighborModel nearestNeighborModel){ super(pmml, nearestNeighborModel); ComparisonMeasure comparisoonMeasure = nearestNeighborModel.getComparisonMeasure(); if(comparisoonMeasure == null){ throw new InvalidFeatureException(nearestNeighborModel); } TrainingInstances trainingInstances = nearestNeighborModel.getTrainingInstances(); if(trainingInstances == null){ throw new InvalidFeatureException(nearestNeighborModel); } InstanceFields instanceFields = trainingInstances.getInstanceFields(); if(instanceFields == null){ throw new InvalidFeatureException(trainingInstances); } // End if if(!instanceFields.hasInstanceFields()){ throw new InvalidFeatureException(instanceFields); } KNNInputs knnInputs = nearestNeighborModel.getKNNInputs(); if(knnInputs == null){ throw new InvalidFeatureException(nearestNeighborModel); } // End if if(!knnInputs.hasKNNInputs()){ throw new InvalidFeatureException(knnInputs); } } @Override public String getSummary(){ return "k-Nearest neighbors model"; } @Override protected DataField getDataField(){ MiningFunction miningFunction = getMiningFunction(); switch(miningFunction){ case REGRESSION: case CLASSIFICATION: case MIXED: return null; default: return super.getDataField(); } } @Override public Map<FieldName, ?> evaluate(ModelEvaluationContext context){ NearestNeighborModel nearestNeighborModel = getModel(); if(!nearestNeighborModel.isScorable()){ throw new InvalidResultException(nearestNeighborModel); } ValueFactory<Double> valueFactory; MathContext mathContext = nearestNeighborModel.getMathContext(); switch(mathContext){ case DOUBLE: valueFactory = (ValueFactory)getValueFactory(); break; default: throw new UnsupportedFeatureException(nearestNeighborModel, mathContext); } Map<FieldName, AffinityDistribution<Double>> predictions; MiningFunction miningFunction = nearestNeighborModel.getMiningFunction(); switch(miningFunction){ // The model contains one or more continuous and/or categorical target(s) case REGRESSION: case CLASSIFICATION: case MIXED: predictions = evaluateMixed(valueFactory, context); break; // The model does not contain targets case CLUSTERING: predictions = evaluateClustering(valueFactory, context); break; default: throw new UnsupportedFeatureException(nearestNeighborModel, miningFunction); } return OutputUtil.evaluate(predictions, context); } private Map<FieldName, AffinityDistribution<Double>> evaluateMixed(ValueFactory<Double> valueFactory, EvaluationContext context){ NearestNeighborModel nearestNeighborModel = getModel(); Table<Integer, FieldName, FieldValue> table = getTrainingInstances(); List<InstanceResult> instanceResults = evaluateInstanceRows(valueFactory, context); Ordering<InstanceResult> ordering = (Ordering.natural()).reverse(); List<InstanceResult> nearestInstanceResults = ordering.sortedCopy(instanceResults); nearestInstanceResults = nearestInstanceResults.subList(0, nearestNeighborModel.getNumberOfNeighbors()); Function<Integer, String> function = new Function<Integer, String>(){ @Override public String apply(Integer row){ return row.toString(); } }; FieldName instanceIdVariable = nearestNeighborModel.getInstanceIdVariable(); if(instanceIdVariable != null){ function = createIdentifierResolver(instanceIdVariable, table); } Map<FieldName, AffinityDistribution<Double>> result = new LinkedHashMap<>(); List<TargetField> targetFields = getTargetFields(); for(TargetField targetField : targetFields){ FieldName name = targetField.getName(); DataField dataField = targetField.getDataField(); Object value; OpType opType = dataField.getOpType(); switch(opType){ case CONTINUOUS: value = calculateContinuousTarget(name, nearestInstanceResults, table); break; case CATEGORICAL: value = calculateCategoricalTarget(name, nearestInstanceResults, table); break; default: throw new UnsupportedFeatureException(dataField, opType); } value = TypeUtil.parseOrCast(dataField.getDataType(), value); result.put(name, createAffinityDistribution(instanceResults, function, value)); } return result; } private Map<FieldName, AffinityDistribution<Double>> evaluateClustering(ValueFactory<Double> valueFactory, EvaluationContext context){ NearestNeighborModel nearestNeighborModel = getModel(); Table<Integer, FieldName, FieldValue> table = getTrainingInstances(); List<InstanceResult> instanceResults = evaluateInstanceRows(valueFactory, context); FieldName instanceIdVariable = nearestNeighborModel.getInstanceIdVariable(); if(instanceIdVariable == null){ throw new InvalidFeatureException(nearestNeighborModel); } Function<Integer, String> function = createIdentifierResolver(instanceIdVariable, table); return Collections.singletonMap(getTargetFieldName(), createAffinityDistribution(instanceResults, function, null)); } private List<InstanceResult> evaluateInstanceRows(ValueFactory<Double> valueFactory, EvaluationContext context){ NearestNeighborModel nearestNeighborModel = getModel(); ComparisonMeasure comparisonMeasure = nearestNeighborModel.getComparisonMeasure(); List<FieldValue> values = new ArrayList<>(); KNNInputs knnInputs = nearestNeighborModel.getKNNInputs(); for(KNNInput knnInput : knnInputs){ FieldValue value = context.evaluate(knnInput.getField()); values.add(value); } Measure measure = comparisonMeasure.getMeasure(); if(MeasureUtil.isSimilarity(measure)){ return evaluateSimilarity(valueFactory, comparisonMeasure, knnInputs.getKNNInputs(), values); } else if(MeasureUtil.isDistance(measure)){ return evaluateDistance(valueFactory, comparisonMeasure, knnInputs.getKNNInputs(), values); } else { throw new UnsupportedFeatureException(measure); } } private List<InstanceResult> evaluateSimilarity(ValueFactory<Double> valueFactory, ComparisonMeasure comparisonMeasure, List<KNNInput> knnInputs, List<FieldValue> values){ BitSet flags = MeasureUtil.toBitSet(values); Map<Integer, BitSet> flagMap = getInstanceFlags(); List<InstanceResult> result = new ArrayList<>(flagMap.size()); Set<Integer> rowKeys = flagMap.keySet(); for(Integer rowKey : rowKeys){ BitSet instanceFlags = flagMap.get(rowKey); Value<Double> similarity = MeasureUtil.evaluateSimilarity(valueFactory, comparisonMeasure, knnInputs, flags, instanceFlags); result.add(new InstanceResult.Similarity(rowKey, similarity)); } return result; } private List<InstanceResult> evaluateDistance(ValueFactory<Double> valueFactory, ComparisonMeasure comparisonMeasure, List<KNNInput> knnInputs, List<FieldValue> values){ Map<Integer, List<FieldValue>> valueMap = getInstanceValues(); List<InstanceResult> result = new ArrayList<>(valueMap.size()); Value<Double> adjustment = MeasureUtil.calculateAdjustment(valueFactory, values); Set<Integer> rowKeys = valueMap.keySet(); for(Integer rowKey : rowKeys){ List<FieldValue> instanceValues = valueMap.get(rowKey); Value<Double> distance = MeasureUtil.evaluateDistance(valueFactory, comparisonMeasure, knnInputs, values, instanceValues, adjustment); result.add(new InstanceResult.Distance(rowKey, distance)); } return result; } private Double calculateContinuousTarget(FieldName name, List<InstanceResult> instanceResults, Table<Integer, FieldName, FieldValue> table){ NearestNeighborModel nearestNeighborModel = getModel(); NearestNeighborModel.ContinuousScoringMethod continuousScoringMethod = nearestNeighborModel.getContinuousScoringMethod(); ValueAggregator<Double> aggregator; switch(continuousScoringMethod){ case AVERAGE: aggregator = new ValueAggregator<>(new SimpleDoubleVector()); break; case WEIGHTED_AVERAGE: aggregator = new ValueAggregator<>(new SimpleDoubleVector(), new SimpleDoubleVector(), new SimpleDoubleVector()); break; case MEDIAN: aggregator = new ValueAggregator<>(new ComplexDoubleVector(instanceResults.size())); break; default: throw new UnsupportedFeatureException(nearestNeighborModel, continuousScoringMethod); } for(InstanceResult instanceResult : instanceResults){ FieldValue value = table.get(instanceResult.getId(), name); if(value == null){ throw new MissingValueException(name); } Number number = value.asNumber(); switch(continuousScoringMethod){ case AVERAGE: case MEDIAN: aggregator.add(number); break; case WEIGHTED_AVERAGE: double weight = instanceResult.getWeight(nearestNeighborModel.getThreshold()); aggregator.add(number, weight); break; default: throw new UnsupportedFeatureException(nearestNeighborModel, continuousScoringMethod); } } switch(continuousScoringMethod){ case AVERAGE: return (aggregator.average()).getValue(); case WEIGHTED_AVERAGE: return (aggregator.weightedAverage()).getValue(); case MEDIAN: return (aggregator.median()).getValue(); default: throw new UnsupportedFeatureException(nearestNeighborModel, continuousScoringMethod); } } @SuppressWarnings ( value = {"rawtypes", "unchecked"} ) private Object calculateCategoricalTarget(FieldName name, List<InstanceResult> instanceResults, Table<Integer, FieldName, FieldValue> table){ NearestNeighborModel nearestNeighborModel = getModel(); VoteAggregator<Object, Double> aggregator = new VoteAggregator<Object, Double>(){ @Override public ValueFactory<Double> getValueFactory(){ return (ValueFactory)NearestNeighborModelEvaluator.this.getValueFactory(); } }; NearestNeighborModel.CategoricalScoringMethod categoricalScoringMethod = nearestNeighborModel.getCategoricalScoringMethod(); for(InstanceResult instanceResult : instanceResults){ FieldValue value = table.get(instanceResult.getId(), name); if(value == null){ throw new MissingValueException(name); } Object object = value.getValue(); switch(categoricalScoringMethod){ case MAJORITY_VOTE: aggregator.add(object); break; case WEIGHTED_MAJORITY_VOTE: double weight = instanceResult.getWeight(nearestNeighborModel.getThreshold()); aggregator.add(object, weight); break; default: throw new UnsupportedFeatureException(nearestNeighborModel, categoricalScoringMethod); } } Set<Object> winners = aggregator.getWinners(); // "In case of a tie, the category with the largest number of cases in the training data is the winner" if(winners.size() > 1){ Multiset<Object> multiset = LinkedHashMultiset.create(); Map<Integer, FieldValue> column = table.column(name); Function<FieldValue, Object> function = new Function<FieldValue, Object>(){ @Override public Object apply(FieldValue value){ return value.getValue(); } }; multiset.addAll(Collections2.transform(column.values(), function)); aggregator.clear(); for(Object winner : winners){ aggregator.add(winner, multiset.count(winner)); } winners = aggregator.getWinners(); // "If multiple categories are tied on the largest number of cases in the training data, then the category with the smallest data value (in lexical order) among the tied categories is the winner" if(winners.size() > 1){ return Collections.min((Collection)winners); } } return Iterables.getFirst(winners, null); } private Function<Integer, String> createIdentifierResolver(final FieldName name, final Table<Integer, FieldName, FieldValue> table){ Function<Integer, String> function = new Function<Integer, String>(){ @Override public String apply(Integer row){ FieldValue value = table.get(row, name); if(value == null){ throw new MissingValueException(name); } return value.asString(); } }; return function; } private AffinityDistribution<Double> createAffinityDistribution(List<InstanceResult> instanceResults, Function<Integer, String> function, Object value){ NearestNeighborModel nearestNeighborModel = getModel(); AffinityDistribution<Double> result; ComparisonMeasure comparisonMeasure = nearestNeighborModel.getComparisonMeasure(); Measure measure = comparisonMeasure.getMeasure(); if(MeasureUtil.isSimilarity(measure)){ result = new AffinityDistribution<>(Classification.Type.SIMILARITY, value); } else if(MeasureUtil.isDistance(measure)){ result = new AffinityDistribution<>(Classification.Type.DISTANCE, value); } else { throw new UnsupportedFeatureException(measure); } for(InstanceResult instanceResult : instanceResults){ result.put(function.apply(instanceResult.getId()), instanceResult.getValue()); } return result; } private Table<Integer, FieldName, FieldValue> getTrainingInstances(){ if(this.trainingInstances == null){ this.trainingInstances = getValue(NearestNeighborModelEvaluator.trainingInstanceCache, createTrainingInstanceLoader(this)); } return this.trainingInstances; } static private Callable<Table<Integer, FieldName, FieldValue>> createTrainingInstanceLoader(final NearestNeighborModelEvaluator modelEvaluator){ return new Callable<Table<Integer, FieldName, FieldValue>>(){ @Override public Table<Integer, FieldName, FieldValue> call(){ return parseTrainingInstances(modelEvaluator); } }; } static private Table<Integer, FieldName, FieldValue> parseTrainingInstances(NearestNeighborModelEvaluator modelEvaluator){ NearestNeighborModel nearestNeighborModel = modelEvaluator.getModel(); FieldName instanceIdVariable = nearestNeighborModel.getInstanceIdVariable(); TrainingInstances trainingInstances = nearestNeighborModel.getTrainingInstances(); List<FieldLoader> fieldLoaders = new ArrayList<>(); InstanceFields instanceFields = trainingInstances.getInstanceFields(); for(InstanceField instanceField : instanceFields){ FieldName name = instanceField.getField(); String column = instanceField.getColumn(); if(instanceIdVariable != null && (instanceIdVariable).equals(name)){ fieldLoaders.add(new IdentifierLoader(name, column)); continue; } TypeDefinitionField field = modelEvaluator.resolveField(name); if(field == null){ throw new MissingFieldException(name, instanceField); } // End if if(field instanceof DataField){ DataField dataField = (DataField)field; MiningField miningField = modelEvaluator.getMiningField(name); fieldLoaders.add(new DataFieldLoader(name, column, dataField, miningField)); } else if(field instanceof DerivedField){ DerivedField derivedField = (DerivedField)field; fieldLoaders.add(new DerivedFieldLoader(name, column, derivedField)); } else { throw new InvalidFeatureException(instanceField); } } Table<Integer, FieldName, FieldValue> result = HashBasedTable.create(); InlineTable inlineTable = InlineTableUtil.getInlineTable(trainingInstances); if(inlineTable != null){ Table<Integer, String, String> table = InlineTableUtil.getContent(inlineTable); Set<Integer> rowKeys = table.rowKeySet(); for(Integer rowKey : rowKeys){ Map<String, String> rowValues = table.row(rowKey); for(FieldLoader fieldLoader : fieldLoaders){ result.put(rowKey, fieldLoader.getName(), fieldLoader.load(rowValues)); } } } KNNInputs knnInputs = nearestNeighborModel.getKNNInputs(); for(KNNInput knnInput : knnInputs){ FieldName name = knnInput.getField(); DerivedField derivedField = modelEvaluator.resolveDerivedField(name); if(derivedField == null){ continue; } Set<Integer> rowKeys = result.rowKeySet(); for(Integer rowKey : rowKeys){ Map<FieldName, FieldValue> rowValues = result.row(rowKey); if(rowValues.containsKey(name)){ continue; } ModelEvaluationContext context = new ModelEvaluationContext(null, modelEvaluator); context.declareAll(rowValues); result.put(rowKey, name, ExpressionUtil.evaluate(derivedField, context)); } } return result; } private Map<Integer, BitSet> getInstanceFlags(){ if(this.instanceFlags == null){ this.instanceFlags = getValue(NearestNeighborModelEvaluator.instanceFlagCache, createInstanceFlagLoader(this)); } return this.instanceFlags; } static private Callable<Map<Integer, BitSet>> createInstanceFlagLoader(final NearestNeighborModelEvaluator modelEvaluator){ return new Callable<Map<Integer, BitSet>>(){ @Override public Map<Integer, BitSet> call(){ return loadInstanceFlags(modelEvaluator); } }; } static private Map<Integer, BitSet> loadInstanceFlags(NearestNeighborModelEvaluator modelEvaluator){ Map<Integer, BitSet> result = new LinkedHashMap<>(); Map<Integer, List<FieldValue>> valueMap = modelEvaluator.getValue(NearestNeighborModelEvaluator.instanceValueCache, createInstanceValueLoader(modelEvaluator)); Maps.EntryTransformer<Integer, List<FieldValue>, BitSet> transformer = new Maps.EntryTransformer<Integer, List<FieldValue>, BitSet>(){ @Override public BitSet transformEntry(Integer key, List<FieldValue> value){ return MeasureUtil.toBitSet(value); } }; result.putAll(Maps.transformEntries(valueMap, transformer)); return result; } private Map<Integer, List<FieldValue>> getInstanceValues(){ if(this.instanceValues == null){ this.instanceValues = getValue(NearestNeighborModelEvaluator.instanceValueCache, createInstanceValueLoader(this)); } return this.instanceValues; } static private Callable<Map<Integer, List<FieldValue>>> createInstanceValueLoader(final NearestNeighborModelEvaluator modelEvaluator){ return new Callable<Map<Integer, List<FieldValue>>>(){ @Override public Map<Integer, List<FieldValue>> call(){ return loadInstanceValues(modelEvaluator); } }; } static private Map<Integer, List<FieldValue>> loadInstanceValues(NearestNeighborModelEvaluator modelEvaluator){ NearestNeighborModel nearestNeighborModel = modelEvaluator.getModel(); Map<Integer, List<FieldValue>> result = new LinkedHashMap<>(); Table<Integer, FieldName, FieldValue> table = modelEvaluator.getValue(NearestNeighborModelEvaluator.trainingInstanceCache, createTrainingInstanceLoader(modelEvaluator)); KNNInputs knnInputs = nearestNeighborModel.getKNNInputs(); Set<Integer> rowKeys = ImmutableSortedSet.copyOf(table.rowKeySet()); for(Integer rowKey : rowKeys){ List<FieldValue> values = new ArrayList<>(); Map<FieldName, FieldValue> rowValues = table.row(rowKey); for(KNNInput knnInput : knnInputs){ FieldValue value = rowValues.get(knnInput.getField()); values.add(value); } result.put(rowKey, values); } return result; } static abstract private class FieldLoader { private FieldName name = null; private String column = null; private FieldLoader(FieldName name, String column){ setName(name); setColumn(column); } abstract public FieldValue prepare(String value); public FieldValue load(Map<String, String> values){ String value = values.get(getColumn()); return prepare(value); } public FieldName getName(){ return this.name; } private void setName(FieldName name){ this.name = name; } public String getColumn(){ return this.column; } private void setColumn(String column){ this.column = column; } } static private class IdentifierLoader extends FieldLoader { private IdentifierLoader(FieldName name, String column){ super(name, column); } @Override public FieldValue prepare(String value){ return FieldValueUtil.create(DataType.STRING, OpType.CATEGORICAL, value); } } static private class DataFieldLoader extends FieldLoader { private DataField dataField = null; private MiningField miningField = null; private DataFieldLoader(FieldName name, String column, DataField dataField, MiningField miningField){ super(name, column); setDataField(dataField); setMiningField(miningField); } @Override public FieldValue prepare(String value){ return FieldValueUtil.prepareInputValue(getDataField(), getMiningField(), value); } public DataField getDataField(){ return this.dataField; } private void setDataField(DataField dataField){ this.dataField = dataField; } public MiningField getMiningField(){ return this.miningField; } private void setMiningField(MiningField miningField){ this.miningField = miningField; } } static private class DerivedFieldLoader extends FieldLoader { private DerivedField derivedField = null; private DerivedFieldLoader(FieldName name, String column, DerivedField derivedField){ super(name, column); setDerivedField(derivedField); } @Override public FieldValue prepare(String value){ return FieldValueUtil.create(getDerivedField(), value); } public DerivedField getDerivedField(){ return this.derivedField; } private void setDerivedField(DerivedField derivedField){ this.derivedField = derivedField; } } static abstract private class InstanceResult implements Comparable<InstanceResult> { private Integer id = null; private Value<Double> value = null; private InstanceResult(Integer id, Value<Double> value){ setId(id); setValue(value); } abstract public double getWeight(double threshold); public Integer getId(){ return this.id; } private void setId(Integer id){ this.id = id; } public Value<Double> getValue(){ return this.value; } private void setValue(Value<Double> value){ this.value = value; } static private class Similarity extends InstanceResult { private Similarity(Integer id, Value<Double> value){ super(id, value); } @Override public int compareTo(InstanceResult that){ if(that instanceof Similarity){ return Classification.Type.SIMILARITY.compareValues(this.getValue(), that.getValue()); } throw new ClassCastException(); } @Override public double getWeight(double threshold){ throw new EvaluationException(); } } static private class Distance extends InstanceResult { private Distance(Integer id, Value<Double> value){ super(id, value); } @Override public int compareTo(InstanceResult that){ if(that instanceof Distance){ return Classification.Type.DISTANCE.compareValues(this.getValue(), that.getValue()); } throw new ClassCastException(); } @Override public double getWeight(double threshold){ Value<Double> value = getValue(); return 1d / (value.doubleValue() + threshold); } } } private static final Cache<NearestNeighborModel, Table<Integer, FieldName, FieldValue>> trainingInstanceCache = CacheUtil.buildCache(); private static final Cache<NearestNeighborModel, Map<Integer, BitSet>> instanceFlagCache = CacheUtil.buildCache(); private static final Cache<NearestNeighborModel, Map<Integer, List<FieldValue>>> instanceValueCache = CacheUtil.buildCache(); }
Refactored the evaluation of nearest neighbor models
pmml-evaluator/src/main/java/org/jpmml/evaluator/nearest_neighbor/NearestNeighborModelEvaluator.java
Refactored the evaluation of nearest neighbor models
<ide><path>mml-evaluator/src/main/java/org/jpmml/evaluator/nearest_neighbor/NearestNeighborModelEvaluator.java <ide> import org.jpmml.evaluator.AffinityDistribution; <ide> import org.jpmml.evaluator.CacheUtil; <ide> import org.jpmml.evaluator.Classification; <del>import org.jpmml.evaluator.ComplexDoubleVector; <ide> import org.jpmml.evaluator.EvaluationContext; <ide> import org.jpmml.evaluator.EvaluationException; <ide> import org.jpmml.evaluator.ExpressionUtil; <ide> import org.jpmml.evaluator.ModelEvaluationContext; <ide> import org.jpmml.evaluator.ModelEvaluator; <ide> import org.jpmml.evaluator.OutputUtil; <del>import org.jpmml.evaluator.SimpleDoubleVector; <ide> import org.jpmml.evaluator.TargetField; <ide> import org.jpmml.evaluator.TypeUtil; <ide> import org.jpmml.evaluator.UnsupportedFeatureException; <ide> throw new InvalidResultException(nearestNeighborModel); <ide> } <ide> <del> ValueFactory<Double> valueFactory; <add> ValueFactory<?> valueFactory; <ide> <ide> MathContext mathContext = nearestNeighborModel.getMathContext(); <ide> switch(mathContext){ <add> case FLOAT: <ide> case DOUBLE: <del> valueFactory = (ValueFactory)getValueFactory(); <add> valueFactory = getValueFactory(); <ide> break; <ide> default: <ide> throw new UnsupportedFeatureException(nearestNeighborModel, mathContext); <ide> } <ide> <del> Map<FieldName, AffinityDistribution<Double>> predictions; <add> Map<FieldName, ? extends AffinityDistribution<?>> predictions; <ide> <ide> MiningFunction miningFunction = nearestNeighborModel.getMiningFunction(); <ide> switch(miningFunction){ <ide> return OutputUtil.evaluate(predictions, context); <ide> } <ide> <del> private Map<FieldName, AffinityDistribution<Double>> evaluateMixed(ValueFactory<Double> valueFactory, EvaluationContext context){ <add> private <V extends Number> Map<FieldName, AffinityDistribution<V>> evaluateMixed(ValueFactory<V> valueFactory, EvaluationContext context){ <ide> NearestNeighborModel nearestNeighborModel = getModel(); <ide> <ide> Table<Integer, FieldName, FieldValue> table = getTrainingInstances(); <ide> <del> List<InstanceResult> instanceResults = evaluateInstanceRows(valueFactory, context); <del> <del> Ordering<InstanceResult> ordering = (Ordering.natural()).reverse(); <del> <del> List<InstanceResult> nearestInstanceResults = ordering.sortedCopy(instanceResults); <add> List<InstanceResult<V>> instanceResults = evaluateInstanceRows(valueFactory, context); <add> <add> Ordering<InstanceResult<V>> ordering = (Ordering.natural()).reverse(); <add> <add> List<InstanceResult<V>> nearestInstanceResults = ordering.sortedCopy(instanceResults); <ide> <ide> nearestInstanceResults = nearestInstanceResults.subList(0, nearestNeighborModel.getNumberOfNeighbors()); <ide> <ide> function = createIdentifierResolver(instanceIdVariable, table); <ide> } <ide> <del> Map<FieldName, AffinityDistribution<Double>> result = new LinkedHashMap<>(); <add> Map<FieldName, AffinityDistribution<V>> result = new LinkedHashMap<>(); <ide> <ide> List<TargetField> targetFields = getTargetFields(); <ide> for(TargetField targetField : targetFields){ <ide> OpType opType = dataField.getOpType(); <ide> switch(opType){ <ide> case CONTINUOUS: <del> value = calculateContinuousTarget(name, nearestInstanceResults, table); <add> value = calculateContinuousTarget(valueFactory, name, nearestInstanceResults, table); <ide> break; <ide> case CATEGORICAL: <del> value = calculateCategoricalTarget(name, nearestInstanceResults, table); <add> value = calculateCategoricalTarget(valueFactory, name, nearestInstanceResults, table); <ide> break; <ide> default: <ide> throw new UnsupportedFeatureException(dataField, opType); <ide> return result; <ide> } <ide> <del> private Map<FieldName, AffinityDistribution<Double>> evaluateClustering(ValueFactory<Double> valueFactory, EvaluationContext context){ <add> private <V extends Number> Map<FieldName, AffinityDistribution<V>> evaluateClustering(ValueFactory<V> valueFactory, EvaluationContext context){ <ide> NearestNeighborModel nearestNeighborModel = getModel(); <ide> <ide> Table<Integer, FieldName, FieldValue> table = getTrainingInstances(); <ide> <del> List<InstanceResult> instanceResults = evaluateInstanceRows(valueFactory, context); <add> List<InstanceResult<V>> instanceResults = evaluateInstanceRows(valueFactory, context); <ide> <ide> FieldName instanceIdVariable = nearestNeighborModel.getInstanceIdVariable(); <ide> if(instanceIdVariable == null){ <ide> return Collections.singletonMap(getTargetFieldName(), createAffinityDistribution(instanceResults, function, null)); <ide> } <ide> <del> private List<InstanceResult> evaluateInstanceRows(ValueFactory<Double> valueFactory, EvaluationContext context){ <add> private <V extends Number> List<InstanceResult<V>> evaluateInstanceRows(ValueFactory<V> valueFactory, EvaluationContext context){ <ide> NearestNeighborModel nearestNeighborModel = getModel(); <ide> <ide> ComparisonMeasure comparisonMeasure = nearestNeighborModel.getComparisonMeasure(); <ide> } <ide> } <ide> <del> private List<InstanceResult> evaluateSimilarity(ValueFactory<Double> valueFactory, ComparisonMeasure comparisonMeasure, List<KNNInput> knnInputs, List<FieldValue> values){ <add> private <V extends Number> List<InstanceResult<V>> evaluateSimilarity(ValueFactory<V> valueFactory, ComparisonMeasure comparisonMeasure, List<KNNInput> knnInputs, List<FieldValue> values){ <ide> BitSet flags = MeasureUtil.toBitSet(values); <ide> <ide> Map<Integer, BitSet> flagMap = getInstanceFlags(); <ide> <del> List<InstanceResult> result = new ArrayList<>(flagMap.size()); <add> List<InstanceResult<V>> result = new ArrayList<>(flagMap.size()); <ide> <ide> Set<Integer> rowKeys = flagMap.keySet(); <ide> for(Integer rowKey : rowKeys){ <ide> BitSet instanceFlags = flagMap.get(rowKey); <ide> <del> Value<Double> similarity = MeasureUtil.evaluateSimilarity(valueFactory, comparisonMeasure, knnInputs, flags, instanceFlags); <del> <del> result.add(new InstanceResult.Similarity(rowKey, similarity)); <add> Value<V> similarity = MeasureUtil.evaluateSimilarity(valueFactory, comparisonMeasure, knnInputs, flags, instanceFlags); <add> <add> result.add(new InstanceResult.Similarity<>(rowKey, similarity)); <ide> } <ide> <ide> return result; <ide> } <ide> <del> private List<InstanceResult> evaluateDistance(ValueFactory<Double> valueFactory, ComparisonMeasure comparisonMeasure, List<KNNInput> knnInputs, List<FieldValue> values){ <add> private <V extends Number> List<InstanceResult<V>> evaluateDistance(ValueFactory<V> valueFactory, ComparisonMeasure comparisonMeasure, List<KNNInput> knnInputs, List<FieldValue> values){ <ide> Map<Integer, List<FieldValue>> valueMap = getInstanceValues(); <ide> <del> List<InstanceResult> result = new ArrayList<>(valueMap.size()); <del> <del> Value<Double> adjustment = MeasureUtil.calculateAdjustment(valueFactory, values); <add> List<InstanceResult<V>> result = new ArrayList<>(valueMap.size()); <add> <add> Value<V> adjustment = MeasureUtil.calculateAdjustment(valueFactory, values); <ide> <ide> Set<Integer> rowKeys = valueMap.keySet(); <ide> for(Integer rowKey : rowKeys){ <ide> List<FieldValue> instanceValues = valueMap.get(rowKey); <ide> <del> Value<Double> distance = MeasureUtil.evaluateDistance(valueFactory, comparisonMeasure, knnInputs, values, instanceValues, adjustment); <del> <del> result.add(new InstanceResult.Distance(rowKey, distance)); <add> Value<V> distance = MeasureUtil.evaluateDistance(valueFactory, comparisonMeasure, knnInputs, values, instanceValues, adjustment); <add> <add> result.add(new InstanceResult.Distance<>(rowKey, distance)); <ide> } <ide> <ide> return result; <ide> } <ide> <del> private Double calculateContinuousTarget(FieldName name, List<InstanceResult> instanceResults, Table<Integer, FieldName, FieldValue> table){ <add> private <V extends Number> V calculateContinuousTarget(final ValueFactory<V> valueFactory, FieldName name, List<InstanceResult<V>> instanceResults, Table<Integer, FieldName, FieldValue> table){ <ide> NearestNeighborModel nearestNeighborModel = getModel(); <ide> <ide> NearestNeighborModel.ContinuousScoringMethod continuousScoringMethod = nearestNeighborModel.getContinuousScoringMethod(); <ide> <del> ValueAggregator<Double> aggregator; <add> ValueAggregator<V> aggregator; <ide> <ide> switch(continuousScoringMethod){ <ide> case AVERAGE: <del> aggregator = new ValueAggregator<>(new SimpleDoubleVector()); <add> aggregator = new ValueAggregator<>(valueFactory.newVector(0)); <ide> break; <ide> case WEIGHTED_AVERAGE: <del> aggregator = new ValueAggregator<>(new SimpleDoubleVector(), new SimpleDoubleVector(), new SimpleDoubleVector()); <add> aggregator = new ValueAggregator<>(valueFactory.newVector(0), valueFactory.newVector(0), valueFactory.newVector(0)); <ide> break; <ide> case MEDIAN: <del> aggregator = new ValueAggregator<>(new ComplexDoubleVector(instanceResults.size())); <add> aggregator = new ValueAggregator<>(valueFactory.newVector(instanceResults.size())); <ide> break; <ide> default: <ide> throw new UnsupportedFeatureException(nearestNeighborModel, continuousScoringMethod); <ide> } <ide> <del> for(InstanceResult instanceResult : instanceResults){ <add> for(InstanceResult<V> instanceResult : instanceResults){ <ide> FieldValue value = table.get(instanceResult.getId(), name); <ide> if(value == null){ <ide> throw new MissingValueException(name); <ide> aggregator.add(number); <ide> break; <ide> case WEIGHTED_AVERAGE: <del> double weight = instanceResult.getWeight(nearestNeighborModel.getThreshold()); <del> <del> aggregator.add(number, weight); <add> Value<V> weight = instanceResult.getWeight(nearestNeighborModel.getThreshold()); <add> <add> aggregator.add(number, weight.doubleValue()); <ide> break; <ide> default: <ide> throw new UnsupportedFeatureException(nearestNeighborModel, continuousScoringMethod); <ide> @SuppressWarnings ( <ide> value = {"rawtypes", "unchecked"} <ide> ) <del> private Object calculateCategoricalTarget(FieldName name, List<InstanceResult> instanceResults, Table<Integer, FieldName, FieldValue> table){ <add> private <V extends Number> Object calculateCategoricalTarget(final ValueFactory<V> valueFactory, FieldName name, List<InstanceResult<V>> instanceResults, Table<Integer, FieldName, FieldValue> table){ <ide> NearestNeighborModel nearestNeighborModel = getModel(); <ide> <del> VoteAggregator<Object, Double> aggregator = new VoteAggregator<Object, Double>(){ <del> <del> @Override <del> public ValueFactory<Double> getValueFactory(){ <del> return (ValueFactory)NearestNeighborModelEvaluator.this.getValueFactory(); <add> VoteAggregator<Object, V> aggregator = new VoteAggregator<Object, V>(){ <add> <add> @Override <add> public ValueFactory<V> getValueFactory(){ <add> return valueFactory; <ide> } <ide> }; <ide> <ide> NearestNeighborModel.CategoricalScoringMethod categoricalScoringMethod = nearestNeighborModel.getCategoricalScoringMethod(); <ide> <del> for(InstanceResult instanceResult : instanceResults){ <add> for(InstanceResult<V> instanceResult : instanceResults){ <ide> FieldValue value = table.get(instanceResult.getId(), name); <ide> if(value == null){ <ide> throw new MissingValueException(name); <ide> aggregator.add(object); <ide> break; <ide> case WEIGHTED_MAJORITY_VOTE: <del> double weight = instanceResult.getWeight(nearestNeighborModel.getThreshold()); <del> <del> aggregator.add(object, weight); <add> Value<V> weight = instanceResult.getWeight(nearestNeighborModel.getThreshold()); <add> <add> aggregator.add(object, weight.doubleValue()); <ide> break; <ide> default: <ide> throw new UnsupportedFeatureException(nearestNeighborModel, categoricalScoringMethod); <ide> return function; <ide> } <ide> <del> private AffinityDistribution<Double> createAffinityDistribution(List<InstanceResult> instanceResults, Function<Integer, String> function, Object value){ <add> private <V extends Number> AffinityDistribution<V> createAffinityDistribution(List<InstanceResult<V>> instanceResults, Function<Integer, String> function, Object value){ <ide> NearestNeighborModel nearestNeighborModel = getModel(); <ide> <del> AffinityDistribution<Double> result; <del> <ide> ComparisonMeasure comparisonMeasure = nearestNeighborModel.getComparisonMeasure(); <add> <add> AffinityDistribution<V> result; <ide> <ide> Measure measure = comparisonMeasure.getMeasure(); <ide> <ide> throw new UnsupportedFeatureException(measure); <ide> } <ide> <del> for(InstanceResult instanceResult : instanceResults){ <add> for(InstanceResult<V> instanceResult : instanceResults){ <ide> result.put(function.apply(instanceResult.getId()), instanceResult.getValue()); <ide> } <ide> <ide> <ide> static <ide> abstract <del> private class InstanceResult implements Comparable<InstanceResult> { <add> private class InstanceResult<V extends Number> implements Comparable<InstanceResult<V>> { <ide> <ide> private Integer id = null; <ide> <del> private Value<Double> value = null; <del> <del> <del> private InstanceResult(Integer id, Value<Double> value){ <add> private Value<V> value = null; <add> <add> <add> private InstanceResult(Integer id, Value<V> value){ <ide> setId(id); <ide> setValue(value); <ide> } <ide> <ide> abstract <del> public double getWeight(double threshold); <add> public Value<V> getWeight(double threshold); <ide> <ide> public Integer getId(){ <ide> return this.id; <ide> this.id = id; <ide> } <ide> <del> public Value<Double> getValue(){ <add> public Value<V> getValue(){ <ide> return this.value; <ide> } <ide> <del> private void setValue(Value<Double> value){ <add> private void setValue(Value<V> value){ <ide> this.value = value; <ide> } <ide> <ide> static <del> private class Similarity extends InstanceResult { <del> <del> private Similarity(Integer id, Value<Double> value){ <add> private class Similarity<V extends Number> extends InstanceResult<V> { <add> <add> private Similarity(Integer id, Value<V> value){ <ide> super(id, value); <ide> } <ide> <ide> @Override <del> public int compareTo(InstanceResult that){ <add> public int compareTo(InstanceResult<V> that){ <ide> <ide> if(that instanceof Similarity){ <ide> return Classification.Type.SIMILARITY.compareValues(this.getValue(), that.getValue()); <ide> } <ide> <ide> @Override <del> public double getWeight(double threshold){ <add> public Value<V> getWeight(double threshold){ <ide> throw new EvaluationException(); <ide> } <ide> } <ide> <ide> static <del> private class Distance extends InstanceResult { <del> <del> private Distance(Integer id, Value<Double> value){ <add> private class Distance<V extends Number> extends InstanceResult<V> { <add> <add> private Distance(Integer id, Value<V> value){ <ide> super(id, value); <ide> } <ide> <ide> @Override <del> public int compareTo(InstanceResult that){ <add> public int compareTo(InstanceResult<V> that){ <ide> <ide> if(that instanceof Distance){ <ide> return Classification.Type.DISTANCE.compareValues(this.getValue(), that.getValue()); <ide> } <ide> <ide> @Override <del> public double getWeight(double threshold){ <del> Value<Double> value = getValue(); <del> <del> return 1d / (value.doubleValue() + threshold); <add> public Value<V> getWeight(double threshold){ <add> Value<V> value = getValue(); <add> <add> value = value.copy(); <add> <add> if(threshold != 0d){ <add> value.add(threshold); <add> } <add> <add> return value.reciprocal(); <ide> } <ide> } <ide> }
Java
apache-2.0
856ef75e28312edcbaf51acb3452da51e76c3bd7
0
francisdb/flicklib,heitorfm/flicklib,francisdb/flicklib,heitorfm/flicklib
/* * This file is part of Flicklib. * * Copyright (C) Francis De Brabandere * * 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.flicklib.service.movie.porthu; import static com.flicklib.tools.StringUtils.unbracket; import java.io.IOException; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.htmlparser.jericho.Element; import net.htmlparser.jericho.Source; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.flicklib.api.AbstractMovieInfoFetcher; import com.flicklib.domain.MoviePage; import com.flicklib.domain.MovieSearchResult; import com.flicklib.domain.MovieService; import com.flicklib.service.SourceLoader; import com.flicklib.tools.ElementOnlyTextExtractor; import com.flicklib.tools.LevenshteinDistance; import com.flicklib.tools.StringUtils; import com.google.inject.Inject; public class PorthuFetcher extends AbstractMovieInfoFetcher { private static final Logger LOGGER = LoggerFactory.getLogger(PorthuFetcher.class); private static final String FILM_INFO_URL = "/pls/fi/films.film_page"; private static final String TEST_CITY_ID = "3372"; private static final Pattern FILM_ID_PATTERN = Pattern.compile("i_film_id=(\\d*)"); private static final Pattern YEAR_END_PATTERN = Pattern.compile("(\\d+)\\z"); private static final Pattern RUNTIME_PATTERN = Pattern.compile("(\\d+) perc"); /** * match (x.y)/10 where x and y are numbers. */ private static final Pattern SCORE_PATTERN = Pattern.compile("(\\d+([\\.,]\\d)?)/10"); private final SourceLoader sourceLoader; @Inject public PorthuFetcher(final SourceLoader sourceLoader) { this.sourceLoader = sourceLoader; } @Override public MoviePage getMovieInfo(String id) throws IOException { String url = generateUrlForFilmID(id); Source source = sourceLoader.loadSource(url).getJerichoSource(); MoviePage mp = parseMovieInfoPage(source, id); mp.setUrl(url); return mp; } private MoviePage parseMovieInfoPage(Source source, String id) throws IOException { MoviePage mp = new MoviePage(MovieService.PORTHU); mp.setIdForSite(id); { List<Element> titleElements = source.getAllElements("class", "blackbigtitle", false); if (titleElements.size() == 0) { throw new RuntimeException("no <span class='blackbigtitle'> found!"); } Element titleElement = titleElements.get(0); setEnglishAndOriginalTitle(mp, getOriginalAndEnglishTitle(titleElement), titleElement.getContent().getTextExtractor().toString()); } { List<Element> spanElements = source.getAllElements("span"); int btxtCount = 0; for (int i = 0; i < spanElements.size(); i++) { Element span = spanElements.get(i); if ("btxt".equals(span.getAttributeValue("class"))) { btxtCount++; String content = span.getTextExtractor().toString(); // the first <span class='btxt'> contains the description if (btxtCount == 1) { Element firstTxt = span.getParentElement().getFirstElement("class", "txt", false); if (firstTxt != null) { content = firstTxt.getTextExtractor().toString(); } initDescriptionAndYear(content, mp); } else { if (content.trim().equals("rendező:")) { // the next span contains the name of the director Element nextSpan = spanElements.get(i + 1); LOGGER.debug("director is : " + nextSpan); mp.getDirectors().add(nextSpan.getTextExtractor().toString()); } // forgatókönyvíró: // zeneszerző: if (content.startsWith("A film értékelése:")) { mp.setScore(getScore(content)); // the next span contains the vote count Element nextSpan = spanElements.get(i + 1); LOGGER.debug("vote count : " + nextSpan); mp.setVotes(getVotes(nextSpan.getTextExtractor().toString())); } } } } if (mp.getScore()==null) { // we have to fetch with ajax parseAjaxVoteObjectResponse(mp, id); } } mp.setPlot(getPlot(source)); return mp; } private String getPlot(Source source) { List<Element> tables = source.getAllElements("table"); // find a table which doesn't have 'id', it's width='100%' // cellpadding="0" cellspacing="0' and it's parent a td for (Element table : tables) { // if (table.getAttributeValue("id") == null && "100%".equals(table.getAttributeValue("width")) && "0".equals(table.getAttributeValue("cellpadding")) && "0".equals(table.getAttributeValue("cellspacing"))) { if ("td".equals(table.getParentElement().getName())) { List<Element> txtElements = table.getAllElements("class", "txt", true); if (txtElements.size() > 0) { return txtElements.get(0).getContent().getTextExtractor().toString(); } } } } return null; } private String getOriginalAndEnglishTitle(Element titleElement) { // // strange, this doesn't works, the span content is always // List<Element> alternateTitleSpan = // titleElement.getParentElement().findAllElements("class", "txt", // false); // if (alternateTitleSpan.size()==0) { // throw new // RuntimeException("no <span class='txt'> found next to the title!"); // } // mp.setAlternateTitle(alternateTitleSpan.get(0).getContent().getTextExtractor().toString());*/ List<Element> allElements = titleElement.getParentElement().getAllElements("class", "txt", false); if (allElements.size()>0) { String txt = allElements.get(0).getTextExtractor().toString(); return StringUtils.unbracket(txt); } String fullTag = titleElement.getParentElement().toString(); // pattern for matching: <span class="txt">(<SOMETHING>) Pattern p = Pattern.compile("<span class=\"txt\">\\((.*)\\)"); Matcher matcher = p.matcher(fullTag); if (matcher.find()) { if (matcher.groupCount() > 0) { LOGGER.debug("match:" + matcher.group() + " -> " + matcher.group(1)); return matcher.group(1); } } return null; } public List<MovieSearchResult> search(String title) throws IOException { List<MovieSearchResult> result = new ArrayList<MovieSearchResult>(); String url = generateUrlForTitleSearch(title); com.flicklib.service.Source flicklibSource = sourceLoader.loadSource(url); Source jerichoSource = flicklibSource.getJerichoSource(); if (isMoviePageUrl(flicklibSource.getUrl())) { String id = collectIdFromUrl(flicklibSource.getUrl()); MoviePage mp = parseMovieInfoPage(jerichoSource, id); mp.setUrl(flicklibSource.getUrl()); result.add(mp); return result; } MovieSearchResultComparator comparator = new MovieSearchResultComparator(); TreeSet<MovieSearchResult> orderedSet = new TreeSet<MovieSearchResult>(comparator); List<Element> spans = jerichoSource.getAllElements("span"); for (int i = 0; i < spans.size(); i++) { Element span = spans.get(i); if ("btxt".equals(span.getAttributeValue("class"))) { List<Element> childs = span.getContent().getAllElements(); if (childs.size() > 0) { Element link = childs.get(0); LOGGER.trace("link : " + link); if ("a".equals(link.getName())) { String href = link.getAttributeValue("href"); if (href.indexOf(FILM_INFO_URL)!=-1) { LOGGER.info("film url :" + href); String movieTitle = link.getContent().getTextExtractor().toString(); MovieSearchResult msr = new MovieSearchResult(MovieService.PORTHU); msr.setUrl(new java.net.URL(new java.net.URL("http://port.hu"),href).toString()); msr.setIdForSite(collectIdFromUrl(href)); String basetitle = unbracket(new ElementOnlyTextExtractor(span.getContent()).toString()); setEnglishAndOriginalTitle(msr, basetitle, movieTitle); int distance = LevenshteinDistance.distance(movieTitle, title); int distance2 = LevenshteinDistance.distance(msr.getAlternateTitle(), title); LOGGER .info("found [distance:" + distance + ", alternate distance:" + distance2 + "]:" + movieTitle + '/' + msr.getAlternateTitle()); comparator.set(msr, Math.min(distance, distance2)); // next span has style 'txt' and contains the // description if (i + 1 < spans.size()) { Element descSpan = spans.get(i + 1); if ("txt".equals(descSpan.getAttributeValue("class"))) { String description = descSpan.getContent().getTextExtractor().toString(); initDescriptionAndYear(description, msr); } } orderedSet.add(msr); } } } } } result.addAll(orderedSet); return result; } private void setEnglishAndOriginalTitle(MovieSearchResult msr, String basetitle, String alternateTitle) { if (basetitle != null) { int perPos = basetitle.indexOf('/'); if (perPos != -1) { // original title/english title msr.setOriginalTitle(basetitle.substring(0, perPos)); msr.setTitle(basetitle.substring(perPos + 1)); } else { msr.setTitle(basetitle); } msr.setAlternateTitle(alternateTitle); } else { msr.setTitle(unbracket(alternateTitle)); } } private static class MovieSearchResultComparator implements Comparator<MovieSearchResult>, Serializable { /** * */ private static final long serialVersionUID = 1L; private final Map<MovieSearchResult, Integer> scoreMap; public MovieSearchResultComparator() { this.scoreMap = new HashMap<MovieSearchResult, Integer>(); } public void set(MovieSearchResult movie, Integer score) { this.scoreMap.put(movie, score); } @Override public int compare(MovieSearchResult o1, MovieSearchResult o2) { Integer d1 = scoreMap.get(o1); Integer d2 = scoreMap.get(o2); int value = safeCompare(d1, d2); if (value != 0) { return value; } // both null, or both not-null, but both has the same score. value = o1.getTitle().compareTo(o2.getTitle()); if (value != 0) { return value; } // they have the same title ... // sort according to the creation year, newer first. value = -safeCompare(o1.getYear(), o2.getYear()); return value; } private int safeCompare(Integer d1, Integer d2) { if (d1 != null) { if (d2 != null) { return d1.compareTo(d2); } else { return -1; } } else { if (d2 != null) { return 1; } } return 0; } } /** * initialize the description and year field based on a generic, plain * description: 'színes magyarul beszélő amerikai gengszterfilm, 171 perc, * 1972' * * @param description * @param msr */ private void initDescriptionAndYear(String description, MovieSearchResult msr) { description = unbracket(description); if (msr instanceof MoviePage) { MoviePage m = (MoviePage) msr; m.setRuntime(getRuntime(description)); Set<String> skipWordList = new HashSet<String>(); skipWordList.add("színes"); skipWordList.add("magyarul"); skipWordList.add("beszélő"); skipWordList.add("perc"); // concatenate 'animációs film ' to 'animációsfilm' String[] strings = description.replaceAll(" film[ ,]", "film ").split("[ \\-,]"); for (String word : strings) { if (word.length()>0 && !skipWordList.contains(word)) { try { Integer.parseInt(word); // it's a number, skip } catch (NumberFormatException e) { LOGGER.debug("found genre:"+word); m.addGenre(word); } } } } msr.setYear(getYear(description)); msr.setDescription(description); } /** * search for port.hu movie id in the url. * * @param url * @return */ private String collectIdFromUrl(String url) { Matcher matcher = FILM_ID_PATTERN.matcher(url); if (matcher.find()) { if (matcher.groupCount() == 1) { return matcher.group(1); } } return null; } private Integer getYear(String description) { Matcher matcher = YEAR_END_PATTERN.matcher(description); if (matcher.find()) { if (matcher.groupCount() == 1) { return Integer.parseInt(matcher.group(1)); } } return null; } private Integer getRuntime(String description) { Matcher matcher = RUNTIME_PATTERN.matcher(description); if (matcher.find()) { if (matcher.groupCount() == 1) { return Integer.parseInt(matcher.group(1)); } } return null; } private Integer getScore(String scoreText) { Matcher matcher = SCORE_PATTERN.matcher(scoreText); if (matcher.find()) { if (matcher.groupCount() == 2) { float score = Float.parseFloat(matcher.group(1)); return Integer.valueOf((int) (score * 10)); } } return null; } /** * get vote count from a string like: "(32 szavazat)" -> 32 * * @param string * @return */ private Integer getVotes(String string) { String txt = unbracket(string); String[] array = txt.split(" "); if (array.length == 2 && "szavazat".equals(array[1])) { return Integer.parseInt(array[0]); } return null; } private void parseAjaxVoteObjectResponse(MoviePage mp, String id) throws IOException { Source voteObject = fetchVoteObject(id); List<Element> spanElements = voteObject.getAllElements("span"); for (Element span : spanElements) { String content = span.getTextExtractor().toString(); String classAttr = span.getAttributeValue("class"); if ("btxt".equals(classAttr)) { mp.setScore(getScore(content)); } if ("rtxt".equals(classAttr)) { mp.setVotes(getVotes(content)); } } } private Source fetchVoteObject(String id) throws IOException { Map<String,String> params = new LinkedHashMap<String,String>(); //i_object_id=73833&i_area_id=6&i_is_separator=0 params.put("i_object_id", id); params.put("i_area_id","6"); params.put("i_is_separator", "0"); params.put("i_reload_container","id=\"vote_box\""); Map<String,String> headers = new LinkedHashMap<String,String>(); headers.put("X-Requested-With", "XMLHttpRequest"); //headers.put("X-Prototype-Version", "1.6.0.2"); headers.put("Referer", generateUrlForFilmID(id)); // http://port.hu/indiana_jones_es_a_kristalykoponya_kiralysaga_indiana_jones_and_the_kingdom_of_the_crystal_skull/pls/fi/vote.print_vote_box?i_object_id=73047&i_area_id=6&i_reload_container=id%3D%22vote_box%22&i_is_separator=0 com.flicklib.service.Source content = sourceLoader.post("http://port.hu/pls/fi/vote.print_vote_box?", params, headers); return content.getJerichoSource(); } protected String generateUrlForTitleSearch(String title) { try { return "http://port.hu/pls/ci/cinema.film_creator?i_text=" + URLEncoder.encode(title, "ISO-8859-2") + "&i_film_creator=1&i_city_id=" + TEST_CITY_ID; } catch (UnsupportedEncodingException e) { throw new RuntimeException("Encoding problem with UTF-8? " + e.getMessage(), e); } } protected String generateUrlForFilmID(String id) { return "http://port.hu" + FILM_INFO_URL + "?i_where=2&i_film_id=" + id + "&i_city_id=" + TEST_CITY_ID + "&i_county_id=-1"; } protected boolean isMoviePageUrl(String url) { // FIXME is this first cause correct? return FILM_INFO_URL.startsWith(url) || (url.startsWith("http://port.hu") && url.indexOf(FILM_INFO_URL)!=-1); } }
flicklib-core/src/main/java/com/flicklib/service/movie/porthu/PorthuFetcher.java
/* * This file is part of Flicklib. * * Copyright (C) Francis De Brabandere * * 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.flicklib.service.movie.porthu; import static com.flicklib.tools.StringUtils.unbracket; import java.io.IOException; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.htmlparser.jericho.Element; import net.htmlparser.jericho.Source; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.flicklib.api.AbstractMovieInfoFetcher; import com.flicklib.domain.MoviePage; import com.flicklib.domain.MovieSearchResult; import com.flicklib.domain.MovieService; import com.flicklib.service.SourceLoader; import com.flicklib.tools.ElementOnlyTextExtractor; import com.flicklib.tools.LevenshteinDistance; import com.google.inject.Inject; public class PorthuFetcher extends AbstractMovieInfoFetcher { private static final Logger LOGGER = LoggerFactory.getLogger(PorthuFetcher.class); private static final String FILM_INFO_URL = "/pls/fi/films.film_page"; private static final String TEST_CITY_ID = "3372"; private static final Pattern FILM_ID_PATTERN = Pattern.compile("i_film_id=(\\d*)"); private static final Pattern YEAR_END_PATTERN = Pattern.compile("(\\d+)\\z"); private static final Pattern RUNTIME_PATTERN = Pattern.compile("(\\d+) perc"); /** * match (x.y)/10 where x and y are numbers. */ private static final Pattern SCORE_PATTERN = Pattern.compile("(\\d+(\\.\\d)?)/10"); private final SourceLoader sourceLoader; @Inject public PorthuFetcher(final SourceLoader sourceLoader) { this.sourceLoader = sourceLoader; } @Override public MoviePage getMovieInfo(String id) throws IOException { String url = generateUrlForFilmID(id); Source source = sourceLoader.loadSource(url).getJerichoSource(); MoviePage mp = parseMovieInfoPage(source, id); mp.setUrl(url); return mp; } private MoviePage parseMovieInfoPage(Source source, String id) throws IOException { MoviePage mp = new MoviePage(MovieService.PORTHU); mp.setIdForSite(id); { List<Element> titleElements = source.getAllElements("class", "blackbigtitle", false); if (titleElements.size() == 0) { throw new RuntimeException("no <span class='blackbigtitle'> found!"); } Element titleElement = titleElements.get(0); setEnglishAndOriginalTitle(mp, getOriginalAndEnglishTitle(titleElement), titleElement.getContent().getTextExtractor().toString()); } { List<Element> spanElements = source.getAllElements("span"); int btxtCount = 0; for (int i = 0; i < spanElements.size(); i++) { Element span = spanElements.get(i); if ("btxt".equals(span.getAttributeValue("class"))) { btxtCount++; String content = span.getTextExtractor().toString(); // the first <span class='btxt'> contains the description if (btxtCount == 1) { initDescriptionAndYear(content, mp); } else { if (content.trim().equals("rendező:")) { // the next span contains the name of the director Element nextSpan = spanElements.get(i + 1); LOGGER.debug("director is : " + nextSpan); mp.getDirectors().add(nextSpan.getTextExtractor().toString()); } if (content.startsWith("A film értékelése:")) { mp.setScore(getScore(content)); // the next span contains the vote count Element nextSpan = spanElements.get(i + 1); LOGGER.debug("vote count : " + nextSpan); mp.setVotes(getVotes(nextSpan.getTextExtractor().toString())); } } } } if (mp.getScore()==null) { // we have to fetch with ajax parseAjaxVoteObjectResponse(mp, id); } } mp.setPlot(getPlot(source)); return mp; } private String getPlot(Source source) { List<Element> tables = source.getAllElements("table"); // find a table which doesn't have 'id', it's width='100%' // cellpadding="0" cellspacing="0' and it's parent a td for (Element table : tables) { // if (table.getAttributeValue("id") == null && "100%".equals(table.getAttributeValue("width")) && "0".equals(table.getAttributeValue("cellpadding")) && "0".equals(table.getAttributeValue("cellspacing"))) { if ("td".equals(table.getParentElement().getName())) { List<Element> txtElements = table.getAllElements("class", "txt", true); if (txtElements.size() > 0) { return txtElements.get(0).getContent().getTextExtractor().toString(); } } } } return null; } private String getOriginalAndEnglishTitle(Element titleElement) { // // strange, this doesn't works, the span content is always // List<Element> alternateTitleSpan = // titleElement.getParentElement().findAllElements("class", "txt", // false); // if (alternateTitleSpan.size()==0) { // throw new // RuntimeException("no <span class='txt'> found next to the title!"); // } // mp.setAlternateTitle(alternateTitleSpan.get(0).getContent().getTextExtractor().toString());*/ String fullTag = titleElement.getParentElement().toString(); // pattern for matching: <span class="txt">(<SOMETHING>) Pattern p = Pattern.compile("<span class=\"txt\">\\((.*)\\)"); Matcher matcher = p.matcher(fullTag); if (matcher.find()) { if (matcher.groupCount() > 0) { LOGGER.debug("match:" + matcher.group() + " -> " + matcher.group(1)); return matcher.group(1); } } return null; } public List<MovieSearchResult> search(String title) throws IOException { List<MovieSearchResult> result = new ArrayList<MovieSearchResult>(); String url = generateUrlForTitleSearch(title); com.flicklib.service.Source flicklibSource = sourceLoader.loadSource(url); Source jerichoSource = flicklibSource.getJerichoSource(); if (isMoviePageUrl(flicklibSource.getUrl())) { String id = collectIdFromUrl(flicklibSource.getUrl()); MoviePage mp = parseMovieInfoPage(jerichoSource, id); mp.setUrl(flicklibSource.getUrl()); result.add(mp); return result; } MovieSearchResultComparator comparator = new MovieSearchResultComparator(); TreeSet<MovieSearchResult> orderedSet = new TreeSet<MovieSearchResult>(comparator); List<Element> spans = jerichoSource.getAllElements("span"); for (int i = 0; i < spans.size(); i++) { Element span = spans.get(i); if ("btxt".equals(span.getAttributeValue("class"))) { List<Element> childs = span.getContent().getAllElements(); if (childs.size() > 0) { Element link = childs.get(0); LOGGER.trace("link : " + link); if ("a".equals(link.getName())) { String href = link.getAttributeValue("href"); if (href.indexOf(FILM_INFO_URL)!=-1) { LOGGER.info("film url :" + href); String movieTitle = link.getContent().getTextExtractor().toString(); MovieSearchResult msr = new MovieSearchResult(MovieService.PORTHU); msr.setUrl(new java.net.URL(new java.net.URL("http://port.hu"),href).toString()); msr.setIdForSite(collectIdFromUrl(href)); String basetitle = unbracket(new ElementOnlyTextExtractor(span.getContent()).toString()); setEnglishAndOriginalTitle(msr, basetitle, movieTitle); int distance = LevenshteinDistance.distance(movieTitle, title); int distance2 = LevenshteinDistance.distance(msr.getAlternateTitle(), title); LOGGER .info("found [distance:" + distance + ", alternate distance:" + distance2 + "]:" + movieTitle + '/' + msr.getAlternateTitle()); comparator.set(msr, Math.min(distance, distance2)); // next span has style 'txt' and contains the // description if (i + 1 < spans.size()) { Element descSpan = spans.get(i + 1); if ("txt".equals(descSpan.getAttributeValue("class"))) { String description = descSpan.getContent().getTextExtractor().toString(); initDescriptionAndYear(description, msr); } } orderedSet.add(msr); } } } } } result.addAll(orderedSet); return result; } private void setEnglishAndOriginalTitle(MovieSearchResult msr, String basetitle, String alternateTitle) { if (basetitle != null) { int perPos = basetitle.indexOf('/'); if (perPos != -1) { // original title/english title msr.setOriginalTitle(basetitle.substring(0, perPos)); msr.setTitle(basetitle.substring(perPos + 1)); } else { msr.setTitle(basetitle); } msr.setAlternateTitle(alternateTitle); } else { msr.setTitle(unbracket(alternateTitle)); } } private static class MovieSearchResultComparator implements Comparator<MovieSearchResult>, Serializable { /** * */ private static final long serialVersionUID = 1L; private final Map<MovieSearchResult, Integer> scoreMap; public MovieSearchResultComparator() { this.scoreMap = new HashMap<MovieSearchResult, Integer>(); } public void set(MovieSearchResult movie, Integer score) { this.scoreMap.put(movie, score); } @Override public int compare(MovieSearchResult o1, MovieSearchResult o2) { Integer d1 = scoreMap.get(o1); Integer d2 = scoreMap.get(o2); int value = safeCompare(d1, d2); if (value != 0) { return value; } // both null, or both not-null, but both has the same score. value = o1.getTitle().compareTo(o2.getTitle()); if (value != 0) { return value; } // they have the same title ... // sort according to the creation year, newer first. value = -safeCompare(o1.getYear(), o2.getYear()); return value; } private int safeCompare(Integer d1, Integer d2) { if (d1 != null) { if (d2 != null) { return d1.compareTo(d2); } else { return -1; } } else { if (d2 != null) { return 1; } } return 0; } } /** * initialize the description and year field based on a generic, plain * description: 'színes magyarul beszélő amerikai gengszterfilm, 171 perc, * 1972' * * @param description * @param msr */ private void initDescriptionAndYear(String description, MovieSearchResult msr) { description = unbracket(description); if (msr instanceof MoviePage) { MoviePage m = (MoviePage) msr; m.setRuntime(getRuntime(description)); Set<String> skipWordList = new HashSet<String>(); skipWordList.add("színes"); skipWordList.add("magyarul"); skipWordList.add("beszélő"); skipWordList.add("perc"); // concatenate 'animációs film ' to 'animációsfilm' String[] strings = description.replaceAll(" film[ ,]", "film ").split("[ \\-,]"); for (String word : strings) { if (word.length()>0 && !skipWordList.contains(word)) { try { Integer.parseInt(word); // it's a number, skip } catch (NumberFormatException e) { LOGGER.debug("found genre:"+word); m.addGenre(word); } } } } msr.setYear(getYear(description)); msr.setDescription(description); } /** * search for port.hu movie id in the url. * * @param url * @return */ private String collectIdFromUrl(String url) { Matcher matcher = FILM_ID_PATTERN.matcher(url); if (matcher.find()) { if (matcher.groupCount() == 1) { return matcher.group(1); } } return null; } private Integer getYear(String description) { Matcher matcher = YEAR_END_PATTERN.matcher(description); if (matcher.find()) { if (matcher.groupCount() == 1) { return Integer.parseInt(matcher.group(1)); } } return null; } private Integer getRuntime(String description) { Matcher matcher = RUNTIME_PATTERN.matcher(description); if (matcher.find()) { if (matcher.groupCount() == 1) { return Integer.parseInt(matcher.group(1)); } } return null; } private Integer getScore(String scoreText) { Matcher matcher = SCORE_PATTERN.matcher(scoreText); if (matcher.find()) { if (matcher.groupCount() == 2) { float score = Float.parseFloat(matcher.group(1)); return Integer.valueOf((int) (score * 10)); } } return null; } /** * get vote count from a string like: "(32 szavazat)" -> 32 * * @param string * @return */ private Integer getVotes(String string) { String txt = unbracket(string); String[] array = txt.split(" "); if (array.length == 2 && "szavazat".equals(array[1])) { return Integer.parseInt(array[0]); } return null; } private void parseAjaxVoteObjectResponse(MoviePage mp, String id) throws IOException { Source voteObject = fetchVoteObject(id); List<Element> spanElements = voteObject.getAllElements("span"); for (Element span : spanElements) { String content = span.getTextExtractor().toString(); String classAttr = span.getAttributeValue("class"); if ("btxt".equals(classAttr)) { mp.setScore(getScore(content)); } if ("rtxt".equals(classAttr)) { mp.setVotes(getVotes(content)); } } } private Source fetchVoteObject(String id) throws IOException { Map<String,String> params = new LinkedHashMap<String,String>(); //i_object_id=73833&i_area_id=6&i_is_separator=0 params.put("i_object_id", id); params.put("i_area_id","6"); params.put("i_is_separator", "0"); Map<String,String> headers = new LinkedHashMap<String,String>(); headers.put("X-Requested-With", "XMLHttpRequest"); headers.put("X-Prototype-Version", "1.6.0.2"); headers.put("Referer", generateUrlForFilmID(id)); com.flicklib.service.Source content = sourceLoader.post("http://port.hu/pls/fi/VOTE.print_vote_box?", params, headers); return content.getJerichoSource(); } protected String generateUrlForTitleSearch(String title) { try { return "http://port.hu/pls/ci/cinema.film_creator?i_text=" + URLEncoder.encode(title, "ISO-8859-2") + "&i_film_creator=1&i_city_id=" + TEST_CITY_ID; } catch (UnsupportedEncodingException e) { throw new RuntimeException("Encoding problem with UTF-8? " + e.getMessage(), e); } } protected String generateUrlForFilmID(String id) { return "http://port.hu" + FILM_INFO_URL + "?i_where=2&i_film_id=" + id + "&i_city_id=" + TEST_CITY_ID + "&i_county_id=-1"; } protected boolean isMoviePageUrl(String url) { // FIXME is this first cause correct? return FILM_INFO_URL.startsWith(url) || (url.startsWith("http://port.hu") && url.indexOf(FILM_INFO_URL)!=-1); } }
fix a couple of port.hu tests
flicklib-core/src/main/java/com/flicklib/service/movie/porthu/PorthuFetcher.java
fix a couple of port.hu tests
<ide><path>licklib-core/src/main/java/com/flicklib/service/movie/porthu/PorthuFetcher.java <ide> import com.flicklib.service.SourceLoader; <ide> import com.flicklib.tools.ElementOnlyTextExtractor; <ide> import com.flicklib.tools.LevenshteinDistance; <add>import com.flicklib.tools.StringUtils; <ide> import com.google.inject.Inject; <ide> <ide> <ide> /** <ide> * match (x.y)/10 where x and y are numbers. <ide> */ <del> private static final Pattern SCORE_PATTERN = Pattern.compile("(\\d+(\\.\\d)?)/10"); <add> private static final Pattern SCORE_PATTERN = Pattern.compile("(\\d+([\\.,]\\d)?)/10"); <ide> <ide> private final SourceLoader sourceLoader; <ide> <ide> String content = span.getTextExtractor().toString(); <ide> // the first <span class='btxt'> contains the description <ide> if (btxtCount == 1) { <add> Element firstTxt = span.getParentElement().getFirstElement("class", "txt", false); <add> if (firstTxt != null) { <add> content = firstTxt.getTextExtractor().toString(); <add> } <ide> initDescriptionAndYear(content, mp); <ide> } else { <ide> if (content.trim().equals("rendező:")) { <ide> LOGGER.debug("director is : " + nextSpan); <ide> mp.getDirectors().add(nextSpan.getTextExtractor().toString()); <ide> } <add> // forgatókönyvíró: <add> // zeneszerző: <add> <ide> if (content.startsWith("A film értékelése:")) { <ide> <ide> mp.setScore(getScore(content)); <ide> // RuntimeException("no <span class='txt'> found next to the title!"); <ide> // } <ide> // mp.setAlternateTitle(alternateTitleSpan.get(0).getContent().getTextExtractor().toString());*/ <add> <add> List<Element> allElements = titleElement.getParentElement().getAllElements("class", "txt", false); <add> if (allElements.size()>0) { <add> String txt = allElements.get(0).getTextExtractor().toString(); <add> return StringUtils.unbracket(txt); <add> } <add> <ide> String fullTag = titleElement.getParentElement().toString(); <ide> // pattern for matching: <span class="txt">(<SOMETHING>) <ide> Pattern p = Pattern.compile("<span class=\"txt\">\\((.*)\\)"); <ide> params.put("i_object_id", id); <ide> params.put("i_area_id","6"); <ide> params.put("i_is_separator", "0"); <add> params.put("i_reload_container","id=\"vote_box\""); <ide> <ide> Map<String,String> headers = new LinkedHashMap<String,String>(); <ide> headers.put("X-Requested-With", "XMLHttpRequest"); <del> headers.put("X-Prototype-Version", "1.6.0.2"); <add> //headers.put("X-Prototype-Version", "1.6.0.2"); <ide> headers.put("Referer", generateUrlForFilmID(id)); <ide> <del> com.flicklib.service.Source content = sourceLoader.post("http://port.hu/pls/fi/VOTE.print_vote_box?", params, headers); <add> // http://port.hu/indiana_jones_es_a_kristalykoponya_kiralysaga_indiana_jones_and_the_kingdom_of_the_crystal_skull/pls/fi/vote.print_vote_box?i_object_id=73047&i_area_id=6&i_reload_container=id%3D%22vote_box%22&i_is_separator=0 <add> com.flicklib.service.Source content = sourceLoader.post("http://port.hu/pls/fi/vote.print_vote_box?", params, headers); <ide> return content.getJerichoSource(); <ide> } <ide>
Java
apache-2.0
1cd3191cb52753d24475130878d6b0aa821594fa
0
tateshitah/jspwiki,tateshitah/jspwiki,tateshitah/jspwiki,tateshitah/jspwiki
/* JSPWiki - a JSP-based WikiWiki clone. Copyright (C) 2001-2005 Janne Jalkanen ([email protected]) This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.ecyrd.jspwiki.auth; import java.security.Principal; import java.util.Date; import java.util.Map; import java.util.Properties; import java.util.WeakHashMap; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import com.ecyrd.jspwiki.NoRequiredPropertyException; import com.ecyrd.jspwiki.WikiContext; import com.ecyrd.jspwiki.WikiEngine; import com.ecyrd.jspwiki.WikiSession; import com.ecyrd.jspwiki.auth.authorize.DefaultGroupManager; import com.ecyrd.jspwiki.auth.authorize.GroupManager; import com.ecyrd.jspwiki.auth.user.*; import com.ecyrd.jspwiki.ui.InputValidator; import com.ecyrd.jspwiki.util.ClassUtil; /** * Provides a facade for user and group information. * * @author Janne Jalkanen * @version $Revision: 1.42 $ $Date: 2005-12-12 07:03:48 $ * @since 2.3 */ public class UserManager { private WikiEngine m_engine; private static final Logger log = Logger.getLogger(UserManager.class); private static final String PROP_USERDATABASE = "jspwiki.userdatabase"; // private static final String PROP_ACLMANAGER = "jspwiki.aclManager"; /** Associateds wiki sessions with profiles */ private Map m_profiles = new WeakHashMap(); /** The user database loads, manages and persists user identities */ private UserDatabase m_database = null; /** The group manager loads, manages and persists wiki groups */ private GroupManager m_groupManager = null; /** * Constructs a new UserManager instance. */ public UserManager() { } /** * Initializes the engine for its nefarious purposes. * * @param engine the current wiki engine * @param props the wiki engine initialization properties */ public void initialize( WikiEngine engine, Properties props ) { m_engine = engine; } /** * Returns the GroupManager employed by this WikiEngine. * The GroupManager is lazily initialized. * @since 2.3 */ public GroupManager getGroupManager() { if( m_groupManager != null ) { return m_groupManager; } String dbClassName = "<unknown>"; String dbInstantiationError = null; Throwable cause = null; try { Properties props = m_engine.getWikiProperties(); dbClassName = props.getProperty( GroupManager.PROP_GROUPMANAGER ); if( dbClassName == null ) { dbClassName = DefaultGroupManager.class.getName(); } log.info("Attempting to load group manager class " + dbClassName); Class dbClass = ClassUtil.findClass( "com.ecyrd.jspwiki.auth.authorize", dbClassName ); m_groupManager = (GroupManager) dbClass.newInstance(); m_groupManager.initialize( m_engine, m_engine.getWikiProperties() ); log.info("GroupManager initialized."); } catch( ClassNotFoundException e ) { log.error( "UserDatabase class " + dbClassName + " cannot be found", e ); dbInstantiationError = "Failed to locate GroupManager class " + dbClassName; cause = e; } catch( InstantiationException e ) { log.error( "UserDatabase class " + dbClassName + " cannot be created", e ); dbInstantiationError = "Failed to create GroupManager class " + dbClassName; cause = e; } catch( IllegalAccessException e ) { log.error( "You are not allowed to access user database class " + dbClassName, e ); dbInstantiationError = "Access GroupManager class " + dbClassName + " denied"; cause = e; } if( dbInstantiationError != null ) { throw new RuntimeException( dbInstantiationError, cause ); } return m_groupManager; } /** * Returns the UserDatabase employed by this WikiEngine. * The UserDatabase is lazily initialized by this method, if * it does not exist yet. If the initialization fails, this * method will use the inner class DummyUserDatabase as * a default (which is enough to get JSPWiki running). * * @since 2.3 */ // FIXME: Must not throw RuntimeException, but something else. public UserDatabase getUserDatabase() { if( m_database != null ) { return m_database; } String dbClassName = "<unknown>"; try { dbClassName = WikiEngine.getRequiredProperty( m_engine.getWikiProperties(), PROP_USERDATABASE ); log.info("Attempting to load user database class "+dbClassName); Class dbClass = ClassUtil.findClass( "com.ecyrd.jspwiki.auth.user", dbClassName ); m_database = (UserDatabase) dbClass.newInstance(); m_database.initialize( m_engine, m_engine.getWikiProperties() ); log.info("UserDatabase initialized."); } catch( NoRequiredPropertyException e ) { log.error( "You have not set the '"+PROP_USERDATABASE+"'. You need to do this if you want to enable user management by JSPWiki." ); } catch( ClassNotFoundException e ) { log.error( "UserDatabase class " + dbClassName + " cannot be found", e ); } catch( InstantiationException e ) { log.error( "UserDatabase class " + dbClassName + " cannot be created", e ); } catch( IllegalAccessException e ) { log.error( "You are not allowed to access this user database class", e ); } finally { if( m_database == null ) { log.info("I could not create a database object you specified (or didn't specify), so I am falling back to a default."); m_database = new DummyUserDatabase(); } } return m_database; } /** * Retrieves the {@link com.ecyrd.jspwiki.auth.user.UserProfile}for the * user in a wiki session. If the user is authenticated, the UserProfile * returned will be the one stored in the user database; if one does not * exist, a new one will be initialized and returned. If the user is * anonymous or asserted, the UserProfile will <i>always</i> be newly * initialized to prevent spoofing of identities. If a UserProfile needs to * be initialized, its * {@link com.ecyrd.jspwiki.auth.user.UserProfile#isNew()} method will * return <code>true</code>, and its login name will will be set * automatically if the user is authenticated. Note that this method does * not modify the retrieved (or newly created) profile otherwise; other * fields in the user profile may be <code>null</code>. * @param session the wiki session, which may not be <code>null</code> * @return the user's profile, which will be newly initialized if the user * is anonymous or asserted, or if the user cannot be found in the user * database * @throws WikiSecurityException if the database returns an exception * @throws IllegalStateException if a new UserProfile was created, but its * {@link com.ecyrd.jspwiki.auth.user.UserProfile#isNew()} method returns * <code>false</code>. This is meant as a quality check for UserDatabase * providers; it should only be thrown if the implementation is faulty. */ public UserProfile getUserProfile( WikiSession session ) { // Look up cached user profile UserProfile profile = (UserProfile)m_profiles.get( session ); boolean newProfile = ( profile == null ); Principal user = null; // If user is authenticated, figure out if this is an existing profile if ( session.isAuthenticated() ) { user = session.getUserPrincipal(); try { profile = m_database.find( user.getName() ); newProfile = false; } catch( NoSuchPrincipalException e ) { } } if ( newProfile ) { profile = m_database.newProfile(); if ( user != null ) { profile.setLoginName( user.getName() ); } if ( !profile.isNew() ) { throw new IllegalStateException( "New profile should be marked 'new'. Check your UserProfile implementation." ); } } // Stash the profile for next time m_profiles.put( session, profile ); return profile; } /** * Saves the {@link com.ecyrd.jspwiki.auth.user.UserProfile}for the user in * a wiki session. This method verifies that a user profile to be saved * doesn't collide with existing profiles; that is, the login name, wiki * name or full name is already used by another profile. If the profile * collides, a <code>DuplicateUserException</code> is thrown. After saving * the profile, the user database changes are committed, and the user's * credential set is refreshed; if custom authentication is used, this means * the user will be automatically be logged in. * @param session the wiki session, which may not be <code>null</code> * @param profile the user profile, which may not be <code>null</code> */ public void setUserProfile( WikiSession session, UserProfile profile ) throws WikiSecurityException, DuplicateUserException { boolean newProfile = profile.isNew(); UserProfile oldProfile = getUserProfile( session ); // User profiles that may already have wikiname, fullname or loginname UserProfile otherProfile; try { otherProfile = m_database.findByLoginName( profile.getLoginName() ); if ( otherProfile != null && !otherProfile.equals( oldProfile ) ) { throw new DuplicateUserException( "The login name '" + profile.getLoginName() + "' is already taken." ); } } catch( NoSuchPrincipalException e ) { } try { otherProfile = m_database.findByFullName( profile.getFullname() ); if ( otherProfile != null && !otherProfile.equals( oldProfile ) ) { throw new DuplicateUserException( "The full name '" + profile.getFullname() + "' is already taken." ); } } catch( NoSuchPrincipalException e ) { } try { otherProfile = m_database.findByWikiName( profile.getWikiName() ); if ( otherProfile != null && !otherProfile.equals( oldProfile ) ) { throw new DuplicateUserException( "The wiki name '" + profile.getWikiName() + "' is already taken." ); } } catch( NoSuchPrincipalException e ) { } Date modDate = new Date(); if ( newProfile ) { profile.setCreated( modDate ); } profile.setLastModified( modDate ); m_database.save( profile ); m_database.commit(); // Refresh the credential set AuthenticationManager mgr = m_engine.getAuthenticationManager(); if ( newProfile && !mgr.isContainerAuthenticated() ) { mgr.login( session, profile.getLoginName(), profile.getPassword() ); } else { mgr.refreshCredentials( session ); } } /** * <p> Extracts user profile parameters from the HTTP request and populates * a UserProfile with them. The UserProfile will either be a copy of the * user's existing profile (if one can be found), or a new profile (if not). * The rules for populating the profile as as follows: </p> <ul> <li>If the * <code>email</code> or <code>password</code> parameter values differ * from those in the existing profile, the passed parameters override the * old values.</li> <li>For new profiles, the user-supplied * <code>fullname</code> and <code>wikiname</code> parameters are always * used; for existing profiles the existing values are used, and whatever * values the user supplied are discarded.</li> <li>In all cases, the * created/last modified timestamps of the user's existing or new profile * always override whatever values the user supplied.</li> <li>If * container authentication is used, the login name property of the profile * is set to the name of * {@link com.ecyrd.jspwiki.WikiSession#getLoginPrincipal()}. Otherwise, * the value of the <code>loginname</code> parameter is used.</li> </ul> * @param context the current wiki context * @return a new, populated user profile */ public UserProfile parseProfile( WikiContext context ) { // Retrieve the user's profile (may have been previously cached) UserProfile profile = getUserProfile( context.getWikiSession() ); HttpServletRequest request = context.getHttpRequest(); // Extract values from request stream (cleanse whitespace as needed) String loginName = request.getParameter( "loginname" ); String password = request.getParameter( "password" ); String wikiname = request.getParameter( "wikiname" ); String fullname = request.getParameter( "fullname" ); String email = request.getParameter( "email" ); loginName = InputValidator.isBlank( loginName ) ? null : loginName; password = InputValidator.isBlank( password ) ? null : password; wikiname = InputValidator.isBlank( wikiname ) ? null : wikiname.replaceAll("\\s", ""); fullname = InputValidator.isBlank( fullname ) ? null : fullname; email = InputValidator.isBlank( email ) ? null : email; // If using container auth, login name is always taken from container if ( context.getWikiSession().isAuthenticated() && m_engine.getAuthenticationManager().isContainerAuthenticated() ) { loginName = context.getWikiSession().getLoginPrincipal().getName(); } if ( profile.isNew() ) { // If new profile, use whatever values the user supplied profile.setLoginName( loginName ); profile.setEmail( email); profile.setFullname( fullname ); profile.setPassword( password ); profile.setWikiName( wikiname ); } else { // If modifying an existing profile, always override // the timestamp, login name, full name and wiki name properties profile.setEmail( email); profile.setPassword( password ); } return profile; } /** * Validates a user profile, and appends any errors to the session errors * list. If the profile is new, the password will be checked to make sure it * isn't null. Otherwise, the password is checked for length and that it * matches the value of the 'password2' HTTP parameter. Note that we have * a special case when container-managed authentication is used and * the user is not authenticated; this will always cause validation to fail. * Any validation errors are added to the wiki session's messages collection * (see {@link WikiSession#getMessages()}. * @param context the current wiki context * @param profile the supplied UserProfile */ public void validateProfile( WikiContext context, UserProfile profile ) { boolean isNew = ( profile.isNew() ); WikiSession session = context.getWikiSession(); InputValidator validator = new InputValidator( "profile", session ); if ( !context.getWikiSession().isAuthenticated() && m_engine.getAuthenticationManager().isContainerAuthenticated() ) { session.addMessage( "You must log in before creating a profile." ); } validator.validateNotNull( profile.getLoginName(), "Login name" ); validator.validateNotNull( profile.getWikiName(), "Wiki name" ); validator.validateNotNull( profile.getFullname(), "Full name" ); validator.validateNotNull( profile.getEmail(), "E-mail address", InputValidator.EMAIL ); // If new profile, passwords must match and can't be null if ( !m_engine.getAuthenticationManager().isContainerAuthenticated() ) { String password = profile.getPassword(); if ( password == null ) { if ( isNew ) { session.addMessage( "profile", "Password cannot be blank" ); } } else { HttpServletRequest request = context.getHttpRequest(); String password2 = ( request == null ) ? null : request.getParameter( "password2" ); if ( !password.equals( password2 ) ) { session.addMessage( "profile", "Passwords don't match" ); } } } } /** * This is a database that gets used if nothing else is available. It does * nothing of note - it just mostly thorws NoSuchPrincipalExceptions if * someone tries to log in. * @author Janne Jalkanen */ public class DummyUserDatabase extends AbstractUserDatabase { public void commit() throws WikiSecurityException { // No operation } public UserProfile findByEmail(String index) throws NoSuchPrincipalException { throw new NoSuchPrincipalException("No user profiles available"); } public UserProfile findByFullName(String index) throws NoSuchPrincipalException { throw new NoSuchPrincipalException("No user profiles available"); } public UserProfile findByLoginName(String index) throws NoSuchPrincipalException { throw new NoSuchPrincipalException("No user profiles available"); } public UserProfile findByWikiName(String index) throws NoSuchPrincipalException { throw new NoSuchPrincipalException("No user profiles available"); } public void initialize(WikiEngine engine, Properties props) throws NoRequiredPropertyException { } public void save( UserProfile profile ) throws WikiSecurityException { } } }
src/com/ecyrd/jspwiki/auth/UserManager.java
/* JSPWiki - a JSP-based WikiWiki clone. Copyright (C) 2001-2005 Janne Jalkanen ([email protected]) This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.ecyrd.jspwiki.auth; import java.security.Principal; import java.util.Date; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.WeakHashMap; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import com.ecyrd.jspwiki.NoRequiredPropertyException; import com.ecyrd.jspwiki.WikiContext; import com.ecyrd.jspwiki.WikiEngine; import com.ecyrd.jspwiki.WikiSession; import com.ecyrd.jspwiki.auth.authorize.DefaultGroupManager; import com.ecyrd.jspwiki.auth.authorize.GroupManager; import com.ecyrd.jspwiki.auth.user.*; import com.ecyrd.jspwiki.util.ClassUtil; /** * Provides a facade for user and group information. * * @author Janne Jalkanen * @version $Revision: 1.41 $ $Date: 2005-12-04 18:42:09 $ * @since 2.3 */ public class UserManager { private WikiEngine m_engine; private static final Logger log = Logger.getLogger(UserManager.class); private static final String PROP_USERDATABASE = "jspwiki.userdatabase"; // private static final String PROP_ACLMANAGER = "jspwiki.aclManager"; /** Associateds wiki sessions with profiles */ private Map m_profiles = new WeakHashMap(); /** The user database loads, manages and persists user identities */ private UserDatabase m_database = null; /** The group manager loads, manages and persists wiki groups */ private GroupManager m_groupManager = null; /** * Constructs a new UserManager instance. */ public UserManager() { } /** * Initializes the engine for its nefarious purposes. * * @param engine the current wiki engine * @param props the wiki engine initialization properties */ public void initialize( WikiEngine engine, Properties props ) { m_engine = engine; } /** * Returns the GroupManager employed by this WikiEngine. * The GroupManager is lazily initialized. * @since 2.3 */ public GroupManager getGroupManager() { if( m_groupManager != null ) { return m_groupManager; } String dbClassName = "<unknown>"; String dbInstantiationError = null; Throwable cause = null; try { Properties props = m_engine.getWikiProperties(); dbClassName = props.getProperty( GroupManager.PROP_GROUPMANAGER ); if( dbClassName == null ) { dbClassName = DefaultGroupManager.class.getName(); } log.info("Attempting to load group manager class " + dbClassName); Class dbClass = ClassUtil.findClass( "com.ecyrd.jspwiki.auth.authorize", dbClassName ); m_groupManager = (GroupManager) dbClass.newInstance(); m_groupManager.initialize( m_engine, m_engine.getWikiProperties() ); log.info("GroupManager initialized."); } catch( ClassNotFoundException e ) { log.error( "UserDatabase class " + dbClassName + " cannot be found", e ); dbInstantiationError = "Failed to locate GroupManager class " + dbClassName; cause = e; } catch( InstantiationException e ) { log.error( "UserDatabase class " + dbClassName + " cannot be created", e ); dbInstantiationError = "Failed to create GroupManager class " + dbClassName; cause = e; } catch( IllegalAccessException e ) { log.error( "You are not allowed to access user database class " + dbClassName, e ); dbInstantiationError = "Access GroupManager class " + dbClassName + " denied"; cause = e; } if( dbInstantiationError != null ) { throw new RuntimeException( dbInstantiationError, cause ); } return m_groupManager; } /** * Returns the UserDatabase employed by this WikiEngine. * The UserDatabase is lazily initialized by this method, if * it does not exist yet. If the initialization fails, this * method will use the inner class DummyUserDatabase as * a default (which is enough to get JSPWiki running). * * @since 2.3 */ // FIXME: Must not throw RuntimeException, but something else. public UserDatabase getUserDatabase() { if( m_database != null ) { return m_database; } String dbClassName = "<unknown>"; try { dbClassName = WikiEngine.getRequiredProperty( m_engine.getWikiProperties(), PROP_USERDATABASE ); log.info("Attempting to load user database class "+dbClassName); Class dbClass = ClassUtil.findClass( "com.ecyrd.jspwiki.auth.user", dbClassName ); m_database = (UserDatabase) dbClass.newInstance(); m_database.initialize( m_engine, m_engine.getWikiProperties() ); log.info("UserDatabase initialized."); } catch( NoRequiredPropertyException e ) { log.error( "You have not set the '"+PROP_USERDATABASE+"'. You need to do this if you want to enable user management by JSPWiki." ); } catch( ClassNotFoundException e ) { log.error( "UserDatabase class " + dbClassName + " cannot be found", e ); } catch( InstantiationException e ) { log.error( "UserDatabase class " + dbClassName + " cannot be created", e ); } catch( IllegalAccessException e ) { log.error( "You are not allowed to access this user database class", e ); } finally { if( m_database == null ) { log.info("I could not create a database object you specified (or didn't specify), so I am falling back to a default."); m_database = new DummyUserDatabase(); } } return m_database; } /** * Retrieves the {@link com.ecyrd.jspwiki.auth.user.UserProfile}for the * user in a wiki session. If the user is authenticated, the UserProfile * returned will be the one stored in the user database; if one does not * exist, a new one will be initialized and returned. If the user is * anonymous or asserted, the UserProfile will <i>always</i> be newly * initialized to prevent spoofing of identities. If a UserProfile needs to * be initialized, its * {@link com.ecyrd.jspwiki.auth.user.UserProfile#isNew()} method will * return <code>true</code>, and its login name will will be set * automatically if the user is authenticated. Note that this method does * not modify the retrieved (or newly created) profile otherwise; other * fields in the user profile may be <code>null</code>. * @param session the wiki session, which may not be <code>null</code> * @return the user's profile, which will be newly initialized if the user * is anonymous or asserted, or if the user cannot be found in the user * database * @throws WikiSecurityException if the database returns an exception * @throws IllegalStateException if a new UserProfile was created, but its * {@link com.ecyrd.jspwiki.auth.user.UserProfile#isNew()} method returns * <code>false</code>. This is meant as a quality check for UserDatabase * providers; it should only be thrown if the implementation is faulty. */ public UserProfile getUserProfile( WikiSession session ) throws WikiSecurityException { // Look up cached user profile UserProfile profile = (UserProfile)m_profiles.get( session ); boolean newProfile = ( profile == null ); Principal user = null; // If user is authenticated, figure out if this is an existing profile if ( session.isAuthenticated() ) { user = session.getUserPrincipal(); try { profile = m_database.find( user.getName() ); newProfile = false; } catch( NoSuchPrincipalException e ) { } } if ( newProfile ) { profile = m_database.newProfile(); if ( user != null ) { profile.setLoginName( user.getName() ); } if ( !profile.isNew() ) { throw new IllegalStateException( "New profile should be marked 'new'. Check your UserProfile implementation." ); } } // Stash the profile for next time m_profiles.put( session, profile ); return profile; } /** * Saves the {@link com.ecyrd.jspwiki.auth.user.UserProfile}for the user in * a wiki session. This method verifies that a user profile to be saved * doesn't collide with existing profiles; that is, the login name, wiki * name or full name is already used by another profile. If the profile * collides, a <code>DuplicateUserException</code> is thrown. After saving * the profile, the user database changes are committed, and the user's * credential set is refreshed; if custom authentication is used, this means * the user will be automatically be logged in. * @param session the wiki session, which may not be <code>null</code> * @param profile the user profile, which may not be <code>null</code> */ public void setUserProfile( WikiSession session, UserProfile profile ) throws WikiSecurityException, DuplicateUserException { boolean newProfile = profile.isNew(); UserProfile oldProfile = getUserProfile( session ); // User profiles that may already have wikiname, fullname or loginname UserProfile otherProfile; try { otherProfile = m_database.findByLoginName( profile.getLoginName() ); if ( otherProfile != null && !otherProfile.equals( oldProfile ) ) { throw new DuplicateUserException( "The login name '" + profile.getLoginName() + "' is already taken." ); } } catch( NoSuchPrincipalException e ) { } try { otherProfile = m_database.findByFullName( profile.getFullname() ); if ( otherProfile != null && !otherProfile.equals( oldProfile ) ) { throw new DuplicateUserException( "The full name '" + profile.getFullname() + "' is already taken." ); } } catch( NoSuchPrincipalException e ) { } try { otherProfile = m_database.findByWikiName( profile.getWikiName() ); if ( otherProfile != null && !otherProfile.equals( oldProfile ) ) { throw new DuplicateUserException( "The wiki name '" + profile.getWikiName() + "' is already taken." ); } } catch( NoSuchPrincipalException e ) { } Date modDate = new Date(); if ( newProfile ) { profile.setCreated( modDate ); } profile.setLastModified( modDate ); m_database.save( profile ); m_database.commit(); // Refresh the credential set AuthenticationManager mgr = m_engine.getAuthenticationManager(); if ( newProfile && !mgr.isContainerAuthenticated() ) { mgr.login( session, profile.getLoginName(), profile.getPassword() ); } else { mgr.refreshCredentials( session ); } } /** * <p> * Extracts user profile parameters from the HTTP request and populates a * new UserProfile with them. The UserProfile will either be a copy of the * user's existing profile (if one can be found), or a new profile (if not). * The rules for populating the profile as as follows: * </p> * <ul> * <li>If the <code>email</code> or <code>password</code> parameter * values differ from those in the existing profile, the passed parameters * override the old values.</li> * <li>For new profiles, the <code>fullname</code> and * <code>wikiname</code> parameters are always used; otherwise they are * ignored.</li> * <li>In all cases, the created/last modified timestamps of the user's * existing/new profile are always used.</li> * <li>If container authentication is used, the login name property of the * profile is set to the name of * {@link com.ecyrd.jspwiki.WikiSession#getLoginPrincipal()}. Otherwise, * the value of the <code>loginname</code> parameter is used.</li> * </ul> * @param context the current wiki context * @return a new, populated user profile */ public UserProfile parseProfile( WikiContext context ) { // TODO:this class is probably the wrong place for this method... UserProfile profile = m_database.newProfile(); UserProfile existingProfile = null; try { // Look up the existing profile, if it exists existingProfile = getUserProfile( context.getWikiSession() ); } catch( WikiSecurityException e ) { } HttpServletRequest request = context.getHttpRequest(); // Set e-mail to user's supplied value; if null, use existing value String email = request.getParameter( "email" ); email = isNotBlank( email ) ? email : existingProfile.getEmail(); profile.setEmail( email ); // Set password to user's supplied value; if null, skip it String password = request.getParameter( "password" ); password = isNotBlank( password ) ? password : null; profile.setPassword( password ); // For new profiles, we use what the user supplied for // full name and wiki name String fullname = request.getParameter( "fullname" ); String wikiname = request.getParameter( "wikiname" ); if ( existingProfile.isNew() ) { fullname = isNotBlank( fullname ) ? fullname : null; wikiname = isNotBlank( wikiname ) ? wikiname : null; } else { fullname = existingProfile.getFullname(); wikiname = existingProfile.getWikiName(); } profile.setFullname( fullname ); profile.setWikiName( wikiname ); // For all profiles, we use the login name from the looked-up // profile. If the looked-up profile doesn't have a login // name, we either use the one from the session (if container auth) // or the one the user supplies (if custom auth). String loginName = existingProfile.getLoginName(); if ( loginName == null ) { if ( m_engine.getAuthenticationManager().isContainerAuthenticated() ) { Principal principal = context.getWikiSession().getLoginPrincipal(); loginName = principal.getName(); } else { loginName = request.getParameter( "loginname" ); wikiname = isNotBlank( loginName ) ? loginName : null; } } profile.setLoginName( loginName ); // Always use existing profile's lastModified and Created properties profile.setCreated( existingProfile.getCreated() ); profile.setLastModified( existingProfile.getLastModified() ); return profile; } /** * Returns <code>true</code> if a supplied string is null or blank * @param parameter */ private static boolean isNotBlank( String parameter ) { return ( parameter != null && parameter.length() > 0 ); } /** * Validates a user profile, and appends any errors to a user-supplied Set * of error strings. If the wiki request context is REGISTER, the password * will be checked to make sure it isn't null. Otherwise, the password * is checked. * @param context the current wiki context * @param profile the supplied UserProfile * @param errors the set of error strings */ public void validateProfile( WikiContext context, UserProfile profile, Set errors ) { // TODO:this class is probably the wrong place for this method... boolean isNew = ( WikiContext.REGISTER.equals( context.getRequestContext() ) ); if ( profile.getFullname() == null ) { errors.add( "Full name cannot be blank" ); } if ( profile.getLoginName() == null ) { errors.add( "Login name cannot be blank" ); } if ( profile.getWikiName() == null ) { errors.add( "Wiki name cannot be blank" ); } // If new profile, passwords must match and can't be null if ( !m_engine.getAuthenticationManager().isContainerAuthenticated() ) { String password = profile.getPassword(); if ( password == null ) { if ( isNew ) { errors.add( "Password cannot be blank" ); } } else { HttpServletRequest request = context.getHttpRequest(); String password2 = ( request == null ) ? null : request.getParameter( "password2" ); if ( !password.equals( password2 ) ) { errors.add( "Passwords don't match" ); } } } } /** * This is a database that gets used if nothing else is available. It does * nothing of note - it just mostly thorws NoSuchPrincipalExceptions if * someone tries to log in. * @author Janne Jalkanen */ public class DummyUserDatabase extends AbstractUserDatabase { public void commit() throws WikiSecurityException { // No operation } public UserProfile findByEmail(String index) throws NoSuchPrincipalException { throw new NoSuchPrincipalException("No user profiles available"); } public UserProfile findByFullName(String index) throws NoSuchPrincipalException { throw new NoSuchPrincipalException("No user profiles available"); } public UserProfile findByLoginName(String index) throws NoSuchPrincipalException { throw new NoSuchPrincipalException("No user profiles available"); } public UserProfile findByWikiName(String index) throws NoSuchPrincipalException { throw new NoSuchPrincipalException("No user profiles available"); } public void initialize(WikiEngine engine, Properties props) throws NoRequiredPropertyException { } public void save( UserProfile profile ) throws WikiSecurityException { } } }
UserManager validation routines were moved into new UI class InputValidator; additional refactorings including the new validation classes and WikiSession messages. git-svn-id: 6c0206e3b9edd104850923da33ebd73b435d374d@624893 13f79535-47bb-0310-9956-ffa450edef68
src/com/ecyrd/jspwiki/auth/UserManager.java
UserManager validation routines were moved into new UI class InputValidator; additional refactorings including the new validation classes and WikiSession messages.
<ide><path>rc/com/ecyrd/jspwiki/auth/UserManager.java <ide> import java.util.Date; <ide> import java.util.Map; <ide> import java.util.Properties; <del>import java.util.Set; <ide> import java.util.WeakHashMap; <ide> <ide> import javax.servlet.http.HttpServletRequest; <ide> import com.ecyrd.jspwiki.auth.authorize.DefaultGroupManager; <ide> import com.ecyrd.jspwiki.auth.authorize.GroupManager; <ide> import com.ecyrd.jspwiki.auth.user.*; <add>import com.ecyrd.jspwiki.ui.InputValidator; <ide> import com.ecyrd.jspwiki.util.ClassUtil; <ide> <ide> /** <ide> * Provides a facade for user and group information. <ide> * <ide> * @author Janne Jalkanen <del> * @version $Revision: 1.41 $ $Date: 2005-12-04 18:42:09 $ <add> * @version $Revision: 1.42 $ $Date: 2005-12-12 07:03:48 $ <ide> * @since 2.3 <ide> */ <ide> public class UserManager <ide> * <code>false</code>. This is meant as a quality check for UserDatabase <ide> * providers; it should only be thrown if the implementation is faulty. <ide> */ <del> public UserProfile getUserProfile( WikiSession session ) throws WikiSecurityException <add> public UserProfile getUserProfile( WikiSession session ) <ide> { <ide> // Look up cached user profile <ide> UserProfile profile = (UserProfile)m_profiles.get( session ); <ide> } <ide> <ide> /** <del> * <p> <del> * Extracts user profile parameters from the HTTP request and populates a <del> * new UserProfile with them. The UserProfile will either be a copy of the <add> * <p> Extracts user profile parameters from the HTTP request and populates <add> * a UserProfile with them. The UserProfile will either be a copy of the <ide> * user's existing profile (if one can be found), or a new profile (if not). <del> * The rules for populating the profile as as follows: <del> * </p> <del> * <ul> <del> * <li>If the <code>email</code> or <code>password</code> parameter <del> * values differ from those in the existing profile, the passed parameters <del> * override the old values.</li> <del> * <li>For new profiles, the <code>fullname</code> and <del> * <code>wikiname</code> parameters are always used; otherwise they are <del> * ignored.</li> <del> * <li>In all cases, the created/last modified timestamps of the user's <del> * existing/new profile are always used.</li> <del> * <li>If container authentication is used, the login name property of the <del> * profile is set to the name of <add> * The rules for populating the profile as as follows: </p> <ul> <li>If the <add> * <code>email</code> or <code>password</code> parameter values differ <add> * from those in the existing profile, the passed parameters override the <add> * old values.</li> <li>For new profiles, the user-supplied <add> * <code>fullname</code> and <code>wikiname</code> parameters are always <add> * used; for existing profiles the existing values are used, and whatever <add> * values the user supplied are discarded.</li> <li>In all cases, the <add> * created/last modified timestamps of the user's existing or new profile <add> * always override whatever values the user supplied.</li> <li>If <add> * container authentication is used, the login name property of the profile <add> * is set to the name of <ide> * {@link com.ecyrd.jspwiki.WikiSession#getLoginPrincipal()}. Otherwise, <del> * the value of the <code>loginname</code> parameter is used.</li> <del> * </ul> <add> * the value of the <code>loginname</code> parameter is used.</li> </ul> <ide> * @param context the current wiki context <ide> * @return a new, populated user profile <ide> */ <ide> public UserProfile parseProfile( WikiContext context ) <ide> { <del> // TODO:this class is probably the wrong place for this method... <del> <del> UserProfile profile = m_database.newProfile(); <del> UserProfile existingProfile = null; <del> try <del> { <del> // Look up the existing profile, if it exists <del> existingProfile = getUserProfile( context.getWikiSession() ); <del> } <del> catch( WikiSecurityException e ) <del> { <del> } <add> // Retrieve the user's profile (may have been previously cached) <add> UserProfile profile = getUserProfile( context.getWikiSession() ); <ide> HttpServletRequest request = context.getHttpRequest(); <del> <del> // Set e-mail to user's supplied value; if null, use existing value <add> <add> // Extract values from request stream (cleanse whitespace as needed) <add> String loginName = request.getParameter( "loginname" ); <add> String password = request.getParameter( "password" ); <add> String wikiname = request.getParameter( "wikiname" ); <add> String fullname = request.getParameter( "fullname" ); <ide> String email = request.getParameter( "email" ); <del> email = isNotBlank( email ) ? email : existingProfile.getEmail(); <del> profile.setEmail( email ); <del> <del> // Set password to user's supplied value; if null, skip it <del> String password = request.getParameter( "password" ); <del> password = isNotBlank( password ) ? password : null; <del> profile.setPassword( password ); <del> <del> // For new profiles, we use what the user supplied for <del> // full name and wiki name <del> String fullname = request.getParameter( "fullname" ); <del> String wikiname = request.getParameter( "wikiname" ); <del> if ( existingProfile.isNew() ) <del> { <del> fullname = isNotBlank( fullname ) ? fullname : null; <del> wikiname = isNotBlank( wikiname ) ? wikiname : null; <add> loginName = InputValidator.isBlank( loginName ) ? null : loginName; <add> password = InputValidator.isBlank( password ) ? null : password; <add> wikiname = InputValidator.isBlank( wikiname ) ? null : wikiname.replaceAll("\\s", ""); <add> fullname = InputValidator.isBlank( fullname ) ? null : fullname; <add> email = InputValidator.isBlank( email ) ? null : email; <add> <add> // If using container auth, login name is always taken from container <add> if ( context.getWikiSession().isAuthenticated() && <add> m_engine.getAuthenticationManager().isContainerAuthenticated() ) <add> { <add> loginName = context.getWikiSession().getLoginPrincipal().getName(); <add> } <add> <add> if ( profile.isNew() ) <add> { <add> // If new profile, use whatever values the user supplied <add> profile.setLoginName( loginName ); <add> profile.setEmail( email); <add> profile.setFullname( fullname ); <add> profile.setPassword( password ); <add> profile.setWikiName( wikiname ); <ide> } <ide> else <ide> { <del> fullname = existingProfile.getFullname(); <del> wikiname = existingProfile.getWikiName(); <del> } <del> profile.setFullname( fullname ); <del> profile.setWikiName( wikiname ); <del> <del> // For all profiles, we use the login name from the looked-up <del> // profile. If the looked-up profile doesn't have a login <del> // name, we either use the one from the session (if container auth) <del> // or the one the user supplies (if custom auth). <del> String loginName = existingProfile.getLoginName(); <del> if ( loginName == null ) <del> { <del> if ( m_engine.getAuthenticationManager().isContainerAuthenticated() ) <del> { <del> Principal principal = context.getWikiSession().getLoginPrincipal(); <del> loginName = principal.getName(); <del> } <del> else <del> { <del> loginName = request.getParameter( "loginname" ); <del> wikiname = isNotBlank( loginName ) ? loginName : null; <del> } <del> } <del> profile.setLoginName( loginName ); <del> <del> // Always use existing profile's lastModified and Created properties <del> profile.setCreated( existingProfile.getCreated() ); <del> profile.setLastModified( existingProfile.getLastModified() ); <del> <add> // If modifying an existing profile, always override <add> // the timestamp, login name, full name and wiki name properties <add> profile.setEmail( email); <add> profile.setPassword( password ); <add> } <ide> return profile; <ide> } <ide> <ide> /** <del> * Returns <code>true</code> if a supplied string is null or blank <del> * @param parameter <del> */ <del> private static boolean isNotBlank( String parameter ) <del> { <del> return ( parameter != null && parameter.length() > 0 ); <del> } <del> <del> /** <del> * Validates a user profile, and appends any errors to a user-supplied Set <del> * of error strings. If the wiki request context is REGISTER, the password <del> * will be checked to make sure it isn't null. Otherwise, the password <del> * is checked. <add> * Validates a user profile, and appends any errors to the session errors <add> * list. If the profile is new, the password will be checked to make sure it <add> * isn't null. Otherwise, the password is checked for length and that it <add> * matches the value of the 'password2' HTTP parameter. Note that we have <add> * a special case when container-managed authentication is used and <add> * the user is not authenticated; this will always cause validation to fail. <add> * Any validation errors are added to the wiki session's messages collection <add> * (see {@link WikiSession#getMessages()}. <ide> * @param context the current wiki context <ide> * @param profile the supplied UserProfile <del> * @param errors the set of error strings <del> */ <del> public void validateProfile( WikiContext context, UserProfile profile, Set errors ) <del> { <del> // TODO:this class is probably the wrong place for this method... <del> boolean isNew = ( WikiContext.REGISTER.equals( context.getRequestContext() ) ); <del> <del> if ( profile.getFullname() == null ) <del> { <del> errors.add( "Full name cannot be blank" ); <del> } <del> if ( profile.getLoginName() == null ) <del> { <del> errors.add( "Login name cannot be blank" ); <del> } <del> if ( profile.getWikiName() == null ) <del> { <del> errors.add( "Wiki name cannot be blank" ); <del> } <add> */ <add> public void validateProfile( WikiContext context, UserProfile profile ) <add> { <add> boolean isNew = ( profile.isNew() ); <add> WikiSession session = context.getWikiSession(); <add> InputValidator validator = new InputValidator( "profile", session ); <add> <add> if ( !context.getWikiSession().isAuthenticated() <add> && m_engine.getAuthenticationManager().isContainerAuthenticated() ) <add> { <add> session.addMessage( "You must log in before creating a profile." ); <add> } <add> <add> validator.validateNotNull( profile.getLoginName(), "Login name" ); <add> validator.validateNotNull( profile.getWikiName(), "Wiki name" ); <add> validator.validateNotNull( profile.getFullname(), "Full name" ); <add> validator.validateNotNull( profile.getEmail(), "E-mail address", InputValidator.EMAIL ); <ide> <ide> // If new profile, passwords must match and can't be null <ide> if ( !m_engine.getAuthenticationManager().isContainerAuthenticated() ) <ide> { <ide> if ( isNew ) <ide> { <del> errors.add( "Password cannot be blank" ); <add> session.addMessage( "profile", "Password cannot be blank" ); <ide> } <ide> } <ide> else <ide> String password2 = ( request == null ) ? null : request.getParameter( "password2" ); <ide> if ( !password.equals( password2 ) ) <ide> { <del> errors.add( "Passwords don't match" ); <add> session.addMessage( "profile", "Passwords don't match" ); <ide> } <ide> } <ide> }
Java
apache-2.0
17d59d27bb3231f8ca66882cdfbdd9c6f3bf636e
0
RWTH-i5-IDSG/jamocha,RWTH-i5-IDSG/jamocha
/* * Copyright 2002-2013 The Jamocha Team * * * 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.jamocha.org/ * * 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.jamocha.dn.memory.javaimpl; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.Map; import java.util.Set; import lombok.ToString; import lombok.Value; import org.jamocha.dn.memory.MemoryHandler; import org.jamocha.dn.memory.SlotAddress; import org.jamocha.dn.nodes.AddressPredecessor; import org.jamocha.dn.nodes.CouldNotAcquireLockException; import org.jamocha.dn.nodes.Edge; import org.jamocha.dn.nodes.Node; import org.jamocha.dn.nodes.SlotInFactAddress; import org.jamocha.filter.AddressFilter; import org.jamocha.filter.AddressFilter.AddressFilterElement; import org.jamocha.filter.fwa.PredicateWithArguments; import org.jamocha.visitor.Visitable; /** * Java-implementation of the {@link org.jamocha.dn.memory.MemoryHandlerPlusTemp} interface. * * @author Fabian Ohler <[email protected]> * @author Christoph Terwelp <[email protected]> * @see org.jamocha.dn.memory.MemoryHandlerPlusTemp */ @ToString(callSuper = true, of = "valid") public abstract class MemoryHandlerPlusTemp<T extends MemoryHandlerMain> extends MemoryHandlerTemp<T> implements org.jamocha.dn.memory.MemoryHandlerPlusTemp, Visitable<MemoryHandlerPlusTempVisitor> { static class Semaphore { int count; public Semaphore(final int count) { super(); this.count = count; } public synchronized boolean release() { return --this.count != 0; } } final Semaphore lock; /** * set to false as soon as the memory has been committed to its main memory */ boolean valid = true; protected MemoryHandlerPlusTemp(final T originatingMainHandler, final int numChildren, final boolean empty, final boolean omitSemaphore) { super(originatingMainHandler); if (empty) { this.lock = null; this.valid = false; } else if (omitSemaphore || numChildren == 0) { this.lock = null; originatingMainHandler.getValidOutgoingPlusTokens().add(this); // commit and invalidate the token final org.jamocha.dn.memory.MemoryHandlerTemp pendingTemp = commitAndInvalidate(); /* * if this token was a MemoryHandlerPlusTempNewRowsAndCounterUpdates we may have * produced new temps by calling commitAndInvalidate, yet we cannot process them without * lots of ugly code at the worst location to think of, so this is unsupported for now * as it has no purpose in a production system where the only nodes without children are * terminal nodes */ if (null != pendingTemp) { throw new IllegalArgumentException( "Nodes using existentials without children are unsupported!"); } } else { this.lock = new Semaphore(numChildren); originatingMainHandler.getValidOutgoingPlusTokens().add(this); } } @Override final public org.jamocha.dn.memory.MemoryHandlerTemp releaseLock() { try { if (this.lock.release()) return null; } catch (final NullPointerException e) { // lock was null return null; } // all children have processed the temp memory, now we have to write its // content to main memory return commitAndInvalidate(); } final protected org.jamocha.dn.memory.MemoryHandlerTemp commitAndInvalidate() { this.originatingMainHandler.acquireWriteLock(); assert this == this.originatingMainHandler.getValidOutgoingPlusTokens().peek(); this.originatingMainHandler.getValidOutgoingPlusTokens().remove(); final org.jamocha.dn.memory.MemoryHandlerTemp newTemp = commitToMain(); this.originatingMainHandler.releaseWriteLock(); this.valid = false; return newTemp; } abstract protected org.jamocha.dn.memory.MemoryHandlerTemp commitToMain(); @Override public void enqueueInEdge(final Edge edge) { edge.enqueueMemory(this); } /* * * * * * * * * STATIC FACTORY PART * * * * * * * * */ protected static boolean canOmitSemaphore(final Edge originEdge) { return originEdge.getTargetNode().getIncomingEdges().length <= 1; } protected static boolean canOmitSemaphore(final Node sourceNode) { for (final Edge edge : sourceNode.getOutgoingEdges()) { if (!canOmitSemaphore(edge)) return false; } return true; } @Override public MemoryHandlerPlusTemp<?> newBetaTemp(final MemoryHandlerMain originatingMainHandler, final Edge originIncomingEdge, final AddressFilter filter) throws CouldNotAcquireLockException { // create follow-up-temp final MemoryHandlerPlusTemp<?> token = newRegularBetaTemp(originatingMainHandler, filter, this, originIncomingEdge); // push old temp into incoming edge to augment the memory seen by its target originIncomingEdge.getTempMemories().add(token); // return new temp return token; } @Override public MemoryHandlerPlusTemp<?> newBetaTemp( final MemoryHandlerMainWithExistentials originatingMainHandler, final Edge originIncomingEdge, final AddressFilter filter) throws CouldNotAcquireLockException { // create follow-up-temp final MemoryHandlerPlusTemp<?> token = newExistentialBetaTemp(originatingMainHandler, filter, this, originIncomingEdge); // push old temp into incoming edge to augment the memory seen by its target originIncomingEdge.getTempMemories().add(token); // return new temp return token; } static MemoryHandlerPlusTemp<MemoryHandlerMain> newAlphaTemp( final MemoryHandlerMain originatingMainHandler, final MemoryHandlerPlusTemp<? extends MemoryHandlerMain> token, final Edge originIncomingEdge, final AddressFilter filter) throws CouldNotAcquireLockException { final ArrayList<Row> factList = new ArrayList<>(1); factLoop: for (final Row row : token.getRowsForSucessorNodes()) { assert row.getFactTuple().length == 1; for (final AddressFilterElement filterElement : filter.getFilterElements()) { if (!applyFilterElement(row.getFactTuple()[0], filterElement)) { continue factLoop; } } factList.add(row); } return new MemoryHandlerPlusTempValidRowsAdder(originatingMainHandler, factList, originIncomingEdge.getTargetNode().getNumberOfOutgoingEdges(), canOmitSemaphore(originIncomingEdge)); // FIXME only use Semaphores if one of the outgoing edges is connected to the beta network // return new MemoryHandlerPlusTemp(originatingMainHandler, // originIncomingEdge.getTargetNode().getNumberOfOutgoingEdges(), // needsSemaphore(originIncomingEdge)); } @Override public MemoryHandlerPlusTemp<MemoryHandlerMain> newAlphaTemp( final MemoryHandlerMain originatingMainHandler, final Edge originIncomingEdge, final AddressFilter filter) throws CouldNotAcquireLockException { return newAlphaTemp((MemoryHandlerMain) originatingMainHandler, this, originIncomingEdge, filter); } static MemoryHandlerPlusTemp<MemoryHandlerMain> newRootTemp( final MemoryHandlerMain originatingMainHandler, final Node otn, final org.jamocha.dn.memory.Fact... facts) { final ArrayList<Row> factList = new ArrayList<>(facts.length); for (final org.jamocha.dn.memory.Fact fact : facts) { assert fact.getTemplate() == otn.getMemory().getTemplate()[0]; factList.add(originatingMainHandler.newRow(new Fact(fact.getSlotValues()))); } return new MemoryHandlerPlusTempValidRowsAdder(originatingMainHandler, factList, otn.getNumberOfOutgoingEdges(), canOmitSemaphore(otn)); // new MemoryHandlerPlusTemp(originatingMainHandler, factList, // otn.getNumberOfOutgoingEdges(), needsSemaphore(otn)); } static abstract class StackElement { int rowIndex, memIndex; ArrayList<ArrayList<Row>> memStack; final int offset; private StackElement(final ArrayList<ArrayList<Row>> memStack, final int offset) { this.memStack = memStack; this.offset = offset; } public static StackElement ordinaryInput(final Edge edge, final int offset) { final LinkedList<? extends MemoryHandler> temps = edge.getTempMemories(); final ArrayList<ArrayList<Row>> memStack = new ArrayList<ArrayList<Row>>(temps.size() + 1); memStack.add(((org.jamocha.dn.memory.javaimpl.MemoryHandlerMain) edge.getSourceNode() .getMemory()).getRowsForSucessorNodes()); for (final Iterator<? extends MemoryHandler> iter = temps.iterator(); iter.hasNext();) { final MemoryHandlerPlusTemp<?> temp = (MemoryHandlerPlusTemp<?>) iter.next(); if (!temp.valid) { iter.remove(); continue; } memStack.add(temp.getRowsForSucessorNodes()); } return new StackElement(memStack, offset) { @Override Object getValue(final AddressPredecessor addr, final SlotAddress slot) { return this.getRow().getFactTuple()[((org.jamocha.dn.memory.javaimpl.FactAddress) addr .getAddress()).index].getValue((slot)); } }; } public static StackElement originInput(final int columns, final Edge originEdge, final MemoryHandlerPlusTemp<?> token, final int offset) { final ArrayList<Row> listWithHoles = new ArrayList<>(token.getRowsForSucessorNodes().size()); for (final Row row : token.getRowsForSucessorNodes()) { final Row wideRow = ((MemoryHandlerMain) originEdge.getTargetNode().getMemory()) .newRow(columns); assert columns >= offset + row.getFactTuple().length; wideRow.copy(offset, row); listWithHoles.add(wideRow); } final ArrayList<ArrayList<Row>> memStack = new ArrayList<ArrayList<Row>>(1); memStack.add(listWithHoles); return new StackElement(memStack, offset) { @Override Object getValue(final AddressPredecessor addr, final SlotAddress slot) { return this.getRow().getFactTuple()[((org.jamocha.dn.memory.javaimpl.FactAddress) addr .getEdge().localizeAddress(addr.getAddress())).index].getValue((slot)); } }; } ArrayList<Row> getTable() { return this.memStack.get(this.memIndex); } Row getRow() { return this.getTable().get(this.rowIndex); } abstract Object getValue(final AddressPredecessor addr, final SlotAddress slot); boolean checkMemBounds() { return this.memStack.size() > this.memIndex && this.memIndex >= 0; } boolean checkRowBounds() { return checkMemBounds() && getTable().size() > this.rowIndex && this.rowIndex >= 0; } void resetIndices() { this.rowIndex = 0; this.memIndex = 0; } int getOffset() { return this.offset; } } static interface FunctionPointer { public void apply(final ArrayList<Row> TR, final StackElement originElement); } private static void loop(final FunctionPointer functionPointer, final ArrayList<Row> TR, final Collection<StackElement> stack, final StackElement originElement) { if (stack.isEmpty()) { return; } { final Iterator<StackElement> iter = stack.iterator(); // skip originElement iter.next(); // initialize all memory indices to valid values while (iter.hasNext()) { final StackElement element = iter.next(); while (!element.checkRowBounds()) { if (!element.checkMemBounds()) { // one of the elements doesn't hold any facts, the join will be empty // delete all partial fact tuples in the TR originElement.memStack.set(0, new ArrayList<Row>(0)); TR.clear(); return; } element.memIndex++; } } } outerloop: while (true) { innerloop: while (true) { functionPointer.apply(TR, originElement); // increment row indices for (final Iterator<StackElement> iter = stack.iterator(); iter.hasNext();) { final StackElement element = iter.next(); element.rowIndex++; if (element.checkRowBounds()) break; element.rowIndex = 0; if (!iter.hasNext()) break innerloop; } } // increment memory indices for (final Iterator<StackElement> iter = stack.iterator(); iter.hasNext();) { final StackElement element = iter.next(); element.memIndex++; if (element.checkMemBounds()) break; element.memIndex = 0; if (!iter.hasNext()) break outerloop; } } // reset all indices in the StackElements for (final StackElement elem : stack) { elem.resetIndices(); } } private static final LinkedHashMap<Edge, StackElement> getLocksAndStack( final MemoryHandlerPlusTemp<?> token, final Edge originIncomingEdge, final boolean getOrigin) throws CouldNotAcquireLockException { // get a fixed-size array of indices (size: #inputs of the node), // determine number of inputs for the current join as maxIndex // loop through the inputs line-wise using array[0] .. array[maxIndex] // as line indices, incrementing array[maxIndex] and propagating the // increment to lower indices when input-size is reached // set locks and create stack final Node targetNode = originIncomingEdge.getTargetNode(); final Edge[] nodeIncomingEdges = targetNode.getIncomingEdges(); final LinkedHashMap<Edge, StackElement> edgeToStack = new LinkedHashMap<>(); final int columns = targetNode.getMemory().getTemplate().length; final StackElement originElement; { StackElement tempOriginElement = null; int offset = 0; for (final Edge incomingEdge : nodeIncomingEdges) { if (incomingEdge == originIncomingEdge) { tempOriginElement = StackElement.originInput(columns, originIncomingEdge, token, offset); offset += incomingEdge.getSourceNode().getMemory().getTemplate().length; if (!getOrigin) { // don't lock the originInput continue; } } try { if (!incomingEdge.getSourceNode().getMemory().tryReadLock()) { for (final Edge edge : edgeToStack.keySet()) { edge.getSourceNode().getMemory().releaseReadLock(); } throw new CouldNotAcquireLockException(); } } catch (final InterruptedException ex) { throw new Error( "Should not happen, interruption of this method is not supported!", ex); } edgeToStack.put(incomingEdge, StackElement.ordinaryInput(incomingEdge, offset)); offset += incomingEdge.getSourceNode().getMemory().getTemplate().length; } originElement = tempOriginElement; } edgeToStack.put(originIncomingEdge, originElement); return edgeToStack; } private static void releaseLocks(final Edge originEdge, final boolean releaseOrigin) { final Edge[] nodeIncomingEdges = originEdge.getTargetNode().getIncomingEdges(); // release lock for (final Edge incomingEdge : nodeIncomingEdges) { if (!releaseOrigin && incomingEdge == originEdge) continue; incomingEdge.getSourceNode().getMemory().releaseReadLock(); } } private static MemoryHandlerPlusTemp<?> newRegularBetaTemp( final MemoryHandlerMain originatingMainHandler, final AddressFilter filter, final MemoryHandlerPlusTemp<?> token, final Edge originEdge) throws CouldNotAcquireLockException { final LinkedHashMap<Edge, StackElement> edgeToStack = getLocksAndStack(token, originEdge, false); performJoin(filter, edgeToStack, originEdge); releaseLocks(originEdge, false); final ArrayList<Row> facts = edgeToStack.get(originEdge).getTable(); final int numChildren = originEdge.getTargetNode().getNumberOfOutgoingEdges(); return new MemoryHandlerPlusTempValidRowsAdder(originatingMainHandler, facts, numChildren, canOmitSemaphore(originEdge)); } private static MemoryHandlerPlusTemp<?> newExistentialBetaTemp( final MemoryHandlerMainWithExistentials originatingMainHandler, final AddressFilter filter, final MemoryHandlerPlusTemp<?> token, final Edge originEdge) throws CouldNotAcquireLockException { final LinkedHashMap<Edge, StackElement> edgeToStack = getLocksAndStack(token, originEdge, true); final ArrayList<CounterUpdate> counterUpdates = performExistentialJoin(filter, edgeToStack, originEdge); performJoin(filter, edgeToStack, originEdge); releaseLocks(originEdge, true); final ArrayList<Row> facts = edgeToStack.get(originEdge).getTable(); final int numChildren = originEdge.getTargetNode().getNumberOfOutgoingEdges(); if (null == counterUpdates) { return new MemoryHandlerPlusTempValidRowsAdder(originatingMainHandler, facts, numChildren, canOmitSemaphore(originEdge)); } return MemoryHandlerPlusTempNewRowsAndCounterUpdates.newInstance(originatingMainHandler, counterUpdates, facts, numChildren, canOmitSemaphore(originEdge)); } private static ArrayList<CounterUpdate> performExistentialJoin(final AddressFilter filter, final LinkedHashMap<Edge, StackElement> edgeToStack, final Edge originEdge) { final AddressFilterElement[] filterPartsForCounterColumns = originEdge.getFilterPartsForCounterColumns(); // if there are existential facts in the token, perform a join with the main memory if (filterPartsForCounterColumns.length == 0) { return null; } final ArrayList<CounterUpdate> counterUpdates = new ArrayList<>(); final StackElement originElement = edgeToStack.get(originEdge); final FactAddressPartition partition = partitionFactAddresses(filter, originEdge); final MemoryHandlerMain memoryHandlerMain = (MemoryHandlerMain) originEdge.getTargetNode().getMemory(); final ArrayList<Row> mainRows = memoryHandlerMain.getAllRows(); final ArrayList<Row> tokenRows = originElement.getTable(); final int mainSize = mainRows.size(); final int tokenSize = tokenRows.size(); final boolean[] tokenRowContainsOnlyOldFactsInRegularPart = new boolean[tokenSize]; for (int mainIndex = 0; mainIndex < mainSize; ++mainIndex) { final Row mainRow = mainRows.get(mainIndex); final Fact[] mainFactTuple = mainRow.getFactTuple(); CounterUpdate currentCounterUpdate = null; tokenloop: for (int tokenIndex = 0; tokenIndex < tokenSize; ++tokenIndex) { final Row tokenRow = tokenRows.get(tokenIndex); final Fact[] tokenFactTuple = tokenRow.getFactTuple(); // check whether the allRows are the same in the regular fact part for (final FactAddress factAddress : partition.regular) { if (tokenFactTuple[factAddress.index] != mainFactTuple[factAddress.index]) { continue tokenloop; } } // mark row: does not contain new facts in the regular part tokenRowContainsOnlyOldFactsInRegularPart[tokenIndex] = true; // check whether the existential part fulfill the filter conditions for (final AddressFilterElement filterElement : filterPartsForCounterColumns) { final PredicateWithArguments predicate = filterElement.getFunction(); final SlotInFactAddress[] addresses = filterElement.getAddressesInTarget(); final CounterColumn counterColumn = (CounterColumn) filterElement.getCounterColumn(); final int paramLength = addresses.length; final Object params[] = new Object[paramLength]; // determine parameters using facts in the token where possible for (int i = 0; i < paramLength; ++i) { final SlotInFactAddress address = addresses[i]; final Fact[] factBase; if (partition.existential.contains(address.getFactAddress())) { factBase = tokenFactTuple; } else { factBase = mainFactTuple; } params[i] = factBase[((FactAddress) address.getFactAddress()).index] .getValue(address.getSlotAddress()); } // if combined row doesn't match, try the next token row if (!predicate.evaluate(params)) { continue tokenloop; } // token row matches main row, we can increment the counter if (null == currentCounterUpdate) { currentCounterUpdate = new CounterUpdate(mainRow); counterUpdates.add(currentCounterUpdate); } currentCounterUpdate.increment(counterColumn, 1); } } } // for the join with the other inputs, delete the allRows that did not contain new // regular, but only new existential facts final LazyListCopy<Row> copy = new LazyListCopy<>(tokenRows); for (int i = 0; i < originElement.getTable().size(); ++i) { if (tokenRowContainsOnlyOldFactsInRegularPart[i]) copy.drop(i); else copy.keep(i); } originElement.memStack.set(0, copy.getList()); return counterUpdates; } /* * Assumption: every existentially quantified path/address is only used in a single filter * element. */ private static void performJoin(final AddressFilter filter, final LinkedHashMap<Edge, StackElement> edgeToStack, final Edge originEdge) { final Node targetNode = originEdge.getTargetNode(); final StackElement originElement = edgeToStack.get(originEdge); final Counter counter = ((MemoryHandlerMain) originEdge.getTargetNode().getMemory()).counter; // get filter steps final AddressFilterElement filterSteps[] = filter.getFilterElements(); for (final AddressFilterElement filterElement : filterSteps) { final Collection<StackElement> stack = new ArrayList<>(filterSteps.length); final PredicateWithArguments predicate = filterElement.getFunction(); final SlotInFactAddress addresses[] = filterElement.getAddressesInTarget(); final CounterColumn counterColumn = (CounterColumn) filterElement.getCounterColumn(); final boolean existential = (counterColumn == null); /* * requirement: if filter element is existential, all edges on the stack except * originEdge are existential as well (meaning all regular parts have been join already) */ // determine new edges final Set<Edge> newEdges = new HashSet<>(); stack.add(originElement); for (final SlotInFactAddress address : addresses) { final Edge edge = targetNode.delocalizeAddress(address.getFactAddress()).getEdge(); final StackElement element = edgeToStack.get(edge); if (element != originElement) { assert !existential || originEdge.getSourceNode().getOutgoingExistentialEdges() .contains(edge); if (newEdges.add(edge)) { stack.add(element); } } } // if existential, perform slightly different join not copying but only changing // counters. final ArrayList<Row> TR = new ArrayList<>(); loop(new FunctionPointer() { @Override public void apply(final ArrayList<Row> TR, final StackElement originElement) { final int paramLength = addresses.length; final Object params[] = new Object[paramLength]; // determine parameters for (int i = 0; i < paramLength; ++i) { final SlotInFactAddress slotInTargetAddress = addresses[i]; final org.jamocha.dn.memory.FactAddress targetAddress = slotInTargetAddress.getFactAddress(); final AddressPredecessor upwardsAddress = targetNode.delocalizeAddress(targetAddress); final StackElement se = edgeToStack.get(upwardsAddress.getEdge()); params[i] = se.getValue(upwardsAddress, slotInTargetAddress.getSlotAddress()); } // copy result to new TR if facts match predicate or existentials are present final boolean match = predicate.evaluate(params); if (match || existential) { // copy current row from old TR final Row row = originElement.getRow().copy(); // insert information from new inputs for (final Edge edge : newEdges) { // source is some temp, destination new TR final StackElement se = edgeToStack.get(edge); row.copy(se.getOffset(), se.getRow()); } if (match) { // use counter to set counterColumn to 1 if counterColumn is not null counter.increment(row, counterColumn, 1); } // copy the result to new TR TR.add(row); } } }, TR, stack, originElement); // replace TR in originElement with new temporary result originElement.memStack.set(0, TR); // point all inputs that were joint during this turn to the TR // StackElement for (final Edge incomingEdge : newEdges) { edgeToStack.put(incomingEdge, originElement); } if (!originElement.checkRowBounds()) { return; } } // full join with all inputs not pointing to TR now for (final Map.Entry<Edge, StackElement> entry : edgeToStack.entrySet()) { if (entry.getValue() == originElement) continue; final Edge nodeInput = entry.getKey(); final StackElement se = entry.getValue(); final Collection<StackElement> stack = Arrays.asList(originElement, se); final ArrayList<Row> TR = new ArrayList<>(); loop(new FunctionPointer() { @Override public void apply(final ArrayList<Row> TR, final StackElement originElement) { // copy result to new TR // copy current row from old TR // insert information from new input // source is some temp, destination new TR // copy the result to new TR TR.add(originElement.getRow().copy().copy(se.getOffset(), se.getRow())); } }, TR, stack, originElement); // replace TR in originElement with new temporary result originElement.memStack.set(0, TR); // point all inputs that were joint during this turn to the TR // StackElement edgeToStack.put(nodeInput, originElement); } } @Value static class FactAddressPartition { FactAddress regular[]; Set<FactAddress> existential; } private static FactAddressPartition partitionFactAddresses(final AddressFilter filter, final Edge originEdge) { final FactAddress[] originAddresses = ((MemoryHandlerMain) originEdge.getSourceNode().getMemory()).addresses; final Set<org.jamocha.dn.memory.FactAddress> filterNegativeExistentialAddresses = filter.getNegativeExistentialAddresses(); final Set<org.jamocha.dn.memory.FactAddress> filterPositiveExistentialAddresses = filter.getPositiveExistentialAddresses(); final ArrayList<FactAddress> regular = new ArrayList<>(originAddresses.length); final Set<FactAddress> existential = new HashSet<>(originAddresses.length); for (final FactAddress sourceFactAddress : originAddresses) { final FactAddress targetFactAddress = (FactAddress) originEdge.localizeAddress(sourceFactAddress); if (!filterNegativeExistentialAddresses.contains(targetFactAddress) && !filterPositiveExistentialAddresses.contains(targetFactAddress)) { regular.add(targetFactAddress); } else { existential.add(targetFactAddress); } } return new FactAddressPartition((FactAddress[]) regular.toArray(), existential); } }
src/org/jamocha/dn/memory/javaimpl/MemoryHandlerPlusTemp.java
/* * Copyright 2002-2013 The Jamocha Team * * * 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.jamocha.org/ * * 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.jamocha.dn.memory.javaimpl; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.Map; import java.util.Set; import lombok.ToString; import lombok.Value; import org.jamocha.dn.memory.MemoryHandler; import org.jamocha.dn.memory.SlotAddress; import org.jamocha.dn.nodes.AddressPredecessor; import org.jamocha.dn.nodes.CouldNotAcquireLockException; import org.jamocha.dn.nodes.Edge; import org.jamocha.dn.nodes.Node; import org.jamocha.dn.nodes.SlotInFactAddress; import org.jamocha.filter.AddressFilter; import org.jamocha.filter.AddressFilter.AddressFilterElement; import org.jamocha.filter.fwa.PredicateWithArguments; import org.jamocha.visitor.Visitable; /** * Java-implementation of the {@link org.jamocha.dn.memory.MemoryHandlerPlusTemp} interface. * * @author Fabian Ohler <[email protected]> * @author Christoph Terwelp <[email protected]> * @see org.jamocha.dn.memory.MemoryHandlerPlusTemp */ @ToString(callSuper = true, of = "valid") public abstract class MemoryHandlerPlusTemp<T extends MemoryHandlerMain> extends MemoryHandlerTemp<T> implements org.jamocha.dn.memory.MemoryHandlerPlusTemp, Visitable<MemoryHandlerPlusTempVisitor> { static class Semaphore { int count; public Semaphore(final int count) { super(); this.count = count; } public synchronized boolean release() { return --this.count != 0; } } final Semaphore lock; /** * set to false as soon as the memory has been committed to its main memory */ boolean valid = true; protected MemoryHandlerPlusTemp(final T originatingMainHandler, final int numChildren, final boolean empty, final boolean omitSemaphore) { super(originatingMainHandler); if (empty) { this.lock = null; this.valid = false; } else if (omitSemaphore || numChildren == 0) { this.lock = null; originatingMainHandler.getValidOutgoingPlusTokens().add(this); // commit and invalidate the token final org.jamocha.dn.memory.MemoryHandlerTemp pendingTemp = commitAndInvalidate(); /* * if this token was a MemoryHandlerPlusTempNewRowsAndCounterUpdates we may have * produced new temps by calling commitAndInvalidate, yet we cannot process them without * lots of ugly code at the worst location to think of, so this is unsupported for now * as it has no purpose in a production system where the only nodes without children are * terminal nodes */ if (null != pendingTemp) { throw new IllegalArgumentException( "Nodes using existentials without children are unsupported!"); } } else { this.lock = new Semaphore(numChildren); originatingMainHandler.getValidOutgoingPlusTokens().add(this); } } @Override final public org.jamocha.dn.memory.MemoryHandlerTemp releaseLock() { try { if (this.lock.release()) return null; } catch (final NullPointerException e) { // lock was null return null; } // all children have processed the temp memory, now we have to write its // content to main memory return commitAndInvalidate(); } final protected org.jamocha.dn.memory.MemoryHandlerTemp commitAndInvalidate() { this.originatingMainHandler.acquireWriteLock(); assert this == this.originatingMainHandler.getValidOutgoingPlusTokens().peek(); this.originatingMainHandler.getValidOutgoingPlusTokens().remove(); final org.jamocha.dn.memory.MemoryHandlerTemp newTemp = commitToMain(); this.originatingMainHandler.releaseWriteLock(); this.valid = false; return newTemp; } abstract protected org.jamocha.dn.memory.MemoryHandlerTemp commitToMain(); @Override public void enqueueInEdge(final Edge edge) { edge.enqueueMemory(this); } /* * * * * * * * * STATIC FACTORY PART * * * * * * * * */ protected static boolean canOmitSemaphore(final Edge originEdge) { return originEdge.getTargetNode().getIncomingEdges().length <= 1; } protected static boolean canOmitSemaphore(final Node sourceNode) { for (final Edge edge : sourceNode.getOutgoingEdges()) { if (!canOmitSemaphore(edge)) return false; } return true; } @Override public MemoryHandlerPlusTemp<?> newBetaTemp(final MemoryHandlerMain originatingMainHandler, final Edge originIncomingEdge, final AddressFilter filter) throws CouldNotAcquireLockException { // create follow-up-temp final MemoryHandlerPlusTemp<?> token = newRegularBetaTemp(originatingMainHandler, filter, this, originIncomingEdge); // push old temp into incoming edge to augment the memory seen by its target originIncomingEdge.getTempMemories().add(token); // return new temp return token; } @Override public MemoryHandlerPlusTemp<?> newBetaTemp( final MemoryHandlerMainWithExistentials originatingMainHandler, final Edge originIncomingEdge, final AddressFilter filter) throws CouldNotAcquireLockException { // create follow-up-temp final MemoryHandlerPlusTemp<?> token = newExistentialBetaTemp(originatingMainHandler, filter, this, originIncomingEdge); // push old temp into incoming edge to augment the memory seen by its target originIncomingEdge.getTempMemories().add(token); // return new temp return token; } static MemoryHandlerPlusTemp<MemoryHandlerMain> newAlphaTemp( final MemoryHandlerMain originatingMainHandler, final MemoryHandlerPlusTemp<? extends MemoryHandlerMain> token, final Edge originIncomingEdge, final AddressFilter filter) throws CouldNotAcquireLockException { final ArrayList<Row> factList = new ArrayList<>(1); factLoop: for (final Row row : token.getRowsForSucessorNodes()) { assert row.getFactTuple().length == 1; for (final AddressFilterElement filterElement : filter.getFilterElements()) { if (!applyFilterElement(row.getFactTuple()[0], filterElement)) { continue factLoop; } } factList.add(row); } return new MemoryHandlerPlusTempValidRowsAdder(originatingMainHandler, factList, originIncomingEdge.getTargetNode().getNumberOfOutgoingEdges(), canOmitSemaphore(originIncomingEdge)); // FIXME only use Semaphores if one of the outgoing edges is connected to the beta network // return new MemoryHandlerPlusTemp(originatingMainHandler, // originIncomingEdge.getTargetNode().getNumberOfOutgoingEdges(), // needsSemaphore(originIncomingEdge)); } @Override public MemoryHandlerPlusTemp<MemoryHandlerMain> newAlphaTemp( final MemoryHandlerMain originatingMainHandler, final Edge originIncomingEdge, final AddressFilter filter) throws CouldNotAcquireLockException { return newAlphaTemp((MemoryHandlerMain) originatingMainHandler, this, originIncomingEdge, filter); } static MemoryHandlerPlusTemp<MemoryHandlerMain> newRootTemp( final MemoryHandlerMain originatingMainHandler, final Node otn, final org.jamocha.dn.memory.Fact... facts) { final ArrayList<Row> factList = new ArrayList<>(facts.length); for (final org.jamocha.dn.memory.Fact fact : facts) { assert fact.getTemplate() == otn.getMemory().getTemplate()[0]; factList.add(originatingMainHandler.newRow(new Fact(fact.getSlotValues()))); } return new MemoryHandlerPlusTempValidRowsAdder(originatingMainHandler, factList, otn.getNumberOfOutgoingEdges(), canOmitSemaphore(otn)); // new MemoryHandlerPlusTemp(originatingMainHandler, factList, // otn.getNumberOfOutgoingEdges(), needsSemaphore(otn)); } static abstract class StackElement { int rowIndex, memIndex; ArrayList<ArrayList<Row>> memStack; final int offset; private StackElement(final ArrayList<ArrayList<Row>> memStack, final int offset) { this.memStack = memStack; this.offset = offset; } public static StackElement ordinaryInput(final Edge edge, final int offset) { final LinkedList<? extends MemoryHandler> temps = edge.getTempMemories(); final ArrayList<ArrayList<Row>> memStack = new ArrayList<ArrayList<Row>>(temps.size() + 1); memStack.add(((org.jamocha.dn.memory.javaimpl.MemoryHandlerMain) edge.getSourceNode() .getMemory()).getRowsForSucessorNodes()); for (final Iterator<? extends MemoryHandler> iter = temps.iterator(); iter.hasNext();) { final MemoryHandlerPlusTemp<?> temp = (MemoryHandlerPlusTemp<?>) iter.next(); if (!temp.valid) { iter.remove(); continue; } memStack.add(temp.getRowsForSucessorNodes()); } return new StackElement(memStack, offset) { @Override Object getValue(final AddressPredecessor addr, final SlotAddress slot) { return this.getRow().getFactTuple()[((org.jamocha.dn.memory.javaimpl.FactAddress) addr .getAddress()).index].getValue((slot)); } }; } public static StackElement originInput(final int columns, final Edge originEdge, final MemoryHandlerPlusTemp<?> token, final int offset) { final ArrayList<Row> listWithHoles = new ArrayList<>(token.getRowsForSucessorNodes().size()); for (final Row row : token.getRowsForSucessorNodes()) { final Row wideRow = ((MemoryHandlerMain) originEdge.getTargetNode().getMemory()) .newRow(columns); assert columns >= offset + row.getFactTuple().length; wideRow.copy(offset, row); listWithHoles.add(wideRow); } final ArrayList<ArrayList<Row>> memStack = new ArrayList<ArrayList<Row>>(1); memStack.add(listWithHoles); return new StackElement(memStack, offset) { @Override Object getValue(final AddressPredecessor addr, final SlotAddress slot) { return this.getRow().getFactTuple()[((org.jamocha.dn.memory.javaimpl.FactAddress) addr .getEdge().localizeAddress(addr.getAddress())).index].getValue((slot)); } }; } ArrayList<Row> getTable() { return this.memStack.get(this.memIndex); } Row getRow() { return this.getTable().get(this.rowIndex); } abstract Object getValue(final AddressPredecessor addr, final SlotAddress slot); boolean checkMemBounds() { return this.memStack.size() > this.memIndex && this.memIndex >= 0; } boolean checkRowBounds() { return checkMemBounds() && getTable().size() > this.rowIndex && this.rowIndex >= 0; } void resetIndices() { this.rowIndex = 0; this.memIndex = 0; } int getOffset() { return this.offset; } } static interface FunctionPointer { public void apply(final ArrayList<Row> TR, final StackElement originElement); } private static void loop(final FunctionPointer functionPointer, final ArrayList<Row> TR, final Collection<StackElement> stack, final StackElement originElement) { if (stack.isEmpty()) { return; } { final Iterator<StackElement> iter = stack.iterator(); // skip originElement iter.next(); // initialize all memory indices to valid values while (iter.hasNext()) { final StackElement element = iter.next(); while (!element.checkRowBounds()) { if (!element.checkMemBounds()) { // one of the elements doesn't hold any facts, the join will be empty // delete all partial fact tuples in the TR originElement.memStack.set(0, new ArrayList<Row>(0)); TR.clear(); return; } element.memIndex++; } } } outerloop: while (true) { innerloop: while (true) { functionPointer.apply(TR, originElement); // increment row indices for (final Iterator<StackElement> iter = stack.iterator(); iter.hasNext();) { final StackElement element = iter.next(); element.rowIndex++; if (element.checkRowBounds()) break; element.rowIndex = 0; if (!iter.hasNext()) break innerloop; } } // increment memory indices for (final Iterator<StackElement> iter = stack.iterator(); iter.hasNext();) { final StackElement element = iter.next(); element.memIndex++; if (element.checkMemBounds()) break; element.memIndex = 0; if (!iter.hasNext()) break outerloop; } } // reset all indices in the StackElements for (final StackElement elem : stack) { elem.resetIndices(); } } private static final LinkedHashMap<Edge, StackElement> getLocksAndStack( final MemoryHandlerPlusTemp<?> token, final Edge originIncomingEdge, final boolean getOrigin) throws CouldNotAcquireLockException { // get a fixed-size array of indices (size: #inputs of the node), // determine number of inputs for the current join as maxIndex // loop through the inputs line-wise using array[0] .. array[maxIndex] // as line indices, incrementing array[maxIndex] and propagating the // increment to lower indices when input-size is reached // set locks and create stack final Node targetNode = originIncomingEdge.getTargetNode(); final Edge[] nodeIncomingEdges = targetNode.getIncomingEdges(); final LinkedHashMap<Edge, StackElement> edgeToStack = new LinkedHashMap<>(); final int columns = targetNode.getMemory().getTemplate().length; final StackElement originElement; { StackElement tempOriginElement = null; int offset = 0; for (final Edge incomingEdge : nodeIncomingEdges) { if (incomingEdge == originIncomingEdge) { tempOriginElement = StackElement.originInput(columns, originIncomingEdge, token, offset); offset += incomingEdge.getSourceNode().getMemory().getTemplate().length; if (!getOrigin) { // don't lock the originInput continue; } } try { if (!incomingEdge.getSourceNode().getMemory().tryReadLock()) { for (final Edge edge : edgeToStack.keySet()) { edge.getSourceNode().getMemory().releaseReadLock(); } throw new CouldNotAcquireLockException(); } } catch (final InterruptedException ex) { throw new Error( "Should not happen, interruption of this method is not supported!", ex); } edgeToStack.put(incomingEdge, StackElement.ordinaryInput(incomingEdge, offset)); offset += incomingEdge.getSourceNode().getMemory().getTemplate().length; } originElement = tempOriginElement; } edgeToStack.put(originIncomingEdge, originElement); return edgeToStack; } private static void releaseLocks(final Edge originEdge, final boolean releaseOrigin) { final Edge[] nodeIncomingEdges = originEdge.getTargetNode().getIncomingEdges(); // release lock for (final Edge incomingEdge : nodeIncomingEdges) { if (!releaseOrigin && incomingEdge == originEdge) continue; incomingEdge.getSourceNode().getMemory().releaseReadLock(); } } private static MemoryHandlerPlusTemp<?> newRegularBetaTemp( final MemoryHandlerMain originatingMainHandler, final AddressFilter filter, final MemoryHandlerPlusTemp<?> token, final Edge originEdge) throws CouldNotAcquireLockException { final LinkedHashMap<Edge, StackElement> edgeToStack = getLocksAndStack(token, originEdge, false); performJoin(filter, edgeToStack, originEdge); releaseLocks(originEdge, false); final ArrayList<Row> facts = edgeToStack.get(originEdge).getTable(); final int numChildren = originEdge.getTargetNode().getNumberOfOutgoingEdges(); return new MemoryHandlerPlusTempValidRowsAdder(originatingMainHandler, facts, numChildren, canOmitSemaphore(originEdge)); } private static MemoryHandlerPlusTemp<?> newExistentialBetaTemp( final MemoryHandlerMainWithExistentials originatingMainHandler, final AddressFilter filter, final MemoryHandlerPlusTemp<?> token, final Edge originEdge) throws CouldNotAcquireLockException { final LinkedHashMap<Edge, StackElement> edgeToStack = getLocksAndStack(token, originEdge, true); final ArrayList<CounterUpdate> counterUpdates = performExistentialJoin(filter, edgeToStack, originEdge); performJoin(filter, edgeToStack, originEdge); releaseLocks(originEdge, true); final ArrayList<Row> facts = edgeToStack.get(originEdge).getTable(); final int numChildren = originEdge.getTargetNode().getNumberOfOutgoingEdges(); if (null == counterUpdates) { return new MemoryHandlerPlusTempValidRowsAdder(originatingMainHandler, facts, numChildren, canOmitSemaphore(originEdge)); } return MemoryHandlerPlusTempNewRowsAndCounterUpdates.newInstance(originatingMainHandler, counterUpdates, facts, numChildren, canOmitSemaphore(originEdge)); } private static ArrayList<CounterUpdate> performExistentialJoin(final AddressFilter filter, final LinkedHashMap<Edge, StackElement> edgeToStack, final Edge originEdge) { final AddressFilterElement[] filterPartsForCounterColumns = originEdge.getFilterPartsForCounterColumns(); // if there are existential facts in the token, perform a join with the main memory if (filterPartsForCounterColumns.length == 0) { return null; } final ArrayList<CounterUpdate> counterUpdates = new ArrayList<>(); final StackElement originElement = edgeToStack.get(originEdge); final FactAddressPartition partition = partitionFactAddresses(filter, originEdge); final MemoryHandlerMain memoryHandlerMain = (MemoryHandlerMain) originEdge.getTargetNode().getMemory(); final ArrayList<Row> mainRows = memoryHandlerMain.getAllRows(); final ArrayList<Row> tokenRows = originElement.getTable(); final int mainSize = mainRows.size(); final int tokenSize = tokenRows.size(); final boolean[] tokenRowContainsOnlyOldFactsInRegularPart = new boolean[tokenSize]; for (int mainIndex = 0; mainIndex < mainSize; ++mainIndex) { final Row mainRow = mainRows.get(mainIndex); final Fact[] mainFactTuple = mainRow.getFactTuple(); CounterUpdate currentCounterUpdate = null; tokenloop: for (int tokenIndex = 0; tokenIndex < tokenSize; ++tokenIndex) { final Row tokenRow = tokenRows.get(tokenIndex); final Fact[] tokenFactTuple = tokenRow.getFactTuple(); // check whether the allRows are the same in the regular fact part for (final FactAddress factAddress : partition.regular) { if (tokenFactTuple[factAddress.index] != mainFactTuple[factAddress.index]) { continue tokenloop; } } // mark row: does not contain new facts in the regular part tokenRowContainsOnlyOldFactsInRegularPart[tokenIndex] = true; // check whether the existential part fulfill the filter conditions for (final AddressFilterElement filterElement : filterPartsForCounterColumns) { final PredicateWithArguments predicate = filterElement.getFunction(); final SlotInFactAddress[] addresses = filterElement.getAddressesInTarget(); final CounterColumn counterColumn = (CounterColumn) filterElement.getCounterColumn(); final int paramLength = addresses.length; final Object params[] = new Object[paramLength]; // determine parameters using facts in the token where possible for (int i = 0; i < paramLength; ++i) { final SlotInFactAddress address = addresses[i]; final Fact[] factBase; if (partition.existential.contains(address.getFactAddress())) { factBase = tokenFactTuple; } else { factBase = mainFactTuple; } params[i] = factBase[((FactAddress) address.getFactAddress()).index] .getValue(address.getSlotAddress()); } // if combined row doesn't match, try the next token row if (!predicate.evaluate(params)) { continue tokenloop; } // token row matches main row, we can increment the counter if (null == currentCounterUpdate) { currentCounterUpdate = new CounterUpdate(mainRow); counterUpdates.add(currentCounterUpdate); } currentCounterUpdate.increment(counterColumn, 1); } } } // for the join with the other inputs, delete the allRows that did not contain new // regular, but only new existential facts final LazyListCopy<Row> copy = new LazyListCopy<>(tokenRows); for (int i = 0; i < originElement.getTable().size(); ++i) { if (tokenRowContainsOnlyOldFactsInRegularPart[i]) copy.drop(i); else copy.keep(i); } originElement.memStack.set(0, copy.getList()); return counterUpdates; } /* * Assumption: every existentially quantified path/address is only used in a single filter * element. */ private static void performJoin(final AddressFilter filter, final LinkedHashMap<Edge, StackElement> edgeToStack, final Edge originEdge) { final Node targetNode = originEdge.getTargetNode(); final StackElement originElement = edgeToStack.get(originEdge); final Counter counter = ((MemoryHandlerMain) originEdge.getTargetNode().getMemory()).counter; // get filter steps final AddressFilterElement filterSteps[] = filter.getFilterElements(); for (final AddressFilterElement filterElement : filterSteps) { final Collection<StackElement> stack = new ArrayList<>(filterSteps.length); final PredicateWithArguments predicate = filterElement.getFunction(); final SlotInFactAddress addresses[] = filterElement.getAddressesInTarget(); final CounterColumn counterColumn = (CounterColumn) filterElement.getCounterColumn(); final boolean existential = (counterColumn == null); // determine new edges final Set<Edge> newEdges = new HashSet<>(); stack.add(originElement); for (final SlotInFactAddress address : addresses) { final Edge edge = targetNode.delocalizeAddress(address.getFactAddress()).getEdge(); final StackElement element = edgeToStack.get(edge); if (element != originElement) { if (newEdges.add(edge)) { stack.add(element); } } } final ArrayList<Row> TR = new ArrayList<>(); loop(new FunctionPointer() { @Override public void apply(final ArrayList<Row> TR, final StackElement originElement) { final int paramLength = addresses.length; final Object params[] = new Object[paramLength]; // determine parameters for (int i = 0; i < paramLength; ++i) { final SlotInFactAddress slotInTargetAddress = addresses[i]; final org.jamocha.dn.memory.FactAddress targetAddress = slotInTargetAddress.getFactAddress(); final AddressPredecessor upwardsAddress = targetNode.delocalizeAddress(targetAddress); final StackElement se = edgeToStack.get(upwardsAddress.getEdge()); params[i] = se.getValue(upwardsAddress, slotInTargetAddress.getSlotAddress()); } // copy result to new TR if facts match predicate or existentials are present final boolean match = predicate.evaluate(params); if (match || existential) { // copy current row from old TR final Row row = originElement.getRow().copy(); // insert information from new inputs for (final Edge edge : newEdges) { // source is some temp, destination new TR final StackElement se = edgeToStack.get(edge); row.copy(se.getOffset(), se.getRow()); } if (match) { // use counter to set counterColumn to 1 if counterColumn is not null counter.increment(row, counterColumn, 1); } // copy the result to new TR TR.add(row); } } }, TR, stack, originElement); // replace TR in originElement with new temporary result originElement.memStack.set(0, TR); // point all inputs that were joint during this turn to the TR // StackElement for (final Edge incomingEdge : newEdges) { edgeToStack.put(incomingEdge, originElement); } if (!originElement.checkRowBounds()) { return; } } // full join with all inputs not pointing to TR now for (final Map.Entry<Edge, StackElement> entry : edgeToStack.entrySet()) { if (entry.getValue() == originElement) continue; final Edge nodeInput = entry.getKey(); final StackElement se = entry.getValue(); final Collection<StackElement> stack = Arrays.asList(originElement, se); final ArrayList<Row> TR = new ArrayList<>(); loop(new FunctionPointer() { @Override public void apply(final ArrayList<Row> TR, final StackElement originElement) { // copy result to new TR // copy current row from old TR // insert information from new input // source is some temp, destination new TR // copy the result to new TR TR.add(originElement.getRow().copy().copy(se.getOffset(), se.getRow())); } }, TR, stack, originElement); // replace TR in originElement with new temporary result originElement.memStack.set(0, TR); // point all inputs that were joint during this turn to the TR // StackElement edgeToStack.put(nodeInput, originElement); } } @Value static class FactAddressPartition { FactAddress regular[]; Set<FactAddress> existential; } private static FactAddressPartition partitionFactAddresses(final AddressFilter filter, final Edge originEdge) { final FactAddress[] originAddresses = ((MemoryHandlerMain) originEdge.getSourceNode().getMemory()).addresses; final Set<org.jamocha.dn.memory.FactAddress> filterNegativeExistentialAddresses = filter.getNegativeExistentialAddresses(); final Set<org.jamocha.dn.memory.FactAddress> filterPositiveExistentialAddresses = filter.getPositiveExistentialAddresses(); final ArrayList<FactAddress> regular = new ArrayList<>(originAddresses.length); final Set<FactAddress> existential = new HashSet<>(originAddresses.length); for (final FactAddress sourceFactAddress : originAddresses) { final FactAddress targetFactAddress = (FactAddress) originEdge.localizeAddress(sourceFactAddress); if (!filterNegativeExistentialAddresses.contains(targetFactAddress) && !filterPositiveExistentialAddresses.contains(targetFactAddress)) { regular.add(targetFactAddress); } else { existential.add(targetFactAddress); } } return new FactAddressPartition((FactAddress[]) regular.toArray(), existential); } }
plus temp: added some notes
src/org/jamocha/dn/memory/javaimpl/MemoryHandlerPlusTemp.java
plus temp: added some notes
<ide><path>rc/org/jamocha/dn/memory/javaimpl/MemoryHandlerPlusTemp.java <ide> final SlotInFactAddress addresses[] = filterElement.getAddressesInTarget(); <ide> final CounterColumn counterColumn = (CounterColumn) filterElement.getCounterColumn(); <ide> final boolean existential = (counterColumn == null); <add> /* <add> * requirement: if filter element is existential, all edges on the stack except <add> * originEdge are existential as well (meaning all regular parts have been join already) <add> */ <ide> <ide> // determine new edges <ide> final Set<Edge> newEdges = new HashSet<>(); <ide> final Edge edge = targetNode.delocalizeAddress(address.getFactAddress()).getEdge(); <ide> final StackElement element = edgeToStack.get(edge); <ide> if (element != originElement) { <add> assert !existential <add> || originEdge.getSourceNode().getOutgoingExistentialEdges() <add> .contains(edge); <ide> if (newEdges.add(edge)) { <ide> stack.add(element); <ide> } <ide> } <ide> } <add> <add> // if existential, perform slightly different join not copying but only changing <add> // counters. <ide> <ide> final ArrayList<Row> TR = new ArrayList<>(); <ide> loop(new FunctionPointer() {
JavaScript
mit
1974c64e7beaf7a94fb6e9237e8e0797a15f5e84
0
candiii-lin/dementia
var Firebase = require('firebase'); var moment = require('moment'); var Patient = require('../models/patient'); var motherload = new Firebase("https://dementia.firebaseio.com/"); exports.recieveAlert = function (dark, patientID, callback) { var alert = {}; var patient = Patient.findOne({_id: patientID}, function(err, pat) { pati = motherload.child(JSON.stringify(pat.caregiver)); alert.name = pat.first_name + " " + pat.last_name; alert.timestamp = moment().format(); alert.type = "Fall"; if (dark=="TRUE") { pat.is_in_dark = true; } else { pat.is_in_dark = false; } pat.save(); pati.push(alert); callback(); }) } exports.recieveNotMoving = function (dark, patientID, callback) { var alert = {}; var patient = Patient.findOne({_id: patientID}, function(err, pat) { pati = motherload.child(JSON.stringify(pat.caregiver)); alert.name = pat.first_name + " " + pat.last_name; alert.timestamp = moment().format(); alert.type = "Not Moving"; if (dark=="TRUE") { pat.is_in_dark = true; } else { pat.is_in_dark = false; } pat.save(); pati.push(alert); callback(); }) }
app/controller/alerts.js
var Firebase = require('firebase'); var moment = require('moment'); var Patient = require('../models/patient'); var motherload = new Firebase("https://dementia.firebaseio.com/"); exports.recieveAlert = function (dark, patientID, callback) { var alert = {}; var patient = Patient.findOne({_id: patientID}, function(err, pat) { pati = motherload.child(JSON.stringify(pat.caregiver)); alert.name = pat.first_name + " " + pat.last_name; alert.timestamp = moment().format(); alert.type = "Fall"; if (dark=="true") { pat.is_in_dark = true; } else { pat.is_in_dark = false; } pat.save(); pati.push(alert); callback(); }) } exports.recieveNotMoving = function (dark, patientID, callback) { var alert = {}; var patient = Patient.findOne({_id: patientID}, function(err, pat) { pati = motherload.child(JSON.stringify(pat.caregiver)); alert.name = pat.first_name + " " + pat.last_name; alert.timestamp = moment().format(); alert.type = "Not Moving"; if (dark=="true") { pat.is_in_dark = true; } else { pat.is_in_dark = false; } pat.save(); pati.push(alert); callback(); }) }
fix true false
app/controller/alerts.js
fix true false
<ide><path>pp/controller/alerts.js <ide> alert.timestamp = moment().format(); <ide> alert.type = "Fall"; <ide> <del> if (dark=="true") { <add> if (dark=="TRUE") { <ide> pat.is_in_dark = true; <ide> } else { <ide> pat.is_in_dark = false; <ide> alert.timestamp = moment().format(); <ide> alert.type = "Not Moving"; <ide> <del> if (dark=="true") { <add> if (dark=="TRUE") { <ide> pat.is_in_dark = true; <ide> } else { <ide> pat.is_in_dark = false;
JavaScript
agpl-3.0
ad582af7b9f979a432c058298dd36aa90de7232c
0
ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs
/** @enum */ var c_oSerFormat = { Version:2, //1.0.0.2 Signature: "XLSY" }; var g_nCurFileVersion = c_oSerFormat.Version; //dif: //Version:2 добавлены свойства колонок и строк CustomWidth, CustomHeight(раньше считались true) /** @enum */ var c_oSerTableTypes = { Other: 0, SharedStrings: 1, Styles: 2, Workbook: 3, Worksheets: 4, CalcChain: 5 }; /** @enum */ var c_oSerStylesTypes = { Borders: 0, Border: 1, CellXfs: 2, Xfs: 3, Fills: 4, Fill: 5, Fonts: 6, Font: 7, NumFmts: 8, NumFmt: 9, Dxfs: 10, Dxf: 11, TableStyles: 12, CellStyleXfs: 14, CellStyles: 15, CellStyle: 16 }; /** @enum */ var c_oSerBorderTypes = { Bottom: 0, Diagonal: 1, End: 2, Horizontal: 3, Start: 4, Top: 5, Vertical: 6, DiagonalDown: 7, DiagonalUp: 8, Outline: 9 }; /** @enum */ var c_oSerBorderPropTypes = { Color: 0, Style: 1 }; /** @enum */ var c_oSerXfsTypes = { ApplyAlignment: 0, ApplyBorder: 1, ApplyFill: 2, ApplyFont: 3, ApplyNumberFormat: 4, ApplyProtection: 5, BorderId: 6, FillId: 7, FontId: 8, NumFmtId: 9, PivotButton: 10, QuotePrefix: 11, XfId: 12, Aligment: 13, Protection: 14 }; /** @enum */ var c_oSerAligmentTypes = { Horizontal: 0, Indent: 1, JustifyLastLine: 2, ReadingOrder: 3, RelativeIndent: 4, ShrinkToFit: 5, TextRotation: 6, Vertical: 7, WrapText: 8 }; /** @enum */ var c_oSerFillTypes = { PatternFill: 0, PatternFillBgColor: 1 }; /** @enum */ var c_oSerFontTypes = { Bold: 0, Color: 1, Italic: 3, RFont: 4, Strike: 5, Sz: 6, Underline: 7, VertAlign: 8 }; /** @enum */ var c_oSerNumFmtTypes = { FormatCode: 0, NumFmtId: 1 }; /** @enum */ var c_oSerSharedStringTypes = { Si: 0, Run: 1, RPr: 2, Text: 3 }; /** @enum */ var c_oSerWorkbookTypes = { WorkbookPr: 0, BookViews: 1, WorkbookView: 2, DefinedNames: 3, DefinedName: 4 }; /** @enum */ var c_oSerWorkbookPrTypes = { Date1904: 0, DateCompatibility: 1 }; /** @enum */ var c_oSerWorkbookViewTypes = { ActiveTab: 0 }; /** @enum */ var c_oSerDefinedNameTypes = { Name: 0, Ref: 1, LocalSheetId: 2 }; /** @enum */ var c_oSerWorksheetsTypes = { Worksheet: 0, WorksheetProp: 1, Cols: 2, Col: 3, Dimension: 4, Hyperlinks: 5, Hyperlink: 6, MergeCells: 7, MergeCell: 8, SheetData: 9, Row: 10, SheetFormatPr: 11, Drawings: 12, Drawing: 13, PageMargins: 14, PageSetup: 15, PrintOptions: 16, Autofilter: 17, TableParts: 18, Comments: 19, Comment: 20, ConditionalFormatting: 21, SheetViews: 22, SheetView: 23 }; /** @enum */ var c_oSerWorksheetPropTypes = { Name: 0, SheetId: 1, State: 2 }; /** @enum */ var c_oSerWorksheetColTypes = { BestFit: 0, Hidden: 1, Max: 2, Min: 3, Style: 4, Width: 5, CustomWidth: 6 }; /** @enum */ var c_oSerHyperlinkTypes = { Ref: 0, Hyperlink: 1, Location: 2, Tooltip: 3 }; /** @enum */ var c_oSerSheetFormatPrTypes = { DefaultColWidth : 0, DefaultRowHeight : 1, BaseColWidth : 2 }; /** @enum */ var c_oSerRowTypes = { Row: 0, Style: 1, Height: 2, Hidden: 3, Cells: 4, Cell: 5, CustomHeight: 6 }; /** @enum */ var c_oSerCellTypes = { Ref: 0, Style: 1, Type: 2, Value: 3, Formula: 4 }; /** @enum */ var c_oSerFormulaTypes = { Aca: 0, Bx: 1, Ca: 2, Del1: 3, Del2: 4, Dt2D: 5, Dtr: 6, R1: 7, R2: 8, Ref: 9, Si: 10, T: 11, Text: 12 }; /** @enum */ var c_oSer_DrawingFromToType = { Col: 0, ColOff: 1, Row: 2, RowOff: 3 }; /** @enum */ var c_oSer_DrawingPosType = { X: 0, Y: 1 }; /** @enum */ var c_oSer_DrawingExtType = { Cx: 0, Cy: 1 }; /** @enum */ var c_oSer_OtherType = { Media: 0, MediaItem: 1, MediaId: 2, MediaSrc: 3, EmbeddedFonts: 4, Theme: 5 }; /** @enum */ var c_oSer_CalcChainType = { CalcChainItem: 0, Array: 1, SheetId: 2, DependencyLevel: 3, Ref: 4, ChildChain: 5, NewThread: 6 }; /** @enum */ var c_oSer_ColorObjectType = { Rgb: 0, Type: 1, Theme: 2, Tint: 3 }; /** @enum */ var c_oSer_ColorType = { Auto: 0 }; /** @enum */ var c_oSer_CalcChainType = { CalcChainItem: 0, Array: 1, SheetId: 2, DependencyLevel: 3, Ref: 4, ChildChain: 5, NewThread: 6 }; /** @enum */ var c_oSer_PageMargins = { Left: 0, Top: 1, Right: 2, Bottom: 3, Header: 4, Footer: 5 }; /** @enum */ var c_oSer_PageSetup = { Orientation: 0, PaperSize: 1 }; /** @enum */ var c_oSer_PrintOptions = { GridLines: 0, Headings: 1 }; /** @enum */ var c_oSer_TablePart = { Table:0, Ref:1, TotalsRowCount:2, DisplayName:3, AutoFilter:4, SortState:5, TableColumns:6, TableStyleInfo:7, HeaderRowCount:8 }; /** @enum */ var c_oSer_TableStyleInfo = { Name:0, ShowColumnStripes:1, ShowRowStripes:2, ShowFirstColumn:3, ShowLastColumn:4 }; /** @enum */ var c_oSer_TableColumns = { TableColumn:0, Name:1, DataDxfId:2, TotalsRowLabel:3, TotalsRowFunction:4, TotalsRowFormula:5, CalculatedColumnFormula:6 }; /** @enum */ var c_oSer_SortState = { Ref:0, CaseSensitive:1, SortConditions:2, SortCondition:3, ConditionRef:4, ConditionSortBy:5, ConditionDescending:6, ConditionDxfId:7 }; /** @enum */ var c_oSer_AutoFilter = { Ref:0, FilterColumns:1, FilterColumn:2, SortState:3 }; /** @enum */ var c_oSer_FilterColumn = { ColId:0, Filters:1, Filter:2, DateGroupItem:3, CustomFilters:4, ColorFilter:5, Top10:6, DynamicFilter: 7, HiddenButton: 8, ShowButton: 9, FiltersBlank: 10 }; /** @enum */ var c_oSer_Filter = { Val:0 }; /** @enum */ var c_oSer_DateGroupItem = { DateTimeGrouping:0, Day:1, Hour:2, Minute:3, Month:4, Second:5, Year:6 }; /** @enum */ var c_oSer_CustomFilters = { And:0, CustomFilters:1, CustomFilter:2, Operator:3, Val:4 }; /** @enum */ var c_oSer_DynamicFilter = { Type: 0, Val: 1, MaxVal: 2 }; /** @enum */ var c_oSer_ColorFilter = { CellColor:0, DxfId:1 }; /** @enum */ var c_oSer_Top10 = { FilterVal:0, Percent:1, Top:2, Val:3 }; /** @enum */ var c_oSer_Dxf = { Alignment:0, Border:1, Fill:2, Font:3, NumFmt:4 }; /** @enum */ var c_oSer_TableStyles = { DefaultTableStyle:0, DefaultPivotStyle:1, TableStyles: 2, TableStyle: 3 }; var c_oSer_TableStyle = { Name: 0, Pivot: 1, Table: 2, Elements: 3, Element: 4 }; var c_oSer_TableStyleElement = { DxfId: 0, Size: 1, Type: 2 }; var c_oSer_Comments = { Row: 0, Col: 1, CommentDatas : 2, CommentData : 3, Left: 4, LeftOffset: 5, Top: 6, TopOffset: 7, Right: 8, RightOffset: 9, Bottom: 10, BottomOffset: 11, LeftMM: 12, TopMM: 13, WidthMM: 14, HeightMM: 15, MoveWithCells: 16, SizeWithCells: 17 }; var c_oSer_CommentData = { Text : 0, Time : 1, UserId : 2, UserName : 3, QuoteText : 4, Solved : 5, Document : 6, Replies : 7, Reply : 8 }; var c_oSer_ConditionalFormatting = { Pivot : 0, SqRef : 1, ConditionalFormattingRule : 2 }; var c_oSer_ConditionalFormattingRule = { AboveAverage : 0, Bottom : 1, DxfId : 2, EqualAverage : 3, Operator : 4, Percent : 5, Priority : 6, Rank : 7, StdDev : 8, StopIfTrue : 9, Text : 10, TimePeriod : 11, Type : 12, ColorScale : 14, DataBar : 15, FormulaCF : 16, IconSet : 17 }; var c_oSer_ConditionalFormattingRuleColorScale = { CFVO : 0, Color : 1 }; var c_oSer_ConditionalFormattingDataBar = { CFVO : 0, Color : 1, MaxLength : 2, MinLength : 3, ShowValue : 4 }; var c_oSer_ConditionalFormattingIconSet = { CFVO : 0, IconSet : 1, Percent : 2, Reverse : 3, ShowValue : 4 }; var c_oSer_ConditionalFormattingValueObject = { Gte : 0, Type : 1, Val : 2 }; var c_oSer_SheetView = { ColorId : 0, DefaultGridColor : 1, RightToLeft : 2, ShowFormulas : 3, ShowGridLines : 4, ShowOutlineSymbols : 5, ShowRowColHeaders : 6, ShowRuler : 7, ShowWhiteSpace : 8, ShowZeros : 9, TabSelected : 10, TopLeftCell : 11, View : 12, WindowProtection : 13, WorkbookViewId : 14, ZoomScale : 15, ZoomScaleNormal : 16, ZoomScalePageLayoutView : 17, ZoomScaleSheetLayoutView : 18 }; var c_oSer_CellStyle = { BuiltinId : 0, CustomBuiltin : 1, Hidden : 2, ILevel : 3, Name : 4, XfId : 5 }; /** @enum */ var EBorderStyle = { borderstyleDashDot: 0, borderstyleDashDotDot: 1, borderstyleDashed: 2, borderstyleDotted: 3, borderstyleDouble: 4, borderstyleHair: 5, borderstyleMedium: 6, borderstyleMediumDashDot: 7, borderstyleMediumDashDotDot: 8, borderstyleMediumDashed: 9, borderstyleNone: 10, borderstyleSlantDashDot: 11, borderstyleThick: 12, borderstyleThin: 13 }; /** @enum */ var EUnderline = { underlineDouble: 0, underlineDoubleAccounting: 1, underlineNone: 2, underlineSingle: 3, underlineSingleAccounting: 4 }; /** @enum */ var EVerticalAlignRun = { verticalalignrunBaseline: 0, verticalalignrunSubscript: 1, verticalalignrunSuperscript: 2 }; /** @enum */ var ECellAnchorType = { cellanchorAbsolute: 0, cellanchorOneCell: 1, cellanchorTwoCell: 2 }; /** @enum */ var EVisibleType = { visibleHidden: 0, visibleVeryHidden: 1, visibleVisible: 2 }; /** @enum */ var EHorizontalAlignment = { horizontalalignmentCenter: 0, horizontalalignmentcenterContinuous: 1, horizontalalignmentDistributed: 2, horizontalalignmentFill: 3, horizontalalignmentGeneral: 4, horizontalalignmentJustify: 5, horizontalalignmentLeft: 6, horizontalalignmentRight: 7 }; /** @enum */ var EVerticalAlignment = { verticalalignmentBottom: 0, verticalalignmentCenter: 1, verticalalignmentDistributed: 2, verticalalignmentJustify: 3, verticalalignmentTop: 4 }; /** @enum */ var ECellTypeType = { celltypeBool: 0, celltypeDate: 1, celltypeError: 2, celltypeInlineStr: 3, celltypeNumber: 4, celltypeSharedString: 5, celltypeStr: 6 }; /** @enum */ var ECellFormulaType = { cellformulatypeArray: 0, cellformulatypeDataTable: 1, cellformulatypeNormal: 2, cellformulatypeShared: 3 }; /** @enum */ var EPageOrientation = { pageorientLandscape: 0, pageorientPortrait: 1 }; /** @enum */ var EPageSize = { pagesizeLetterPaper: 1, pagesizeLetterSmall: 2, pagesizeTabloidPaper: 3, pagesizeLedgerPaper: 4, pagesizeLegalPaper: 5, pagesizeStatementPaper: 6, pagesizeExecutivePaper: 7, pagesizeA3Paper: 8, pagesizeA4Paper: 9, pagesizeA4SmallPaper: 10, pagesizeA5Paper: 11, pagesizeB4Paper: 12, pagesizeB5Paper: 13, pagesizeFolioPaper: 14, pagesizeQuartoPaper: 15, pagesizeStandardPaper1: 16, pagesizeStandardPaper2: 17, pagesizeNotePaper: 18, pagesize9Envelope: 19, pagesize10Envelope: 20, pagesize11Envelope: 21, pagesize12Envelope: 22, pagesize14Envelope: 23, pagesizeCPaper: 24, pagesizeDPaper: 25, pagesizeEPaper: 26, pagesizeDLEnvelope: 27, pagesizeC5Envelope: 28, pagesizeC3Envelope: 29, pagesizeC4Envelope: 30, pagesizeC6Envelope: 31, pagesizeC65Envelope: 32, pagesizeB4Envelope: 33, pagesizeB5Envelope: 34, pagesizeB6Envelope: 35, pagesizeItalyEnvelope: 36, pagesizeMonarchEnvelope: 37, pagesize6_3_4Envelope: 38, pagesizeUSStandardFanfold: 39, pagesizeGermanStandardFanfold: 40, pagesizeGermanLegalFanfold: 41, pagesizeISOB4: 42, pagesizeJapaneseDoublePostcard: 43, pagesizeStandardPaper3: 44, pagesizeStandardPaper4: 45, pagesizeStandardPaper5: 46, pagesizeInviteEnvelope: 47, pagesizeLetterExtraPaper: 50, pagesizeLegalExtraPaper: 51, pagesizeTabloidExtraPaper: 52, pagesizeA4ExtraPaper: 53, pagesizeLetterTransversePaper: 54, pagesizeA4TransversePaper: 55, pagesizeLetterExtraTransversePaper: 56, pagesizeSuperA_SuperA_A4Paper: 57, pagesizeSuperB_SuperB_A3Paper: 58, pagesizeLetterPlusPaper: 59, pagesizeA4PlusPaper: 60, pagesizeA5TransversePaper: 61, pagesizeJISB5TransversePaper: 62, pagesizeA3ExtraPaper: 63, pagesizeA5ExtraPaper: 64, pagesizeISOB5ExtraPaper: 65, pagesizeA2Paper: 66, pagesizeA3TransversePaper: 67, pagesizeA3ExtraTransversePaper: 68 }; /** @enum */ var ETotalsRowFunction = { totalrowfunctionAverage: 1, totalrowfunctionCount: 2, totalrowfunctionCountNums: 3, totalrowfunctionCustom: 4, totalrowfunctionMax: 5, totalrowfunctionMin: 6, totalrowfunctionNone: 7, totalrowfunctionStdDev: 8, totalrowfunctionSum: 9, totalrowfunctionVar: 10 }; /** @enum */ var ESortBy = { sortbyCellColor: 1, sortbyFontColor: 2, sortbyIcon: 3, sortbyValue: 4 }; /** @enum */ var ECustomFilter = { customfilterEqual: 1, customfilterGreaterThan: 2, customfilterGreaterThanOrEqual: 3, customfilterLessThan: 4, customfilterLessThanOrEqual: 5, customfilterNotEqual: 6 }; /** @enum */ var EDateTimeGroup = { datetimegroupDay: 1, datetimegroupHour: 2, datetimegroupMinute: 3, datetimegroupMonth: 4, datetimegroupSecond: 5, datetimegroupYear: 6 }; /** @enum */ var ETableStyleType = { tablestyletypeBlankRow: 0, tablestyletypeFirstColumn: 1, tablestyletypeFirstColumnStripe: 2, tablestyletypeFirstColumnSubheading: 3, tablestyletypeFirstHeaderCell: 4, tablestyletypeFirstRowStripe: 5, tablestyletypeFirstRowSubheading: 6, tablestyletypeFirstSubtotalColumn: 7, tablestyletypeFirstSubtotalRow: 8, tablestyletypeFirstTotalCell: 9, tablestyletypeHeaderRow: 10, tablestyletypeLastColumn: 11, tablestyletypeLastHeaderCell: 12, tablestyletypeLastTotalCell: 13, tablestyletypePageFieldLabels: 14, tablestyletypePageFieldValues: 15, tablestyletypeSecondColumnStripe: 16, tablestyletypeSecondColumnSubheading: 17, tablestyletypeSecondRowStripe: 18, tablestyletypeSecondRowSubheading: 19, tablestyletypeSecondSubtotalColumn: 20, tablestyletypeSecondSubtotalRow: 21, tablestyletypeThirdColumnSubheading: 22, tablestyletypeThirdRowSubheading: 23, tablestyletypeThirdSubtotalColumn: 24, tablestyletypeThirdSubtotalRow: 25, tablestyletypeTotalRow: 26, tablestyletypeWholeTable: 27 }; /** @enum */ var EFontScheme = { fontschemeNone: 0, fontschemeMinor: 1, fontschemeMajor: 2 }; var DocumentPageSize = new function() { this.oSizes = [ {id:EPageSize.pagesizeLetterPaper, w_mm: 215.9, h_mm: 279.4}, {id:EPageSize.pagesizeLetterSmall, w_mm: 215.9, h_mm: 279.4}, {id:EPageSize.pagesizeTabloidPaper, w_mm: 279.4, h_mm: 431.7}, {id:EPageSize.pagesizeLedgerPaper, w_mm: 431.8, h_mm: 279.4}, {id:EPageSize.pagesizeLegalPaper, w_mm: 215.9, h_mm: 355.6}, {id:EPageSize.pagesizeStatementPaper, w_mm: 495.3, h_mm: 215.9}, {id:EPageSize.pagesizeExecutivePaper, w_mm: 184.2, h_mm: 266.7}, {id:EPageSize.pagesizeA3Paper, w_mm: 297, h_mm: 420.1}, {id:EPageSize.pagesizeA4Paper, w_mm: 210, h_mm: 297}, {id:EPageSize.pagesizeA4SmallPaper, w_mm: 210, h_mm: 297}, {id:EPageSize.pagesizeA5Paper, w_mm: 148.1, h_mm: 209.9}, {id:EPageSize.pagesizeB4Paper, w_mm: 250, h_mm: 353}, {id:EPageSize.pagesizeB5Paper, w_mm: 176, h_mm: 250.1}, {id:EPageSize.pagesizeFolioPaper, w_mm: 215.9, h_mm: 330.2}, {id:EPageSize.pagesizeQuartoPaper, w_mm: 215, h_mm: 275}, {id:EPageSize.pagesizeStandardPaper1, w_mm: 254, h_mm: 355.6}, {id:EPageSize.pagesizeStandardPaper2, w_mm: 279.4, h_mm: 431.8}, {id:EPageSize.pagesizeNotePaper, w_mm: 215.9, h_mm: 279.4}, {id:EPageSize.pagesize9Envelope, w_mm: 98.4, h_mm: 225.4}, {id:EPageSize.pagesize10Envelope, w_mm: 104.8, h_mm: 241.3}, {id:EPageSize.pagesize11Envelope, w_mm: 114.3, h_mm: 263.5}, {id:EPageSize.pagesize12Envelope, w_mm: 120.7, h_mm: 279.4}, {id:EPageSize.pagesize14Envelope, w_mm: 127, h_mm: 292.1}, {id:EPageSize.pagesizeCPaper, w_mm: 431.8, h_mm: 558.8}, {id:EPageSize.pagesizeDPaper, w_mm: 558.8, h_mm: 863.6}, {id:EPageSize.pagesizeEPaper, w_mm: 863.6, h_mm: 1117.6}, {id:EPageSize.pagesizeDLEnvelope, w_mm: 110.1, h_mm: 220.1}, {id:EPageSize.pagesizeC5Envelope, w_mm: 162, h_mm: 229}, {id:EPageSize.pagesizeC3Envelope, w_mm: 324, h_mm: 458}, {id:EPageSize.pagesizeC4Envelope, w_mm: 229, h_mm: 324}, {id:EPageSize.pagesizeC6Envelope, w_mm: 114, h_mm: 162}, {id:EPageSize.pagesizeC65Envelope, w_mm: 114, h_mm: 229}, {id:EPageSize.pagesizeB4Envelope, w_mm: 250, h_mm: 353}, {id:EPageSize.pagesizeB5Envelope, w_mm: 176, h_mm: 250}, {id:EPageSize.pagesizeB6Envelope, w_mm: 176, h_mm: 125}, {id:EPageSize.pagesizeItalyEnvelope, w_mm: 110, h_mm: 230}, {id:EPageSize.pagesizeMonarchEnvelope, w_mm: 98.4, h_mm: 190.5}, {id:EPageSize.pagesize6_3_4Envelope, w_mm: 92.1, h_mm: 165.1}, {id:EPageSize.pagesizeUSStandardFanfold, w_mm: 377.8, h_mm: 279.4}, {id:EPageSize.pagesizeGermanStandardFanfold, w_mm: 215.9, h_mm: 304.8}, {id:EPageSize.pagesizeGermanLegalFanfold, w_mm: 215.9, h_mm: 330.2}, {id:EPageSize.pagesizeISOB4, w_mm: 250, h_mm: 353}, {id:EPageSize.pagesizeJapaneseDoublePostcard, w_mm: 200, h_mm: 148}, {id:EPageSize.pagesizeStandardPaper3, w_mm: 228.6, h_mm: 279.4}, {id:EPageSize.pagesizeStandardPaper4, w_mm: 254, h_mm: 279.4}, {id:EPageSize.pagesizeStandardPaper5, w_mm: 381, h_mm: 279.4}, {id:EPageSize.pagesizeInviteEnvelope, w_mm: 220, h_mm: 220}, {id:EPageSize.pagesizeLetterExtraPaper, w_mm: 235.6, h_mm: 304.8}, {id:EPageSize.pagesizeLegalExtraPaper, w_mm: 235.6, h_mm: 381}, {id:EPageSize.pagesizeTabloidExtraPaper, w_mm: 296.9, h_mm: 457.2}, {id:EPageSize.pagesizeA4ExtraPaper, w_mm: 236, h_mm: 322}, {id:EPageSize.pagesizeLetterTransversePaper, w_mm: 210.2, h_mm: 279.4}, {id:EPageSize.pagesizeA4TransversePaper, w_mm: 210, h_mm: 297}, {id:EPageSize.pagesizeLetterExtraTransversePaper, w_mm: 235.6, h_mm: 304.8}, {id:EPageSize.pagesizeSuperA_SuperA_A4Paper, w_mm: 227, h_mm: 356}, {id:EPageSize.pagesizeSuperB_SuperB_A3Paper, w_mm: 305, h_mm: 487}, {id:EPageSize.pagesizeLetterPlusPaper, w_mm: 215.9, h_mm: 12.69}, {id:EPageSize.pagesizeA4PlusPaper, w_mm: 210, h_mm: 330}, {id:EPageSize.pagesizeA5TransversePaper, w_mm: 148, h_mm: 210}, {id:EPageSize.pagesizeJISB5TransversePaper, w_mm: 182, h_mm: 257}, {id:EPageSize.pagesizeA3ExtraPaper, w_mm: 322, h_mm: 445}, {id:EPageSize.pagesizeA5ExtraPaper, w_mm: 174, h_mm: 235}, {id:EPageSize.pagesizeISOB5ExtraPaper, w_mm: 201, h_mm: 276}, {id:EPageSize.pagesizeA2Paper, w_mm: 420, h_mm: 594}, {id:EPageSize.pagesizeA3TransversePaper, w_mm: 297, h_mm: 420}, {id:EPageSize.pagesizeA3ExtraTransversePaper, w_mm: 322, h_mm: 445} ]; this.getSizeByWH = function(widthMm, heightMm) { for( index in this.oSizes) { var item = this.oSizes[index]; if(widthMm == item.w_mm && heightMm == item.h_mm) return item; } return this.oSizes[8];//A4 }; this.getSizeById = function(id) { for( index in this.oSizes) { var item = this.oSizes[index]; if(id == item.id) return item; } return this.oSizes[8];//A4 }; }; function OpenColor() { this.rgb = null; this.auto = null; this.theme = null; this.tint = null; } var g_nodeAttributeStart = 0xFA; var g_nodeAttributeEnd = 0xFB; /** @constructor */ function BinaryTableWriter(memory, aDxfs) { this.memory = memory; this.aDxfs = aDxfs; this.bs = new BinaryCommonWriter(this.memory); this.Write = function(aTables) { var oThis = this; for(var i = 0, length = aTables.length; i < length; ++i) this.bs.WriteItem(c_oSer_TablePart.Table, function(){oThis.WriteTable(aTables[i]);}); } this.WriteTable = function(table) { var oThis = this; //Ref if(null != table.Ref) { this.memory.WriteByte(c_oSer_TablePart.Ref); this.memory.WriteString2(table.Ref); } //HeaderRowCount if(null != table.HeaderRowCount) this.bs.WriteItem(c_oSer_TablePart.HeaderRowCount, function(){oThis.memory.WriteLong(table.HeaderRowCount);}); //TotalsRowCount if(null != table.TotalsRowCount) this.bs.WriteItem(c_oSer_TablePart.TotalsRowCount, function(){oThis.memory.WriteLong(table.TotalsRowCount);}); //Display Name if(null != table.DisplayName) { this.memory.WriteByte(c_oSer_TablePart.DisplayName); this.memory.WriteString2(table.DisplayName); } //AutoFilter if(null != table.AutoFilter) this.bs.WriteItem(c_oSer_TablePart.AutoFilter, function(){oThis.WriteAutoFilter(table.AutoFilter);}); //SortState if(null != table.SortState) this.bs.WriteItem(c_oSer_TablePart.SortState, function(){oThis.WriteSortState(table.SortState);}); //TableColumns if(null != table.TableColumns) this.bs.WriteItem(c_oSer_TablePart.TableColumns, function(){oThis.WriteTableColumns(table.TableColumns);}); //TableStyleInfo if(null != table.TableStyleInfo) this.bs.WriteItem(c_oSer_TablePart.TableStyleInfo, function(){oThis.WriteTableStyleInfo(table.TableStyleInfo);}); } this.WriteAutoFilter = function(autofilter) { var oThis = this; //Ref if(null != autofilter.Ref) { this.memory.WriteByte(c_oSer_AutoFilter.Ref); this.memory.WriteString2(autofilter.Ref); } //FilterColumns if(null != autofilter.FilterColumns) this.bs.WriteItem(c_oSer_AutoFilter.FilterColumns, function(){oThis.WriteFilterColumns(autofilter.FilterColumns);}); //SortState if(null != autofilter.SortState) this.bs.WriteItem(c_oSer_AutoFilter.SortState, function(){oThis.WriteSortState(autofilter.SortState);}); } this.WriteFilterColumns = function(filterColumns) { var oThis = this; for(var i = 0, length = filterColumns.length; i < length; ++i) this.bs.WriteItem(c_oSer_AutoFilter.FilterColumn, function(){oThis.WriteFilterColumn(filterColumns[i]);}); } this.WriteFilterColumn = function(filterColumn) { var oThis = this; //ColId if(null != filterColumn.ColId) this.bs.WriteItem(c_oSer_FilterColumn.ColId, function(){oThis.memory.WriteLong(filterColumn.ColId);}); //Filters if(null != filterColumn.Filters) this.bs.WriteItem(c_oSer_FilterColumn.Filters, function(){oThis.WriteFilters(filterColumn.Filters);}); //CustomFilters if(null != filterColumn.CustomFiltersObj) this.bs.WriteItem(c_oSer_FilterColumn.CustomFilters, function(){oThis.WriteCustomFilters(filterColumn.CustomFiltersObj);}); //DynamicFilter if(null != filterColumn.DynamicFilter) this.bs.WriteItem(c_oSer_FilterColumn.DynamicFilter, function(){oThis.WriteDynamicFilter(filterColumn.DynamicFilter);}); //ColorFilter if(null != filterColumn.ColorFilter) this.bs.WriteItem(c_oSer_FilterColumn.ColorFilter, function(){oThis.WriteColorFilter(filterColumn.ColorFilter);}); //Top10 if(null != filterColumn.Top10) this.bs.WriteItem(c_oSer_FilterColumn.Top10, function(){oThis.WriteTop10(filterColumn.Top10);}); //ShowButton if(null != filterColumn.ShowButton) this.bs.WriteItem(c_oSer_FilterColumn.ShowButton, function(){oThis.memory.WriteBool(filterColumn.ShowButton);}); } this.WriteFilters = function(filters) { var oThis = this; if(null != filters.Values) { for(var i = 0, length = filters.Values.length; i < length; ++i) this.bs.WriteItem(c_oSer_FilterColumn.Filter, function(){oThis.WriteFilter(filters.Values[i]);}); } if(null != filters.Dates) { for(var i = 0, length = filters.Dates.length; i < length; ++i) this.bs.WriteItem(c_oSer_FilterColumn.DateGroupItem, function(){oThis.WriteDateGroupItem(filters.Dates[i]);}); } if(null != filters.Blank) this.bs.WriteItem(c_oSer_FilterColumn.FiltersBlank, function(){oThis.memory.WriteBool(filters.Blank);}); } this.WriteFilter = function(val) { var oThis = this; if(null != val) { this.memory.WriteByte(c_oSer_Filter.Val); this.memory.WriteString2(val); } } this.WriteDateGroupItem = function(dateGroupItem) { var oThis = this; if(null != dateGroupItem.DateTimeGrouping) { this.memory.WriteByte(c_oSer_DateGroupItem.DateTimeGrouping); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteByte(dateGroupItem.DateTimeGrouping); } if(null != dateGroupItem.Day) { this.memory.WriteByte(c_oSer_DateGroupItem.Day); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(dateGroupItem.Day); } if(null != dateGroupItem.Hour) { this.memory.WriteByte(c_oSer_DateGroupItem.Hour); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(dateGroupItem.Hour); } if(null != dateGroupItem.Minute) { this.memory.WriteByte(c_oSer_DateGroupItem.Minute); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(dateGroupItem.Minute); } if(null != dateGroupItem.Month) { this.memory.WriteByte(c_oSer_DateGroupItem.Month); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(dateGroupItem.Month); } if(null != dateGroupItem.Second) { this.memory.WriteByte(c_oSer_DateGroupItem.Second); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(dateGroupItem.Second); } if(null != dateGroupItem.Year) { this.memory.WriteByte(c_oSer_DateGroupItem.Year); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(dateGroupItem.Year); } } this.WriteCustomFilters = function(customFilters) { var oThis = this; if(null != customFilters.And) this.bs.WriteItem(c_oSer_CustomFilters.And, function(){oThis.memory.WriteBool(customFilters.And);}); if(null != customFilters.CustomFilters && customFilters.CustomFilters.length > 0) this.bs.WriteItem(c_oSer_CustomFilters.CustomFilters, function(){oThis.WriteCustomFiltersItems(customFilters.CustomFilters);}); } this.WriteCustomFiltersItems = function(aCustomFilters) { var oThis = this; for(var i = 0, length = aCustomFilters.length; i < length; ++i) this.bs.WriteItem(c_oSer_CustomFilters.CustomFilter, function(){oThis.WriteCustomFiltersItem(aCustomFilters[i]);}); } this.WriteCustomFiltersItem = function(customFilter) { var oThis = this; if(null != customFilter.Operator) { this.memory.WriteByte(c_oSer_CustomFilters.Operator); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteByte(customFilter.Operator); } if(null != customFilter.Val) { this.memory.WriteByte(c_oSer_CustomFilters.Val); this.memory.WriteByte(c_oSerPropLenType.Variable); this.memory.WriteString2(customFilter.Val); } } this.WriteDynamicFilter = function(dynamicFilter) { var oThis = this; if(null != dynamicFilter.Type) { this.memory.WriteByte(c_oSer_DynamicFilter.Type); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteByte(dynamicFilter.Type); } if(null != dynamicFilter.Val) { this.memory.WriteByte(c_oSer_DynamicFilter.Val); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(dynamicFilter.Val); } if(null != dynamicFilter.MaxVal) { this.memory.WriteByte(c_oSer_DynamicFilter.MaxVal); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(dynamicFilter.MaxVal); } } this.WriteColorFilter = function(colorFilter) { var oThis = this; if(null != colorFilter.CellColor) { this.memory.WriteByte(c_oSer_ColorFilter.CellColor); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(colorFilter.CellColor); } if(null != colorFilter.dxf) { this.memory.WriteByte(c_oSer_ColorFilter.DxfId); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(this.aDxfs.length); this.aDxfs.push(colorFilter.dxf); } } this.WriteTop10 = function(top10) { var oThis = this; if(null != top10.FilterVal) { this.memory.WriteByte(c_oSer_Top10.FilterVal); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(top10.FilterVal); } if(null != top10.Percent) { this.memory.WriteByte(c_oSer_Top10.Percent); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(top10.Percent); } if(null != top10.Top) { this.memory.WriteByte(c_oSer_Top10.Top); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(top10.Top); } if(null != top10.Val) { this.memory.WriteByte(c_oSer_Top10.Val); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(top10.Val); } } this.WriteSortState = function(sortState) { var oThis = this; if(null != sortState.Ref) { this.memory.WriteByte(c_oSer_SortState.Ref); this.memory.WriteString2(sortState.Ref); } if(null != sortState.CaseSensitive) this.bs.WriteItem(c_oSer_SortState.CaseSensitive, function(){oThis.memory.WriteBool(sortState.CaseSensitive);}); if(null != sortState.SortConditions) this.bs.WriteItem(c_oSer_SortState.SortConditions, function(){oThis.WriteSortConditions(sortState.SortConditions);}); } this.WriteSortConditions = function(sortConditions) { var oThis = this; for(var i = 0, length = sortConditions.length; i < length; ++i) this.bs.WriteItem(c_oSer_SortState.SortCondition, function(){oThis.WriteSortCondition(sortConditions[i]);}); } this.WriteSortCondition = function(sortCondition) { var oThis = this; if(null != sortCondition.Ref) { this.memory.WriteByte(c_oSer_SortState.ConditionRef); this.memory.WriteByte(c_oSerPropLenType.Variable); this.memory.WriteString2(sortCondition.Ref); } if(null != sortCondition.ConditionSortBy) { this.memory.WriteByte(c_oSer_SortState.ConditionSortBy); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteByte(sortCondition.ConditionSortBy); } if(null != sortCondition.ConditionDescending) { this.memory.WriteByte(c_oSer_SortState.ConditionDescending); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(sortCondition.ConditionDescending); } if(null != sortCondition.dxf) { this.memory.WriteByte(c_oSer_SortState.ConditionDxfId); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(this.aDxfs.length); this.aDxfs.push(sortCondition.dxf); } } this.WriteTableColumns = function(tableColumns) { var oThis = this; for(var i = 0, length = tableColumns.length; i < length; ++i) this.bs.WriteItem(c_oSer_TableColumns.TableColumn, function(){oThis.WriteTableColumn(tableColumns[i]);}); } this.WriteTableColumn = function(tableColumn) { var oThis = this; if(null != tableColumn.Name) { this.memory.WriteByte(c_oSer_TableColumns.Name); this.memory.WriteString2(tableColumn.Name); } if(null != tableColumn.TotalsRowLabel) { this.memory.WriteByte(c_oSer_TableColumns.TotalsRowLabel); this.memory.WriteString2(tableColumn.TotalsRowLabel); } if(null != tableColumn.TotalsRowFunction) this.bs.WriteItem(c_oSer_TableColumns.TotalsRowFunction, function(){oThis.memory.WriteByte(tableColumn.TotalsRowFunction);}); if(null != tableColumn.TotalsRowFormula) { this.memory.WriteByte(c_oSer_TableColumns.TotalsRowFormula); this.memory.WriteString2(tableColumn.TotalsRowFormula); } if(null != tableColumn.dxf) { this.bs.WriteItem(c_oSer_TableColumns.DataDxfId, function(){oThis.memory.WriteLong(oThis.aDxfs.length);}); this.aDxfs.push(tableColumn.dxf); } if(null != tableColumn.CalculatedColumnFormula) { this.memory.WriteByte(c_oSer_TableColumns.CalculatedColumnFormula); this.memory.WriteString2(tableColumn.CalculatedColumnFormula); } } this.WriteTableStyleInfo = function(tableStyleInfo) { var oThis = this; if(null != tableStyleInfo.Name) { this.memory.WriteByte(c_oSer_TableStyleInfo.Name); this.memory.WriteByte(c_oSerPropLenType.Variable); this.memory.WriteString2(tableStyleInfo.Name); } if(null != tableStyleInfo.ShowColumnStripes) { this.memory.WriteByte(c_oSer_TableStyleInfo.ShowColumnStripes); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(tableStyleInfo.ShowColumnStripes); } if(null != tableStyleInfo.ShowRowStripes) { this.memory.WriteByte(c_oSer_TableStyleInfo.ShowRowStripes); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(tableStyleInfo.ShowRowStripes); } if(null != tableStyleInfo.ShowFirstColumn) { this.memory.WriteByte(c_oSer_TableStyleInfo.ShowFirstColumn); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(tableStyleInfo.ShowFirstColumn); } if(null != tableStyleInfo.ShowLastColumn) { this.memory.WriteByte(c_oSer_TableStyleInfo.ShowLastColumn); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(tableStyleInfo.ShowLastColumn); } } } /** @constructor */ function BinarySharedStringsTableWriter(memory, oSharedStrings) { this.memory = memory; this.bs = new BinaryCommonWriter(this.memory); this.bsw = new BinaryStylesTableWriter(this.memory); this.oSharedStrings = oSharedStrings; this.Write = function() { var oThis = this; this.bs.WriteItemWithLength(function(){oThis.WriteSharedStringsContent();}); }; this.WriteSharedStringsContent = function() { var oThis = this; var aSharedStrings = new Array(); for(var i in this.oSharedStrings.strings) { var item = this.oSharedStrings.strings[i]; if(null != item.t) aSharedStrings[item.t.id] = {t: item.t.val}; if(null != item.a) { for(var j = 0, length2 = item.a.length; j < length2; ++j) { var oCurText = item.a[j]; aSharedStrings[oCurText.id] = {a: oCurText.val}; } } } for(var i = 0, length = aSharedStrings.length; i < length; ++i) { var si = aSharedStrings[i]; if(null != si) this.bs.WriteItem(c_oSerSharedStringTypes.Si, function(){oThis.WriteSi(si);}); } }; this.WriteSi = function(si) { var oThis = this; if(null != si.t) { this.memory.WriteByte(c_oSerSharedStringTypes.Text); this.memory.WriteString2(si.t); } else if(null != si.a) { for(var i = 0, length = si.a.length; i < length; ++i) { var run = si.a[i]; this.bs.WriteItem(c_oSerSharedStringTypes.Run, function(){oThis.WriteRun(run);}); } } }; this.WriteRun = function(run) { var oThis = this; if(null != run.format) this.bs.WriteItem(c_oSerSharedStringTypes.RPr, function(){oThis.bsw.WriteFont(run.format);}); if(null != run.text) { this.memory.WriteByte(c_oSerSharedStringTypes.Text); this.memory.WriteString2(run.text); } }; }; /** @constructor */ function BinaryStylesTableWriter(memory, wb, oBinaryWorksheetsTableWriter) { this.memory = memory; this.bs = new BinaryCommonWriter(this.memory); this.wb = wb; this.aDxfs = null; this.oXfsStylesMap = null; this.oXfsMap = null; this.oFontMap = null; this.oFillMap = null; this.oBorderMap = null; this.oNumMap = null; if(null != oBinaryWorksheetsTableWriter) { this.aDxfs = oBinaryWorksheetsTableWriter.aDxfs; this.oXfsStylesMap = oBinaryWorksheetsTableWriter.oXfsStylesMap; this.oXfsMap = oBinaryWorksheetsTableWriter.oXfsMap; this.oFontMap = oBinaryWorksheetsTableWriter.oFontMap; this.oFillMap = oBinaryWorksheetsTableWriter.oFillMap; this.oBorderMap = oBinaryWorksheetsTableWriter.oBorderMap; this.oNumMap = oBinaryWorksheetsTableWriter.oNumMap; } this.Write = function() { var oThis = this; this.bs.WriteItemWithLength(function(){oThis.WriteStylesContent();}); }; this.WriteStylesContent = function() { var oThis = this; var wb = this.wb; //borders this.bs.WriteItem(c_oSerStylesTypes.Borders, function(){oThis.WriteBorders();}); //fills this.bs.WriteItem(c_oSerStylesTypes.Fills, function(){oThis.WriteFills();}); //fonts this.bs.WriteItem(c_oSerStylesTypes.Fonts, function(){oThis.WriteFonts();}); //numfmts this.bs.WriteItem(c_oSerStylesTypes.NumFmts, function(){oThis.WriteNumFmts();}); //CellStyleXfs this.bs.WriteItem(c_oSerStylesTypes.CellStyleXfs, function(){oThis.WriteCellStyleXfs();}); //cellxfs this.bs.WriteItem(c_oSerStylesTypes.CellXfs, function(){oThis.WriteCellXfs();}); //CellStyles this.bs.WriteItem(c_oSerStylesTypes.CellStyles, function(){oThis.WriteCellStyles(wb.CellStyles.CustomStyles);}); if(null != wb.TableStyles) this.bs.WriteItem(c_oSerStylesTypes.TableStyles, function(){oThis.WriteTableStyles(wb.TableStyles);}); if(null != this.aDxfs && this.aDxfs.length > 0) this.bs.WriteItem(c_oSerStylesTypes.Dxfs, function(){oThis.WriteDxfs(oThis.aDxfs);}); }; this.WriteBorders = function() { var oThis = this; var aBorders = new Array(); for(var i in this.oBorderMap) { var elem = this.oBorderMap[i]; aBorders[elem.index] = elem.val; } for(var i = 0, length = aBorders.length; i < length; ++i) { var border = aBorders[i]; this.bs.WriteItem(c_oSerStylesTypes.Border, function(){oThis.WriteBorder(border.getDif(g_oDefaultBorderAbs));}); } }; this.WriteBorder = function(border) { if(null == border) return; var oThis = this; //Bottom if(null != border.b) this.bs.WriteItem(c_oSerBorderTypes.Bottom, function(){oThis.WriteBorderProp(border.b);}); //Diagonal if(null != border.d) this.bs.WriteItem(c_oSerBorderTypes.Diagonal, function(){oThis.WriteBorderProp(border.d);}); //End if(null != border.r) this.bs.WriteItem(c_oSerBorderTypes.End, function(){oThis.WriteBorderProp(border.r);}); //Horizontal if(null != border.h) this.bs.WriteItem(c_oSerBorderTypes.Horizontal, function(){oThis.WriteBorderProp(border.h);}); //Start if(null != border.l) this.bs.WriteItem(c_oSerBorderTypes.Start, function(){oThis.WriteBorderProp(border.l);}); //Top if(null != border.t) this.bs.WriteItem(c_oSerBorderTypes.Top, function(){oThis.WriteBorderProp(border.t);}); //Vertical if(null != border.v) this.bs.WriteItem(c_oSerBorderTypes.Vertical, function(){oThis.WriteBorderProp(border.v);}); //DiagonalDown if(null != border.dd) this.bs.WriteItem(c_oSerBorderTypes.DiagonalDown, function(){oThis.memory.WriteBool(border.dd);}); //DiagonalUp if(null != border.du) this.bs.WriteItem(c_oSerBorderTypes.DiagonalUp, function(){oThis.memory.WriteBool(border.du);}); }; this.WriteBorderProp = function(borderProp) { var oThis = this; if(null != borderProp.c) { this.memory.WriteByte(c_oSerBorderPropTypes.Color); this.memory.WriteByte(c_oSerPropLenType.Variable); this.bs.WriteItemWithLength(function(){oThis.bs.WriteColorSpreadsheet(borderProp.c);}); } if(null != borderProp.s) { var nStyle = EBorderStyle.borderstyleNone; switch(borderProp.s) { case "dashDot":nStyle = EBorderStyle.borderstyleDashDot;break; case "dashDotDot":nStyle = EBorderStyle.borderstyleDashDotDot;break; case "dashed":nStyle = EBorderStyle.borderstyleDashed;break; case "dotted":nStyle = EBorderStyle.borderstyleDotted;break; case "double":nStyle = EBorderStyle.borderstyleDouble;break; case "hair":nStyle = EBorderStyle.borderstyleHair;break; case "medium":nStyle = EBorderStyle.borderstyleMedium;break; case "mediumDashDot":nStyle = EBorderStyle.borderstyleMediumDashDot;break; case "mediumDashDotDot":nStyle = EBorderStyle.borderstyleMediumDashDotDot;break; case "mediumDashed":nStyle = EBorderStyle.borderstyleMediumDashed;break; case "none":nStyle = EBorderStyle.borderstyleNone;break; case "slantDashDot":nStyle = EBorderStyle.borderstyleSlantDashDot;break; case "thick":nStyle = EBorderStyle.borderstyleThick;break; case "thin":nStyle = EBorderStyle.borderstyleThin;break; } this.memory.WriteByte(c_oSerBorderPropTypes.Style); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteByte(nStyle); } }; this.WriteFills = function() { var oThis = this; var aFills = new Array(); for(var i in this.oFillMap) { var elem = this.oFillMap[i]; aFills[elem.index] = elem.val; } aFills[1] = aFills[0]; for(var i = 0, length = aFills.length; i < length; ++i) { var fill = aFills[i]; this.bs.WriteItem(c_oSerStylesTypes.Fill, function(){oThis.WriteFill(fill);}); } }; this.WriteFill = function(fill) { var oThis = this; this.bs.WriteItem(c_oSerFillTypes.PatternFill, function(){oThis.WritePatternFill(fill);}); }; this.WritePatternFill = function(fill) { var oThis = this; if(null != fill.bg) this.bs.WriteItem(c_oSerFillTypes.PatternFillBgColor, function(){oThis.bs.WriteColorSpreadsheet(fill.bg);}); }; this.WriteFonts = function() { var oThis = this; var aFonts = new Array(); for(var i in this.oFontMap) { var elem = this.oFontMap[i]; aFonts[elem.index] = elem.val; } for(var i = 0, length = aFonts.length; i < length; ++i) { var font = aFonts[i]; var fontMinimized = font.getDif(g_oDefaultFont); if(null == fontMinimized) fontMinimized = new Font(); if(null == fontMinimized.fn) fontMinimized.fn = g_oDefaultFont.fn; if(null == fontMinimized.fs) fontMinimized.fs = g_oDefaultFont.fs; if(null == fontMinimized.c) fontMinimized.c = g_oDefaultFont.c; this.bs.WriteItem(c_oSerStylesTypes.Font, function(){oThis.WriteFont(fontMinimized);}); } }; this.WriteFont = function(font) { var oThis = this; if(null != font.b) { this.memory.WriteByte(c_oSerFontTypes.Bold); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(font.b); } if(null != font.c) { this.memory.WriteByte(c_oSerFontTypes.Color); this.memory.WriteByte(c_oSerPropLenType.Variable); this.bs.WriteItemWithLength(function(){oThis.bs.WriteColorSpreadsheet(font.c);}); } if(null != font.i) { this.memory.WriteByte(c_oSerFontTypes.Italic); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(font.i); } if(null != font.fn) { this.memory.WriteByte(c_oSerFontTypes.RFont); this.memory.WriteByte(c_oSerPropLenType.Variable); this.memory.WriteString2(font.fn); } if(null != font.s) { this.memory.WriteByte(c_oSerFontTypes.Strike); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(font.s); } if(null != font.fs) { this.memory.WriteByte(c_oSerFontTypes.Sz); this.memory.WriteByte(c_oSerPropLenType.Double); //tood write double this.memory.WriteDouble2(font.fs); } if(null != font.u) { var nUnderline = EUnderline.underlineNone; switch(font.u) { case "double": nUnderline = EUnderline.underlineDouble;break; case "doubleAccounting": nUnderline = EUnderline.underlineDoubleAccounting;break; case "none": nUnderline = EUnderline.underlineNone;break; case "single": nUnderline = EUnderline.underlineSingle;break; case "singleAccounting": nUnderline = EUnderline.underlineSingleAccounting;break; } this.memory.WriteByte(c_oSerFontTypes.Underline); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteByte(nUnderline); } if(null != font.va) { var nVertAlign = EVerticalAlignRun.verticalalignrunBaseline; switch(font.va) { case "baseline": nVertAlign = EVerticalAlignRun.verticalalignrunBaseline;break; case "subscript": nVertAlign = EVerticalAlignRun.verticalalignrunSubscript;break; case "superscript": nVertAlign = EVerticalAlignRun.verticalalignrunSuperscript;break; } this.memory.WriteByte(c_oSerFontTypes.VertAlign); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteByte(nVertAlign); } }; this.WriteNumFmts = function() { var oThis = this; var index = 0; var aNums = new Array(); for(var i in this.oNumMap) { var num = this.oNumMap[i]; if(false == num.val.isEqual(g_oDefaultNumAbs)) this.bs.WriteItem(c_oSerStylesTypes.NumFmt, function(){oThis.WriteNum({id: num.index, f: num.val.f});}); } }; this.WriteNum = function(num) { if(null != num.f) { this.memory.WriteByte(c_oSerNumFmtTypes.FormatCode); this.memory.WriteByte(c_oSerPropLenType.Variable); this.memory.WriteString2(num.f); } if(null != num.id) { this.memory.WriteByte(c_oSerNumFmtTypes.NumFmtId); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(num.id); } }; this.WriteCellStyleXfs = function(cellStyles) { var oThis = this; for(var i = 0, length = this.oXfsStylesMap.length; i < length; ++i) { var cellStyleXfs = this.oXfsStylesMap[i]; this.bs.WriteItem(c_oSerStylesTypes.Xfs, function(){oThis.WriteXfs(cellStyleXfs);}); } }; this.WriteCellXfs = function() { var oThis = this; var aXfs = new Array(); for(var i in this.oXfsMap) { var elem = this.oXfsMap[i]; aXfs[elem.index] = elem.val; } for(var i = 0, length = aXfs.length; i < length; ++i) { var cellxfs = aXfs[i]; this.bs.WriteItem(c_oSerStylesTypes.Xfs, function(){oThis.WriteXfs(cellxfs);}); } }; this.WriteXfs = function(xfs) { var oThis = this; if(null != xfs.borderid) { if(0 != xfs.borderid) { this.memory.WriteByte(c_oSerXfsTypes.ApplyBorder); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(true); } this.memory.WriteByte(c_oSerXfsTypes.BorderId); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(xfs.borderid); } if(null != xfs.fillid) { if(0 != xfs.fillid) { this.memory.WriteByte(c_oSerXfsTypes.ApplyFill); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(true); } this.memory.WriteByte(c_oSerXfsTypes.FillId); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(xfs.fillid); } if(null != xfs.fontid) { if(0 != xfs.fontid) { this.memory.WriteByte(c_oSerXfsTypes.ApplyFont); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(true); } this.memory.WriteByte(c_oSerXfsTypes.FontId); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(xfs.fontid); } if(null != xfs.numid) { if(0 != xfs.numid) { this.memory.WriteByte(c_oSerXfsTypes.ApplyNumberFormat); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(true); } this.memory.WriteByte(c_oSerXfsTypes.NumFmtId); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(xfs.numid); } if(null != xfs.align) { var alignMinimized = xfs.align.getDif(g_oDefaultAlignAbs); if(null != alignMinimized) { this.memory.WriteByte(c_oSerXfsTypes.ApplyAlignment); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(true); this.memory.WriteByte(c_oSerXfsTypes.Aligment); this.memory.WriteByte(c_oSerPropLenType.Variable); this.bs.WriteItemWithLength(function(){oThis.WriteAlign(alignMinimized);}); } } if(null != xfs.QuotePrefix) { this.memory.WriteByte(c_oSerXfsTypes.QuotePrefix); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(xfs.QuotePrefix); } if(null != xfs.XfId) { this.memory.WriteByte(c_oSerXfsTypes.XfId); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(xfs.XfId); } }; this.WriteAlign = function(align) { if(null != align.hor) { var nHorizontalAlignment = EHorizontalAlignment.horizontalalignmentGeneral; switch(align.hor) { case "center" : nHorizontalAlignment = EHorizontalAlignment.horizontalalignmentCenter;break; case "justify" : nHorizontalAlignment = EHorizontalAlignment.horizontalalignmentJustify;break; case "none" : nHorizontalAlignment = EHorizontalAlignment.horizontalalignmentGeneral;break; case "left" : nHorizontalAlignment = EHorizontalAlignment.horizontalalignmentLeft;break; case "right" : nHorizontalAlignment = EHorizontalAlignment.horizontalalignmentRight;break; } this.memory.WriteByte(c_oSerAligmentTypes.Horizontal); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteByte(nHorizontalAlignment); } if(null != align.indent) { this.memory.WriteByte(c_oSerAligmentTypes.Indent); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(align.indent); } if(null != align.RelativeIndent) { this.memory.WriteByte(c_oSerAligmentTypes.RelativeIndent); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(align.RelativeIndent); } if(null != align.shrink) { this.memory.WriteByte(c_oSerAligmentTypes.ShrinkToFit); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(align.shrink); } if(null != align.angle) { this.memory.WriteByte(c_oSerAligmentTypes.TextRotation); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(align.angle); } if(null != align.ver) { var nVerticalAlignment = EHorizontalAlignment.horizontalalignmentGeneral; switch(align.ver) { case "bottom" : nVerticalAlignment = EVerticalAlignment.verticalalignmentBottom;break; case "center" : nVerticalAlignment = EVerticalAlignment.verticalalignmentCenter;break; case "distributed" : nVerticalAlignment = EVerticalAlignment.verticalalignmentDistributed;break; case "justify" : nVerticalAlignment = EVerticalAlignment.verticalalignmentJustify;break; case "top" : nVerticalAlignment = EVerticalAlignment.verticalalignmentTop;break; } this.memory.WriteByte(c_oSerAligmentTypes.Vertical); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteByte(nVerticalAlignment); } if(null != align.wrap) { this.memory.WriteByte(c_oSerAligmentTypes.WrapText); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(align.wrap); } }; this.WriteDxfs = function(Dxfs) { var oThis = this; for(var i = 0, length = Dxfs.length; i < length; ++i) this.bs.WriteItem(c_oSerStylesTypes.Dxf, function(){oThis.WriteDxf(Dxfs[i]);}); } this.WriteDxf = function(Dxf) { var oThis = this; if(null != Dxf.align) this.bs.WriteItem(c_oSer_Dxf.Alignment, function(){oThis.WriteAlign(Dxf.align);}); if(null != Dxf.border) this.bs.WriteItem(c_oSer_Dxf.Border, function(){oThis.WriteBorder(Dxf.border);}); if(null != Dxf.fill) this.bs.WriteItem(c_oSer_Dxf.Fill, function(){oThis.WriteFill(Dxf.fill);}); if(null != Dxf.font) this.bs.WriteItem(c_oSer_Dxf.Font, function(){oThis.WriteFont(Dxf.font);}); if(null != Dxf.numFmt) this.bs.WriteItem(c_oSer_Dxf.NumFmt, function(){oThis.WriteNum(Dxf.numFmt);}); }; this.WriteCellStyles = function (cellStyles) { var oThis = this; for(var i = 0, length = cellStyles.length; i < length; ++i) { var style = cellStyles[i]; this.bs.WriteItem(c_oSerStylesTypes.CellStyle, function(){oThis.WriteCellStyle(style);}); } }; this.WriteCellStyle = function (oCellStyle) { var oThis = this; if (null != oCellStyle.BuiltinId) this.bs.WriteItem(c_oSer_CellStyle.BuiltinId, function(){oThis.memory.WriteLong(oCellStyle.BuiltinId);}); if (null != oCellStyle.CustomBuiltin) this.bs.WriteItem(c_oSer_CellStyle.CustomBuiltin, function(){oThis.memory.WriteBool(oCellStyle.CustomBuiltin);}); if (null != oCellStyle.Hidden) this.bs.WriteItem(c_oSer_CellStyle.Hidden, function(){oThis.memory.WriteBool(oCellStyle.Hidden);}); if (null != oCellStyle.ILevel) this.bs.WriteItem(c_oSer_CellStyle.ILevel, function(){oThis.memory.WriteLong(oCellStyle.ILevel);}); if (null != oCellStyle.Name) { this.memory.WriteByte(c_oSer_CellStyle.Name); this.memory.WriteString2(oCellStyle.Name); } if (null != oCellStyle.XfId) this.bs.WriteItem(c_oSer_CellStyle.XfId, function(){oThis.memory.WriteLong(oCellStyle.XfId);}); }; this.WriteTableStyles = function(tableStyles) { var oThis = this; if(null != tableStyles.DefaultTableStyle) { this.memory.WriteByte(c_oSer_TableStyles.DefaultTableStyle); this.memory.WriteString2(tableStyles.DefaultTableStyle); } if(null != tableStyles.DefaultPivotStyle) { this.memory.WriteByte(c_oSer_TableStyles.DefaultPivotStyle); this.memory.WriteString2(tableStyles.DefaultPivotStyle); } var bEmptyCustom = true; for(var i in tableStyles.CustomStyles) { bEmptyCustom = false; break; } if(false == bEmptyCustom) { this.bs.WriteItem(c_oSer_TableStyles.TableStyles, function(){oThis.WriteTableCustomStyles(tableStyles.CustomStyles);}); } } this.WriteTableCustomStyles = function(customStyles) { var oThis = this; for(var i in customStyles) { var style = customStyles[i]; this.bs.WriteItem(c_oSer_TableStyles.TableStyle, function(){oThis.WriteTableCustomStyle(style);}); } } this.WriteTableCustomStyle = function(customStyle) { var oThis = this; if(null != customStyle.name) { this.memory.WriteByte(c_oSer_TableStyle.Name); this.memory.WriteString2(customStyle.name); } if(null != customStyle.pivot) this.bs.WriteItem(c_oSer_TableStyle.Pivot, function(){oThis.memory.WriteBool(customStyle.pivot);}); if(null != customStyle.table) this.bs.WriteItem(c_oSer_TableStyle.Table, function(){oThis.memory.WriteBool(customStyle.table);}); this.bs.WriteItem(c_oSer_TableStyle.Elements, function(){oThis.WriteTableCustomStyleElements(customStyle);}); } this.WriteTableCustomStyleElements = function(customStyle) { var oThis = this; if(null != customStyle.blankRow) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeBlankRow, customStyle.blankRow);}); if(null != customStyle.firstColumn) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeFirstColumn, customStyle.firstColumn);}); if(null != customStyle.firstColumnStripe) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeFirstColumnStripe, customStyle.firstColumnStripe);}); if(null != customStyle.firstColumnSubheading) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeFirstColumnSubheading, customStyle.firstColumnSubheading);}); if(null != customStyle.firstHeaderCell) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeFirstHeaderCell, customStyle.firstHeaderCell);}); if(null != customStyle.firstRowStripe) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeFirstRowStripe, customStyle.firstRowStripe);}); if(null != customStyle.firstRowSubheading) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeFirstRowSubheading, customStyle.firstRowSubheading);}); if(null != customStyle.firstSubtotalColumn) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeFirstSubtotalColumn, customStyle.firstSubtotalColumn);}); if(null != customStyle.firstSubtotalRow) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeFirstSubtotalRow, customStyle.firstSubtotalRow);}); if(null != customStyle.firstTotalCell) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeFirstTotalCell, customStyle.firstTotalCell);}); if(null != customStyle.headerRow) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeHeaderRow, customStyle.headerRow);}); if(null != customStyle.lastColumn) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeLastColumn, customStyle.lastColumn);}); if(null != customStyle.lastHeaderCell) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeLastHeaderCell, customStyle.lastHeaderCell);}); if(null != customStyle.lastTotalCell) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeLastTotalCell, customStyle.lastTotalCell);}); if(null != customStyle.pageFieldLabels) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypePageFieldLabels, customStyle.pageFieldLabels);}); if(null != customStyle.pageFieldValues) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypePageFieldValues, customStyle.pageFieldValues);}); if(null != customStyle.secondColumnStripe) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeSecondColumnStripe, customStyle.secondColumnStripe);}); if(null != customStyle.secondColumnSubheading) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeSecondColumnSubheading, customStyle.secondColumnSubheading);}); if(null != customStyle.secondRowStripe) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeSecondRowStripe, customStyle.secondRowStripe);}); if(null != customStyle.secondRowSubheading) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeSecondRowSubheading, customStyle.secondRowSubheading);}); if(null != customStyle.secondSubtotalColumn) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeSecondSubtotalColumn, customStyle.secondSubtotalColumn);}); if(null != customStyle.secondSubtotalRow) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeSecondSubtotalRow, customStyle.secondSubtotalRow);}); if(null != customStyle.thirdColumnSubheading) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeThirdColumnSubheading, customStyle.thirdColumnSubheading);}); if(null != customStyle.thirdRowSubheading) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeThirdRowSubheading, customStyle.thirdRowSubheading);}); if(null != customStyle.thirdSubtotalColumn) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeThirdSubtotalColumn, customStyle.thirdSubtotalColumn);}); if(null != customStyle.thirdSubtotalRow) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeThirdSubtotalRow, customStyle.thirdSubtotalRow);}); if(null != customStyle.totalRow) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeTotalRow, customStyle.totalRow);}); if(null != customStyle.wholeTable) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeWholeTable, customStyle.wholeTable);}); } this.WriteTableCustomStyleElement = function(type, customElement) { if(null != type) { this.memory.WriteByte(c_oSer_TableStyleElement.Type); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteByte(type); } if(null != customElement.size) { this.memory.WriteByte(c_oSer_TableStyleElement.Size); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(customElement.size); } if(null != customElement.dxf && null != this.aDxfs) { this.memory.WriteByte(c_oSer_TableStyleElement.DxfId); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(this.aDxfs.length); this.aDxfs.push(customElement.dxf); } } }; function BinaryWorkbookTableWriter(memory, wb) { this.memory = memory; this.bs = new BinaryCommonWriter(this.memory); this.wb = wb; this.Write = function() { var oThis = this; this.bs.WriteItemWithLength(function(){oThis.WriteWorkbookContent();}); }; this.WriteWorkbookContent = function() { var oThis = this; //WorkbookPr this.bs.WriteItem(c_oSerWorkbookTypes.WorkbookPr, function(){oThis.WriteWorkbookPr();}); //BookViews this.bs.WriteItem(c_oSerWorkbookTypes.BookViews, function(){oThis.WriteBookViews();}); //DefinedNames this.bs.WriteItem(c_oSerWorkbookTypes.DefinedNames, function(){oThis.WriteDefinedNames();}); }; this.WriteWorkbookPr = function() { var oWorkbookPr = this.wb.WorkbookPr; if(null != oWorkbookPr) { if(null != oWorkbookPr.Date1904) { this.memory.WriteByte(c_oSerBorderPropTypes.Date1904); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(oWorkbookPr.Date1904); } else if (null != oWorkbookPr.DateCompatibility) { this.memory.WriteByte(c_oSerBorderPropTypes.DateCompatibility); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(oWorkbookPr.DateCompatibility); } } }; this.WriteBookViews = function() { var oThis = this; this.bs.WriteItem(c_oSerWorkbookTypes.WorkbookView, function(){oThis.WriteWorkbookView();}); }; this.WriteWorkbookView = function() { if (null != this.wb.nActive) { this.memory.WriteByte( c_oSerWorkbookViewTypes.ActiveTab); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(this.wb.nActive); } }; this.WriteDefinedNames = function() { var oThis = this; //собираем все defined names в массив var allDefined = new Object(); if(null != this.wb.oRealDefinedNames) { for(var i in this.wb.oRealDefinedNames) { var oDefinedName = this.wb.oRealDefinedNames[i]; if(null == allDefined[oDefinedName.Name]) allDefined[oDefinedName.Name] = {global: oDefinedName, local: {}}; } } for(var i = 0, length = this.wb.aWorksheets.length; i < length; ++i) { var ws = this.wb.aWorksheets[i]; if(null != ws.DefinedNames) { for(var j in ws.DefinedNames) { var oDefinedName = ws.DefinedNames[j]; var elem = allDefined[oDefinedName.Name]; if(null == elem) { elem = {global: null, local: {}}; allDefined[oDefinedName.Name] = elem; } elem.local[i] = oDefinedName; } } } for(var i in allDefined) { var elem = allDefined[i]; for(var j in elem.local) { var localElem = elem.local[j]; var nLocalIndex = j - 0; if(null != localElem) this.bs.WriteItem(c_oSerWorkbookTypes.DefinedName, function(){oThis.WriteDefinedName(localElem, nLocalIndex);}); } if(null != elem.global) this.bs.WriteItem(c_oSerWorkbookTypes.DefinedName, function(){oThis.WriteDefinedName(elem.global);}); } }; this.WriteDefinedName = function(oDefinedName, LocalSheetId) { var oThis = this; if (null != oDefinedName.Name) { this.memory.WriteByte(c_oSerDefinedNameTypes.Name); this.memory.WriteString2(oDefinedName.Name); } if (null != oDefinedName.Ref) { this.memory.WriteByte(c_oSerDefinedNameTypes.Ref); this.memory.WriteString2(oDefinedName.Ref); } if (null != LocalSheetId) this.bs.WriteItem(c_oSerDefinedNameTypes.LocalSheetId, function(){oThis.memory.WriteLong(LocalSheetId);}); }; }; function BinaryWorksheetsTableWriter(memory, wb, oSharedStrings, oDrawings, aDxfs, aXfs, aFonts, aFills, aBorders, aNums, idWorksheet) { this.memory = memory; this.bs = new BinaryCommonWriter(this.memory); this.wb = wb; this.oSharedStrings = oSharedStrings; this.oDrawings = oDrawings; this.aDxfs = aDxfs; this.aXfs = aXfs; this.aFonts = aFonts; this.aFills = aFills; this.aBorders = aBorders; this.aNums = aNums; this.oXfsStylesMap = []; this.oXfsMap = new Object(); this.nXfsMapIndex = 0; this.oFontMap = new Object(); this.nFontMapIndex = 0; this.oFillMap = new Object(); this.nFillMapIndex = 0; this.oBorderMap = new Object(); this.nBorderMapIndex = 0; this.oNumMap = new Object(); this.nNumMapIndex = 0; this.oMerged = new Object(); this.oHyperlinks = new Object(); this.idWorksheet = idWorksheet; this.oAllColXfsId = null; this._getCrc32FromObjWithProperty = function(val) { return Asc.crc32(this._getStringFromObjWithProperty(val)); } this._getStringFromObjWithProperty = function(val) { var sRes = ""; if(val.getProperties) { var properties = val.getProperties(); for(var i in properties) { var oCurProp = val.getProperty(properties[i]); if(null != oCurProp && oCurProp.getProperties) sRes += this._getStringFromObjWithProperty(oCurProp); else sRes += oCurProp; } } return sRes; } this._prepeareStyles = function() { this.oFontMap[this._getStringFromObjWithProperty(g_oDefaultFont)] = {index: this.nFontMapIndex++, val: g_oDefaultFont}; this.oFillMap[this._getStringFromObjWithProperty(g_oDefaultFill)] = {index: this.nFillMapIndex++, val: g_oDefaultFill}; this.nFillMapIndex++; this.oBorderMap[this._getStringFromObjWithProperty(g_oDefaultBorder)] = {index: this.nBorderMapIndex++, val: g_oDefaultBorder}; this.nNumMapIndex = g_nNumsMaxId; var sAlign = "0"; var oAlign = null; if(false == g_oDefaultAlign.isEqual(g_oDefaultAlignAbs)) { oAlign = g_oDefaultAlign; sAlign = this._getStringFromObjWithProperty(g_oDefaultAlign); } this.prepareXfsStyles(); var xfs = {borderid: 0, fontid: 0, fillid: 0, numid: 0, align: oAlign, QuotePrefix: null}; this.oXfsMap["0|0|0|0|"+sAlign] = {index: this.nXfsMapIndex++, val: xfs}; }; this.Write = function() { var oThis = this; this._prepeareStyles(); this.bs.WriteItemWithLength(function(){oThis.WriteWorksheetsContent();}); }; this.WriteWorksheetsContent = function() { var oThis = this; for(var i = 0, length = this.wb.aWorksheets.length; i < length; ++i) { var ws = this.wb.aWorksheets[i]; this.oMerged = new Object(); this.oHyperlinks = new Object(); if(null == this.idWorksheet || this.idWorksheet == ws.getId()) this.bs.WriteItem(c_oSerWorksheetsTypes.Worksheet, function(){oThis.WriteWorksheet(ws, i);}); } }; this.WriteWorksheet = function(ws, index) { var oThis = this; this.bs.WriteItem(c_oSerWorksheetsTypes.WorksheetProp, function(){oThis.WriteWorksheetProp(ws, index);}); if(ws.aCols.length > 0 || null != ws.oAllCol) this.bs.WriteItem(c_oSerWorksheetsTypes.Cols, function(){oThis.WriteWorksheetCols(ws);}); this.bs.WriteItem(c_oSerWorksheetsTypes.SheetViews, function(){oThis.WriteSheetViews(ws);}); this.bs.WriteItem(c_oSerWorksheetsTypes.SheetFormatPr, function(){oThis.WriteSheetFormatPr(ws);}); if(null != ws.PagePrintOptions) { this.bs.WriteItem(c_oSerWorksheetsTypes.PageMargins, function(){oThis.WritePageMargins(ws.PagePrintOptions.asc_getPageMargins());}); this.bs.WriteItem(c_oSerWorksheetsTypes.PageSetup, function(){oThis.WritePageSetup(ws.PagePrintOptions.asc_getPageSetup());}); this.bs.WriteItem(c_oSerWorksheetsTypes.PrintOptions, function(){oThis.WritePrintOptions(ws.PagePrintOptions);}); } this.bs.WriteItem(c_oSerWorksheetsTypes.SheetData, function(){oThis.WriteSheetData(ws);}); this.bs.WriteItem(c_oSerWorksheetsTypes.Hyperlinks, function(){oThis.WriteHyperlinks();}); this.bs.WriteItem(c_oSerWorksheetsTypes.MergeCells, function(){oThis.WriteMergeCells();}); if ( ws.Drawings && (ws.Drawings.length) ) this.bs.WriteItem(c_oSerWorksheetsTypes.Drawings, function(){oThis.WriteDrawings(ws.Drawings);}); if(ws.aComments.length > 0 && ws.aCommentsCoords.length > 0) this.bs.WriteItem(c_oSerWorksheetsTypes.Comments, function(){oThis.WriteComments(ws.aComments, ws.aCommentsCoords);}); if(null != ws.AutoFilter) { var oBinaryTableWriter = new BinaryTableWriter(this.memory, this.aDxfs); this.bs.WriteItem(c_oSerWorksheetsTypes.Autofilter, function(){oBinaryTableWriter.WriteAutoFilter(ws.AutoFilter);}); } if(null != ws.TableParts && ws.TableParts.length > 0) { var oBinaryTableWriter = new BinaryTableWriter(this.memory, this.aDxfs); this.bs.WriteItem(c_oSerWorksheetsTypes.TableParts, function(){oBinaryTableWriter.Write(ws.TableParts);}); } }; this.WriteWorksheetProp = function(ws, index) { var oThis = this; //Name this.memory.WriteByte(c_oSerWorksheetPropTypes.Name); this.memory.WriteByte(c_oSerPropLenType.Variable); this.memory.WriteString2(ws.sName); //SheetId this.memory.WriteByte(c_oSerWorksheetPropTypes.SheetId); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(index + 1); //Hidden if(null != ws.bHidden) { this.memory.WriteByte(c_oSerWorksheetPropTypes.State); this.memory.WriteByte(c_oSerPropLenType.Byte); if(true == ws.bHidden) this.memory.WriteByte(EVisibleType.visibleHidden); else this.memory.WriteByte(EVisibleType.visibleVisible); } }; this.WriteWorksheetCols = function(ws) { var oThis = this; var aCols = ws.aCols; var oPrevCol = null; var nPrevIndexStart = null; var nPrevIndex = null; var aIndexes = new Array(); for(var i in aCols) aIndexes.push(i - 0); aIndexes.sort(fSortAscending); var fInitCol = function(col, nMin, nMax){ oThis.AddToMergedAndHyperlink(col); var oRes = {BestFit: col.BestFit, hd: col.hd, Max: nMax, Min: nMin, xfsid: null, width: col.width, CustomWidth: col.CustomWidth}; if(null == oRes.width) { if(null != ws.dDefaultColWidth) oRes.width = ws.dDefaultColWidth; else oRes.width = gc_dDefaultColWidthCharsAttribute; } if(null != col.xfs) oRes.xfsid = oThis.prepareXfs(col.xfs); return oRes; } var oAllCol = null; if(null != ws.oAllCol) { oAllCol = fInitCol(ws.oAllCol, 0, gc_nMaxCol0); this.oAllColXfsId = oAllCol.xfsid; } for(var i = 0 , length = aIndexes.length; i < length; ++i) { var nIndex = aIndexes[i]; var col = aCols[nIndex]; if(null != col) { if(false == col.isEmptyToSave()) { if(null != oAllCol && null == nPrevIndex && nIndex > 0) { oAllCol.Min = 1; oAllCol.Max = nIndex; this.bs.WriteItem(c_oSerWorksheetsTypes.Col, function(){oThis.WriteWorksheetCol(oAllCol);}); } if(null != nPrevIndex && (nPrevIndex + 1 != nIndex || false == oPrevCol.isEqual(col))) { var oColToWrite = fInitCol(oPrevCol, nPrevIndexStart + 1, nPrevIndex + 1); this.bs.WriteItem(c_oSerWorksheetsTypes.Col, function(){oThis.WriteWorksheetCol(oColToWrite);}); nPrevIndexStart = null; if(null != oAllCol && nPrevIndex + 1 != nIndex) { oAllCol.Min = nPrevIndex + 2; oAllCol.Max = nIndex; this.bs.WriteItem(c_oSerWorksheetsTypes.Col, function(){oThis.WriteWorksheetCol(oAllCol);}); } } oPrevCol = col; nPrevIndex = nIndex; if(null == nPrevIndexStart) nPrevIndexStart = nPrevIndex; } } } if(null != nPrevIndexStart && null != nPrevIndex && null != oPrevCol) { var oColToWrite = fInitCol(oPrevCol, nPrevIndexStart + 1, nPrevIndex + 1); this.bs.WriteItem(c_oSerWorksheetsTypes.Col, function(){oThis.WriteWorksheetCol(oColToWrite);}); } if(null != oAllCol) { if(null == nPrevIndex) { oAllCol.Min = 1; oAllCol.Max = gc_nMaxCol0 + 1; this.bs.WriteItem(c_oSerWorksheetsTypes.Col, function(){oThis.WriteWorksheetCol(oAllCol);}); } else if(gc_nMaxCol0 != nPrevIndex) { oAllCol.Min = nPrevIndex + 2; oAllCol.Max = gc_nMaxCol0 + 1; this.bs.WriteItem(c_oSerWorksheetsTypes.Col, function(){oThis.WriteWorksheetCol(oAllCol);}); } } }; this.WriteWorksheetCol = function(oCol) { if(null != oCol.BestFit) { this.memory.WriteByte(c_oSerWorksheetColTypes.BestFit); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(oCol.BestFit); } if(null != oCol.Hidden) { this.memory.WriteByte(c_oSerWorksheetColTypes.Hidden); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(oCol.Hidden); } if(null != oCol.Max) { this.memory.WriteByte(c_oSerWorksheetColTypes.Max); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(oCol.Max); } if(null != oCol.Min) { this.memory.WriteByte(c_oSerWorksheetColTypes.Min); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(oCol.Min); } if(null != oCol.xfsid) { this.memory.WriteByte(c_oSerWorksheetColTypes.Style); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(oCol.xfsid); } if(null != oCol.width) { this.memory.WriteByte(c_oSerWorksheetColTypes.Width); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(oCol.width); } if(null != oCol.CustomWidth) { this.memory.WriteByte(c_oSerWorksheetColTypes.CustomWidth); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(oCol.CustomWidth); } }; this.WriteSheetViews = function (ws) { var oThis = this; for (var i = 0, length = ws.sheetViews.length; i < length; ++i) { this.bs.WriteItem(c_oSerWorksheetsTypes.SheetView, function(){oThis.WriteSheetView(ws.sheetViews[i]);}); } }; this.WriteSheetView = function (oSheetView) { if (null !== oSheetView.showGridLines) { this.memory.WriteByte(c_oSer_SheetView.ShowGridLines); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(oSheetView.showGridLines); } if (null !== oSheetView.showRowColHeaders) { this.memory.WriteByte(c_oSer_SheetView.ShowRowColHeaders); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(oSheetView.showRowColHeaders); } }; this.WriteSheetFormatPr = function(ws) { if(null !== ws.dDefaultColWidth) { this.memory.WriteByte(c_oSerSheetFormatPrTypes.DefaultColWidth); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(ws.dDefaultColWidth); } if(null !== ws.dDefaultheight) { this.memory.WriteByte(c_oSerSheetFormatPrTypes.DefaultRowHeight); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(ws.dDefaultheight); } if (null !== ws.nBaseColWidth) { this.memory.WriteByte(c_oSerSheetFormatPrTypes.BaseColWidth); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(ws.nBaseColWidth); } }; this.WritePageMargins = function(oMargins) { //Left var dLeft = oMargins.asc_getLeft(); if(null != dLeft) { this.memory.WriteByte(c_oSer_PageMargins.Left); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(dLeft); } //Top var dTop = oMargins.asc_getTop(); if(null != dTop) { this.memory.WriteByte(c_oSer_PageMargins.Top); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(dTop); } //Right var dRight = oMargins.asc_getRight(); if(null != dRight) { this.memory.WriteByte(c_oSer_PageMargins.Right); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(dRight); } //Bottom var dBottom = oMargins.asc_getBottom(); if(null != dBottom) { this.memory.WriteByte(c_oSer_PageMargins.Bottom); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(dBottom); } this.memory.WriteByte(c_oSer_PageMargins.Header); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(12.7);//0.5inch this.memory.WriteByte(c_oSer_PageMargins.Footer); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(12.7);//0.5inch }; this.WritePageSetup = function(oPageSetup) { //Orientation var byteOrientation = oPageSetup.asc_getOrientation(); if(null != byteOrientation) { var byteFormatOrientation = null; switch(byteOrientation) { case c_oAscPageOrientation.PagePortrait: byteFormatOrientation = EPageOrientation.pageorientPortrait;break; case c_oAscPageOrientation.PageLandscape: byteFormatOrientation = EPageOrientation.pageorientLandscape;break; } if(null != byteFormatOrientation) { this.memory.WriteByte(c_oSer_PageSetup.Orientation); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteByte(byteFormatOrientation); } } //PageSize var dWidth = oPageSetup.asc_getWidth(); var dHeight = oPageSetup.asc_getHeight(); if(null != dWidth && null != dHeight) { var item = DocumentPageSize.getSizeByWH(dWidth, dHeight); this.memory.WriteByte(c_oSer_PageSetup.PaperSize); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteByte(item.id); } }; this.WritePrintOptions = function(oPrintOptions) { //GridLines var bGridLines = oPrintOptions.asc_getGridLines(); if(null != bGridLines) { this.memory.WriteByte(c_oSer_PrintOptions.GridLines); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(bGridLines); } //Headings var bHeadings = oPrintOptions.asc_getHeadings(); if(null != bHeadings) { this.memory.WriteByte(c_oSer_PrintOptions.Headings); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(bHeadings); } }; this.WriteHyperlinks = function() { var oThis = this; for(var i in this.oHyperlinks) { var hyp = this.oHyperlinks[i]; this.bs.WriteItem(c_oSerWorksheetsTypes.Hyperlink, function(){oThis.WriteHyperlink(hyp);}); } }; this.WriteHyperlink = function(oHyperlink) { if(null != oHyperlink.Ref) { this.memory.WriteByte(c_oSerHyperlinkTypes.Ref); this.memory.WriteString2(oHyperlink.Ref.getName()); } if(null != oHyperlink.Hyperlink) { this.memory.WriteByte(c_oSerHyperlinkTypes.Hyperlink); this.memory.WriteString2(oHyperlink.Hyperlink); } if(null != oHyperlink.Location) { this.memory.WriteByte(c_oSerHyperlinkTypes.Location); this.memory.WriteString2(oHyperlink.Location); } if(null != oHyperlink.Tooltip) { this.memory.WriteByte(c_oSerHyperlinkTypes.Tooltip); this.memory.WriteString2(oHyperlink.Tooltip); } }; this.WriteMergeCells = function() { var oThis = this; for(var i in this.oMerged) { this.memory.WriteByte(c_oSerWorksheetsTypes.MergeCell); this.memory.WriteString2(i); } }; this.WriteDrawings = function(aDrawings) { var oThis = this; for(var i = 0, length = aDrawings.length; i < length; ++i) { var oDrawing = aDrawings[i]; this.bs.WriteItem(c_oSerWorksheetsTypes.Drawing, function(){oThis.WriteDrawing(oDrawing);}); } }; this.WriteDrawing = function(oDrawing) { var oThis = this; if(null != oDrawing.Type) this.bs.WriteItem(c_oSer_DrawingType.Type, function(){oThis.memory.WriteByte(ECellAnchorType.cellanchorOneCell);}); if(null != oDrawing.from) this.bs.WriteItem(c_oSer_DrawingType.From, function(){oThis.WriteFromTo(oDrawing.from);}); if(null != oDrawing.to) this.bs.WriteItem(c_oSer_DrawingType.To, function(){oThis.WriteFromTo(oDrawing.to);}); // if(null != oDrawing.Pos) // this.bs.WriteItem(c_oSer_DrawingType.Pos, function(){oThis.WritePos(oDrawing.Pos);}); if(oDrawing.isChart()) { var oBinaryChartWriter = new BinaryChartWriter(this.memory); this.bs.WriteItem(c_oSer_DrawingType.GraphicFrame, function(){oBinaryChartWriter.Write(oDrawing.chart);}); } else { if ( (null != oDrawing.imageUrl) && ("" != oDrawing.imageUrl)) { if (window['scriptBridge']) { this.bs.WriteItem(c_oSer_DrawingType.Pic, function(){oThis.WritePic(oDrawing.imageUrl.replace(/^.*(\\|\/|\:)/, ''));}); } else { this.bs.WriteItem(c_oSer_DrawingType.Pic, function(){oThis.WritePic(oDrawing.imageUrl);}); } } } }; this.WriteFromTo = function(oFromTo) { if(null != oFromTo.col) { this.memory.WriteByte(c_oSer_DrawingFromToType.Col); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(oFromTo.col); } if(null != oFromTo.colOff) { this.memory.WriteByte(c_oSer_DrawingFromToType.ColOff); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(oFromTo.colOff); } if(null != oFromTo.row) { this.memory.WriteByte(c_oSer_DrawingFromToType.Row); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(oFromTo.row); } if(null != oFromTo.rowOff) { this.memory.WriteByte(c_oSer_DrawingFromToType.RowOff); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(oFromTo.rowOff); } }; this.WritePos = function(oPos) { if(null != oPos.X) { this.memory.WriteByte(c_oSer_DrawingPosType.X); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(oPos.X); } if(null != oPos.Y) { this.memory.WriteByte(c_oSer_DrawingPosType.Y); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(oPos.Y); } }; this.WritePic = function(oPic) { var oThis = this; if(null != oPic && "" != oPic) { var sSrc = oPic; var sLocalUrl = this.wb.sUrlPath + "media/"; if(0 == sSrc.indexOf(sLocalUrl)) sSrc = sSrc.substring(sLocalUrl.length); var nIndex = this.oDrawings.items[sSrc]; if(null == nIndex) { nIndex = this.oDrawings.length; this.oDrawings.items[sSrc] = nIndex; this.oDrawings.length++; } this.bs.WriteItem(c_oSer_DrawingType.PicSrc, function(){oThis.memory.WriteLong(nIndex);}); } }; this.WriteSheetData = function(ws) { var oThis = this; //сортируем Row по индексам var aIndexes = new Array(); for(var i in ws.aGCells) aIndexes.push(i - 0); aIndexes.sort(fSortAscending); for(var i = 0, length = aIndexes.length; i < length; ++i) { var row = ws.aGCells[aIndexes[i]]; if(null != row) { this.AddToMergedAndHyperlink(row); if(false == row.isEmptyToSave()) this.bs.WriteItem(c_oSerWorksheetsTypes.Row, function(){oThis.WriteRow(row);}); } } }; this.WriteRow = function(oRow) { var oThis = this; if(null != oRow.r) { this.memory.WriteByte(c_oSerRowTypes.Row); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(oRow.r); } if(null != oRow.xfs) { var nXfsId = this.prepareXfs(oRow.xfs); this.memory.WriteByte(c_oSerRowTypes.Style); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(nXfsId); } if(null != oRow.h) { this.memory.WriteByte(c_oSerRowTypes.Height); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(oRow.h); } if(null != oRow.CustomHeight) { this.memory.WriteByte(c_oSerRowTypes.CustomHeight); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(oRow.CustomHeight); } if(null != oRow.hd) { this.memory.WriteByte(c_oSerRowTypes.Hidden); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(oRow.hd); } this.memory.WriteByte(c_oSerRowTypes.Cells); this.memory.WriteByte(c_oSerPropLenType.Variable); this.bs.WriteItemWithLength(function(){oThis.WriteCells(oRow.c);}); }; this.WriteCells = function(aCells) { var oThis = this; var aIndexes = new Array(); for(var i in aCells) aIndexes.push(i - 0); aIndexes.sort(fSortAscending); for(var i = 0, length = aIndexes.length; i < length; ++i) { var cell = aCells[aIndexes[i]]; //готовим ячейку к записи var nXfsId = this.prepareXfs(cell.xfs); this.AddToMergedAndHyperlink(cell); if(0 != nXfsId || false == cell.isEmptyText() || null != cell.merged || cell.hyperlinks.length > 0) this.bs.WriteItem(c_oSerRowTypes.Cell, function(){oThis.WriteCell(cell, nXfsId);}); } }; this.prepareXfsStyles = function () { var styles = this.wb.CellStyles.CustomStyles; var xfs = null; for(var i = 0, length = styles.length; i < length; ++i) { xfs = styles[i].xfs; if (xfs) { var sStyle = this.prepareXfsStyle(xfs); var oXfs = {borderid: sStyle.borderid, fontid: sStyle.fontid, fillid: sStyle.fillid, numid: sStyle.numid, align: null, QuotePrefix: null, XfId: xfs.XfId}; if("0" != sStyle.align) oXfs.align = xfs.align; if(null != xfs.QuotePrefix) oXfs.QuotePrefix = xfs.QuotePrefix; this.oXfsStylesMap.push(oXfs); } } }; this.prepareXfsStyle = function(xfs) { var sStyle = {val: "", borderid: 0, fontid: 0, fillid: 0, numid: 0, align: "0"}; if(null != xfs) { if(null != xfs.font) { var sHash = this._getStringFromObjWithProperty(xfs.font); var elem = this.oFontMap[sHash]; if(null == elem) { sStyle.fontid = this.nFontMapIndex++; this.oFontMap[sHash] = {index: sStyle.fontid, val: xfs.font}; } else sStyle.fontid = elem.index; } sStyle.val += sStyle.fontid.toString(); if(null != xfs.fill) { var sHash = this._getStringFromObjWithProperty(xfs.fill); var elem = this.oFillMap[sHash]; if(null == elem) { sStyle.fillid = this.nFillMapIndex++; this.oFillMap[sHash] = {index: sStyle.fillid, val: xfs.fill}; } else sStyle.fillid = elem.index; } sStyle.val += "|" + sStyle.fillid.toString(); if(null != xfs.border) { var sHash = this._getStringFromObjWithProperty(xfs.border); var elem = this.oBorderMap[sHash]; if(null == elem) { sStyle.borderid = this.nBorderMapIndex++; this.oBorderMap[sHash] = {index: sStyle.borderid, val: xfs.border}; } else sStyle.borderid = elem.index; } sStyle.val += "|" + sStyle.borderid.toString(); if(null != xfs.num) { //стандартные форматы не записываем в map, на них можно ссылаться по id var nStandartId = aStandartNumFormatsId[xfs.num.f]; if(null == nStandartId) { var sHash = this._getStringFromObjWithProperty(xfs.num); var elem = this.oNumMap[sHash]; if(null == elem) { sStyle.numid = this.nNumMapIndex++; this.oNumMap[sHash] = {index: sStyle.numid, val: xfs.num}; } else sStyle.numid = elem.index; } else sStyle.numid = nStandartId; } sStyle.val += "|" + sStyle.numid.toString(); if(null != xfs.align && false == xfs.align.isEqual(g_oDefaultAlignAbs)) sStyle.align = this._getStringFromObjWithProperty(xfs.align); sStyle.val += "|" + sStyle.align; } return sStyle; }; this.prepareXfs = function(xfs) { var nXfsId = 0; if(null != xfs) { var sStyle = this.prepareXfsStyle(xfs); var oXfsMapObj = this.oXfsMap[sStyle.val]; if(null == oXfsMapObj) { nXfsId = this.nXfsMapIndex; var oXfs = {borderid: sStyle.borderid, fontid: sStyle.fontid, fillid: sStyle.fillid, numid: sStyle.numid, align: null, QuotePrefix: null, XfId: xfs.XfId}; if("0" != sStyle.align) oXfs.align = xfs.align; if(null != xfs.QuotePrefix) oXfs.QuotePrefix = xfs.QuotePrefix; this.oXfsMap[sStyle.val] = {index: this.nXfsMapIndex++, val: oXfs}; } else nXfsId = oXfsMapObj.index; } return nXfsId; }; this.AddToMergedAndHyperlink = function(container) { if(null != container.merged) this.oMerged[container.merged.getName()] = 1; if(null != container.hyperlinks) { for(var i = 0, length = container.hyperlinks.length; i < length; ++i) { var hyperlink = container.hyperlinks[i]; this.oHyperlinks[hyperlink.Ref.getName()] = hyperlink; } } } this.WriteCell = function(cell, nXfsId) { var oThis = this; if(null != cell.oId) { this.memory.WriteByte(c_oSerCellTypes.Ref); this.memory.WriteString2(cell.oId.getID()); } if(null != nXfsId) { this.bs.WriteItem(c_oSerCellTypes.Style, function(){oThis.memory.WriteLong(nXfsId);}); } var nCellType = cell.getType(); if(null != nCellType) { var nType = ECellTypeType.celltypeNumber; switch(nCellType) { case CellValueType.Bool: nType = ECellTypeType.celltypeBool; break; case CellValueType.Error: nType = ECellTypeType.celltypeError; break; case CellValueType.Number: nType = ECellTypeType.celltypeNumber; break; case CellValueType.String: nType = ECellTypeType.celltypeSharedString; break; } if(ECellTypeType.celltypeNumber != nType) this.bs.WriteItem(c_oSerCellTypes.Type, function(){oThis.memory.WriteByte(nType);}); } if(null != cell.sFormula) this.bs.WriteItem(c_oSerCellTypes.Formula, function(){oThis.WriteFormula(cell.sFormula, cell.sFormulaCA);}); if(null != cell.oValue && false == cell.oValue.isEmpty()) { var dValue = 0; if(CellValueType.Error == nCellType || CellValueType.String == nCellType) { var sText = ""; var aText = null; if(null != cell.oValue.text) sText = cell.oValue.text; else if(null != cell.oValue.multiText) { aText = cell.oValue.multiText; for(var i = 0, length = cell.oValue.multiText.length; i < length; ++i) sText += cell.oValue.multiText[i].text; } var item = this.oSharedStrings.strings[sText]; var bAddItem = false; if(null == item) { item = {t: null, a: []}; bAddItem = true; } if(null == aText) { if(null == item.t) { dValue = this.oSharedStrings.index++; item.t = {id: dValue, val: sText}; } else dValue = item.t.id; } else { var bFound = false; for(var i = 0, length = item.a.length; i < length; ++i) { var oCurItem = item.a[i]; if(oCurItem.val.length == aText.length) { var bEqual = true; for(var j = 0, length2 = aText.length; j < length2; ++j) { if(false == aText[j].isEqual(oCurItem.val[j])) { bEqual = false; break; } } if(bEqual) { bFound = true; dValue = oCurItem.id; break; } } } if(false == bFound) { dValue = this.oSharedStrings.index++; item.a.push({id: dValue, val: aText}); } } if(bAddItem) this.oSharedStrings.strings[sText] = item; } else { if(null != cell.oValue.number) dValue = cell.oValue.number; } this.bs.WriteItem(c_oSerCellTypes.Value, function(){oThis.memory.WriteDouble2(dValue);}); } }; this.WriteFormula = function(sFormula, sFormulaCA) { // if(null != oFormula.aca) // { // this.memory.WriteByte(c_oSerFormulaTypes.Aca); // this.memory.WriteByte(c_oSerPropLenType.Byte); // this.memory.WriteBool(oFormula.aca); // } // if(null != oFormula.bx) // { // this.memory.WriteByte(c_oSerFormulaTypes.Bx); // this.memory.WriteByte(c_oSerPropLenType.Byte); // this.memory.WriteBool(oFormula.bx); // } if(null != sFormulaCA) { this.memory.WriteByte(c_oSerFormulaTypes.Ca); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(sFormulaCA); } // if(null != oFormula.del1) // { // this.memory.WriteByte(c_oSerFormulaTypes.Del1); // this.memory.WriteByte(c_oSerPropLenType.Byte); // this.memory.WriteBool(oFormula.del1); // } // if(null != oFormula.del2) // { // this.memory.WriteByte(c_oSerFormulaTypes.Del2); // this.memory.WriteByte(c_oSerPropLenType.Byte); // this.memory.WriteBool(oFormula.del2); // } // if(null != oFormula.dt2d) // { // this.memory.WriteByte(c_oSerFormulaTypes.Dt2D); // this.memory.WriteByte(c_oSerPropLenType.Byte); // this.memory.WriteBool(oFormula.dt2d); // } // if(null != oFormula.dtr) // { // this.memory.WriteByte(c_oSerFormulaTypes.Dtr); // this.memory.WriteByte(c_oSerPropLenType.Byte); // this.memory.WriteBool(oFormula.dtr); // } // if(null != oFormula.r1) // { // this.memory.WriteByte(c_oSerFormulaTypes.R1); // this.memory.WriteByte(c_oSerPropLenType.Variable); // this.memory.WriteString2(oFormula.r1); // } // if(null != oFormula.r2) // { // this.memory.WriteByte(c_oSerFormulaTypes.R2); // this.memory.WriteByte(c_oSerPropLenType.Variable); // this.memory.WriteString2(oFormula.r2); // } // if(null != oFormula.ref) // { // this.memory.WriteByte(c_oSerFormulaTypes.Ref); // this.memory.WriteByte(c_oSerPropLenType.Variable); // this.memory.WriteString2(oFormula.ref); // } // if(null != oFormula.si) // { // this.memory.WriteByte(c_oSerFormulaTypes.Si); // this.memory.WriteByte(c_oSerPropLenType.Long); // this.memory.WriteLong(oFormula.si); // } // if(null != oFormula.t) // { // this.memory.WriteByte(c_oSerFormulaTypes.T); // this.memory.WriteByte(c_oSerPropLenType.Byte); // this.memory.WriteByte(oFormula.t); // } // if(null != oFormula.v) // { // this.memory.WriteByte(c_oSerFormulaTypes.Text); // this.memory.WriteByte(c_oSerPropLenType.Variable); // this.memory.WriteString2(oFormula.v); // } this.memory.WriteByte(c_oSerFormulaTypes.Text); this.memory.WriteByte(c_oSerPropLenType.Variable); this.memory.WriteString2(sFormula); }; this.WriteComments = function(aComments, aCommentsCoords) { var oThis = this; var oNewComments = new Object(); for(var i = 0, length = aComments.length; i < length; ++i) { var elem = aComments[i]; var nRow = elem.asc_getRow(); if(null == nRow) nRow = 0; var nCol = elem.asc_getCol(); if(null == nCol) nCol = 0; var row = oNewComments[nRow]; if(null == row) { row = new Object(); oNewComments[nRow] = row; } var comment = row[nCol]; if(null == comment) { comment = {data: new Array(), coord: null}; row[nCol] = comment; } comment.data.push(elem); } for(var i = 0, length = aCommentsCoords.length; i < length; ++i) { var elem = aCommentsCoords[i]; var nRow = elem.asc_getRow(); if(null == nRow) nRow = 0; var nCol = elem.asc_getCol(); if(null == nCol) nCol = 0; var row = oNewComments[nRow]; if(null == row) { row = new Object(); oNewComments[nRow] = row; } var comment = row[nCol]; if(null == comment) { comment = {data: new Array(), coord: null}; row[nCol] = comment; } comment.coord = elem; } for(var i in oNewComments) { var row = oNewComments[i]; for(var j in row) { var comment = row[j]; if(null == comment.coord || 0 == comment.data.length) continue; var coord = comment.coord; if(null == coord.asc_getLeft() || null == coord.asc_getTop() || null == coord.asc_getRight() || null == coord.asc_getBottom() || null == coord.asc_getLeftOffset() || null == coord.asc_getTopOffset() || null == coord.asc_getRightOffset() || null == coord.asc_getBottomOffset() || null == coord.asc_getLeftMM() || null == coord.asc_getTopMM() || null == coord.asc_getWidthMM() || null == coord.asc_getHeightMM()) continue; this.bs.WriteItem(c_oSerWorksheetsTypes.Comment, function(){oThis.WriteComment(comment);}); } } }; this.WriteComment = function(comment) { var oThis = this; this.memory.WriteByte(c_oSer_Comments.Row); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(comment.coord.asc_getRow()); this.memory.WriteByte(c_oSer_Comments.Col); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(comment.coord.asc_getCol()); this.memory.WriteByte(c_oSer_Comments.CommentDatas); this.memory.WriteByte(c_oSerPropLenType.Variable); this.bs.WriteItemWithLength(function(){oThis.WriteCommentDatas(comment.data);}); this.memory.WriteByte(c_oSer_Comments.Left); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(comment.coord.asc_getLeft()); this.memory.WriteByte(c_oSer_Comments.Top); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(comment.coord.asc_getTop()); this.memory.WriteByte(c_oSer_Comments.Right); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(comment.coord.asc_getRight()); this.memory.WriteByte(c_oSer_Comments.Bottom); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(comment.coord.asc_getBottom()); this.memory.WriteByte(c_oSer_Comments.LeftOffset); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(comment.coord.asc_getLeftOffset()); this.memory.WriteByte(c_oSer_Comments.TopOffset); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(comment.coord.asc_getTopOffset()); this.memory.WriteByte(c_oSer_Comments.RightOffset); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(comment.coord.asc_getRightOffset()); this.memory.WriteByte(c_oSer_Comments.BottomOffset); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(comment.coord.asc_getBottomOffset()); this.memory.WriteByte(c_oSer_Comments.LeftMM); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(comment.coord.asc_getLeftMM()); this.memory.WriteByte(c_oSer_Comments.TopMM); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(comment.coord.asc_getTopMM()); this.memory.WriteByte(c_oSer_Comments.WidthMM); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(comment.coord.asc_getWidthMM()); this.memory.WriteByte(c_oSer_Comments.HeightMM); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(comment.coord.asc_getHeightMM()); this.memory.WriteByte(c_oSer_Comments.MoveWithCells); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(comment.coord.asc_getMoveWithCells()); this.memory.WriteByte(c_oSer_Comments.SizeWithCells); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(comment.coord.asc_getSizeWithCells()); }; this.WriteCommentDatas = function(aDatas) { var oThis = this; for(var i = 0, length = aDatas.length; i < length; ++i) this.bs.WriteItem( c_oSer_Comments.CommentData, function(){oThis.WriteCommentData(aDatas[i]);}); } this.WriteCommentData = function(oCommentData) { var oThis = this; var sText = oCommentData.asc_getText(); if(null != sText) { this.memory.WriteByte(c_oSer_CommentData.Text); this.memory.WriteString2(sText); } var sTime = oCommentData.asc_getTime(); if(null != sTime) { var oDate = new Date(sTime - 0); this.memory.WriteByte(c_oSer_CommentData.Time); this.memory.WriteString2(this.DateToISO8601(oDate)); } var sUserId = oCommentData.asc_getUserId(); if(null != sUserId) { this.memory.WriteByte(c_oSer_CommentData.UserId); this.memory.WriteString2(sUserId); } var sUserName = oCommentData.asc_getUserName(); if(null != sUserName) { this.memory.WriteByte(c_oSer_CommentData.UserName); this.memory.WriteString2(sUserName); } var sQuoteText = null; if(null != sQuoteText) { this.memory.WriteByte(c_oSer_CommentData.QuoteText); this.memory.WriteString2(sQuoteText); } var bSolved = null; if(null != bSolved) this.bs.WriteItem( c_oSer_CommentData.Solved, function(){oThis.memory.WriteBool(bSolved);}); var bDocumentFlag = oCommentData.asc_getDocumentFlag(); if(null != bDocumentFlag) this.bs.WriteItem( c_oSer_CommentData.Document, function(){oThis.memory.WriteBool(bDocumentFlag);}); var aReplies = oCommentData.aReplies; if(null != aReplies && aReplies.length > 0) this.bs.WriteItem( c_oSer_CommentData.Replies, function(){oThis.WriteReplies(aReplies);}); } this.DateToISO8601 = function(d) { function pad(n){return n < 10 ? '0' + n : n;} return d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate()) + 'T' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds())+'Z'; }; this.WriteReplies = function(aReplies) { var oThis = this; for(var i = 0, length = aReplies.length; i < length; ++i) this.bs.WriteItem( c_oSer_CommentData.Reply, function(){oThis.WriteCommentData(aReplies[i]);}); } }; /** @constructor */ function BinaryOtherTableWriter(memory, wb, oDrawings) { this.memory = memory; this.wb = wb; this.bs = new BinaryCommonWriter(this.memory); this.oDrawings = oDrawings; this.Write = function() { var oThis = this; this.bs.WriteItemWithLength(function(){oThis.WriteOtherContent();}); }; this.WriteOtherContent = function() { var oThis = this; //borders this.bs.WriteItem(c_oSer_OtherType.Media, function(){oThis.WriteMedia();}); this.bs.WriteItem(c_oSer_OtherType.Theme, function(){window.global_pptx_content_writer.WriteTheme(oThis.memory, oThis.wb.theme);}); }; this.WriteMedia = function() { var oThis = this; var aDrawings = new Array(this.oDrawings.length); for(var src in this.oDrawings.items) { var nIndex = this.oDrawings.items[src]; aDrawings[nIndex] = src; } for(var i = 0, length = aDrawings.length; i < length; ++i) { var src = aDrawings[i]; this.bs.WriteItem(c_oSer_OtherType.MediaItem, function(){oThis.WriteMediaItem(src, i);}); } }; this.WriteMediaItem = function(src, index) { var oThis = this; if(null != src) { this.memory.WriteByte(c_oSer_OtherType.MediaSrc); this.memory.WriteString2(src); } if(null != index) this.bs.WriteItem(c_oSer_OtherType.MediaId, function(){oThis.memory.WriteLong(index);}); }; }; /** @constructor */ function BinaryFileWriter(wb) { this.Memory = new CMemory(); this.wb = wb; this.nLastFilePos = 0; this.nRealTableCount = 0; this.bs = new BinaryCommonWriter(this.Memory); this.Write = function(idWorksheet) { //если idWorksheet не null, то надо серализовать только его. this.WriteMainTable(idWorksheet); return this.WriteFileHeader(this.Memory.GetCurPosition()) + this.Memory.GetBase64Memory(); } this.WriteFileHeader = function(nDataSize) { return c_oSerFormat.Signature + ";v" + c_oSerFormat.Version + ";" + nDataSize + ";"; } this.WriteMainTable = function(idWorksheet) { var nTableCount = 128;//Специально ставим большое число, чтобы не увеличивать его при добавлении очередной таблицы. this.nRealTableCount = 0;//Специально ставим большое число, чтобы не увеличивать его при добавлении очередной таблицы. var nStart = this.Memory.GetCurPosition(); //вычисляем с какой позиции можно писать таблицы var nmtItemSize = 5;//5 byte this.nLastFilePos = nStart + nTableCount * nmtItemSize; //Write mtLen this.Memory.WriteByte(0); var oSharedStrings = {index: 0, strings: new Object()}; var oDrawings = {length: 0, items: new Object()}; //Write SharedStrings var nSharedStringsPos = this.ReserveTable(c_oSerTableTypes.SharedStrings); //Write Styles var nStylesTablePos = this.ReserveTable(c_oSerTableTypes.Styles); //Workbook this.WriteTable(c_oSerTableTypes.Workbook, new BinaryWorkbookTableWriter(this.Memory, this.wb)); //Worksheets var aXfs = new Array(); var aFonts = new Array(); var aFills = new Array(); var aBorders = new Array(); var aNums = new Array(); var aDxfs = new Array(); var oBinaryWorksheetsTableWriter = new BinaryWorksheetsTableWriter(this.Memory, this.wb, oSharedStrings, oDrawings, aDxfs, aXfs, aFonts, aFills, aBorders, aNums, idWorksheet); this.WriteTable(c_oSerTableTypes.Worksheets, oBinaryWorksheetsTableWriter); //OtherTable this.WriteTable(c_oSerTableTypes.Other, new BinaryOtherTableWriter(this.Memory, this.wb, oDrawings)); //Write SharedStrings this.WriteReserved(new BinarySharedStringsTableWriter(this.Memory, oSharedStrings), nSharedStringsPos); //Write Styles this.WriteReserved(new BinaryStylesTableWriter(this.Memory, this.wb, oBinaryWorksheetsTableWriter), nStylesTablePos); //Пишем количество таблиц this.Memory.Seek(nStart); this.Memory.WriteByte(this.nRealTableCount); //seek в конец, потому что GetBase64Memory заканчивает запись на текущей позиции. this.Memory.Seek(this.nLastFilePos); } this.WriteTable = function(type, oTableSer) { //Write mtItem //Write mtiType this.Memory.WriteByte(type); //Write mtiOffBits this.Memory.WriteLong(this.nLastFilePos); //Write table //Запоминаем позицию в MainTable var nCurPos = this.Memory.GetCurPosition(); //Seek в свободную область this.Memory.Seek(this.nLastFilePos); oTableSer.Write(); //сдвигаем позицию куда можно следующую таблицу this.nLastFilePos = this.Memory.GetCurPosition(); //Seek вобратно в MainTable this.Memory.Seek(nCurPos); this.nRealTableCount++; } this.ReserveTable = function(type) { var res = 0; //Write mtItem //Write mtiType this.Memory.WriteByte(type); res = this.Memory.GetCurPosition(); //Write mtiOffBits this.Memory.WriteLong(this.nLastFilePos); return res; } this.WriteReserved = function(oTableSer, nPos) { this.Memory.Seek(nPos); this.Memory.WriteLong(this.nLastFilePos); //Write table //Запоминаем позицию в MainTable var nCurPos = this.Memory.GetCurPosition(); //Seek в свободную область this.Memory.Seek(this.nLastFilePos); oTableSer.Write(); //сдвигаем позицию куда можно следующую таблицу this.nLastFilePos = this.Memory.GetCurPosition(); //Seek вобратно в MainTable this.Memory.Seek(nCurPos); this.nRealTableCount++; } }; /** @constructor */ function Binary_TableReader(stream, ws, Dxfs) { this.stream = stream; this.ws = ws; this.Dxfs = Dxfs; this.bcr = new Binary_CommonReader(this.stream); this.Read = function(length, aTables) { var res = c_oSerConstants.ReadOk; var oThis = this; res = this.bcr.Read1(length, function(t,l){ return oThis.ReadTables(t,l, aTables); }); return res; }; this.ReadTables = function(type, length, aTables) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_TablePart.Table == type ) { var oNewTable = new Object(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadTable(t,l, oNewTable); }); if(null != oNewTable.Ref && null != oNewTable.DisplayName) this.ws.workbook.oNameGenerator.addTableName(oNewTable.DisplayName, this.ws, oNewTable.Ref); aTables.push(oNewTable); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadTable = function(type, length, oTable) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_TablePart.Ref == type ) oTable.Ref = this.stream.GetString2LE(length); else if ( c_oSer_TablePart.HeaderRowCount == type ) oTable.HeaderRowCount = this.stream.GetULongLE(); else if ( c_oSer_TablePart.TotalsRowCount == type ) oTable.TotalsRowCount = this.stream.GetULongLE(); else if ( c_oSer_TablePart.DisplayName == type ) oTable.DisplayName = this.stream.GetString2LE(length); else if ( c_oSer_TablePart.AutoFilter == type ) { oTable.AutoFilter = new Object(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadAutoFilter(t,l, oTable.AutoFilter); }); } else if ( c_oSer_TablePart.SortState == type ) { oTable.SortState = new Object(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadSortState(t,l, oTable.SortState); }); } else if ( c_oSer_TablePart.TableColumns == type ) { oTable.TableColumns = new Array(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadTableColumns(t,l, oTable.TableColumns); }); } else if ( c_oSer_TablePart.TableStyleInfo == type ) { oTable.TableStyleInfo = new Object(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadTableStyleInfo(t,l, oTable.TableStyleInfo); }); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadAutoFilter = function(type, length, oAutoFilter) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_AutoFilter.Ref == type ) oAutoFilter.Ref = this.stream.GetString2LE(length); else if ( c_oSer_AutoFilter.FilterColumns == type ) { oAutoFilter.FilterColumns = new Array(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadFilterColumns(t,l, oAutoFilter.FilterColumns); }); } else if ( c_oSer_AutoFilter.SortState == type ) { oAutoFilter.SortState = new Object(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadSortState(t,l, oAutoFilter.SortState); }); } else res = c_oSerConstants.ReadUnknown; return res; } this.ReadFilterColumns = function(type, length, aFilterColumns) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_AutoFilter.FilterColumn == type ) { var oFilterColumn = {ColId: null, Filters: null, CustomFiltersObj: null, DynamicFilter: null, ColorFilter: null, Top10: null, ShowButton: true}; res = this.bcr.Read1(length, function(t,l){ return oThis.ReadFilterColumn(t,l, oFilterColumn); }); aFilterColumns.push(oFilterColumn); } else res = c_oSerConstants.ReadUnknown; return res; } this.ReadFilterColumn = function(type, length, oFilterColumn) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_FilterColumn.ColId == type ) oFilterColumn.ColId = this.stream.GetULongLE(); else if ( c_oSer_FilterColumn.Filters == type ) { oFilterColumn.Filters = {Values: new Array(), Dates: new Array(), Blank: null}; res = this.bcr.Read1(length, function(t,l){ return oThis.ReadFilters(t,l, oFilterColumn.Filters); }); } else if ( c_oSer_FilterColumn.CustomFilters == type ) { oFilterColumn.CustomFiltersObj = new Object(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadCustomFilters(t,l, oFilterColumn.CustomFiltersObj); }); } else if ( c_oSer_FilterColumn.DynamicFilter == type ) { oFilterColumn.DynamicFilter = new Object(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadDynamicFilter(t,l, oFilterColumn.DynamicFilter); }); }else if ( c_oSer_FilterColumn.ColorFilter == type ) { oFilterColumn.ColorFilter = new Object(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadColorFilter(t,l, oFilterColumn.ColorFilter); }); } else if ( c_oSer_FilterColumn.Top10 == type ) { oFilterColumn.Top10 = new Object(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadTop10(t,l, oFilterColumn.Top10); }); } else if ( c_oSer_FilterColumn.HiddenButton == type ) oFilterColumn.ShowButton = !this.stream.GetBool(); else if ( c_oSer_FilterColumn.ShowButton == type ) oFilterColumn.ShowButton = this.stream.GetBool(); else res = c_oSerConstants.ReadUnknown; return res; } this.ReadFilters = function(type, length, oFilters) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_FilterColumn.Filter == type ) { var oFilterVal = new Object(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadFilter(t,l, oFilterVal); }); if(null != oFilterVal.Val) oFilters.Values.push(oFilterVal.Val); } else if ( c_oSer_FilterColumn.DateGroupItem == type ) { var oDateGroupItem = new Object(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadDateGroupItem(t,l, oDateGroupItem); }); oFilters.Dates.push(oDateGroupItem); } else if ( c_oSer_FilterColumn.FiltersBlank == type ) oFilters.Blank = this.stream.GetBool(); else res = c_oSerConstants.ReadUnknown; return res; } this.ReadFilter = function(type, length, oFilter) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_Filter.Val == type ) oFilter.Val = this.stream.GetString2LE(length); else res = c_oSerConstants.ReadUnknown; return res; } this.ReadDateGroupItem = function(type, length, oDateGroupItem) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_DateGroupItem.DateTimeGrouping == type ) oDateGroupItem.DateTimeGrouping = this.stream.GetUChar(); else if ( c_oSer_DateGroupItem.Day == type ) oDateGroupItem.Day = this.stream.GetULongLE(); else if ( c_oSer_DateGroupItem.Hour == type ) oDateGroupItem.Hour = this.stream.GetULongLE(); else if ( c_oSer_DateGroupItem.Minute == type ) oDateGroupItem.Minute = this.stream.GetULongLE(); else if ( c_oSer_DateGroupItem.Month == type ) oDateGroupItem.Month = this.stream.GetULongLE(); else if ( c_oSer_DateGroupItem.Second == type ) oDateGroupItem.Second = this.stream.GetULongLE(); else if ( c_oSer_DateGroupItem.Year == type ) oDateGroupItem.Year = this.stream.GetULongLE(); else res = c_oSerConstants.ReadUnknown; return res; } this.ReadCustomFilters = function(type, length, oCustomFilters) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_CustomFilters.And == type ) oCustomFilters.And = this.stream.GetBool(); else if ( c_oSer_CustomFilters.CustomFilters == type ) { oCustomFilters.CustomFilters = new Array(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadCustomFiltersItems(t,l, oCustomFilters.CustomFilters); }); } else res = c_oSerConstants.ReadUnknown; return res; } this.ReadCustomFiltersItems = function(type, length, aCustomFilters) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_CustomFilters.CustomFilter == type ) { var oCustomFiltersItem = new Object(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadCustomFiltersItem(t,l, oCustomFiltersItem); }); aCustomFilters.push(oCustomFiltersItem); } else res = c_oSerConstants.ReadUnknown; return res; } this.ReadCustomFiltersItem = function(type, length, oCustomFiltersItem) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_CustomFilters.Operator == type ) oCustomFiltersItem.Operator = this.stream.GetUChar(); else if ( c_oSer_CustomFilters.Val == type ) oCustomFiltersItem.Val = this.stream.GetString2LE(length); else res = c_oSerConstants.ReadUnknown; return res; } this.ReadDynamicFilter = function(type, length, oDynamicFilter) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_DynamicFilter.Type == type ) oDynamicFilter.Type = this.stream.GetUChar(); else if ( c_oSer_DynamicFilter.Val == type ) oDynamicFilter.Val = this.stream.GetDoubleLE(); else if ( c_oSer_DynamicFilter.MaxVal == type ) oDynamicFilter.MaxVal = this.stream.GetDoubleLE(); else res = c_oSerConstants.ReadUnknown; return res; } this.ReadColorFilter = function(type, length, oColorFilter) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_ColorFilter.CellColor == type ) oColorFilter.CellColor = this.stream.GetBool(); else if ( c_oSer_ColorFilter.DxfId == type ) { var DxfId = this.stream.GetULongLE(); var dxf = this.Dxfs[DxfId]; oColorFilter.dxf = dxf; } else res = c_oSerConstants.ReadUnknown; return res; } this.ReadTop10 = function(type, length, oTop10) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_Top10.FilterVal == type ) oTop10.FilterVal = this.stream.GetDoubleLE(); else if ( c_oSer_Top10.Percent == type ) oTop10.Percent = this.stream.GetBool(); else if ( c_oSer_Top10.Top == type ) oTop10.Top = this.stream.GetBool(); else if ( c_oSer_Top10.Val == type ) oTop10.Val = this.stream.GetDoubleLE(); else res = c_oSerConstants.ReadUnknown; return res; } this.ReadSortConditionContent = function(type, length, oSortCondition) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_SortState.ConditionRef == type ) oSortCondition.Ref = this.stream.GetString2LE(length); else if ( c_oSer_SortState.ConditionSortBy == type ) oSortCondition.ConditionSortBy = this.stream.GetUChar(); else if ( c_oSer_SortState.ConditionDescending == type ) oSortCondition.ConditionDescending = this.stream.GetBool(); else if ( c_oSer_SortState.ConditionDxfId == type ) { var DxfId = this.stream.GetULongLE(); var dxf = this.Dxfs[DxfId]; oSortCondition.dxf = dxf; } else res = c_oSerConstants.ReadUnknown; return res; } this.ReadSortCondition = function(type, length, aSortConditions) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_SortState.SortCondition == type ) { var oSortCondition = new Object(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadSortConditionContent(t,l, oSortCondition); }); aSortConditions.push(oSortCondition); } else res = c_oSerConstants.ReadUnknown; return res; } this.ReadSortState = function(type, length, oSortState) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_SortState.Ref == type ) oSortState.Ref = this.stream.GetString2LE(length); else if ( c_oSer_SortState.CaseSensitive == type ) oSortState.CaseSensitive = this.stream.GetBool(); else if ( c_oSer_SortState.SortConditions == type ) { oSortState.SortConditions = new Array(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadSortCondition(t,l, oSortState.SortConditions); }); } else res = c_oSerConstants.ReadUnknown; return res; } this.ReadTableColumn = function(type, length, oTableColumn) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_TableColumns.Name == type ) oTableColumn.Name = this.stream.GetString2LE(length); else if ( c_oSer_TableColumns.TotalsRowLabel == type ) oTableColumn.TotalsRowLabel = this.stream.GetString2LE(length); else if ( c_oSer_TableColumns.TotalsRowFunction == type ) oTableColumn.TotalsRowFunction = this.stream.GetUChar(); else if ( c_oSer_TableColumns.TotalsRowFormula == type ) oTableColumn.TotalsRowFormula = this.stream.GetString2LE(length); else if ( c_oSer_TableColumns.DataDxfId == type ) { var DxfId = this.stream.GetULongLE(); var dxf = this.Dxfs[DxfId]; oTableColumn.dxf = dxf; } else if ( c_oSer_TableColumns.CalculatedColumnFormula == type ) oTableColumn.CalculatedColumnFormula = this.stream.GetString2LE(length); else res = c_oSerConstants.ReadUnknown; return res; } this.ReadTableColumns = function(type, length, aTableColumns) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_TableColumns.TableColumn == type ) { var oTableColumn = new Object(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadTableColumn(t,l, oTableColumn); }); aTableColumns.push(oTableColumn); } else res = c_oSerConstants.ReadUnknown; return res; } this.ReadTableStyleInfo = function(type, length, oTableStyleInfo) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_TableStyleInfo.Name == type ) oTableStyleInfo.Name = this.stream.GetString2LE(length); else if ( c_oSer_TableStyleInfo.ShowColumnStripes == type ) oTableStyleInfo.ShowColumnStripes = this.stream.GetBool(); else if ( c_oSer_TableStyleInfo.ShowRowStripes == type ) oTableStyleInfo.ShowRowStripes = this.stream.GetBool(); else if ( c_oSer_TableStyleInfo.ShowFirstColumn == type ) oTableStyleInfo.ShowFirstColumn = this.stream.GetBool(); else if ( c_oSer_TableStyleInfo.ShowLastColumn == type ) oTableStyleInfo.ShowLastColumn = this.stream.GetBool(); else res = c_oSerConstants.ReadUnknown; return res; }; }; /** @constructor */ function Binary_SharedStringTableReader(stream, wb, aSharedStrings) { this.stream = stream; this.wb = wb; this.aSharedStrings = aSharedStrings; this.bcr = new Binary_CommonReader(this.stream); this.Read = function() { var oThis = this; return this.bcr.ReadTable(function(t, l){ return oThis.ReadSharedStringContent(t,l); }); }; this.ReadSharedStringContent = function(type, length) { var res = c_oSerConstants.ReadOk; if ( c_oSerSharedStringTypes.Si === type ) { var oThis = this; var Si = new CCellValue(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadSharedString(t,l,Si); }); if(null != this.aSharedStrings) this.aSharedStrings.push(Si); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadSharedString = function(type, length, Si) { var res = c_oSerConstants.ReadOk; if ( c_oSerSharedStringTypes.Run == type ) { var oThis = this; var oRun = new CCellValueMultiText(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadRun(t,l,oRun); }); if(null == Si.multiText) Si.multiText = new Array(); Si.multiText.push(oRun); } else if ( c_oSerSharedStringTypes.Text == type ) { if(null == Si.text) Si.text = ""; Si.text += this.stream.GetString2LE(length); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadRun = function(type, length, oRun) { var oThis = this; var res = c_oSerConstants.ReadOk; if ( c_oSerSharedStringTypes.RPr == type ) { if(null == oRun.format) oRun.format = new Font(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadRPr(t,l, oRun.format); }); } else if ( c_oSerSharedStringTypes.Text == type ) { if(null == oRun.text) oRun.text = ""; oRun.text += this.stream.GetString2LE(length); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadRPr = function(type, length, rPr) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerFontTypes.Bold == type ) rPr.b = this.stream.GetBool(); else if ( c_oSerFontTypes.Color == type ) { var color = new OpenColor(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.bcr.ReadColorSpreadsheet(t,l, color); }); if(null != color.theme) rPr.c = g_oColorManager.getThemeColor(color.theme, color.tint); else if(null != color.rgb) rPr.c = new RgbColor(0x00ffffff & color.rgb); } else if ( c_oSerFontTypes.Italic == type ) rPr.i = this.stream.GetBool(); else if ( c_oSerFontTypes.RFont == type ) rPr.fn = this.stream.GetString2LE(length); else if ( c_oSerFontTypes.Strike == type ) rPr.s = this.stream.GetBool(); else if ( c_oSerFontTypes.Sz == type ) rPr.fs = this.stream.GetDoubleLE(); else if ( c_oSerFontTypes.Underline == type ) { switch(this.stream.GetUChar()) { case EUnderline.underlineDouble: rPr.u = "double";break; case EUnderline.underlineDoubleAccounting: rPr.u = "doubleAccounting";break; case EUnderline.underlineNone: rPr.u = "none";break; case EUnderline.underlineSingle: rPr.u = "single";break; case EUnderline.underlineSingleAccounting: rPr.u = "singleAccounting";break; default: rPr.u = "none";break; } } else if ( c_oSerFontTypes.VertAlign == type ) { switch(this.stream.GetUChar()) { case EVerticalAlignRun.verticalalignrunBaseline: rPr.va = "baseline";break; case EVerticalAlignRun.verticalalignrunSubscript: rPr.va = "subscript";break; case EVerticalAlignRun.verticalalignrunSuperscript: rPr.va = "superscript";break; default: rPr.va = "baseline";break; } } else res = c_oSerConstants.ReadUnknown; return res; }; }; /** @constructor */ function Binary_StylesTableReader(stream, wb, aCellXfs, Dxfs) { this.stream = stream; this.wb = wb; this.oStyleManager = wb.oStyleManager; this.aCellXfs = aCellXfs; this.Dxfs = Dxfs; this.bcr = new Binary_CommonReader(this.stream); this.bssr = new Binary_SharedStringTableReader(this.stream, wb); this.Read = function() { var oThis = this; var oStyleObject = {aBorders: [], aFills: [], aFonts: [], oNumFmts: {}, aCellStyleXfs: [], aCellXfs: [], aCellStyles: [], oCustomTableStyles: {}}; var res = this.bcr.ReadTable(function (t, l) { return oThis.ReadStylesContent(t, l, oStyleObject); }); this.InitStyleManager(oStyleObject); return res; }; this.InitStyleManager = function (oStyleObject) { for(var i = 0, length = oStyleObject.aCellXfs.length; i < length; ++i) { var xfs = oStyleObject.aCellXfs[i]; var oNewXfs = new CellXfs(); if(null != xfs.borderid) { var border = oStyleObject.aBorders[xfs.borderid]; if(null != border) oNewXfs.border = border.clone(); } if(null != xfs.fillid) { var fill = oStyleObject.aFills[xfs.fillid]; if(null != fill) oNewXfs.fill = fill.clone(); } if(null != xfs.fontid) { var font = oStyleObject.aFonts[xfs.fontid]; if(null != font) oNewXfs.font = font.clone(); } if(null != xfs.numid) { var oCurNum = oStyleObject.oNumFmts[xfs.numid]; if(null != oCurNum) oNewXfs.num = this.ParseNum(oCurNum, oStyleObject.oNumFmts); else oNewXfs.num = this.ParseNum({id: xfs.numid, f: null}, oStyleObject.oNumFmts); } if(null != xfs.QuotePrefix) oNewXfs.QuotePrefix = xfs.QuotePrefix; if(null != xfs.align) oNewXfs.align = xfs.align.clone(); if (null !== xfs.XfId) oNewXfs.XfId = xfs.XfId; if(0 == this.aCellXfs.length) this.oStyleManager.init(oNewXfs); this.minimizeXfs(oNewXfs); this.aCellXfs.push(oNewXfs); } for (var nIndex in oStyleObject.aCellStyles) { if (!oStyleObject.aCellStyles.hasOwnProperty(nIndex)) continue; var oCellStyle = oStyleObject.aCellStyles[nIndex]; var oCellStyleXfs = oStyleObject.aCellStyleXfs[oCellStyle.XfId]; oCellStyle.xfs = new CellXfs(); // Border if (null != oCellStyleXfs.borderid) { var borderCellStyle = oStyleObject.aBorders[oCellStyleXfs.borderid]; if(null != borderCellStyle) oCellStyle.xfs.border = borderCellStyle.clone(); } // Fill if (null != oCellStyleXfs.fillid) { var fillCellStyle = oStyleObject.aFills[oCellStyleXfs.fillid]; if(null != fillCellStyle) oCellStyle.xfs.fill = fillCellStyle.clone(); } // Font if(null != oCellStyleXfs.fontid) { var fontCellStyle = oStyleObject.aFonts[oCellStyleXfs.fontid]; if(null != fontCellStyle) oCellStyle.xfs.font = fontCellStyle.clone(); } // NumFmt if(null != oCellStyleXfs.numid) { var oCurNumCellStyle = oStyleObject.oNumFmts[oCellStyleXfs.numid]; if(null != oCurNumCellStyle) oCellStyle.xfs.num = this.ParseNum(oCurNumCellStyle, oStyleObject.oNumFmts); else oCellStyle.xfs.num = this.ParseNum({id: oCellStyleXfs.numid, f: null}, oStyleObject.oNumFmts); } // QuotePrefix if(null != oCellStyleXfs.QuotePrefix) oCellStyle.xfs.QuotePrefix = oCellStyleXfs.QuotePrefix; // align if(null != oCellStyleXfs.align) oCellStyle.xfs.align = oCellStyleXfs.align.clone(); // XfId if (null !== oCellStyleXfs.XfId) oCellStyle.xfs.XfId = oCellStyleXfs.XfId; // ApplyBorder (ToDo возможно это свойство должно быть в xfs) if (null !== oCellStyleXfs.ApplyBorder) oCellStyle.ApplyBorder = oCellStyleXfs.ApplyBorder; // ApplyFill (ToDo возможно это свойство должно быть в xfs) if (null !== oCellStyleXfs.ApplyFill) oCellStyle.ApplyFill = oCellStyleXfs.ApplyFill; // ApplyFont (ToDo возможно это свойство должно быть в xfs) if (null !== oCellStyleXfs.ApplyFont) oCellStyle.ApplyFont = oCellStyleXfs.ApplyFont; // ApplyNumberFormat (ToDo возможно это свойство должно быть в xfs) if (null !== oCellStyleXfs.ApplyNumberFormat) oCellStyle.ApplyNumberFormat = oCellStyleXfs.ApplyNumberFormat; this.wb.CellStyles.CustomStyles[oCellStyle.XfId] = oCellStyle; } for(var i in oStyleObject.oCustomTableStyles) { var item = oStyleObject.oCustomTableStyles[i]; if(null != item) { var style = item.style; var elems = item.elements; this.initTableStyle(style, elems, this.Dxfs); this.wb.TableStyles.CustomStyles[i] = style; } } }; this.initTableStyle = function(style, elems, Dxfs) { for(var j = 0, length2 = elems.length; j < length2; ++j) { var elem = elems[j]; if(null != elem.DxfId) { var Dxf = Dxfs[elem.DxfId]; if(null != Dxf) { this.minimizeXfs(Dxf); var oTableStyleElement = new CTableStyleElement(); oTableStyleElement.dxf = Dxf; if(null != elem.Size) oTableStyleElement.size = elem.Size; switch(elem.Type) { case ETableStyleType.tablestyletypeBlankRow: style.blankRow = oTableStyleElement;break; case ETableStyleType.tablestyletypeFirstColumn: style.firstColumn = oTableStyleElement;break; case ETableStyleType.tablestyletypeFirstColumnStripe: style.firstColumnStripe = oTableStyleElement;break; case ETableStyleType.tablestyletypeFirstColumnSubheading: style.firstColumnSubheading = oTableStyleElement;break; case ETableStyleType.tablestyletypeFirstHeaderCell: style.firstHeaderCell = oTableStyleElement;break; case ETableStyleType.tablestyletypeFirstRowStripe: style.firstRowStripe = oTableStyleElement;break; case ETableStyleType.tablestyletypeFirstRowSubheading: style.firstRowSubheading = oTableStyleElement;break; case ETableStyleType.tablestyletypeFirstSubtotalColumn: style.firstSubtotalColumn = oTableStyleElement;break; case ETableStyleType.tablestyletypeFirstSubtotalRow: style.firstSubtotalRow = oTableStyleElement;break; case ETableStyleType.tablestyletypeFirstTotalCell: style.firstTotalCell = oTableStyleElement;break; case ETableStyleType.tablestyletypeHeaderRow: style.headerRow = oTableStyleElement;break; case ETableStyleType.tablestyletypeLastColumn: style.lastColumn = oTableStyleElement;break; case ETableStyleType.tablestyletypeLastHeaderCell: style.lastHeaderCell = oTableStyleElement;break; case ETableStyleType.tablestyletypeLastTotalCell: style.lastTotalCell = oTableStyleElement;break; case ETableStyleType.tablestyletypePageFieldLabels: style.pageFieldLabels = oTableStyleElement;break; case ETableStyleType.tablestyletypePageFieldValues: style.pageFieldValues = oTableStyleElement;break; case ETableStyleType.tablestyletypeSecondColumnStripe: style.secondColumnStripe = oTableStyleElement;break; case ETableStyleType.tablestyletypeSecondColumnSubheading: style.secondColumnSubheading = oTableStyleElement;break; case ETableStyleType.tablestyletypeSecondRowStripe: style.secondRowStripe = oTableStyleElement;break; case ETableStyleType.tablestyletypeSecondRowSubheading: style.secondRowSubheading = oTableStyleElement;break; case ETableStyleType.tablestyletypeSecondSubtotalColumn: style.secondSubtotalColumn = oTableStyleElement;break; case ETableStyleType.tablestyletypeSecondSubtotalRow: style.secondSubtotalRow = oTableStyleElement;break; case ETableStyleType.tablestyletypeThirdColumnSubheading: style.thirdColumnSubheading = oTableStyleElement;break; case ETableStyleType.tablestyletypeThirdRowSubheading: style.thirdRowSubheading = oTableStyleElement;break; case ETableStyleType.tablestyletypeThirdSubtotalColumn: style.thirdSubtotalColumn = oTableStyleElement;break; case ETableStyleType.tablestyletypeThirdSubtotalRow: style.thirdSubtotalRow = oTableStyleElement;break; case ETableStyleType.tablestyletypeTotalRow: style.totalRow = oTableStyleElement;break; case ETableStyleType.tablestyletypeWholeTable: style.wholeTable = oTableStyleElement;break; } } } } }; this.minimizeXfs = function(xfs) { if(null != xfs.border && g_oDefaultBorder.isEqual(xfs.border)) xfs.border = null; if(null != xfs.fill && g_oDefaultFill.isEqual(xfs.fill)) xfs.fill = null; if(null != xfs.font && g_oDefaultFont.isEqual(xfs.font)) xfs.font = null; if(null != xfs.num && g_oDefaultNum.isEqual(xfs.num)) xfs.num = null; if(null != xfs.align && g_oDefaultAlign.isEqual(xfs.align)) xfs.align = null; }; this.ParseNum = function(oNum, oNumFmts) { var oRes = null; var sFormat = null; if(null != oNum && null != oNum.f) sFormat = oNum.f; else { if(5 <= oNum.id && oNum.id <= 8) { //В спецификации нет стилей для чисел 5-8, экспериментально установлено, что это денежный формат, зависящий от локали. //Устанавливаем как в Engilsh(US) sFormat = "$#,##0.00_);[Red]($#,##0.00)"; } else { var sStandartNumFormat = aStandartNumFormats[oNum.id]; if(null != sStandartNumFormat) sFormat = sStandartNumFormat; } if(null == sFormat) sFormat = "General"; if(null != oNumFmts) oNumFmts[oNum.id] = {id:oNum.id, f: sFormat}; } if(null != sFormat && "General" != sFormat) { oRes = new Num(); oRes.f = sFormat; } return oRes; }; this.ReadStylesContent = function (type, length, oStyleObject) { var res = c_oSerConstants.ReadOk; var oThis = this; if (c_oSerStylesTypes.Borders === type) { res = this.bcr.Read1(length, function (t, l) { return oThis.ReadBorders(t, l, oStyleObject.aBorders); }); } else if (c_oSerStylesTypes.Fills === type) { res = this.bcr.Read1(length, function (t, l) { return oThis.ReadFills(t, l, oStyleObject.aFills); }); } else if (c_oSerStylesTypes.Fonts === type) { res = this.bcr.Read1(length, function (t, l) { return oThis.ReadFonts(t, l, oStyleObject.aFonts); }); } else if (c_oSerStylesTypes.NumFmts === type) { res = this.bcr.Read1(length, function (t, l) { return oThis.ReadNumFmts(t, l, oStyleObject.oNumFmts); }); } else if (c_oSerStylesTypes.CellStyleXfs === type) { res = this.bcr.Read1(length, function (t, l) { return oThis.ReadCellStyleXfs(t, l, oStyleObject.aCellStyleXfs); }); } else if (c_oSerStylesTypes.CellXfs === type) { res = this.bcr.Read1(length, function (t, l) { return oThis.ReadCellXfs(t,l, oStyleObject.aCellXfs); }); } else if (c_oSerStylesTypes.CellStyles === type) { res = this.bcr.Read1(length, function (t, l) { return oThis.ReadCellStyles(t, l, oStyleObject.aCellStyles); }); } else if (c_oSerStylesTypes.Dxfs === type) { res = this.bcr.Read1(length, function (t, l) { return oThis.ReadDxfs(t, l, oThis.Dxfs); }); } else if (c_oSerStylesTypes.TableStyles === type) { res = this.bcr.Read1(length, function (t, l){ return oThis.ReadTableStyles(t, l, oThis.wb.TableStyles, oStyleObject.oCustomTableStyles); }); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadBorders = function(type, length, aBorders) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerStylesTypes.Border == type ) { var oNewBorder = new Border(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadBorder(t,l,oNewBorder); }); aBorders.push(oNewBorder); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadBorder = function(type, length, oNewBorder) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerBorderTypes.Bottom == type ) { res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadBorderProp(t,l,oNewBorder.b); }); } else if ( c_oSerBorderTypes.Diagonal == type ) { res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadBorderProp(t,l,oNewBorder.d); }); } else if ( c_oSerBorderTypes.End == type ) { res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadBorderProp(t,l,oNewBorder.r); }); } else if ( c_oSerBorderTypes.Horizontal == type ) { res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadBorderProp(t,l,oNewBorder.ih); }); } else if ( c_oSerBorderTypes.Start == type ) { res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadBorderProp(t,l,oNewBorder.l); }); } else if ( c_oSerBorderTypes.Top == type ) { res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadBorderProp(t,l,oNewBorder.t); }); } else if ( c_oSerBorderTypes.Vertical == type ) { res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadBorderProp(t,l,oNewBorder.iv); }); } else if ( c_oSerBorderTypes.DiagonalDown == type ) { oNewBorder.dd = this.stream.GetBool(); } else if ( c_oSerBorderTypes.DiagonalUp == type ) { oNewBorder.du = this.stream.GetBool(); } // else if ( c_oSerBorderTypes.Outline == type ) // { // oNewBorder.outline = this.stream.GetBool(); // } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadBorderProp = function(type, length, oBorderProp) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerBorderPropTypes.Style == type ) { switch(this.stream.GetUChar()) { case EBorderStyle.borderstyleDashDot:oBorderProp.s = "dashDot";break; case EBorderStyle.borderstyleDashDotDot:oBorderProp.s = "dashDotDot";break; case EBorderStyle.borderstyleDashed:oBorderProp.s = "dashed";break; case EBorderStyle.borderstyleDotted:oBorderProp.s = "dotted";break; case EBorderStyle.borderstyleDouble:oBorderProp.s = "double";break; case EBorderStyle.borderstyleHair:oBorderProp.s = "hair";break; case EBorderStyle.borderstyleMedium:oBorderProp.s = "medium";break; case EBorderStyle.borderstyleMediumDashDot:oBorderProp.s = "mediumDashDot";break; case EBorderStyle.borderstyleMediumDashDotDot:oBorderProp.s = "mediumDashDotDot";break; case EBorderStyle.borderstyleMediumDashed:oBorderProp.s = "mediumDashed";break; case EBorderStyle.borderstyleNone:oBorderProp.s = "none";break; case EBorderStyle.borderstyleSlantDashDot:oBorderProp.s = "slantDashDot";break; case EBorderStyle.borderstyleThick:oBorderProp.s = "thick";break; case EBorderStyle.borderstyleThin:oBorderProp.s = "thin";break; default :oBorderProp.s = "none";break; } } else if ( c_oSerBorderPropTypes.Color == type ) { var color = new OpenColor(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.bcr.ReadColorSpreadsheet(t,l, color); }); if(null != color.theme) oBorderProp.c = g_oColorManager.getThemeColor(color.theme, color.tint); else if(null != color.rgb) oBorderProp.c = new RgbColor(0x00ffffff & color.rgb); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadCellStyleXfs = function (type, length, aCellStyleXfs) { var res = c_oSerConstants.ReadOk; var oThis = this; if (c_oSerStylesTypes.Xfs === type) { var oNewXfs = {ApplyAlignment: null, ApplyBorder: null, ApplyFill: null, ApplyFont: null, ApplyNumberFormat: null, BorderId: null, FillId: null, FontId: null, NumFmtId: null, QuotePrefix: null, Aligment: null}; res = this.bcr.Read2Spreadsheet(length, function (t, l) { return oThis.ReadXfs(t, l, oNewXfs); }); aCellStyleXfs.push(oNewXfs); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadCellXfs = function(type, length, aCellXfs) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerStylesTypes.Xfs == type ) { var oNewXfs = {ApplyAlignment: null, ApplyBorder: null, ApplyFill: null, ApplyFont: null, ApplyNumberFormat: null, BorderId: null, FillId: null, FontId: null, NumFmtId: null, QuotePrefix: null, Aligment: null, XfId: null}; res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadXfs(t,l,oNewXfs); }); aCellXfs.push(oNewXfs); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadXfs = function(type, length, oXfs) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerXfsTypes.ApplyAlignment == type ) oXfs.ApplyAlignment = this.stream.GetBool(); else if ( c_oSerXfsTypes.ApplyBorder == type ) oXfs.ApplyBorder = this.stream.GetBool(); else if ( c_oSerXfsTypes.ApplyFill == type ) oXfs.ApplyFill = this.stream.GetBool(); else if ( c_oSerXfsTypes.ApplyFont == type ) oXfs.ApplyFont = this.stream.GetBool(); else if ( c_oSerXfsTypes.ApplyNumberFormat == type ) oXfs.ApplyNumberFormat = this.stream.GetBool(); else if ( c_oSerXfsTypes.BorderId == type ) oXfs.borderid = this.stream.GetULongLE(); else if ( c_oSerXfsTypes.FillId == type ) oXfs.fillid = this.stream.GetULongLE(); else if ( c_oSerXfsTypes.FontId == type ) oXfs.fontid = this.stream.GetULongLE(); else if ( c_oSerXfsTypes.NumFmtId == type ) oXfs.numid = this.stream.GetULongLE(); else if ( c_oSerXfsTypes.QuotePrefix == type ) oXfs.QuotePrefix = this.stream.GetBool(); else if (c_oSerXfsTypes.XfId === type) oXfs.XfId = this.stream.GetULongLE(); else if ( c_oSerXfsTypes.Aligment == type ) { if(null == oXfs.Aligment) oXfs.align = new Align(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadAligment(t,l,oXfs.align); }); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadAligment = function(type, length, oAligment) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerAligmentTypes.Horizontal == type ) { switch(this.stream.GetUChar()) { case EHorizontalAlignment.horizontalalignmentCenter : oAligment.hor = "center";break; case EHorizontalAlignment.horizontalalignmentContinuous : oAligment.hor = "center";break; case EHorizontalAlignment.horizontalalignmentDistributed : oAligment.hor = "justify";break; case EHorizontalAlignment.horizontalalignmentFill : oAligment.hor = "justify";break; case EHorizontalAlignment.horizontalalignmentGeneral : oAligment.hor = "none";break; case EHorizontalAlignment.horizontalalignmentJustify : oAligment.hor = "justify";break; case EHorizontalAlignment.horizontalalignmentLeft : oAligment.hor = "left";break; case EHorizontalAlignment.horizontalalignmentRight : oAligment.hor = "right";break; } } else if ( c_oSerAligmentTypes.Indent == type ) oAligment.indent = this.stream.GetULongLE(); else if ( c_oSerAligmentTypes.RelativeIndent == type ) oAligment.RelativeIndent = this.stream.GetULongLE(); else if ( c_oSerAligmentTypes.ShrinkToFit == type ) oAligment.shrink = this.stream.GetBool(); else if ( c_oSerAligmentTypes.TextRotation == type ) oAligment.angle = this.stream.GetULongLE(); else if ( c_oSerAligmentTypes.Vertical == type ) { switch(this.stream.GetUChar()) { case EVerticalAlignment.verticalalignmentBottom : oAligment.ver = "bottom";break; case EVerticalAlignment.verticalalignmentCenter : oAligment.ver = "center";break; case EVerticalAlignment.verticalalignmentDistributed : oAligment.ver = "distributed";break; case EVerticalAlignment.verticalalignmentJustify : oAligment.ver = "justify";break; case EVerticalAlignment.verticalalignmentTop : oAligment.ver = "top";break; } } else if ( c_oSerAligmentTypes.WrapText == type ) oAligment.wrap= this.stream.GetBool(); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadFills = function(type, length, aFills) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerStylesTypes.Fill == type ) { var oNewFill = new Fill(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadFill(t,l,oNewFill); }); aFills.push(oNewFill); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadFill = function(type, length, oFill) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerFillTypes.PatternFill == type ) { res = this.bcr.Read1(length, function(t,l){ return oThis.ReadPatternFill(t,l,oFill); }); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadPatternFill = function(type, length, oFill) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerFillTypes.PatternFillBgColor == type ) { var color = new OpenColor(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.bcr.ReadColorSpreadsheet(t,l, color); }); if(null != color.theme) oFill.bg = g_oColorManager.getThemeColor(color.theme, color.tint); else if(null != color.rgb) oFill.bg = new RgbColor(0x00ffffff & color.rgb); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadFonts = function(type, length, aFonts) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerStylesTypes.Font == type ) { var oNewFont = new Font(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.bssr.ReadRPr(t,l,oNewFont); }); aFonts.push(oNewFont); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadNumFmts = function(type, length, oNumFmts) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerStylesTypes.NumFmt == type ) { var oNewNumFmt = {f: null, id: null}; res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadNumFmt(t,l,oNewNumFmt); }); if(null != oNewNumFmt.id && null != oNewNumFmt.f) oNumFmts[oNewNumFmt.id] = oNewNumFmt; } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadNumFmt = function(type, length, oNumFmt) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerNumFmtTypes.FormatCode == type ) { oNumFmt.f = this.stream.GetString2LE(length); } else if ( c_oSerNumFmtTypes.NumFmtId == type ) { oNumFmt.id = this.stream.GetULongLE();; } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadCellStyles = function (type, length, aCellStyles) { var res = c_oSerConstants.ReadOk; var oThis = this; var oCellStyle = null; if (c_oSerStylesTypes.CellStyle === type) { oCellStyle = new CCellStyle(); res = this.bcr.Read1(length, function (t, l) { return oThis.ReadCellStyle(t, l, oCellStyle); }); aCellStyles.push(oCellStyle); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadCellStyle = function (type, length, oCellStyle) { var res = c_oSerConstants.ReadOk; if (c_oSer_CellStyle.BuiltinId === type) oCellStyle.BuiltinId = this.stream.GetULongLE(); else if (c_oSer_CellStyle.CustomBuiltin === type) oCellStyle.CustomBuiltin = this.stream.GetBool(); else if (c_oSer_CellStyle.Hidden === type) oCellStyle.Hidden = this.stream.GetBool(); else if (c_oSer_CellStyle.ILevel === type) oCellStyle.ILevel = this.stream.GetULongLE(); else if (c_oSer_CellStyle.Name === type) oCellStyle.Name = this.stream.GetString2LE(length); else if (c_oSer_CellStyle.XfId === type) oCellStyle.XfId = this.stream.GetULongLE(); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadDxfs = function(type, length, aDxfs) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerStylesTypes.Dxf == type ) { var oDxf = new CellXfs(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadDxf(t,l,oDxf); }); aDxfs.push(oDxf); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadDxf = function(type, length, oDxf) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_Dxf.Alignment == type ) { oDxf.align = new Align(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadAligment(t,l,oDxf.align); }); } else if ( c_oSer_Dxf.Border == type ) { var oNewBorder = new Border(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadBorder(t,l,oNewBorder); }); oDxf.border = oNewBorder; } else if ( c_oSer_Dxf.Fill == type ) { var oNewFill = new Fill(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadFill(t,l,oNewFill); }); oDxf.fill = oNewFill; } else if ( c_oSer_Dxf.Font == type ) { var oNewFont = new Font(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.bssr.ReadRPr(t,l,oNewFont); }); oDxf.font = oNewFont; } else if ( c_oSer_Dxf.NumFmt == type ) { var oNewNumFmt = {f: null, id: null}; res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadNumFmt(t,l,oNewNumFmt); }); if(null != oNewNumFmt.id) oDxf.num = this.ParseNum({id: oNewNumFmt.id, f: null}, null); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadTableStyles = function(type, length, oTableStyles, oCustomStyles) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_TableStyles.DefaultTableStyle == type ) oTableStyles.DefaultTableStyle = this.stream.GetString2LE(length); else if ( c_oSer_TableStyles.DefaultPivotStyle == type ) oTableStyles.DefaultPivotStyle = this.stream.GetString2LE(length); else if ( c_oSer_TableStyles.TableStyles == type ) { res = this.bcr.Read1(length, function(t,l){ return oThis.ReadTableCustomStyles(t,l, oCustomStyles); }); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadTableCustomStyles = function(type, length, oCustomStyles) { var res = c_oSerConstants.ReadOk; var oThis = this; if (c_oSer_TableStyles.TableStyle === type) { var oNewStyle = new CTableStyle(); var aElements = new Array(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadTableCustomStyle(t,l, oNewStyle, aElements); }); if(null != oNewStyle.name && aElements.length > 0) oCustomStyles[oNewStyle.name] = {style : oNewStyle, elements: aElements}; } else res = c_oSerConstants.ReadUnknown; return res; } this.ReadTableCustomStyle = function(type, length, oNewStyle, aElements) { var res = c_oSerConstants.ReadOk; var oThis = this; if (c_oSer_TableStyle.Name === type) oNewStyle.name = this.stream.GetString2LE(length); else if (c_oSer_TableStyle.Pivot === type) oNewStyle.pivot = this.stream.GetBool(); else if (c_oSer_TableStyle.Table === type) oNewStyle.table = this.stream.GetBool(); else if (c_oSer_TableStyle.Elements === type) { res = this.bcr.Read1(length, function(t,l){ return oThis.ReadTableCustomStyleElements(t,l, aElements); }); } else res = c_oSerConstants.ReadUnknown; return res; } this.ReadTableCustomStyleElements = function(type, length, aElements) { var res = c_oSerConstants.ReadOk; var oThis = this; if (c_oSer_TableStyle.Element === type) { var oNewStyleElement = {Type: null, Size: null, DxfId: null}; res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadTableCustomStyleElement(t,l, oNewStyleElement); }); if(null != oNewStyleElement.Type && null != oNewStyleElement.DxfId) aElements.push(oNewStyleElement); } else res = c_oSerConstants.ReadUnknown; return res; } this.ReadTableCustomStyleElement = function(type, length, oNewStyleElement) { var res = c_oSerConstants.ReadOk; var oThis = this; if (c_oSer_TableStyleElement.Type === type) oNewStyleElement.Type = this.stream.GetUChar(); else if (c_oSer_TableStyleElement.Size === type) oNewStyleElement.Size = this.stream.GetULongLE(); else if (c_oSer_TableStyleElement.DxfId === type) oNewStyleElement.DxfId = this.stream.GetULongLE(); else res = c_oSerConstants.ReadUnknown; return res; } }; /** @constructor */ function Binary_WorkbookTableReader(stream, oWorkbook) { this.stream = stream; this.oWorkbook = oWorkbook; this.bcr = new Binary_CommonReader(this.stream); this.Read = function() { var oThis = this; return this.bcr.ReadTable(function(t, l){ return oThis.ReadWorkbookContent(t,l); }); }; this.ReadWorkbookContent = function(type, length) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerWorkbookTypes.WorkbookPr === type ) { if(null == this.oWorkbook.WorkbookPr) this.oWorkbook.WorkbookPr = new Object(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadWorkbookPr(t,l,oThis.oWorkbook.WorkbookPr); }); } else if ( c_oSerWorkbookTypes.BookViews === type ) { res = this.bcr.Read1(length, function(t,l){ return oThis.ReadBookViews(t,l); }); } else if ( c_oSerWorkbookTypes.DefinedNames === type ) { res = this.bcr.Read1(length, function(t,l){ return oThis.ReadDefinedNames(t,l); }); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadWorkbookPr = function(type, length, WorkbookPr) { var res = c_oSerConstants.ReadOk; if ( c_oSerWorkbookPrTypes.Date1904 == type ) { WorkbookPr.Date1904 = this.stream.GetBool(); g_bDate1904 = WorkbookPr.Date1904; c_DateCorrectConst = g_bDate1904?c_Date1904Const:c_Date1900Const; } else if ( c_oSerWorkbookPrTypes.DateCompatibility == type ) WorkbookPr.DateCompatibility = this.stream.GetBool(); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadBookViews = function(type, length) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerWorkbookTypes.WorkbookView == type ) { res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadWorkbookView(t,l); }); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadWorkbookView = function(type, length, BookViews) { var res = c_oSerConstants.ReadOk; if ( c_oSerWorkbookViewTypes.ActiveTab == type ) this.oWorkbook.nActive = this.stream.GetULongLE(); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadDefinedNames = function(type, length) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerWorkbookTypes.DefinedName == type ) { var oNewDefinedName = new DefinedName(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadDefinedName(t,l,oNewDefinedName); }); if(null != oNewDefinedName.Name && null != oNewDefinedName.Ref) { if(null != oNewDefinedName.LocalSheetId) { var ws = this.oWorkbook.aWorksheets[oNewDefinedName.LocalSheetId]; if(null != ws) { ws.DefinedNames[oNewDefinedName.Name] = oNewDefinedName; this.oWorkbook.oNameGenerator.addLocalDefinedName(oNewDefinedName); } } else { this.oWorkbook.oNameGenerator.addDefinedName(oNewDefinedName); this.oWorkbook.oRealDefinedNames[oNewDefinedName.Name] = oNewDefinedName; } } } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadDefinedName = function(type, length, oDefinedName) { var res = c_oSerConstants.ReadOk; if ( c_oSerDefinedNameTypes.Name == type ) oDefinedName.Name = this.stream.GetString2LE(length); else if ( c_oSerDefinedNameTypes.Ref == type ) oDefinedName.Ref = this.stream.GetString2LE(length); else if ( c_oSerDefinedNameTypes.LocalSheetId == type ) oDefinedName.LocalSheetId = this.stream.GetULongLE(); else res = c_oSerConstants.ReadUnknown; return res; }; }; /** @constructor */ function Binary_WorksheetTableReader(stream, wb, aSharedStrings, aCellXfs, Dxfs, oMediaArray) { this.stream = stream; this.wb = wb; this.aSharedStrings = aSharedStrings; this.oMediaArray = oMediaArray; this.aCellXfs = aCellXfs; this.Dxfs = Dxfs; this.bcr = new Binary_CommonReader(this.stream); this.aMerged = new Array(); this.aHyperlinks = new Array(); this.Read = function() { var oThis = this; return this.bcr.ReadTable(function(t, l){ return oThis.ReadWorksheetsContent(t,l); }); }; this.ReadWorksheetsContent = function(type, length) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerWorksheetsTypes.Worksheet === type ) { this.aMerged = new Array(); this.aHyperlinks = new Array(); var oNewWorksheet = new Woorksheet(this.wb, wb.aWorksheets.length, false); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadWorksheet(t,l, oNewWorksheet); }); //merged for(var i = 0, length = this.aMerged.length; i < length; ++i) { var range = oNewWorksheet.getRange2(this.aMerged[i]); if(null != range) range.mergeOpen(); } //hyperlinks for(var i = 0, length = this.aHyperlinks.length; i < length; ++i) { var hyperlink = this.aHyperlinks[i]; if (null !== hyperlink.Ref) hyperlink.Ref.setHyperlink(hyperlink, true); } oNewWorksheet.init(); this.wb.aWorksheets.push(oNewWorksheet); this.wb.aWorksheetsById[oNewWorksheet.getId()] = oNewWorksheet; } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadWorksheet = function(type, length, oWorksheet) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerWorksheetsTypes.WorksheetProp == type ) { res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadWorksheetProp(t,l, oWorksheet); }); } else if ( c_oSerWorksheetsTypes.Cols == type ) { var oConditionalFormatting = null; if(null == oWorksheet.Cols) oWorksheet.aCols = new Array(); var aTempCols = new Array(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadWorksheetCols(t,l, aTempCols, oWorksheet); }); var fInitCol = function(oFrom, oTo) { if(null != oFrom.BestFit) oTo.BestFit = oFrom.BestFit; if(null != oFrom.hd) oTo.hd = oFrom.hd; if(null != oFrom.xfs) oTo.xfs = oFrom.xfs.clone(); else if(null != oFrom.xfsid) { var xfs = oThis.aCellXfs[oFrom.xfsid]; if(null != xfs) { oFrom.xfs = xfs; oTo.xfs = xfs.clone(); } } if(null != oFrom.width) oTo.width = oFrom.width; if(null != oFrom.CustomWidth) oTo.CustomWidth = oFrom.CustomWidth; if(oTo.index + 1 > oWorksheet.nColsCount) oWorksheet.nColsCount = oTo.index + 1; } //если есть стиль последней колонки, назначаем его стилем всей таблицы и убираем из колонок var oAllCol = null; if(aTempCols.length > 0) { var oLast = aTempCols[aTempCols.length - 1]; if(gc_nMaxCol == oLast.Max) { oAllCol = oLast; oWorksheet.oAllCol = new Col(oWorksheet, 0); fInitCol(oAllCol, oWorksheet.oAllCol); } } for(var i = 0, length = aTempCols.length; i < length; ++i) { var elem = aTempCols[i]; if(null != oAllCol && elem.BestFit == oAllCol.BestFit && elem.hd == oAllCol.hd && elem.xfs == oAllCol.xfs && elem.width == oAllCol.width && elem.CustomWidth == oAllCol.CustomWidth) continue; if(null == elem.width) { elem.width = 0; elem.hd = true; } for(var j = elem.Min; j <= elem.Max; j++){ var oNewCol = new Col(oWorksheet, j - 1); fInitCol(elem, oNewCol); oWorksheet.aCols[oNewCol.index] = oNewCol; } } } else if ( c_oSerWorksheetsTypes.SheetFormatPr == type ) { res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadSheetFormatPr(t,l, oWorksheet); }); } else if ( c_oSerWorksheetsTypes.PageMargins == type ) { var oPageMargins = new Asc.asc_CPageMargins(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadPageMargins(t,l, oPageMargins); }); if(null == oWorksheet.PagePrintOptions) oWorksheet.PagePrintOptions = new Asc.asc_CPageOptions(); oWorksheet.PagePrintOptions.asc_setPageMargins(oPageMargins); } else if ( c_oSerWorksheetsTypes.PageSetup == type ) { var oPageSetup = new Asc.asc_CPageSetup(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadPageSetup(t,l, oPageSetup); }); if(null == oWorksheet.PagePrintOptions) oWorksheet.PagePrintOptions = new Asc.asc_CPageOptions(); oWorksheet.PagePrintOptions.asc_setPageSetup(oPageSetup); } else if ( c_oSerWorksheetsTypes.PrintOptions == type ) { if(null == oWorksheet.PagePrintOptions) oWorksheet.PagePrintOptions = new Asc.asc_CPageOptions(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadPrintOptions(t,l, oWorksheet.PagePrintOptions); }); } else if ( c_oSerWorksheetsTypes.Hyperlinks == type ) { res = this.bcr.Read1(length, function(t,l){ return oThis.ReadHyperlinks(t,l, oWorksheet); }); } else if ( c_oSerWorksheetsTypes.MergeCells == type ) { res = this.bcr.Read1(length, function(t,l){ return oThis.ReadMergeCells(t,l, oWorksheet); }); } else if ( c_oSerWorksheetsTypes.SheetData == type ) { res = this.bcr.Read1(length, function(t,l){ return oThis.ReadSheetData(t,l, oWorksheet); }); } else if ( c_oSerWorksheetsTypes.Drawings == type ) { res = this.bcr.Read1(length, function(t,l){ return oThis.ReadDrawings(t,l, oWorksheet.Drawings, oWorksheet.Id); }); } else if ( c_oSerWorksheetsTypes.Autofilter == type ) { var oBinary_TableReader = new Binary_TableReader(this.stream, oWorksheet, this.Dxfs); oWorksheet.AutoFilter = new Object(); res = this.bcr.Read1(length, function(t,l){ return oBinary_TableReader.ReadAutoFilter(t,l, oWorksheet.AutoFilter); }); } else if ( c_oSerWorksheetsTypes.TableParts == type ) { oWorksheet.TableParts = new Array(); var oBinary_TableReader = new Binary_TableReader(this.stream, oWorksheet, this.Dxfs); oBinary_TableReader.Read(length, oWorksheet.TableParts); } else if ( c_oSerWorksheetsTypes.Comments == type ) { res = this.bcr.Read1(length, function(t,l){ return oThis.ReadComments(t,l, oWorksheet); }); } else if (c_oSerWorksheetsTypes.ConditionalFormatting === type) { oConditionalFormatting = new Asc.CConditionalFormatting(); res = this.bcr.Read1(length, function (t, l) { return oThis.ReadConditionalFormatting(t, l, oConditionalFormatting, function (sRange) {return oWorksheet.getRange2(sRange);}); }); oWorksheet.aConditionalFormatting.push(oConditionalFormatting); } else if (c_oSerWorksheetsTypes.SheetViews === type) { res = this.bcr.Read1(length, function (t, l) { return oThis.ReadSheetViews(t, l, oWorksheet.sheetViews); }); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadWorksheetProp = function(type, length, oWorksheet) { var res = c_oSerConstants.ReadOk; if ( c_oSerWorksheetPropTypes.Name == type ) oWorksheet.sName = this.stream.GetString2LE(length); else if ( c_oSerWorksheetPropTypes.SheetId == type ) oWorksheet.nSheetId = this.stream.GetULongLE(); else if ( c_oSerWorksheetPropTypes.State == type ) { switch(this.stream.GetUChar()) { case EVisibleType.visibleHidden: oWorksheet.bHidden = true;break; case EVisibleType.visibleVeryHidden: oWorksheet.bHidden = true;break; case EVisibleType.visibleVisible: oWorksheet.bHidden = false;break; } } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadWorksheetCols = function(type, length, aTempCols, oWorksheet) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerWorksheetsTypes.Col == type ) { var oTempCol = {BestFit: null, hd: null, Max: null, Min: null, xfs: null, xfsid: null, width: null, CustomWidth: null}; res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadWorksheetCol(t,l, oTempCol); }); aTempCols.push(oTempCol); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadWorksheetCol = function(type, length, oCol) { var res = c_oSerConstants.ReadOk; if ( c_oSerWorksheetColTypes.BestFit == type ) oCol.BestFit = this.stream.GetBool(); else if ( c_oSerWorksheetColTypes.Hidden == type ) oCol.hd = this.stream.GetBool(); else if ( c_oSerWorksheetColTypes.Max == type ) oCol.Max = this.stream.GetULongLE(); else if ( c_oSerWorksheetColTypes.Min == type ) oCol.Min = this.stream.GetULongLE(); else if ( c_oSerWorksheetColTypes.Style == type ) oCol.xfsid = this.stream.GetULongLE(); else if ( c_oSerWorksheetColTypes.Width == type ) { oCol.width = this.stream.GetDoubleLE(); if(g_nCurFileVersion < 2) oCol.CustomWidth = 1; } else if ( c_oSerWorksheetColTypes.CustomWidth == type ) oCol.CustomWidth = this.stream.GetBool(); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadSheetFormatPr = function(type, length, oWorksheet) { var res = c_oSerConstants.ReadOk; if ( c_oSerSheetFormatPrTypes.DefaultColWidth == type ) oWorksheet.dDefaultColWidth = this.stream.GetDoubleLE(); else if ( c_oSerSheetFormatPrTypes.DefaultRowHeight == type ) oWorksheet.dDefaultheight = this.stream.GetDoubleLE(); else if (c_oSerSheetFormatPrTypes.BaseColWidth === type) oWorksheet.nBaseColWidth = this.stream.GetULongLE(); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadPageMargins = function(type, length, oPageMargins) { var res = c_oSerConstants.ReadOk; if ( c_oSer_PageMargins.Left == type ) oPageMargins.asc_setLeft(this.stream.GetDoubleLE()); else if ( c_oSer_PageMargins.Top == type ) oPageMargins.asc_setTop(this.stream.GetDoubleLE()); else if ( c_oSer_PageMargins.Right == type ) oPageMargins.asc_setRight(this.stream.GetDoubleLE()); else if ( c_oSer_PageMargins.Bottom == type ) oPageMargins.asc_setBottom(this.stream.GetDoubleLE()); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadPageSetup = function(type, length, oPageSetup) { var res = c_oSerConstants.ReadOk; if ( c_oSer_PageSetup.Orientation == type ) { var byteFormatOrientation = this.stream.GetUChar(); var byteOrientation = null; switch(byteFormatOrientation) { case EPageOrientation.pageorientPortrait: byteOrientation = c_oAscPageOrientation.PagePortrait;break; case EPageOrientation.pageorientLandscape: byteOrientation = c_oAscPageOrientation.PageLandscape;break; } if(null != byteOrientation) oPageSetup.asc_setOrientation(byteOrientation); } else if ( c_oSer_PageSetup.PaperSize == type ) { var bytePaperSize = this.stream.GetUChar(); var item = DocumentPageSize.getSizeById(bytePaperSize); oPageSetup.asc_setWidth(item.w_mm); oPageSetup.asc_setHeight(item.h_mm); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadPrintOptions = function(type, length, oPrintOptions) { var res = c_oSerConstants.ReadOk; if ( c_oSer_PrintOptions.GridLines == type ) oPrintOptions.asc_setGridLines(this.stream.GetBool()); else if ( c_oSer_PrintOptions.Headings == type ) oPrintOptions.asc_setHeadings(this.stream.GetBool()); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadHyperlinks = function(type, length, ws) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerWorksheetsTypes.Hyperlink == type ) { var oNewHyperlink = new Hyperlink(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadHyperlink(t,l, ws, oNewHyperlink); }); this.aHyperlinks.push(oNewHyperlink); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadHyperlink = function(type, length, ws, oHyperlink) { var res = c_oSerConstants.ReadOk; if ( c_oSerHyperlinkTypes.Ref == type ) oHyperlink.Ref = ws.getRange2(this.stream.GetString2LE(length)); else if ( c_oSerHyperlinkTypes.Hyperlink == type ) oHyperlink.Hyperlink = this.stream.GetString2LE(length); else if ( c_oSerHyperlinkTypes.Location == type ) oHyperlink.Location = this.stream.GetString2LE(length); else if ( c_oSerHyperlinkTypes.Tooltip == type ) oHyperlink.Tooltip = this.stream.GetString2LE(length); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadMergeCells = function(type, length, ws) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerWorksheetsTypes.MergeCell == type ) { this.aMerged.push(this.stream.GetString2LE(length)); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadSheetData = function(type, length, ws) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerWorksheetsTypes.Row == type ) { var oNewRow = new Row(ws); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadRow(t,l, oNewRow, ws); }); if(null != oNewRow.r) ws.aGCells[oNewRow.r - 1] = oNewRow; } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadRow = function(type, length, oRow, ws) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerRowTypes.Row == type ) { oRow.r = this.stream.GetULongLE(); oRow.index = oRow.r - 1; if(oRow.r > ws.nRowsCount) ws.nRowsCount = oRow.r; } else if ( c_oSerRowTypes.Style == type ) { var xfs = this.aCellXfs[this.stream.GetULongLE()]; if(null != xfs) oRow.xfs = xfs.clone(); } else if ( c_oSerRowTypes.Height == type ) { oRow.h = this.stream.GetDoubleLE(); if(g_nCurFileVersion < 2) oRow.CustomHeight = true; } else if ( c_oSerRowTypes.CustomHeight == type ) oRow.CustomHeight = this.stream.GetBool(); else if ( c_oSerRowTypes.Hidden == type ) oRow.hd = this.stream.GetBool(); else if ( c_oSerRowTypes.Cells == type ) { if(null == oRow.Cells) oRow.c = new Object(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadCells(t,l, ws, oRow.c); }); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadCells = function(type, length, ws, aCells) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerRowTypes.Cell == type ) { var oNewCell = new Cell(ws); var oCellVal = {val: null}; res = this.bcr.Read1(length, function(t,l){ return oThis.ReadCell(t,l, ws, oNewCell, oCellVal); }); if(null != oNewCell.oId) { var nCellCol = 0; //вычисляем nColsCount if(null != oNewCell) { var nCols = oNewCell.oId.getCol(); nCellCol = nCols - 1; if(nCols > ws.nColsCount) ws.nColsCount = nCols; } if(null != oCellVal.val) { var bText = false; if(CellValueType.String == oNewCell.oValue.type || CellValueType.Error == oNewCell.oValue.type) { var ss = this.aSharedStrings[oCellVal.val]; if(null != ss) { bText = true; var nType = oNewCell.oValue.type; oNewCell.oValue = ss.clone(oNewCell); oNewCell.oValue.type = nType; } } //todo убрать to string if(false == bText) oNewCell.oValue.number = oCellVal.val; } aCells[nCellCol] = oNewCell; } } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadCell = function(type, length, ws, oCell, oCellVal) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerCellTypes.Ref == type ) oCell.oId = new CellAddress(this.stream.GetString2LE(length)); else if( c_oSerCellTypes.Style == type ) { var nStyleIndex = this.stream.GetULongLE(); if(0 != nStyleIndex) { var xfs = this.aCellXfs[nStyleIndex]; if(null != xfs) oCell.xfs = xfs.clone(); } } else if( c_oSerCellTypes.Type == type ) { switch(this.stream.GetUChar()) { case ECellTypeType.celltypeBool: oCell.oValue.type = CellValueType.Bool;break; case ECellTypeType.celltypeError: oCell.oValue.type = CellValueType.Error;break; case ECellTypeType.celltypeNumber: oCell.oValue.type = CellValueType.Number;break; case ECellTypeType.celltypeSharedString: oCell.oValue.type = CellValueType.String;break; }; } else if( c_oSerCellTypes.Formula == type ) { if(null == oCell.oFormulaExt) oCell.oFormulaExt = {aca: null, bx: null, ca: null, del1: null, del2: null, dt2d: null, dtr: null, r1: null, r2: null, si: null, t: null, v: null}; res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadFormula(t,l, oCell.oFormulaExt); }); } else if( c_oSerCellTypes.Value == type ) { oCellVal.val = this.stream.GetDoubleLE(); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadFormula = function(type, length, oFormula) { var res = c_oSerConstants.ReadOk; if ( c_oSerFormulaTypes.Aca == type ) oFormula.aca = this.stream.GetBool(); else if ( c_oSerFormulaTypes.Bx == type ) oFormula.bx = this.stream.GetBool(); else if ( c_oSerFormulaTypes.Ca == type ) oFormula.ca = this.stream.GetBool(); else if ( c_oSerFormulaTypes.Del1 == type ) oFormula.del1 = this.stream.GetBool(); else if ( c_oSerFormulaTypes.Del2 == type ) oFormula.del2 = this.stream.GetBool(); else if ( c_oSerFormulaTypes.Dt2D == type ) oFormula.dt2d = this.stream.GetBool(); else if ( c_oSerFormulaTypes.Dtr == type ) oFormula.dtr = this.stream.GetBool(); else if ( c_oSerFormulaTypes.R1 == type ) oFormula.r1 = this.stream.GetString2LE(length); else if ( c_oSerFormulaTypes.R2 == type ) oFormula.r2 = this.stream.GetString2LE(length); else if ( c_oSerFormulaTypes.Ref == type ) oFormula.ref = this.stream.GetString2LE(length); else if ( c_oSerFormulaTypes.Si == type ) oFormula.si = this.stream.GetULongLE(); else if ( c_oSerFormulaTypes.T == type ) oFormula.t = this.stream.GetUChar(); else if ( c_oSerFormulaTypes.Text == type ) oFormula.v = this.stream.GetString2LE(length); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadDrawings = function(type, length, aDrawings, wsId) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerWorksheetsTypes.Drawing == type ) { var objectRender = new DrawingObjects(); var oFlags = {from: false, to: false, pos: false, ext: false}; var oNewDrawing = objectRender.createDrawingObject(); oNewDrawing.id = "sheet" + wsId + "_" + (aDrawings.length + 1); res = this.bcr.Read1(length, function(t, l) { return oThis.ReadDrawing(t, l, oNewDrawing, oFlags); }); if(false != oFlags.from && false != oFlags.to) oNewDrawing.Type = ECellAnchorType.cellanchorTwoCell; else if(false != oFlags.from && false != oFlags.ext) oNewDrawing.Type = ECellAnchorType.cellanchorOneCell; else if(false != oFlags.pos && false != oFlags.ext) oNewDrawing.Type = ECellAnchorType.cellanchorAbsolute; aDrawings.push(oNewDrawing); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadDrawing = function(type, length, oDrawing, oFlags) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_DrawingType.Type == type ) oDrawing.Type = this.stream.GetUChar(); else if ( c_oSer_DrawingType.From == type ) { oFlags.from = true; res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadFromTo(t,l, oDrawing.from); }); } else if ( c_oSer_DrawingType.To == type ) { oFlags.to = true; res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadFromTo(t,l, oDrawing.to); }); } else if ( c_oSer_DrawingType.Pos == type ) { oFlags.pos = true; if(null == oDrawing.Pos) oDrawing.Pos = new Object(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadPos(t,l, oDrawing.Pos); }); } else if ( c_oSer_DrawingType.Ext == type ) { oFlags.ext = true; res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadExt(t,l, oDrawing.ext); }); } else if ( c_oSer_DrawingType.Pic == type ) { oDrawing.image = new Image(); res = this.bcr.Read1(length, function(t,l){ //return oThis.ReadPic(t,l, oDrawing.Pic); return oThis.ReadPic(t,l, oDrawing); }); } else if ( c_oSer_DrawingType.GraphicFrame == type ) { var oBinary_ChartReader = new Binary_ChartReader(this.stream, oDrawing.chart); res = oBinary_ChartReader.Read(length); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadFromTo = function(type, length, oFromTo) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_DrawingFromToType.Col == type ) //oFromTo.Col = this.stream.GetULongLE(); oFromTo.col = this.stream.GetULongLE(); else if ( c_oSer_DrawingFromToType.ColOff == type ) //oFromTo.ColOff = this.stream.GetDoubleLE(); oFromTo.colOff = this.stream.GetDoubleLE(); else if ( c_oSer_DrawingFromToType.Row == type ) //oFromTo.Row = this.stream.GetULongLE(); oFromTo.row = this.stream.GetULongLE(); else if ( c_oSer_DrawingFromToType.RowOff == type ) //oFromTo.RowOff = this.stream.GetDoubleLE(); oFromTo.rowOff = this.stream.GetDoubleLE(); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadPos = function(type, length, oPos) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_DrawingPosType.X == type ) oPos.X = this.stream.GetDoubleLE(); else if ( c_oSer_DrawingPosType.Y == type ) oPos.Y = this.stream.GetDoubleLE(); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadExt = function(type, length, oExt) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_DrawingExtType.Cx == type ) oExt.cx = this.stream.GetDoubleLE(); else if ( c_oSer_DrawingExtType.Cy == type ) oExt.cy = this.stream.GetDoubleLE(); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadPic = function(type, length, oDrawing) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_DrawingType.PicSrc == type ) { var nIndex = this.stream.GetULongLE(); var src = this.oMediaArray[nIndex]; if(null != src) { if (window['scriptBridge']) { oDrawing.image.src = window['scriptBridge']['workPath']() + src; oDrawing.imageUrl = window['scriptBridge']['workPath']() + src; } else { oDrawing.image.src = src; oDrawing.imageUrl = src; } } } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadComments = function(type, length, oWorksheet) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerWorksheetsTypes.Comment == type ) { var oCommentCoords = new Asc.asc_CCommentCoords(); var aCommentData = new Array(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadComment(t,l, oCommentCoords, aCommentData); }); //todo проверка for(var i = 0, length = aCommentData.length; i < length; ++i) { var elem = aCommentData[i]; elem.asc_putRow(oCommentCoords.asc_getRow()); elem.asc_putCol(oCommentCoords.asc_getCol()); elem.wsId = oWorksheet.Id; if (elem.asc_getDocumentFlag()) elem.nId = "doc_" + (oWorksheet.aComments.length + 1); else elem.nId = "sheet" + elem.wsId + "_" + (oWorksheet.aComments.length + 1); oWorksheet.aComments.push(elem); } oWorksheet.aCommentsCoords.push(oCommentCoords); } else res = c_oSerConstants.ReadUnknown; return res; } this.ReadComment = function(type, length, oCommentCoords, aCommentData) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_Comments.Row == type ) oCommentCoords.asc_setRow(this.stream.GetULongLE()); else if ( c_oSer_Comments.Col == type ) oCommentCoords.asc_setCol(this.stream.GetULongLE()); else if ( c_oSer_Comments.CommentDatas == type ) { res = this.bcr.Read1(length, function(t,l){ return oThis.ReadCommentDatas(t,l, aCommentData); }); } else if ( c_oSer_Comments.Left == type ) oCommentCoords.asc_setLeft(this.stream.GetULongLE()); else if ( c_oSer_Comments.LeftOffset == type ) oCommentCoords.asc_setLeftOffset(this.stream.GetULongLE()); else if ( c_oSer_Comments.Top == type ) oCommentCoords.asc_setTop(this.stream.GetULongLE()); else if ( c_oSer_Comments.TopOffset == type ) oCommentCoords.asc_setTopOffset(this.stream.GetULongLE()); else if ( c_oSer_Comments.Right == type ) oCommentCoords.asc_setRight(this.stream.GetULongLE()); else if ( c_oSer_Comments.RightOffset == type ) oCommentCoords.asc_setRightOffset(this.stream.GetULongLE()); else if ( c_oSer_Comments.Bottom == type ) oCommentCoords.asc_setBottom(this.stream.GetULongLE()); else if ( c_oSer_Comments.BottomOffset == type ) oCommentCoords.asc_setBottomOffset(this.stream.GetULongLE()); else if ( c_oSer_Comments.LeftMM == type ) oCommentCoords.asc_setLeftMM(this.stream.GetDoubleLE()); else if ( c_oSer_Comments.TopMM == type ) oCommentCoords.asc_setTopMM(this.stream.GetDoubleLE()); else if ( c_oSer_Comments.WidthMM == type ) oCommentCoords.asc_setWidthMM(this.stream.GetDoubleLE()); else if ( c_oSer_Comments.HeightMM == type ) oCommentCoords.asc_setHeightMM(this.stream.GetDoubleLE()); else if ( c_oSer_Comments.MoveWithCells == type ) oCommentCoords.asc_setMoveWithCells(this.stream.GetBool()); else if ( c_oSer_Comments.SizeWithCells == type ) oCommentCoords.asc_setSizeWithCells(this.stream.GetBool()); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadCommentDatas = function(type, length, aCommentData) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_Comments.CommentData === type ) { var oCommentData = new Asc.asc_CCommentData(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadCommentData(t,l,oCommentData); }); aCommentData.push(oCommentData); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadCommentData = function(type, length, oCommentData) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_CommentData.Text == type ) oCommentData.asc_putText(this.stream.GetString2LE(length)); else if ( c_oSer_CommentData.Time == type ) { var oDate = this.Iso8601ToDate(this.stream.GetString2LE(length)); if(null != oDate) oCommentData.asc_putTime(oDate.getTime() + ""); } else if ( c_oSer_CommentData.UserId == type ) oCommentData.asc_putUserId(this.stream.GetString2LE(length)); else if ( c_oSer_CommentData.UserName == type ) oCommentData.asc_putUserName(this.stream.GetString2LE(length)); else if ( c_oSer_CommentData.QuoteText == type ) { var sQuoteText = this.stream.GetString2LE(length); } else if ( c_oSer_CommentData.Replies == type ) { res = this.bcr.Read1(length, function(t,l){ return oThis.ReadReplies(t,l, oCommentData); }); } else if ( c_oSer_CommentData.Solved == type ) { var bSolved = this.stream.GetBool(); } else if ( c_oSer_CommentData.Document == type ) oCommentData.asc_putDocumentFlag(this.stream.GetBool()); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadConditionalFormatting = function (type, length, oConditionalFormatting, functionGetRange2) { var res = c_oSerConstants.ReadOk; var oThis = this; var oConditionalFormattingRule = null; if (c_oSer_ConditionalFormatting.Pivot === type) oConditionalFormatting.Pivot = this.stream.GetBool(); else if (c_oSer_ConditionalFormatting.SqRef === type) { oConditionalFormatting.SqRef = this.stream.GetString2LE(length); oConditionalFormatting.SqRefRange = functionGetRange2(oConditionalFormatting.SqRef); } else if (c_oSer_ConditionalFormatting.ConditionalFormattingRule === type) { oConditionalFormattingRule = new Asc.CConditionalFormattingRule(); res = this.bcr.Read1(length, function (t, l) { return oThis.ReadConditionalFormattingRule(t, l, oConditionalFormattingRule); }); oConditionalFormatting.aRules.push(oConditionalFormattingRule); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadConditionalFormattingRule = function (type, length, oConditionalFormattingRule) { var res = c_oSerConstants.ReadOk; var oThis = this; var oConditionalFormattingRuleElement = null; if (c_oSer_ConditionalFormattingRule.AboveAverage === type) oConditionalFormattingRule.AboveAverage = this.stream.GetBool(); else if (c_oSer_ConditionalFormattingRule.Bottom === type) oConditionalFormattingRule.Bottom = this.stream.GetBool(); else if (c_oSer_ConditionalFormattingRule.DxfId === type) { var DxfId = this.stream.GetULongLE(); var dxf = this.Dxfs[DxfId]; oConditionalFormattingRule.dxf = dxf; } else if (c_oSer_ConditionalFormattingRule.EqualAverage === type) oConditionalFormattingRule.EqualAverage = this.stream.GetBool(); else if (c_oSer_ConditionalFormattingRule.Operator === type) oConditionalFormattingRule.Operator = this.stream.GetString2LE(length); else if (c_oSer_ConditionalFormattingRule.Percent === type) oConditionalFormattingRule.Percent = this.stream.GetBool(); else if (c_oSer_ConditionalFormattingRule.Priority === type) oConditionalFormattingRule.Priority = this.stream.GetULongLE(); else if (c_oSer_ConditionalFormattingRule.Rank === type) oConditionalFormattingRule.Rank = this.stream.GetULongLE(); else if (c_oSer_ConditionalFormattingRule.StdDev === type) oConditionalFormattingRule.StdDev = this.stream.GetULongLE(); else if (c_oSer_ConditionalFormattingRule.StopIfTrue === type) oConditionalFormattingRule.StopIfTrue = this.stream.GetBool(); else if (c_oSer_ConditionalFormattingRule.Text === type) oConditionalFormattingRule.Text = this.stream.GetString2LE(length); else if (c_oSer_ConditionalFormattingRule.TimePeriod === type) oConditionalFormattingRule.TimePeriod = this.stream.GetString2LE(length); else if (c_oSer_ConditionalFormattingRule.Type === type) oConditionalFormattingRule.Type = this.stream.GetString2LE(length); else if (c_oSer_ConditionalFormattingRule.ColorScale === type) { oConditionalFormattingRuleElement = new Asc.CColorScale(); res = this.bcr.Read1(length, function (t, l) { return oThis.ReadColorScale(t, l, oConditionalFormattingRuleElement); }); oConditionalFormattingRule.aRuleElements.push(oConditionalFormattingRuleElement); } else if (c_oSer_ConditionalFormattingRule.DataBar === type) { oConditionalFormattingRuleElement = new Asc.CDataBar(); res = this.bcr.Read1(length, function (t, l) { return oThis.ReadDataBar(t, l, oConditionalFormattingRuleElement); }); oConditionalFormattingRule.aRuleElements.push(oConditionalFormattingRuleElement); } else if (c_oSer_ConditionalFormattingRule.FormulaCF === type) { oConditionalFormattingRuleElement = new Asc.CFormulaCF(); oConditionalFormattingRuleElement.Text = this.stream.GetString2LE(length); oConditionalFormattingRule.aRuleElements.push(oConditionalFormattingRuleElement); } else if (c_oSer_ConditionalFormattingRule.IconSet === type) { oConditionalFormattingRuleElement = new Asc.CIconSet(); res = this.bcr.Read1(length, function (t, l) { return oThis.ReadIconSet(t, l, oConditionalFormattingRuleElement); }); oConditionalFormattingRule.aRuleElements.push(oConditionalFormattingRuleElement); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadColorScale = function (type, length, oColorScale) { var res = c_oSerConstants.ReadOk; var oThis = this; var oObject = null; if (c_oSer_ConditionalFormattingRuleColorScale.CFVO === type) { oObject = new Asc.CConditionalFormatValueObject(); res = this.bcr.Read1(length, function (t, l) { return oThis.ReadCFVO(t, l, oObject); }); oColorScale.aCFVOs.push(oObject); } else if (c_oSer_ConditionalFormattingRuleColorScale.Color === type) { oObject = new OpenColor(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.bcr.ReadColorSpreadsheet(t,l, oObject); }); if(null != oObject.theme) oColorScale.aColors.push(g_oColorManager.getThemeColor(oObject.theme, oObject.tint)); else if(null != oObject.rgb) oColorScale.aColors.push(new RgbColor(0x00ffffff & oObject.rgb)); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadDataBar = function (type, length, oDataBar) { var res = c_oSerConstants.ReadOk; var oThis = this; var oObject = null; if (c_oSer_ConditionalFormattingDataBar.MaxLength === type) oDataBar.MaxLength = this.stream.GetULongLE(); else if (c_oSer_ConditionalFormattingDataBar.MinLength === type) oDataBar.MinLength = this.stream.GetULongLE(); else if (c_oSer_ConditionalFormattingDataBar.ShowValue === type) oDataBar.ShowValue = this.stream.GetBool(); else if (c_oSer_ConditionalFormattingDataBar.Color === type) { oObject = new OpenColor(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.bcr.ReadColorSpreadsheet(t,l, oObject); }); if(null != oObject.theme) oDataBar.Color = g_oColorManager.getThemeColor(oObject.theme, oObject.tint); else if(null != oObject.rgb) oDataBar.Color = new RgbColor(0x00ffffff & oObject.rgb); } else if (c_oSer_ConditionalFormattingDataBar.CFVO === type) { oObject = new Asc.CConditionalFormatValueObject(); res = this.bcr.Read1(length, function (t, l) { return oThis.ReadCFVO(t, l, oObject); }); oDataBar.aCFVOs.push(oObject); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadIconSet = function (type, length, oIconSet) { var res = c_oSerConstants.ReadOk; var oThis = this; var oObject = null; if (c_oSer_ConditionalFormattingIconSet.IconSet === type) oIconSet.IconSet = this.stream.GetString2LE(length); else if (c_oSer_ConditionalFormattingIconSet.Percent === type) oIconSet.Percent = this.stream.GetBool(); else if (c_oSer_ConditionalFormattingIconSet.Reverse === type) oIconSet.Reverse = this.stream.GetBool(); else if (c_oSer_ConditionalFormattingIconSet.ShowValue === type) oIconSet.ShowValue = this.stream.GetBool(); else if (c_oSer_ConditionalFormattingIconSet.CFVO === type) { oObject = new Asc.CConditionalFormatValueObject(); res = this.bcr.Read1(length, function (t, l) { return oThis.ReadCFVO(t, l, oObject); }); oIconSet.aCFVOs.push(oObject); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadCFVO = function (type, length, oCFVO) { var res = c_oSerConstants.ReadOk; if (c_oSer_ConditionalFormattingValueObject.Gte === type) oCFVO.Gte = this.stream.GetBool(); else if (c_oSer_ConditionalFormattingValueObject.Type === type) oCFVO.Type = this.stream.GetString2LE(length); else if (c_oSer_ConditionalFormattingValueObject.Val === type) oCFVO.Val = this.stream.GetString2LE(length); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadSheetViews = function (type, length, aSheetViews) { var res = c_oSerConstants.ReadOk; var oThis = this; var oSheetView = null; if (c_oSerWorksheetsTypes.SheetView === type) { oSheetView = new Asc.asc_CSheetViewSettings(); res = this.bcr.Read1(length, function (t, l) { return oThis.ReadSheetView(t, l, oSheetView); }); aSheetViews.push(oSheetView); } return res; }; this.ReadSheetView = function (type, length, oSheetView) { var res = c_oSerConstants.ReadOk; if (c_oSer_SheetView.ShowGridLines === type) { oSheetView.showGridLines = this.stream.GetBool(); } else if (c_oSer_SheetView.ShowRowColHeaders === type) { oSheetView.showRowColHeaders = this.stream.GetBool(); } else res = c_oSerConstants.ReadUnknown; return res; }; this.Iso8601ToDate = function(sDate) { var numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ]; var minutesOffset = 0; if ((struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(sDate))) { // avoid NaN timestamps caused by “undefined” values being passed to Date.UTC for (var i = 0, k; (k = numericKeys[i]); ++i) { struct[k] = +struct[k] || 0; } // allow undefined days and months struct[2] = (+struct[2] || 1) - 1; struct[3] = +struct[3] || 1; if (struct[8] !== 'Z' && struct[9] !== undefined) { minutesOffset = struct[10] * 60 + struct[11]; if (struct[9] === '+') { minutesOffset = 0 - minutesOffset; } } return new Date(Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7])); } return null }; this.ReadReplies = function(type, length, oCommentData) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_CommentData.Reply === type ) { var oReplyData = new Asc.asc_CCommentData(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadCommentData(t,l,oReplyData); }); oCommentData.aReplies.push(oReplyData); } else res = c_oSerConstants.ReadUnknown; return res; }; }; /** @constructor */ function Binary_CalcChainTableReader(stream, aCalcChain) { this.stream = stream; this.aCalcChain = aCalcChain; this.bcr = new Binary_CommonReader(this.stream); this.Read = function() { var oThis = this; return this.bcr.ReadTable(function(t, l){ return oThis.ReadCalcChainContent(t,l); }); }; this.ReadCalcChainContent = function(type, length) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_CalcChainType.CalcChainItem === type ) { var oNewCalcChain = new Object(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadCalcChain(t,l, oNewCalcChain); }); this.aCalcChain.push(oNewCalcChain); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadCalcChain = function(type, length, oCalcChain) { var res = c_oSerConstants.ReadOk; if ( c_oSer_CalcChainType.Array == type ) oCalcChain.Array = this.stream.GetBool(); else if ( c_oSer_CalcChainType.SheetId == type ) oCalcChain.SheetId = this.stream.GetULongLE(); else if ( c_oSer_CalcChainType.DependencyLevel == type ) oCalcChain.DependencyLevel = this.stream.GetBool(); else if ( c_oSer_CalcChainType.Ref == type ) oCalcChain.Ref = this.stream.GetString2LE(length); else if ( c_oSer_CalcChainType.ChildChain == type ) oCalcChain.ChildChain = this.stream.GetBool(); else if ( c_oSer_CalcChainType.NewThread == type ) oCalcChain.NewThread = this.stream.GetBool(); else res = c_oSerConstants.ReadUnknown; return res; }; }; /** @constructor */ function Binary_OtherTableReader(stream, oMedia, sUrlPath, wb) { this.stream = stream; this.oMedia = oMedia; this.sUrlPath = sUrlPath; this.wb = wb; this.bcr = new Binary_CommonReader(this.stream); this.Read = function() { var oThis = this; var oRes = this.bcr.ReadTable(function(t, l){ return oThis.ReadOtherContent(t,l); }); g_oColorManager.setTheme(this.wb.theme); g_oDefaultFont = g_oDefaultFontAbs = new Font(); g_oDefaultFill = g_oDefaultFillAbs = new Fill(); g_oDefaultBorder = g_oDefaultBorderAbs = new Border(); g_oDefaultNum = g_oDefaultNumAbs = new Num(); g_oDefaultAlign = g_oDefaultAlignAbs = new Align(); return oRes; }; this.ReadOtherContent = function(type, length) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_OtherType.Media === type ) { res = this.bcr.Read1(length, function(t,l){ return oThis.ReadMediaContent(t,l); }); } else if ( c_oSer_OtherType.EmbeddedFonts === type ) { var _count = this.stream.GetULongLE(); var _embedded_fonts = new Array(); for (var i = 0; i < _count; i++) { var _at = this.stream.GetUChar(); if (_at != g_nodeAttributeStart) break; var _f_i = new Object(); while (true) { _at = this.stream.GetUChar(); if (_at == g_nodeAttributeEnd) break; switch (_at) { case 0: { _f_i.Name = this.stream.GetString(); break; } case 1: { _f_i.Style = this.stream.GetULongLE(); break; } case 2: { _f_i.IsCut = this.stream.GetBool(); break; } case 3: { _f_i.IndexCut = this.stream.GetULongLE(); break; } default: break; } } _embedded_fonts.push(_f_i); } var api = this.wb.oApi; if(true == api.isUseEmbeddedCutFonts) { var font_cuts = api.FontLoader.embedded_cut_manager; font_cuts.Url = this.sUrlPath + "fonts/fonts.js"; font_cuts.init_cut_fonts(_embedded_fonts); font_cuts.bIsCutFontsUse = true; } } else if ( c_oSer_OtherType.Theme === type ) { this.wb.theme = window.global_pptx_content_loader.ReadTheme(this, this.stream); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadMediaContent = function(type, length) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_OtherType.MediaItem === type ) { var oNewMedia = new Object(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadMediaItem(t,l, oNewMedia); }); if(null != oNewMedia.id && null != oNewMedia.src) this.oMedia[oNewMedia.id] = oNewMedia.src; } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadMediaItem = function(type, length, oNewMedia) { var res = c_oSerConstants.ReadOk; if ( c_oSer_OtherType.MediaSrc === type ) { var src = this.stream.GetString2LE(length); if(0 != src.indexOf("http:") && 0 != src.indexOf("data:") && 0 != src.indexOf("https:") && 0 != src.indexOf("ftp:") && 0 != src.indexOf("file:")) oNewMedia.src = this.sUrlPath + "media/" + src; else oNewMedia.src = src; } else if ( c_oSer_OtherType.MediaId === type ) oNewMedia.id = this.stream.GetULongLE(); else res = c_oSerConstants.ReadUnknown; return res; }; }; /** @constructor */ function BinaryFileReader(sUrlPath) { this.stream; this.sUrlPath = sUrlPath; this.getbase64DecodedData = function(szSrc, stream) { var nType = 0; var index = c_oSerFormat.Signature.length; var version = ""; var dst_len = ""; while (true) { index++; var _c = szSrc.charCodeAt(index); if (_c == ";".charCodeAt(0)) { if(0 == nType) { nType = 1; continue; } else { index++; break; } } if(0 == nType) version += String.fromCharCode(_c); else dst_len += String.fromCharCode(_c); } var dstLen = parseInt(dst_len); var pointer = g_memory.Alloc(dstLen); stream = new FT_Stream2(pointer.data, dstLen); stream.obj = pointer.obj; this.getbase64DecodedData2(szSrc, index, stream, 0); if(version.length > 1) { var nTempVersion = version.substring(1) - 0; if(nTempVersion) g_nCurFileVersion = nTempVersion; } return stream; }; this.getbase64DecodedData2 = function(szSrc, szSrcOffset, stream, streamOffset) { var srcLen = szSrc.length; var nWritten = streamOffset; var dstPx = stream.data; var index = szSrcOffset; if (window.chrome) { while (index < srcLen) { var dwCurr = 0; var i; var nBits = 0; for (i=0; i<4; i++) { if (index >= srcLen) break; var nCh = DecodeBase64Char(szSrc.charCodeAt(index++)); if (nCh == -1) { i--; continue; } dwCurr <<= 6; dwCurr |= nCh; nBits += 6; } dwCurr <<= 24-nBits; var nLen = (nBits/8) | 0; for (i=0; i<nLen; i++) { dstPx[nWritten++] = ((dwCurr & 0x00ff0000) >>> 16); dwCurr <<= 8; } } } else { var p = b64_decode; while (index < srcLen) { var dwCurr = 0; var i; var nBits = 0; for (i=0; i<4; i++) { if (index >= srcLen) break; var nCh = p[szSrc.charCodeAt(index++)]; if (nCh == undefined) { i--; continue; } dwCurr <<= 6; dwCurr |= nCh; nBits += 6; } dwCurr <<= 24-nBits; var nLen = (nBits/8) | 0; for (i=0; i<nLen; i++) { dstPx[nWritten++] = ((dwCurr & 0x00ff0000) >>> 16); dwCurr <<= 8; } } } return nWritten; } this.Read = function(data, wb) { this.stream = this.getbase64DecodedData(data); History.TurnOff(); this.ReadFile(wb); ReadDefCellStyles(wb, wb.CellStyles.DefaultStyles); ReadDefTableStyles(wb, wb.TableStyles.DefaultStyles); wb.TableStyles.concatStyles(); History.TurnOn(); }; this.ReadFile = function(wb) { return this.ReadMainTable(wb); }; this.ReadMainTable = function(wb) { var res = c_oSerConstants.ReadOk; //mtLen res = this.stream.EnterFrame(1); if(c_oSerConstants.ReadOk != res) return res; var mtLen = this.stream.GetUChar(); var aSeekTable = new Array(); var nOtherTableOffset = null; var nSharedStringTableOffset = null; var nStyleTableOffset = null; var nWorkbookTableOffset = null; for(var i = 0; i < mtLen; ++i) { //mtItem res = this.stream.EnterFrame(5); if(c_oSerConstants.ReadOk != res) return res; var mtiType = this.stream.GetUChar(); var mtiOffBits = this.stream.GetULongLE(); if(c_oSerTableTypes.Other == mtiType) nOtherTableOffset = mtiOffBits; else if(c_oSerTableTypes.SharedStrings == mtiType) nSharedStringTableOffset = mtiOffBits; else if(c_oSerTableTypes.Styles == mtiType) nStyleTableOffset = mtiOffBits; else if(c_oSerTableTypes.Workbook == mtiType) nWorkbookTableOffset = mtiOffBits; else aSeekTable.push( {type: mtiType, offset: mtiOffBits} ); } var aSharedStrings = new Array(); var aCellXfs = new Array(); var aDxfs = new Array(); var oMediaArray = new Object(); wb.aWorksheets = new Array(); if(null != nOtherTableOffset) { res = this.stream.Seek(nOtherTableOffset); if(c_oSerConstants.ReadOk == res) res = (new Binary_OtherTableReader(this.stream, oMediaArray, this.sUrlPath, wb)).Read(); } if(null != nSharedStringTableOffset) { res = this.stream.Seek(nSharedStringTableOffset); if(c_oSerConstants.ReadOk == res) res = (new Binary_SharedStringTableReader(this.stream, wb, aSharedStrings)).Read(); } if(null != nStyleTableOffset) { res = this.stream.Seek(nStyleTableOffset); if(c_oSerConstants.ReadOk == res) res = (new Binary_StylesTableReader(this.stream, wb, aCellXfs, aDxfs)).Read(); } if(c_oSerConstants.ReadOk == res) { for(var i = 0; i < aSeekTable.length; ++i) { var seek = aSeekTable[i]; var mtiType = seek.type; var mtiOffBits = seek.offset; res = this.stream.Seek(mtiOffBits); if(c_oSerConstants.ReadOk != res) break; switch(mtiType) { // case c_oSerTableTypes.SharedStrings: // res = (new Binary_SharedStringTableReader(this.stream, aSharedStrings)).Read(); // break; // case c_oSerTableTypes.Styles: // res = (new Binary_StylesTableReader(this.stream, wb.oStyleManager, aCellXfs)).Read(); // break; // case c_oSerTableTypes.Workbook: // res = (new Binary_WorkbookTableReader(this.stream, wb)).Read(); // break; case c_oSerTableTypes.Worksheets: res = (new Binary_WorksheetTableReader(this.stream, wb, aSharedStrings, aCellXfs, aDxfs, oMediaArray)).Read(); break; case c_oSerTableTypes.CalcChain: res = (new Binary_CalcChainTableReader(this.stream, wb.calcChain)).Read(); break; // case c_oSerTableTypes.Other: // res = (new Binary_OtherTableReader(this.stream, oMediaArray)).Read(); // break; } if(c_oSerConstants.ReadOk != res) break; } } if(null != nWorkbookTableOffset) { res = this.stream.Seek(nWorkbookTableOffset); if(c_oSerConstants.ReadOk == res) res = (new Binary_WorkbookTableReader(this.stream, wb)).Read(); } wb.init(); return res; }; }; function CTableStyles() { this.DefaultTableStyle = "TableStyleMedium2"; this.DefaultPivotStyle = "PivotStyleLight16"; this.CustomStyles = new Object(); this.DefaultStyles = new Object(); this.AllStyles = new Object(); } CTableStyles.prototype = { concatStyles : function() { for(var i in this.DefaultStyles) this.AllStyles[i] = this.DefaultStyles[i]; for(var i in this.CustomStyles) this.AllStyles[i] = this.CustomStyles[i]; } } function CTableStyle() { this.name = null; this.pivot = true; this.table = true; this.compiled = null; this.blankRow = null; this.firstColumn = null; this.firstColumnStripe = null; this.firstColumnSubheading = null; this.firstHeaderCell = null; this.firstRowStripe = null; this.firstRowSubheading = null; this.firstSubtotalColumn = null; this.firstSubtotalRow = null; this.firstTotalCell = null; this.headerRow = null; this.lastColumn = null; this.lastHeaderCell = null; this.lastTotalCell = null; this.pageFieldLabels = null; this.pageFieldValues = null; this.secondColumnStripe = null; this.secondColumnSubheading = null; this.secondRowStripe = null; this.secondRowSubheading = null; this.secondSubtotalColumn = null; this.secondSubtotalRow = null; this.thirdColumnSubheading = null; this.thirdRowSubheading = null; this.thirdSubtotalColumn = null; this.thirdSubtotalRow = null; this.totalRow = null; this.wholeTable = null; } CTableStyle.prototype = { getStyle: function(bbox, rowIndex, colIndex, options, headerRowCount, totalsRowCount) { //todo есть проблемы при малых размерах таблиц var res = null; if(null == this.compiled) this._compile(); var styles = this._getOption(options, headerRowCount, totalsRowCount); if(headerRowCount > 0 && rowIndex == bbox.r1) { if(colIndex == bbox.c1) res = styles.headerLeftTop; else if(colIndex == bbox.c2) res = styles.headerRightTop; else res = styles.header; } else if(totalsRowCount > 0 && rowIndex == bbox.r2) { if(colIndex == bbox.c1) res = styles.totalLeftBottom; else if(colIndex == bbox.c2) res = styles.totalRightBottom; else res = styles.total; } else if(options.ShowFirstColumn && colIndex == bbox.c1) { if(rowIndex == bbox.r1 + headerRowCount) res = styles.leftTopFC; else if(rowIndex == bbox.r2 - totalsRowCount) { if(0 == (rowIndex - headerRowCount) % 2) res = styles.leftBottomRowBand1FC; else res = styles.leftBottomRowBand2FC; } else { if(0 == (rowIndex - headerRowCount) % 2) res = styles.leftRowBand1FC; else res = styles.leftRowBand2FC; } } else if(options.ShowLastColumn && colIndex == bbox.c2) { if(rowIndex == bbox.r1 + headerRowCount) { if(0 == colIndex % 2) res = styles.rightTopColBand1LC; else res = styles.rightTopColBand2LC; } else if(rowIndex == bbox.r2 - totalsRowCount) { if(0 == (rowIndex - headerRowCount) % 2) { if(0 == colIndex % 2) res = styles.rightRowBand1ColBand1LC; else res = styles.rightRowBand1ColBand2LC; } else { if(0 == colIndex % 2) res = styles.rightRowBand2ColBand1LC; else res = styles.rightRowBand2ColBand2LC; } } else { if(0 == (rowIndex - headerRowCount) % 2) { if(0 == colIndex % 2) res = styles.rightBottomRowBand1ColBand1LC; else res = styles.rightBottomRowBand1ColBand2LC; } else { if(0 == colIndex % 2) res = styles.rightBottomRowBand2ColBand1LC; else res = styles.rightBottomRowBand2ColBand2LC; } } } else if(options.ShowRowStripes || options.ShowColumnStripes) { if(rowIndex == bbox.r1 + headerRowCount) { if(colIndex == bbox.c1) res = styles.leftTop; else if(colIndex == bbox.c2) { if(0 == colIndex % 2) res = styles.rightTopColBand1; else res = styles.rightTopColBand2; } else { if(0 == colIndex % 2) res = styles.topColBand1; else res = styles.topColBand2; } } else if(rowIndex == bbox.r2 - totalsRowCount) { if(colIndex == bbox.c1) { if(0 == (rowIndex - headerRowCount) % 2) res = styles.leftBottomRowBand1; else res = styles.leftBottomRowBand2; } else if(colIndex == bbox.c2) { if(0 == (rowIndex - headerRowCount) % 2) { if(0 == colIndex % 2) res = styles.rightBottomRowBand1ColBand1; else res = styles.rightBottomRowBand1ColBand2; } else { if(0 == colIndex % 2) res = styles.rightBottomRowBand2ColBand1; else res = styles.rightBottomRowBand2ColBand2; } } else { if(0 == (rowIndex - headerRowCount) % 2) { if(0 == colIndex % 2) res = styles.bottomRowBand1ColBand1; else res = styles.bottomRowBand1ColBand2; } else { if(0 == colIndex % 2) res = styles.bottomRowBand2ColBand1; else res = styles.bottomRowBand2ColBand2; } } } else if(colIndex == bbox.c1) { if(0 == (rowIndex - headerRowCount) % 2) res = styles.leftRowBand1; else res = styles.leftRowBand2; } else if(colIndex == bbox.c2) { if(0 == (rowIndex - headerRowCount) % 2) { if(0 == colIndex % 2) res = styles.rightRowBand1ColBand1; else res = styles.rightRowBand1ColBand2; } else { if(0 == colIndex % 2) res = styles.rightRowBand2ColBand1; else res = styles.rightRowBand2ColBand2; } } else { if(0 == (rowIndex - headerRowCount) % 2) { if(0 == colIndex % 2) res = styles.innerRowBand1ColBand1; else res = styles.innerRowBand1ColBand2; } else { if(0 == colIndex % 2) res = styles.innerRowBand2ColBand1; else res = styles.innerRowBand2ColBand2; } } } else { if(rowIndex == bbox.r1 + headerRowCount) { if(colIndex == bbox.c1) res = styles.leftTop; else if(colIndex == bbox.c2) res = styles.rightTopColBand1; else res = styles.topColBand1; } else if(rowIndex == bbox.r2 - totalsRowCount) { if(colIndex == bbox.c1) res = styles.leftBottomRowBand1; else if(colIndex == bbox.c2) res = styles.rightBottomRowBand1ColBand1; else res = styles.bottomRowBand1ColBand1; } else if(colIndex == bbox.c1) res = styles.leftRowBand1; else if(colIndex == bbox.c2) res = styles.rightRowBand1ColBand1; else res = styles.innerRowBand1ColBand1; } return res; }, _getOption: function(options, headerRowCount, totalsRowCount) { var nBitMask = 0; if(options.ShowFirstColumn) nBitMask += 1; if(options.ShowLastColumn) nBitMask += 1 << 1; if(options.ShowRowStripes) nBitMask += 1 << 2; if(options.ShowColumnStripes) nBitMask += 1 << 3; if(headerRowCount > 0) nBitMask += 1 << 4; if(totalsRowCount > 0) nBitMask += 1 << 5; var styles = this.compiled.options[nBitMask]; if(null == styles) { var configs = { header: {header: true, top: true}, headerLeftTop: {header: true, left: true, top: true}, headerRightTop: {header: true, right: true, top: true}, total: {total: true, bottom: true}, totalLeftBottom: {total: true, left: true, bottom: true}, totalRightBottom: {total: true, right: true, bottom: true}, leftTop: {ShowRowStripes: true, ShowColumnStripes: true, left: true, top: true, RowBand1: true, ColBand1: true}, leftBottomRowBand1: {ShowRowStripes: true, ShowColumnStripes: true, left: true, bottom: true, RowBand1: true, ColBand1: true}, leftBottomRowBand2: {ShowRowStripes: true, ShowColumnStripes: true, left: true, bottom: true, RowBand2: true, ColBand1: true}, leftRowBand1: {ShowRowStripes: true, ShowColumnStripes: true, left: true, RowBand1: true, ColBand1: true}, leftRowBand2: {ShowRowStripes: true, ShowColumnStripes: true, left: true, RowBand2: true, ColBand1: true}, rightTopColBand1: {ShowRowStripes: true, ShowColumnStripes: true, right: true, top: true, RowBand1: true, ColBand1: true}, rightTopColBand2: {ShowRowStripes: true, ShowColumnStripes: true, right: true, top: true, RowBand1: true, ColBand2: true}, rightRowBand1ColBand1: {ShowRowStripes: true, ShowColumnStripes: true, right: true, RowBand1: true, ColBand1: true}, rightRowBand1ColBand2: {ShowRowStripes: true, ShowColumnStripes: true, right: true, RowBand1: true, ColBand2: true}, rightRowBand2ColBand1: {ShowRowStripes: true, ShowColumnStripes: true, right: true, RowBand2: true, ColBand1: true}, rightRowBand2ColBand2: {ShowRowStripes: true, ShowColumnStripes: true, right: true, RowBand2: true, ColBand2: true}, rightBottomRowBand1ColBand1: {ShowRowStripes: true, ShowColumnStripes: true, right: true, bottom: true, RowBand1: true, ColBand1: true}, rightBottomRowBand1ColBand2: {ShowRowStripes: true, ShowColumnStripes: true, right: true, bottom: true, RowBand1: true, ColBand2: true}, rightBottomRowBand2ColBand1: {ShowRowStripes: true, ShowColumnStripes: true, right: true, bottom: true, RowBand2: true, ColBand1: true}, rightBottomRowBand2ColBand2: {ShowRowStripes: true, ShowColumnStripes: true, right: true, bottom: true, RowBand2: true, ColBand2: true}, topColBand1: {ShowRowStripes: true, ShowColumnStripes: true, top: true, RowBand1: true, ColBand1: true}, topColBand2: {ShowRowStripes: true, ShowColumnStripes: true, top: true, RowBand1: true, ColBand2: true}, bottomRowBand1ColBand1: {ShowRowStripes: true, ShowColumnStripes: true, bottom: true, RowBand1: true, ColBand1: true}, bottomRowBand1ColBand2: {ShowRowStripes: true, ShowColumnStripes: true, bottom: true, RowBand1: true, ColBand2: true}, bottomRowBand2ColBand1: {ShowRowStripes: true, ShowColumnStripes: true, bottom: true, RowBand2: true, ColBand1: true}, bottomRowBand2ColBand2: {ShowRowStripes: true, ShowColumnStripes: true, bottom: true, RowBand2: true, ColBand2: true}, innerRowBand1ColBand1: {ShowRowStripes: true, ShowColumnStripes: true, RowBand1: true, ColBand1: true}, innerRowBand1ColBand2: {ShowRowStripes: true, ShowColumnStripes: true, RowBand1: true, ColBand2: true}, innerRowBand2ColBand1: {ShowRowStripes: true, ShowColumnStripes: true, RowBand2: true, ColBand1: true}, innerRowBand2ColBand2: {ShowRowStripes: true, ShowColumnStripes: true, RowBand2: true, ColBand2: true}, leftTopFC: {ShowFirstColumn: true, ShowRowStripes: true, ShowColumnStripes: true, left: true, top: true, RowBand1: true, ColBand1: true}, leftBottomRowBand1FC: {ShowFirstColumn: true, ShowRowStripes: true, ShowColumnStripes: true, left: true, bottom: true, RowBand1: true, ColBand1: true}, leftBottomRowBand2FC: {ShowFirstColumn: true, ShowRowStripes: true, ShowColumnStripes: true, left: true, bottom: true, RowBand2: true, ColBand1: true}, leftRowBand1FC: {ShowFirstColumn: true, ShowRowStripes: true, ShowColumnStripes: true, left: true, RowBand1: true, ColBand1: true}, leftRowBand2FC: {ShowFirstColumn: true, ShowRowStripes: true, ShowColumnStripes: true, left: true, RowBand2: true, ColBand1: true}, rightTopColBand1LC: {ShowLastColumn: true, ShowRowStripes: true, ShowColumnStripes: true, right: true, top: true, RowBand1: true, ColBand1: true}, rightTopColBand2LC: {ShowLastColumn: true, ShowRowStripes: true, ShowColumnStripes: true, right: true, top: true, RowBand1: true, ColBand2: true}, rightRowBand1ColBand1LC: {ShowLastColumn: true, ShowRowStripes: true, ShowColumnStripes: true, right: true, RowBand1: true, ColBand1: true}, rightRowBand1ColBand2LC: {ShowLastColumn: true, ShowRowStripes: true, ShowColumnStripes: true, right: true, RowBand1: true, ColBand2: true}, rightRowBand2ColBand1LC: {ShowLastColumn: true, ShowRowStripes: true, ShowColumnStripes: true, right: true, RowBand2: true, ColBand1: true}, rightRowBand2ColBand2LC: {ShowLastColumn: true, ShowRowStripes: true, ShowColumnStripes: true, right: true, RowBand2: true, ColBand2: true}, rightBottomRowBand1ColBand1LC: {ShowLastColumn: true, ShowRowStripes: true, ShowColumnStripes: true, right: true, bottom: true, RowBand1: true, ColBand1: true}, rightBottomRowBand1ColBand2LC: {ShowLastColumn: true, ShowRowStripes: true, ShowColumnStripes: true, right: true, bottom: true, RowBand1: true, ColBand2: true}, rightBottomRowBand2ColBand1LC: {ShowLastColumn: true, ShowRowStripes: true, ShowColumnStripes: true, right: true, bottom: true, RowBand2: true, ColBand1: true}, rightBottomRowBand2ColBand2LC: {ShowLastColumn: true, ShowRowStripes: true, ShowColumnStripes: true, right: true, bottom: true, RowBand2: true, ColBand2: true} } var styles = new Object(); for(var i in configs) { styles[i] = new CellXfs(); } this._compileOption(options, headerRowCount, totalsRowCount, styles, configs); this.compiled.options[nBitMask] = styles; } return styles; }, _compileSetBorder : function(inputDxf, outputDxf, bLeft, bTop, bRight, bBottom, bInnerHor, bInnerVer) { if(null != inputDxf && null != inputDxf.border) { var oCurBorder = inputDxf.border; var oNewBorder = new Border(); if(bLeft) oNewBorder.l = oCurBorder.l; else if(bInnerVer) oNewBorder.l = oCurBorder.iv; if(bTop) oNewBorder.t = oCurBorder.t; else if(bInnerHor) oNewBorder.t = oCurBorder.ih; if(bRight) oNewBorder.r = oCurBorder.r; else if(bInnerVer) oNewBorder.r = oCurBorder.iv; if(bBottom) oNewBorder.b = oCurBorder.b; else if(bInnerHor) oNewBorder.b = oCurBorder.ih; if(null == outputDxf.border) outputDxf.border = oNewBorder; else outputDxf.border = outputDxf.border.merge(oNewBorder); } }, _compileSetHeaderBorder : function(inputDxf, outputDxf, bHeader) { if(null != inputDxf && null != inputDxf.border) { var oCurBorder = inputDxf.border; var oNewBorder = new Border(); if(bHeader) oNewBorder.t = oCurBorder.b; else oNewBorder.b = oCurBorder.t; if(null == outputDxf.border) outputDxf.border = oNewBorder; else outputDxf.border = outputDxf.border.merge(oNewBorder); } }, _compileOption : function(options, headerRowCount, totalsRowCount, styles, configs) { for(var i in styles) { var xfs = styles[i]; var config = configs[i]; //заглушка для бордеров, чтобы при конфликте нижние бордеры не перекрывали бордеры заголовка if(headerRowCount > 0 && config.top && true != config.header) { if(options.ShowFirstColumn && null != this.firstHeaderCell && config.left) this._compileSetHeaderBorder(this.firstHeaderCell.dxf, xfs, true); else if(options.ShowLastColumn && null != this.lastHeaderCell && config.right) this._compileSetHeaderBorder(this.lastHeaderCell.dxf, xfs, true); if(null != this.headerRow) this._compileSetHeaderBorder(this.headerRow.dxf, xfs, true); } if(totalsRowCount > 0 && config.bottom && true != config.total) { if(options.ShowFirstColumn && null != this.firstTotalCell && config.left) this._compileSetHeaderBorder(this.firstTotalCell.dxf, xfs, false); else if(options.ShowLastColumn && null != this.lastTotalCell && config.right) this._compileSetHeaderBorder(this.lastTotalCell.dxf, xfs, false); if(null != this.totalRow) this._compileSetHeaderBorder(this.totalRow.dxf, xfs, false); } if(headerRowCount > 0 && config.header) { if(options.ShowFirstColumn && null != this.firstHeaderCell && config.left) xfs = xfs.merge(this.firstHeaderCell.dxf); if(options.ShowLastColumn && null != this.lastHeaderCell && config.right) xfs = xfs.merge(this.lastHeaderCell.dxf); if(null != this.headerRow) { xfs = xfs.merge(this.compiled.headerRow.dxf); //применяем бордер if(config.left) this._compileSetBorder(this.headerRow.dxf, xfs, true, true, false, true, false, true); else if(config.right) this._compileSetBorder(this.headerRow.dxf, xfs, false, true, true, true, false, true); else this._compileSetBorder(this.headerRow.dxf, xfs, false, true, false, true, false, true); } if(options.ShowFirstColumn && null != this.firstColumn && config.left) { xfs = xfs.merge(this.compiled.firstColumn.dxf); //применяем бордер this._compileSetBorder(this.firstColumn.dxf, xfs, true, true, true, false, true, false); } if(options.ShowLastColumn && null != this.lastColumn && config.right) { xfs = xfs.merge(this.compiled.lastColumn.dxf); //применяем бордер this._compileSetBorder(this.lastColumn.dxf, xfs, true, true, true, false, true, false); } } else if(totalsRowCount > 0 && config.total) { if(options.ShowFirstColumn && null != this.firstTotalCell && config.left) xfs = xfs.merge(this.firstTotalCell.dxf); if(options.ShowLastColumn && null != this.lastTotalCell && config.right) xfs = xfs.merge(this.lastTotalCell.dxf); if(null != this.totalRow) { xfs = xfs.merge(this.compiled.totalRow.dxf); //применяем бордер if(config.left) this._compileSetBorder(this.totalRow.dxf, xfs, true, true, false, true, false, true); else if(config.right) this._compileSetBorder(this.totalRow.dxf, xfs, false, true, true, true, false, true); else this._compileSetBorder(this.totalRow.dxf, xfs, false, true, false, true, false, true); } if(options.ShowFirstColumn && null != this.firstColumn && config.left) { xfs = xfs.merge(this.compiled.firstColumn.dxf); //применяем бордер this._compileSetBorder(this.firstColumn.dxf, xfs, true, false, true, true, true, false); } if(options.ShowLastColumn && null != this.lastColumn && config.right) { xfs = xfs.merge(this.compiled.lastColumn.dxf); //применяем бордер this._compileSetBorder(this.lastColumn.dxf, xfs, true, false, true, true, true, false); } } else { if(options.ShowFirstColumn && null != this.firstColumn && config.ShowFirstColumn) { xfs = xfs.merge(this.compiled.firstColumn.dxf); //применяем бордер if(config.left && config.top) { if(headerRowCount > 0) this._compileSetBorder(this.firstColumn.dxf, xfs, true, false, true, false, true, false); else this._compileSetBorder(this.firstColumn.dxf, xfs, true, true, true, false, true, false); } else if(config.left && config.bottom) { if(totalsRowCount > 0) this._compileSetBorder(this.firstColumn.dxf, xfs, true, false, true, false, true, false); else this._compileSetBorder(this.firstColumn.dxf, xfs, true, false, true, true, true, false); } else this._compileSetBorder(this.firstColumn.dxf, xfs, true, false, true, false, true, false); } else if(options.ShowLastColumn && null != this.lastColumn && config.ShowLastColumn) { xfs = xfs.merge(this.compiled.lastColumn.dxf); //применяем бордер if(config.right && config.top) { if(headerRowCount > 0) this._compileSetBorder(this.lastColumn.dxf, xfs, true, false, true, false, true, false); else this._compileSetBorder(this.lastColumn.dxf, xfs, true, true, true, false, true, false); } else if(config.right && config.bottom) { if(totalsRowCount > 0) this._compileSetBorder(this.lastColumn.dxf, xfs, true, false, true, false, true, false); else this._compileSetBorder(this.lastColumn.dxf, xfs, true, false, true, true, true, false); } else this._compileSetBorder(this.lastColumn.dxf, xfs, true, false, true, false, true, false); } if(options.ShowRowStripes && config.ShowRowStripes) { if(null != this.firstRowStripe && config.RowBand1) { xfs = xfs.merge(this.compiled.firstRowStripe.dxf); //применяем бордер if(config.left) this._compileSetBorder(this.firstRowStripe.dxf, xfs, true, true, false, true, false, true); else if(config.right) this._compileSetBorder(this.firstRowStripe.dxf, xfs, false, true, true, true, false, true); else this._compileSetBorder(this.firstRowStripe.dxf, xfs, false, true, false, true, false, true); } else if(null != this.secondRowStripe && config.RowBand2) { xfs = xfs.merge(this.compiled.secondRowStripe.dxf); //применяем бордер if(config.left) this._compileSetBorder(this.secondRowStripe.dxf, xfs, true, true, false, true, false, true); else if(config.right) this._compileSetBorder(this.secondRowStripe.dxf, xfs, false, true, true, true, false, true); else this._compileSetBorder(this.secondRowStripe.dxf, xfs, false, true, false, true, false, true); } } if(options.ShowColumnStripes && config.ShowRowStripes) { if(null != this.firstColumnStripe && config.ColBand1) { xfs = xfs.merge(this.compiled.firstColumnStripe.dxf); //применяем бордер if(config.top) this._compileSetBorder(this.firstColumnStripe.dxf, xfs, true, true, true, false, true, false); else if(config.bottom) this._compileSetBorder(this.firstColumnStripe.dxf, xfs, true, false, true, true, true, false); else this._compileSetBorder(this.firstColumnStripe.dxf, xfs, true, false, true, false, true, false); } else if(null != this.secondColumnStripe && config.ColBand2) { xfs = xfs.merge(this.compiled.secondColumnStripe.dxf); //применяем бордер if(config.top) this._compileSetBorder(this.secondColumnStripe.dxf, xfs, true, true, true, false, true, false); else if(config.bottom) this._compileSetBorder(this.secondColumnStripe.dxf, xfs, true, false, true, true, true, false); else this._compileSetBorder(this.secondColumnStripe.dxf, xfs, true, false, true, false, true, false); } } } if(null != this.wholeTable) { xfs = xfs.merge(this.compiled.wholeTable.dxf); //применяем бордер if(config.top) { if(headerRowCount > 0 && true != config.header) { if(config.left) this._compileSetBorder(this.wholeTable.dxf, xfs, true, false, false, false, true, true); else if(config.right) this._compileSetBorder(this.wholeTable.dxf, xfs, false, false, true, false, true, true); else this._compileSetBorder(this.wholeTable.dxf, xfs, false, false, false, false, true, true); } else { if(config.left) this._compileSetBorder(this.wholeTable.dxf, xfs, true, true, false, false, true, true); else if(config.right) this._compileSetBorder(this.wholeTable.dxf, xfs, false, true, true, false, true, true); else this._compileSetBorder(this.wholeTable.dxf, xfs, false, true, false, false, true, true); } } else if(config.bottom) { if(totalsRowCount > 0 && true != config.total) { if(config.left) this._compileSetBorder(this.wholeTable.dxf, xfs, true, false, false, false, true, true); else if(config.right) this._compileSetBorder(this.wholeTable.dxf, xfs, false, false, true, false, true, true); else this._compileSetBorder(this.wholeTable.dxf, xfs, false, false, false, false, true, true); } else { if(config.left) this._compileSetBorder(this.wholeTable.dxf, xfs, true, false, false, true, true, true); else if(config.right) this._compileSetBorder(this.wholeTable.dxf, xfs, false, false, true, true, true, true); else this._compileSetBorder(this.wholeTable.dxf, xfs, false, false, false, true, true, true); } } else if(config.left) this._compileSetBorder(this.wholeTable.dxf, xfs, true, false, false, false, true, true); else if(config.right) this._compileSetBorder(this.wholeTable.dxf, xfs, false, false, true, false, true, true); else this._compileSetBorder(this.wholeTable.dxf, xfs, false, false, false, false, true, true); } styles[i] = xfs; } }, _compile : function() { this.compiled = { options: new Object(), blankRow: null, firstColumn: null, firstColumnStripe: null, firstColumnSubheading: null, firstHeaderCell: null, firstRowStripe: null, firstRowSubheading: null, firstSubtotalColumn: null, firstSubtotalRow: null, firstTotalCell: null, headerRow: null, lastColumn: null, lastHeaderCell: null, lastTotalCell: null, pageFieldLabels: null, pageFieldValues: null, secondColumnStripe: null, secondColumnSubheading: null, secondRowStripe: null, secondRowSubheading: null, secondSubtotalColumn: null, secondSubtotalRow: null, thirdColumnSubheading: null, thirdRowSubheading: null, thirdSubtotalColumn: null, thirdSubtotalRow: null, totalRow: null, wholeTable: null } //копируем исходные стили только без border for(var i in this) { var elem = this[i]; if(null != elem && elem instanceof CTableStyleElement) { var oNewElem = new CTableStyleElement(); oNewElem.size = elem.size; oNewElem.dxf = elem.dxf.clone(); oNewElem.dxf.border = null; this.compiled[i] = oNewElem; } } } } function CTableStyleElement() { this.size = 1; this.dxf = null; } function ReadDefTableStyles(wb, oOutput) { var Types = { Style: 0, Dxf: 1, tableStyles: 2 }; var sStyles = "X4kAAAB+AgAAAYYBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBCQMFmsxMZiYz4z8LHAAAAAIXAAAAABIAAAABDQAAAAIBCQMFmsxMZiYz4z8LEQAAAAMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAFDAAAAAAGAwAAAAIBCQEBBgMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQvRAAAAAaIAAAAAFgAAAAAGDQAAAAIBCQMFzWRmMjOZ2T8BAQ0CFgAAAAAGDQAAAAIBCQMFzWRmMjOZ2T8BAQ0DFgAAAAAGDQAAAAIBCQMFzWRmMjOZ2T8BAQ0EFgAAAAAGDQAAAAIBCQMFzWRmMjOZ2T8BAQ0FFgAAAAAGDQAAAAIBCQMFzWRmMjOZ2T8BAQ0GFgAAAAAGDQAAAAIBCQMFzWRmMjOZ2T8BAQ0CFwAAAAASAAAAAQ0AAAACAQkDBc1l5jJzmek/AwkAAAABBgMAAAACAQEC7gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKbAAAAA5YAAAAAJAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AMgA4AAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAfgIAAAGGAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQgDBZrMTGYmM+M/CxwAAAACFwAAAAASAAAAAQ0AAAACAQgDBZrMTGYmM+M/CxEAAAADDAAAAAABAQEGAwAAAAIBAQsRAAAAAwwAAAAAAQEBBgMAAAACAQELJwAAAAERAAAABQwAAAAABgMAAAACAQgBAQYDDAAAAAABAQEGAwAAAAIBAQsRAAAAAwwAAAAAAQEBBgMAAAACAQEL0QAAAAGiAAAAABYAAAAABg0AAAACAQgDBc1kZjIzmdk/AQENAhYAAAAABg0AAAACAQgDBc1kZjIzmdk/AQENAxYAAAAABg0AAAACAQgDBc1kZjIzmdk/AQENBBYAAAAABg0AAAACAQgDBc1kZjIzmdk/AQENBRYAAAAABg0AAAACAQgDBc1kZjIzmdk/AQENBhYAAAAABg0AAAACAQgDBc1kZjIzmdk/AQENAhcAAAAAEgAAAAENAAAAAgEIAwXNZeYyc5npPwMJAAAAAQYDAAAAAgEBAu4AAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgACmwAAAAOWAAAAACQAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADIANwABAQAAAAADYgAAAAQJAAAAAgEbAAQHAAAABAkAAAACAQoABAYAAAAECQAAAAIBGgAEBQAAAAQJAAAAAgEBAAQEAAAABAkAAAACAQsABAMAAAAECQAAAAIBBQAEAgAAAAQJAAAAAgECAAQBAAAAAH4CAAABhgEAAAscAAAAAhcAAAAAEgAAAAENAAAAAgEHAwWazExmJjPjPwscAAAAAhcAAAAAEgAAAAENAAAAAgEHAwWazExmJjPjPwsRAAAAAwwAAAAAAQEBBgMAAAACAQELEQAAAAMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAUMAAAAAAYDAAAAAgEHAQEGAwwAAAAAAQEBBgMAAAACAQELEQAAAAMMAAAAAAEBAQYDAAAAAgEBC9EAAAABogAAAAAWAAAAAAYNAAAAAgEHAwXNZGYyM5nZPwEBDQIWAAAAAAYNAAAAAgEHAwXNZGYyM5nZPwEBDQMWAAAAAAYNAAAAAgEHAwXNZGYyM5nZPwEBDQQWAAAAAAYNAAAAAgEHAwXNZGYyM5nZPwEBDQUWAAAAAAYNAAAAAgEHAwXNZGYyM5nZPwEBDQYWAAAAAAYNAAAAAgEHAwXNZGYyM5nZPwEBDQIXAAAAABIAAAABDQAAAAIBBwMFzWXmMnOZ6T8DCQAAAAEGAwAAAAIBAQLuAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApsAAAADlgAAAAAkAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQAyADYAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAAB+AgAAAYYBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBBgMFmsxMZiYz4z8LHAAAAAIXAAAAABIAAAABDQAAAAIBBgMFmsxMZiYz4z8LEQAAAAMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAFDAAAAAAGAwAAAAIBBgEBBgMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQvRAAAAAaIAAAAAFgAAAAAGDQAAAAIBBgMFzWRmMjOZ2T8BAQ0CFgAAAAAGDQAAAAIBBgMFzWRmMjOZ2T8BAQ0DFgAAAAAGDQAAAAIBBgMFzWRmMjOZ2T8BAQ0EFgAAAAAGDQAAAAIBBgMFzWRmMjOZ2T8BAQ0FFgAAAAAGDQAAAAIBBgMFzWRmMjOZ2T8BAQ0GFgAAAAAGDQAAAAIBBgMFzWRmMjOZ2T8BAQ0CFwAAAAASAAAAAQ0AAAACAQYDBc1l5jJzmek/AwkAAAABBgMAAAACAQEC7gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKbAAAAA5YAAAAAJAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AMgA1AAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAfgIAAAGGAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQUDBZrMTGYmM+M/CxwAAAACFwAAAAASAAAAAQ0AAAACAQUDBZrMTGYmM+M/CxEAAAADDAAAAAABAQEGAwAAAAIBAQsRAAAAAwwAAAAAAQEBBgMAAAACAQELJwAAAAERAAAABQwAAAAABgMAAAACAQUBAQYDDAAAAAABAQEGAwAAAAIBAQsRAAAAAwwAAAAAAQEBBgMAAAACAQEL0QAAAAGiAAAAABYAAAAABg0AAAACAQUDBc1kZjIzmdk/AQENAhYAAAAABg0AAAACAQUDBc1kZjIzmdk/AQENAxYAAAAABg0AAAACAQUDBc1kZjIzmdk/AQENBBYAAAAABg0AAAACAQUDBc1kZjIzmdk/AQENBRYAAAAABg0AAAACAQUDBc1kZjIzmdk/AQENBhYAAAAABg0AAAACAQUDBc1kZjIzmdk/AQENAhcAAAAAEgAAAAENAAAAAgEFAwXNZeYyc5npPwMJAAAAAQYDAAAAAgEBAu4AAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgACmwAAAAOWAAAAACQAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADIANAABAQAAAAADYgAAAAQJAAAAAgEbAAQHAAAABAkAAAACAQoABAYAAAAECQAAAAIBGgAEBQAAAAQJAAAAAgEBAAQEAAAABAkAAAACAQsABAMAAAAECQAAAAIBBQAEAgAAAAQJAAAAAgECAAQBAAAAAH4CAAABhgEAAAscAAAAAhcAAAAAEgAAAAENAAAAAgEEAwWazExmJjPjPwscAAAAAhcAAAAAEgAAAAENAAAAAgEEAwWazExmJjPjPwsRAAAAAwwAAAAAAQEBBgMAAAACAQELEQAAAAMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAUMAAAAAAYDAAAAAgEEAQEGAwwAAAAAAQEBBgMAAAACAQELEQAAAAMMAAAAAAEBAQYDAAAAAgEBC9EAAAABogAAAAAWAAAAAAYNAAAAAgEEAwXNZGYyM5nZPwEBDQIWAAAAAAYNAAAAAgEEAwXNZGYyM5nZPwEBDQMWAAAAAAYNAAAAAgEEAwXNZGYyM5nZPwEBDQQWAAAAAAYNAAAAAgEEAwXNZGYyM5nZPwEBDQUWAAAAAAYNAAAAAgEEAwXNZGYyM5nZPwEBDQYWAAAAAAYNAAAAAgEEAwXNZGYyM5nZPwEBDQIXAAAAABIAAAABDQAAAAIBBAMFzWXmMnOZ6T8DCQAAAAEGAwAAAAIBAQLuAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApsAAAADlgAAAAAkAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQAyADMAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAABCAgAAAUoBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBAAMFs5hZzCxm1r8LHAAAAAIXAAAAABIAAAABDQAAAAIBAAMFs5hZzCxm1r8LEQAAAAMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAFDAAAAAAGAwAAAAIBAQEBBgMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQuVAAAAAWYAAAAADAAAAAAGAwAAAAIBAQEBDQIMAAAAAAYDAAAAAgEBAQENAwwAAAAABgMAAAACAQEBAQ0EDAAAAAAGAwAAAAIBAQEBDQUMAAAAAAYDAAAAAgEBAQENBgwAAAAABgMAAAACAQEBAQ0CFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/AwkAAAABBgMAAAACAQEC7gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKbAAAAA5YAAAAAJAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AMgAyAAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAHQIAAAElAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CyMAAAACDQAAAAAIAAAAAQMAAAACAQkDDAAAAAABAQEGAwAAAAIBAAsjAAAAAg0AAAAACAAAAAEDAAAAAgEJAwwAAAAAAQEBBgMAAAACAQALFgAAAAERAAAABQwAAAAABgMAAAACAQEBAQQLOQAAAAERAAAAAAwAAAAABgMAAAACAQEBAQYCDQAAAAAIAAAAAQMAAAACAQkDDAAAAAABAQEGAwAAAAIBAAs1AAAAASIAAAAADAAAAAAGAwAAAAIBAQEBBgUMAAAAAAYDAAAAAgEBAQEGAwkAAAABBgMAAAACAQEC7gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKbAAAAA5YAAAAAJAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AMgAxAAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAHQIAAAElAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CyMAAAACDQAAAAAIAAAAAQMAAAACAQgDDAAAAAABAQEGAwAAAAIBAAsjAAAAAg0AAAAACAAAAAEDAAAAAgEIAwwAAAAAAQEBBgMAAAACAQALFgAAAAERAAAABQwAAAAABgMAAAACAQEBAQQLOQAAAAERAAAAAAwAAAAABgMAAAACAQEBAQYCDQAAAAAIAAAAAQMAAAACAQgDDAAAAAABAQEGAwAAAAIBAAs1AAAAASIAAAAADAAAAAAGAwAAAAIBAQEBBgUMAAAAAAYDAAAAAgEBAQEGAwkAAAABBgMAAAACAQEC7gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKbAAAAA5YAAAAAJAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AMgAwAAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAHQIAAAElAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CyMAAAACDQAAAAAIAAAAAQMAAAACAQcDDAAAAAABAQEGAwAAAAIBAAsjAAAAAg0AAAAACAAAAAEDAAAAAgEHAwwAAAAAAQEBBgMAAAACAQALFgAAAAERAAAABQwAAAAABgMAAAACAQEBAQQLOQAAAAERAAAAAAwAAAAABgMAAAACAQEBAQYCDQAAAAAIAAAAAQMAAAACAQcDDAAAAAABAQEGAwAAAAIBAAs1AAAAASIAAAAADAAAAAAGAwAAAAIBAQEBBgUMAAAAAAYDAAAAAgEBAQEGAwkAAAABBgMAAAACAQEC7gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKbAAAAA5YAAAAAJAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AMQA5AAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAHQIAAAElAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CyMAAAACDQAAAAAIAAAAAQMAAAACAQYDDAAAAAABAQEGAwAAAAIBAAsjAAAAAg0AAAAACAAAAAEDAAAAAgEGAwwAAAAAAQEBBgMAAAACAQALFgAAAAERAAAABQwAAAAABgMAAAACAQEBAQQLOQAAAAERAAAAAAwAAAAABgMAAAACAQEBAQYCDQAAAAAIAAAAAQMAAAACAQYDDAAAAAABAQEGAwAAAAIBAAs1AAAAASIAAAAADAAAAAAGAwAAAAIBAQEBBgUMAAAAAAYDAAAAAgEBAQEGAwkAAAABBgMAAAACAQEC7gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKbAAAAA5YAAAAAJAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AMQA4AAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAHQIAAAElAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CyMAAAACDQAAAAAIAAAAAQMAAAACAQUDDAAAAAABAQEGAwAAAAIBAAsjAAAAAg0AAAAACAAAAAEDAAAAAgEFAwwAAAAAAQEBBgMAAAACAQALFgAAAAERAAAABQwAAAAABgMAAAACAQEBAQQLOQAAAAERAAAAAAwAAAAABgMAAAACAQEBAQYCDQAAAAAIAAAAAQMAAAACAQUDDAAAAAABAQEGAwAAAAIBAAs1AAAAASIAAAAADAAAAAAGAwAAAAIBAQEBBgUMAAAAAAYDAAAAAgEBAQEGAwkAAAABBgMAAAACAQEC7gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKbAAAAA5YAAAAAJAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AMQA3AAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAHQIAAAElAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CyMAAAACDQAAAAAIAAAAAQMAAAACAQQDDAAAAAABAQEGAwAAAAIBAAsjAAAAAg0AAAAACAAAAAEDAAAAAgEEAwwAAAAAAQEBBgMAAAACAQALFgAAAAERAAAABQwAAAAABgMAAAACAQEBAQQLOQAAAAERAAAAAAwAAAAABgMAAAACAQEBAQYCDQAAAAAIAAAAAQMAAAACAQQDDAAAAAABAQEGAwAAAAIBAAs1AAAAASIAAAAADAAAAAAGAwAAAAIBAQEBBgUMAAAAAAYDAAAAAgEBAQEGAwkAAAABBgMAAAACAQEC7gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKbAAAAA5YAAAAAJAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AMQA2AAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAYQIAAAFpAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CyMAAAACDQAAAAAIAAAAAQMAAAACAQEDDAAAAAABAQEGAwAAAAIBAAsjAAAAAg0AAAAACAAAAAEDAAAAAgEBAwwAAAAAAQEBBgMAAAACAQALFgAAAAERAAAABQwAAAAABgMAAAACAQEBAQQLOQAAAAERAAAAAAwAAAAABgMAAAACAQEBAQYCDQAAAAAIAAAAAQMAAAACAQEDDAAAAAABAQEGAwAAAAIBAAt5AAAAAWYAAAAADAAAAAAGAwAAAAIBAQEBBgIMAAAAAAYDAAAAAgEBAQENAwwAAAAABgMAAAACAQEBAQ0EDAAAAAAGAwAAAAIBAQEBDQUMAAAAAAYDAAAAAgEBAQEGBgwAAAAABgMAAAACAQEBAQ0DCQAAAAEGAwAAAAIBAQLuAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApsAAAADlgAAAAAkAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQAxADUAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAABcAgAAAWQBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBCQMFmsxMZiYz4z8LHAAAAAIXAAAAABIAAAABDQAAAAIBCQMFmsxMZiYz4z8LIwAAAAINAAAAAAgAAAABAwAAAAIBCQMMAAAAAAEBAQYDAAAAAgEACyMAAAACDQAAAAAIAAAAAQMAAAACAQkDDAAAAAABAQEGAwAAAAIBAAs5AAAAAREAAAAFDAAAAAAGAwAAAAIBAAEBDAINAAAAAAgAAAABAwAAAAIBCQMMAAAAAAEBAQYDAAAAAgEACzkAAAABEQAAAAAMAAAAAAYDAAAAAgEAAQEMAg0AAAAACAAAAAEDAAAAAgEJAwwAAAAAAQEBBgMAAAACAQALUQAAAAEiAAAAAwwAAAAABgMAAAACAQABAQ0GDAAAAAAGAwAAAAIBAAEBDQIXAAAAABIAAAABDQAAAAIBCQMFzWXmMnOZ6T8DCQAAAAEGAwAAAAIBAQLuAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApsAAAADlgAAAAAkAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQAxADQAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAABcAgAAAWQBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBCAMFmsxMZiYz4z8LHAAAAAIXAAAAABIAAAABDQAAAAIBCAMFmsxMZiYz4z8LIwAAAAINAAAAAAgAAAABAwAAAAIBCAMMAAAAAAEBAQYDAAAAAgEACyMAAAACDQAAAAAIAAAAAQMAAAACAQgDDAAAAAABAQEGAwAAAAIBAAs5AAAAAREAAAAFDAAAAAAGAwAAAAIBAAEBDAINAAAAAAgAAAABAwAAAAIBCAMMAAAAAAEBAQYDAAAAAgEACzkAAAABEQAAAAAMAAAAAAYDAAAAAgEAAQEMAg0AAAAACAAAAAEDAAAAAgEIAwwAAAAAAQEBBgMAAAACAQALUQAAAAEiAAAAAwwAAAAABgMAAAACAQABAQ0GDAAAAAAGAwAAAAIBAAEBDQIXAAAAABIAAAABDQAAAAIBCAMFzWXmMnOZ6T8DCQAAAAEGAwAAAAIBAQLuAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApsAAAADlgAAAAAkAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQAxADMAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAABcAgAAAWQBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBBwMFmsxMZiYz4z8LHAAAAAIXAAAAABIAAAABDQAAAAIBBwMFmsxMZiYz4z8LIwAAAAINAAAAAAgAAAABAwAAAAIBBwMMAAAAAAEBAQYDAAAAAgEACyMAAAACDQAAAAAIAAAAAQMAAAACAQcDDAAAAAABAQEGAwAAAAIBAAs5AAAAAREAAAAFDAAAAAAGAwAAAAIBAAEBDAINAAAAAAgAAAABAwAAAAIBBwMMAAAAAAEBAQYDAAAAAgEACzkAAAABEQAAAAAMAAAAAAYDAAAAAgEAAQEMAg0AAAAACAAAAAEDAAAAAgEHAwwAAAAAAQEBBgMAAAACAQALUQAAAAEiAAAAAwwAAAAABgMAAAACAQABAQ0GDAAAAAAGAwAAAAIBAAEBDQIXAAAAABIAAAABDQAAAAIBBwMFzWXmMnOZ6T8DCQAAAAEGAwAAAAIBAQLuAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApsAAAADlgAAAAAkAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQAxADIAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAABcAgAAAWQBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBBgMFmsxMZiYz4z8LHAAAAAIXAAAAABIAAAABDQAAAAIBBgMFmsxMZiYz4z8LIwAAAAINAAAAAAgAAAABAwAAAAIBBgMMAAAAAAEBAQYDAAAAAgEACyMAAAACDQAAAAAIAAAAAQMAAAACAQYDDAAAAAABAQEGAwAAAAIBAAs5AAAAAREAAAAFDAAAAAAGAwAAAAIBAAEBDAINAAAAAAgAAAABAwAAAAIBBgMMAAAAAAEBAQYDAAAAAgEACzkAAAABEQAAAAAMAAAAAAYDAAAAAgEAAQEMAg0AAAAACAAAAAEDAAAAAgEGAwwAAAAAAQEBBgMAAAACAQALUQAAAAEiAAAAAwwAAAAABgMAAAACAQABAQ0GDAAAAAAGAwAAAAIBAAEBDQIXAAAAABIAAAABDQAAAAIBBgMFzWXmMnOZ6T8DCQAAAAEGAwAAAAIBAQLuAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApsAAAADlgAAAAAkAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQAxADEAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAABcAgAAAWQBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBBQMFmsxMZiYz4z8LHAAAAAIXAAAAABIAAAABDQAAAAIBBQMFmsxMZiYz4z8LIwAAAAINAAAAAAgAAAABAwAAAAIBBQMMAAAAAAEBAQYDAAAAAgEACyMAAAACDQAAAAAIAAAAAQMAAAACAQUDDAAAAAABAQEGAwAAAAIBAAs5AAAAAREAAAAFDAAAAAAGAwAAAAIBAAEBDAINAAAAAAgAAAABAwAAAAIBBQMMAAAAAAEBAQYDAAAAAgEACzkAAAABEQAAAAAMAAAAAAYDAAAAAgEAAQEMAg0AAAAACAAAAAEDAAAAAgEFAwwAAAAAAQEBBgMAAAACAQALUQAAAAEiAAAAAwwAAAAABgMAAAACAQABAQ0GDAAAAAAGAwAAAAIBAAEBDQIXAAAAABIAAAABDQAAAAIBBQMFzWXmMnOZ6T8DCQAAAAEGAwAAAAIBAQLuAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApsAAAADlgAAAAAkAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQAxADAAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAABaAgAAAWQBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBBAMFmsxMZiYz4z8LHAAAAAIXAAAAABIAAAABDQAAAAIBBAMFmsxMZiYz4z8LIwAAAAINAAAAAAgAAAABAwAAAAIBBAMMAAAAAAEBAQYDAAAAAgEACyMAAAACDQAAAAAIAAAAAQMAAAACAQQDDAAAAAABAQEGAwAAAAIBAAs5AAAAAREAAAAFDAAAAAAGAwAAAAIBAAEBDAINAAAAAAgAAAABAwAAAAIBBAMMAAAAAAEBAQYDAAAAAgEACzkAAAABEQAAAAAMAAAAAAYDAAAAAgEAAQEMAg0AAAAACAAAAAEDAAAAAgEEAwwAAAAAAQEBBgMAAAACAQALUQAAAAEiAAAAAwwAAAAABgMAAAACAQABAQ0GDAAAAAAGAwAAAAIBAAEBDQIXAAAAABIAAAABDQAAAAIBBAMFzWXmMnOZ6T8DCQAAAAEGAwAAAAIBAQLsAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApkAAAADlAAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAWgIAAAFkAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQADBbOYWcwsZta/CxwAAAACFwAAAAASAAAAAQ0AAAACAQADBbOYWcwsZta/CyMAAAACDQAAAAAIAAAAAQMAAAACAQEDDAAAAAABAQEGAwAAAAIBAAsjAAAAAg0AAAAACAAAAAEDAAAAAgEBAwwAAAAAAQEBBgMAAAACAQALOQAAAAERAAAABQwAAAAABgMAAAACAQABAQwCDQAAAAAIAAAAAQMAAAACAQEDDAAAAAABAQEGAwAAAAIBAAs5AAAAAREAAAAADAAAAAAGAwAAAAIBAAEBDAINAAAAAAgAAAABAwAAAAIBAQMMAAAAAAEBAQYDAAAAAgEAC1EAAAABIgAAAAMMAAAAAAYDAAAAAgEAAQENBgwAAAAABgMAAAACAQABAQ0CFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/AwkAAAABBgMAAAACAQEC7AAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKZAAAAA5QAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOAABAQAAAAADYgAAAAQJAAAAAgEbAAQHAAAABAkAAAACAQoABAYAAAAECQAAAAIBGgAEBQAAAAQJAAAAAgEBAAQEAAAABAkAAAACAQsABAMAAAAECQAAAAIBBQAEAgAAAAQJAAAAAgECAAQBAAAAAFcCAAABYQEAAAscAAAAAhcAAAAAEgAAAAENAAAAAgEJAwXNZeYyc5npPwscAAAAAhcAAAAAEgAAAAENAAAAAgEJAwXNZeYyc5npPwsRAAAAAwwAAAAAAQEBBgMAAAACAQELEQAAAAMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAUMAAAAAAYDAAAAAgEJAQEEAwwAAAAAAQEBBgMAAAACAQELIwAAAAINAAAAAAgAAAABAwAAAAIBCQMMAAAAAAEBAQYDAAAAAgEAC5oAAAABhwAAAAAWAAAAAAYNAAAAAgEJAwXNZGYyM5nZPwEBDQIWAAAAAAYNAAAAAgEJAwXNZGYyM5nZPwEBDQMWAAAAAAYNAAAAAgEJAwXNZGYyM5nZPwEBDQQWAAAAAAYNAAAAAgEJAwXNZGYyM5nZPwEBDQUWAAAAAAYNAAAAAgEJAwXNZGYyM5nZPwEBDQMJAAAAAQYDAAAAAgEBAuwAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgACmQAAAAOUAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADcAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAABXAgAAAWEBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBCAMFzWXmMnOZ6T8LHAAAAAIXAAAAABIAAAABDQAAAAIBCAMFzWXmMnOZ6T8LEQAAAAMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAFDAAAAAAGAwAAAAIBCAEBBAMMAAAAAAEBAQYDAAAAAgEBCyMAAAACDQAAAAAIAAAAAQMAAAACAQgDDAAAAAABAQEGAwAAAAIBAAuaAAAAAYcAAAAAFgAAAAAGDQAAAAIBCAMFzWRmMjOZ2T8BAQ0CFgAAAAAGDQAAAAIBCAMFzWRmMjOZ2T8BAQ0DFgAAAAAGDQAAAAIBCAMFzWRmMjOZ2T8BAQ0EFgAAAAAGDQAAAAIBCAMFzWRmMjOZ2T8BAQ0FFgAAAAAGDQAAAAIBCAMFzWRmMjOZ2T8BAQ0DCQAAAAEGAwAAAAIBAQLsAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApkAAAADlAAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA2AAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAVwIAAAFhAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQcDBc1l5jJzmek/CxwAAAACFwAAAAASAAAAAQ0AAAACAQcDBc1l5jJzmek/CxEAAAADDAAAAAABAQEGAwAAAAIBAQsRAAAAAwwAAAAAAQEBBgMAAAACAQELJwAAAAERAAAABQwAAAAABgMAAAACAQcBAQQDDAAAAAABAQEGAwAAAAIBAQsjAAAAAg0AAAAACAAAAAEDAAAAAgEHAwwAAAAAAQEBBgMAAAACAQALmgAAAAGHAAAAABYAAAAABg0AAAACAQcDBc1kZjIzmdk/AQENAhYAAAAABg0AAAACAQcDBc1kZjIzmdk/AQENAxYAAAAABg0AAAACAQcDBc1kZjIzmdk/AQENBBYAAAAABg0AAAACAQcDBc1kZjIzmdk/AQENBRYAAAAABg0AAAACAQcDBc1kZjIzmdk/AQENAwkAAAABBgMAAAACAQEC7AAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKZAAAAA5QAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0ANQABAQAAAAADYgAAAAQJAAAAAgEbAAQHAAAABAkAAAACAQoABAYAAAAECQAAAAIBGgAEBQAAAAQJAAAAAgEBAAQEAAAABAkAAAACAQsABAMAAAAECQAAAAIBBQAEAgAAAAQJAAAAAgECAAQBAAAAAFcCAAABYQEAAAscAAAAAhcAAAAAEgAAAAENAAAAAgEGAwXNZeYyc5npPwscAAAAAhcAAAAAEgAAAAENAAAAAgEGAwXNZeYyc5npPwsRAAAAAwwAAAAAAQEBBgMAAAACAQELEQAAAAMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAUMAAAAAAYDAAAAAgEGAQEEAwwAAAAAAQEBBgMAAAACAQELIwAAAAINAAAAAAgAAAABAwAAAAIBBgMMAAAAAAEBAQYDAAAAAgEAC5oAAAABhwAAAAAWAAAAAAYNAAAAAgEGAwXNZGYyM5nZPwEBDQIWAAAAAAYNAAAAAgEGAwXNZGYyM5nZPwEBDQMWAAAAAAYNAAAAAgEGAwXNZGYyM5nZPwEBDQQWAAAAAAYNAAAAAgEGAwXNZGYyM5nZPwEBDQUWAAAAAAYNAAAAAgEGAwXNZGYyM5nZPwEBDQMJAAAAAQYDAAAAAgEBAuwAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgACmQAAAAOUAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADQAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAABXAgAAAWEBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBBQMFzWXmMnOZ6T8LHAAAAAIXAAAAABIAAAABDQAAAAIBBQMFzWXmMnOZ6T8LEQAAAAMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAFDAAAAAAGAwAAAAIBBQEBBAMMAAAAAAEBAQYDAAAAAgEBCyMAAAACDQAAAAAIAAAAAQMAAAACAQUDDAAAAAABAQEGAwAAAAIBAAuaAAAAAYcAAAAAFgAAAAAGDQAAAAIBBQMFzWRmMjOZ2T8BAQ0CFgAAAAAGDQAAAAIBBQMFzWRmMjOZ2T8BAQ0DFgAAAAAGDQAAAAIBBQMFzWRmMjOZ2T8BAQ0EFgAAAAAGDQAAAAIBBQMFzWRmMjOZ2T8BAQ0FFgAAAAAGDQAAAAIBBQMFzWRmMjOZ2T8BAQ0DCQAAAAEGAwAAAAIBAQLsAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApkAAAADlAAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQAzAAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAVwIAAAFhAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQQDBc1l5jJzmek/CxwAAAACFwAAAAASAAAAAQ0AAAACAQQDBc1l5jJzmek/CxEAAAADDAAAAAABAQEGAwAAAAIBAQsRAAAAAwwAAAAAAQEBBgMAAAACAQELJwAAAAERAAAABQwAAAAABgMAAAACAQQBAQQDDAAAAAABAQEGAwAAAAIBAQsjAAAAAg0AAAAACAAAAAEDAAAAAgEEAwwAAAAAAQEBBgMAAAACAQALmgAAAAGHAAAAABYAAAAABg0AAAACAQQDBc1kZjIzmdk/AQENAhYAAAAABg0AAAACAQQDBc1kZjIzmdk/AQENAxYAAAAABg0AAAACAQQDBc1kZjIzmdk/AQENBBYAAAAABg0AAAACAQQDBc1kZjIzmdk/AQENBRYAAAAABg0AAAACAQQDBc1kZjIzmdk/AQENAwkAAAABBgMAAAACAQEC7AAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKZAAAAA5QAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AMgABAQAAAAADYgAAAAQJAAAAAgEbAAQHAAAABAkAAAACAQoABAYAAAAECQAAAAIBGgAEBQAAAAQJAAAAAgEBAAQEAAAABAkAAAACAQsABAMAAAAECQAAAAIBBQAEAgAAAAQJAAAAAgECAAQBAAAAACUCAAABLwEAAAscAAAAAhcAAAAAEgAAAAENAAAAAgEAAwWazExmJjPDvwscAAAAAhcAAAAAEgAAAAENAAAAAgEAAwWazExmJjPDvwsRAAAAAwwAAAAAAQEBBgMAAAACAQELEQAAAAMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAUMAAAAAAYDAAAAAgEBAQEEAwwAAAAAAQEBBgMAAAACAQELIwAAAAINAAAAAAgAAAABAwAAAAIBAQMMAAAAAAEBAQYDAAAAAgEAC2gAAAABVQAAAAAMAAAAAAYDAAAAAgEBAQENAgwAAAAABgMAAAACAQEBAQ0DDAAAAAAGAwAAAAIBAQEBDQQMAAAAAAYDAAAAAgEBAQENBQwAAAAABgMAAAACAQEBAQ0DCQAAAAEGAwAAAAIBAQLsAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApkAAAADlAAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQAxAAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAOgIAAAFEAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQkDBc1l5jJzmek/CxwAAAACFwAAAAASAAAAAQ0AAAACAQkDBc1l5jJzmek/CxEAAAADDAAAAAABAQEGAwAAAAIBAQsRAAAAAwwAAAAAAQEBBgMAAAACAQELJwAAAAERAAAABQwAAAAABgMAAAACAQkBAQQDDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAADAAAAAAGAwAAAAIBCQEBBgMMAAAAAAEBAQYDAAAAAgEBC3kAAAABZgAAAAAMAAAAAAYDAAAAAgEJAQENAgwAAAAABgMAAAACAQkBAQ0DDAAAAAAGAwAAAAIBCQEBDQQMAAAAAAYDAAAAAgEJAQENBQwAAAAABgMAAAACAQkBAQ0GDAAAAAAGAwAAAAIBCQEBDQMJAAAAAQYDAAAAAgEBAuwAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgACmQAAAAOUAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAEwAaQBnAGgAdAAyADEAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAAA6AgAAAUQBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBCAMFzWXmMnOZ6T8LHAAAAAIXAAAAABIAAAABDQAAAAIBCAMFzWXmMnOZ6T8LEQAAAAMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAFDAAAAAAGAwAAAAIBCAEBBAMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAAMAAAAAAYDAAAAAgEIAQEGAwwAAAAAAQEBBgMAAAACAQELeQAAAAFmAAAAAAwAAAAABgMAAAACAQgBAQ0CDAAAAAAGAwAAAAIBCAEBDQMMAAAAAAYDAAAAAgEIAQENBAwAAAAABgMAAAACAQgBAQ0FDAAAAAAGAwAAAAIBCAEBDQYMAAAAAAYDAAAAAgEIAQENAwkAAAABBgMAAAACAQEC7AAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKZAAAAA5QAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATABpAGcAaAB0ADIAMAABAQAAAAADYgAAAAQJAAAAAgEbAAQHAAAABAkAAAACAQoABAYAAAAECQAAAAIBGgAEBQAAAAQJAAAAAgEBAAQEAAAABAkAAAACAQsABAMAAAAECQAAAAIBBQAEAgAAAAQJAAAAAgECAAQBAAAAADoCAAABRAEAAAscAAAAAhcAAAAAEgAAAAENAAAAAgEHAwXNZeYyc5npPwscAAAAAhcAAAAAEgAAAAENAAAAAgEHAwXNZeYyc5npPwsRAAAAAwwAAAAAAQEBBgMAAAACAQELEQAAAAMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAUMAAAAAAYDAAAAAgEHAQEEAwwAAAAAAQEBBgMAAAACAQELJwAAAAERAAAAAAwAAAAABgMAAAACAQcBAQYDDAAAAAABAQEGAwAAAAIBAQt5AAAAAWYAAAAADAAAAAAGAwAAAAIBBwEBDQIMAAAAAAYDAAAAAgEHAQENAwwAAAAABgMAAAACAQcBAQ0EDAAAAAAGAwAAAAIBBwEBDQUMAAAAAAYDAAAAAgEHAQENBgwAAAAABgMAAAACAQcBAQ0DCQAAAAEGAwAAAAIBAQLsAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApkAAAADlAAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA5AAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAOgIAAAFEAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQYDBc1l5jJzmek/CxwAAAACFwAAAAASAAAAAQ0AAAACAQYDBc1l5jJzmek/CxEAAAADDAAAAAABAQEGAwAAAAIBAQsRAAAAAwwAAAAAAQEBBgMAAAACAQELJwAAAAERAAAABQwAAAAABgMAAAACAQYBAQQDDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAADAAAAAAGAwAAAAIBBgEBBgMMAAAAAAEBAQYDAAAAAgEBC3kAAAABZgAAAAAMAAAAAAYDAAAAAgEGAQENAgwAAAAABgMAAAACAQYBAQ0DDAAAAAAGAwAAAAIBBgEBDQQMAAAAAAYDAAAAAgEGAQENBQwAAAAABgMAAAACAQYBAQ0GDAAAAAAGAwAAAAIBBgEBDQMJAAAAAQYDAAAAAgEBAuwAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgACmQAAAAOUAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAEwAaQBnAGgAdAAxADgAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAAA6AgAAAUQBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBBQMFzWXmMnOZ6T8LHAAAAAIXAAAAABIAAAABDQAAAAIBBQMFzWXmMnOZ6T8LEQAAAAMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAFDAAAAAAGAwAAAAIBBQEBBAMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAAMAAAAAAYDAAAAAgEFAQEGAwwAAAAAAQEBBgMAAAACAQELeQAAAAFmAAAAAAwAAAAABgMAAAACAQUBAQ0CDAAAAAAGAwAAAAIBBQEBDQMMAAAAAAYDAAAAAgEFAQENBAwAAAAABgMAAAACAQUBAQ0FDAAAAAAGAwAAAAIBBQEBDQYMAAAAAAYDAAAAAgEFAQENAwkAAAABBgMAAAACAQEC7AAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKZAAAAA5QAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATABpAGcAaAB0ADEANwABAQAAAAADYgAAAAQJAAAAAgEbAAQHAAAABAkAAAACAQoABAYAAAAECQAAAAIBGgAEBQAAAAQJAAAAAgEBAAQEAAAABAkAAAACAQsABAMAAAAECQAAAAIBBQAEAgAAAAQJAAAAAgECAAQBAAAAADoCAAABRAEAAAscAAAAAhcAAAAAEgAAAAENAAAAAgEEAwXNZeYyc5npPwscAAAAAhcAAAAAEgAAAAENAAAAAgEEAwXNZeYyc5npPwsRAAAAAwwAAAAAAQEBBgMAAAACAQELEQAAAAMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAUMAAAAAAYDAAAAAgEEAQEEAwwAAAAAAQEBBgMAAAACAQELJwAAAAERAAAAAAwAAAAABgMAAAACAQQBAQYDDAAAAAABAQEGAwAAAAIBAQt5AAAAAWYAAAAADAAAAAAGAwAAAAIBBAEBDQIMAAAAAAYDAAAAAgEEAQENAwwAAAAABgMAAAACAQQBAQ0EDAAAAAAGAwAAAAIBBAEBDQUMAAAAAAYDAAAAAgEEAQENBgwAAAAABgMAAAACAQQBAQ0DCQAAAAEGAwAAAAIBAQLsAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApkAAAADlAAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAOgIAAAFEAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CxEAAAADDAAAAAABAQEGAwAAAAIBAQsRAAAAAwwAAAAAAQEBBgMAAAACAQELJwAAAAERAAAABQwAAAAABgMAAAACAQEBAQQDDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAADAAAAAAGAwAAAAIBAQEBBgMMAAAAAAEBAQYDAAAAAgEBC3kAAAABZgAAAAAMAAAAAAYDAAAAAgEBAQENAgwAAAAABgMAAAACAQEBAQ0DDAAAAAAGAwAAAAIBAQEBDQQMAAAAAAYDAAAAAgEBAQENBQwAAAAABgMAAAACAQEBAQ0GDAAAAAAGAwAAAAIBAQEBDQMJAAAAAQYDAAAAAgEBAuwAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgACmQAAAAOUAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAEwAaQBnAGgAdAAxADUAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAABaAgAAAUgBAAALFgAAAAERAAAABAwAAAAABgMAAAACAQkBAQ0LFgAAAAERAAAABAwAAAAABgMAAAACAQkBAQ0LFgAAAAERAAAABQwAAAAABgMAAAACAQkBAQ0LFgAAAAERAAAABQwAAAAABgMAAAACAQkBAQ0LEQAAAAMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAFDAAAAAAGAwAAAAIBCQEBBAMMAAAAAAEBAQYDAAAAAgEBCyMAAAACDQAAAAAIAAAAAQMAAAACAQkDDAAAAAABAQEGAwAAAAIBAAtXAAAAAUQAAAAADAAAAAAGAwAAAAIBCQEBDQIMAAAAAAYDAAAAAgEJAQENBAwAAAAABgMAAAACAQkBAQ0FDAAAAAAGAwAAAAIBCQEBDQMJAAAAAQYDAAAAAgEBAggBAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgACtQAAAAOwAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAEwAaQBnAGgAdAAxADQAAQEAAAAAA34AAAAECQAAAAIBGwAECQAAAAQJAAAAAgEKAAQIAAAABAkAAAACARoABAcAAAAECQAAAAIBAQAEBgAAAAQJAAAAAgELAAQFAAAABAkAAAACAQUABAQAAAAECQAAAAIBEgAEAwAAAAQJAAAAAgECAAQCAAAABAkAAAACARAABAEAAAAAWgIAAAFIAQAACxYAAAABEQAAAAQMAAAAAAYDAAAAAgEIAQENCxYAAAABEQAAAAQMAAAAAAYDAAAAAgEIAQENCxYAAAABEQAAAAUMAAAAAAYDAAAAAgEIAQENCxYAAAABEQAAAAUMAAAAAAYDAAAAAgEIAQENCxEAAAADDAAAAAABAQEGAwAAAAIBAQsRAAAAAwwAAAAAAQEBBgMAAAACAQELJwAAAAERAAAABQwAAAAABgMAAAACAQgBAQQDDAAAAAABAQEGAwAAAAIBAQsjAAAAAg0AAAAACAAAAAEDAAAAAgEIAwwAAAAAAQEBBgMAAAACAQALVwAAAAFEAAAAAAwAAAAABgMAAAACAQgBAQ0CDAAAAAAGAwAAAAIBCAEBDQQMAAAAAAYDAAAAAgEIAQENBQwAAAAABgMAAAACAQgBAQ0DCQAAAAEGAwAAAAIBAQIIAQAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAArUAAAADsAAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBMAGkAZwBoAHQAMQAzAAEBAAAAAAN+AAAABAkAAAACARsABAkAAAAECQAAAAIBCgAECAAAAAQJAAAAAgEaAAQHAAAABAkAAAACAQEABAYAAAAECQAAAAIBCwAEBQAAAAQJAAAAAgEFAAQEAAAABAkAAAACARIABAMAAAAECQAAAAIBAgAEAgAAAAQJAAAAAgEQAAQBAAAAAFoCAAABSAEAAAsWAAAAAREAAAAEDAAAAAAGAwAAAAIBBwEBDQsWAAAAAREAAAAEDAAAAAAGAwAAAAIBBwEBDQsWAAAAAREAAAAFDAAAAAAGAwAAAAIBBwEBDQsWAAAAAREAAAAFDAAAAAAGAwAAAAIBBwEBDQsRAAAAAwwAAAAAAQEBBgMAAAACAQELEQAAAAMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAUMAAAAAAYDAAAAAgEHAQEEAwwAAAAAAQEBBgMAAAACAQELIwAAAAINAAAAAAgAAAABAwAAAAIBBwMMAAAAAAEBAQYDAAAAAgEAC1cAAAABRAAAAAAMAAAAAAYDAAAAAgEHAQENAgwAAAAABgMAAAACAQcBAQ0EDAAAAAAGAwAAAAIBBwEBDQUMAAAAAAYDAAAAAgEHAQENAwkAAAABBgMAAAACAQECCAEAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAK1AAAAA7AAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATABpAGcAaAB0ADEAMgABAQAAAAADfgAAAAQJAAAAAgEbAAQJAAAABAkAAAACAQoABAgAAAAECQAAAAIBGgAEBwAAAAQJAAAAAgEBAAQGAAAABAkAAAACAQsABAUAAAAECQAAAAIBBQAEBAAAAAQJAAAAAgESAAQDAAAABAkAAAACAQIABAIAAAAECQAAAAIBEAAEAQAAAABaAgAAAUgBAAALFgAAAAERAAAABAwAAAAABgMAAAACAQYBAQ0LFgAAAAERAAAABAwAAAAABgMAAAACAQYBAQ0LFgAAAAERAAAABQwAAAAABgMAAAACAQYBAQ0LFgAAAAERAAAABQwAAAAABgMAAAACAQYBAQ0LEQAAAAMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAFDAAAAAAGAwAAAAIBBgEBBAMMAAAAAAEBAQYDAAAAAgEBCyMAAAACDQAAAAAIAAAAAQMAAAACAQYDDAAAAAABAQEGAwAAAAIBAAtXAAAAAUQAAAAADAAAAAAGAwAAAAIBBgEBDQIMAAAAAAYDAAAAAgEGAQENBAwAAAAABgMAAAACAQYBAQ0FDAAAAAAGAwAAAAIBBgEBDQMJAAAAAQYDAAAAAgEBAggBAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgACtQAAAAOwAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAEwAaQBnAGgAdAAxADEAAQEAAAAAA34AAAAECQAAAAIBGwAECQAAAAQJAAAAAgEKAAQIAAAABAkAAAACARoABAcAAAAECQAAAAIBAQAEBgAAAAQJAAAAAgELAAQFAAAABAkAAAACAQUABAQAAAAECQAAAAIBEgAEAwAAAAQJAAAAAgECAAQCAAAABAkAAAACARAABAEAAAAAWgIAAAFIAQAACxYAAAABEQAAAAQMAAAAAAYDAAAAAgEFAQENCxYAAAABEQAAAAQMAAAAAAYDAAAAAgEFAQENCxYAAAABEQAAAAUMAAAAAAYDAAAAAgEFAQENCxYAAAABEQAAAAUMAAAAAAYDAAAAAgEFAQENCxEAAAADDAAAAAABAQEGAwAAAAIBAQsRAAAAAwwAAAAAAQEBBgMAAAACAQELJwAAAAERAAAABQwAAAAABgMAAAACAQUBAQQDDAAAAAABAQEGAwAAAAIBAQsjAAAAAg0AAAAACAAAAAEDAAAAAgEFAwwAAAAAAQEBBgMAAAACAQALVwAAAAFEAAAAAAwAAAAABgMAAAACAQUBAQ0CDAAAAAAGAwAAAAIBBQEBDQQMAAAAAAYDAAAAAgEFAQENBQwAAAAABgMAAAACAQUBAQ0DCQAAAAEGAwAAAAIBAQIIAQAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAArUAAAADsAAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBMAGkAZwBoAHQAMQAwAAEBAAAAAAN+AAAABAkAAAACARsABAkAAAAECQAAAAIBCgAECAAAAAQJAAAAAgEaAAQHAAAABAkAAAACAQEABAYAAAAECQAAAAIBCwAEBQAAAAQJAAAAAgEFAAQEAAAABAkAAAACARIABAMAAAAECQAAAAIBAgAEAgAAAAQJAAAAAgEQAAQBAAAAAFgCAAABSAEAAAsWAAAAAREAAAAEDAAAAAAGAwAAAAIBBAEBDQsWAAAAAREAAAAEDAAAAAAGAwAAAAIBBAEBDQsWAAAAAREAAAAFDAAAAAAGAwAAAAIBBAEBDQsWAAAAAREAAAAFDAAAAAAGAwAAAAIBBAEBDQsRAAAAAwwAAAAAAQEBBgMAAAACAQELEQAAAAMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAUMAAAAAAYDAAAAAgEEAQEEAwwAAAAAAQEBBgMAAAACAQELIwAAAAINAAAAAAgAAAABAwAAAAIBBAMMAAAAAAEBAQYDAAAAAgEAC1cAAAABRAAAAAAMAAAAAAYDAAAAAgEEAQENAgwAAAAABgMAAAACAQQBAQ0EDAAAAAAGAwAAAAIBBAEBDQUMAAAAAAYDAAAAAgEEAQENAwkAAAABBgMAAAACAQECBgEAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKzAAAAA64AAAAAIAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATABpAGcAaAB0ADkAAQEAAAAAA34AAAAECQAAAAIBGwAECQAAAAQJAAAAAgEKAAQIAAAABAkAAAACARoABAcAAAAECQAAAAIBAQAEBgAAAAQJAAAAAgELAAQFAAAABAkAAAACAQUABAQAAAAECQAAAAIBEgAEAwAAAAQJAAAAAgECAAQCAAAABAkAAAACARAABAEAAAAAWAIAAAFIAQAACxYAAAABEQAAAAQMAAAAAAYDAAAAAgEBAQENCxYAAAABEQAAAAQMAAAAAAYDAAAAAgEBAQENCxYAAAABEQAAAAUMAAAAAAYDAAAAAgEBAQENCxYAAAABEQAAAAUMAAAAAAYDAAAAAgEBAQENCxEAAAADDAAAAAABAQEGAwAAAAIBAQsRAAAAAwwAAAAAAQEBBgMAAAACAQELJwAAAAERAAAABQwAAAAABgMAAAACAQEBAQQDDAAAAAABAQEGAwAAAAIBAQsjAAAAAg0AAAAACAAAAAEDAAAAAgEBAwwAAAAAAQEBBgMAAAACAQALVwAAAAFEAAAAAAwAAAAABgMAAAACAQEBAQ0CDAAAAAAGAwAAAAIBAQEBDQQMAAAAAAYDAAAAAgEBAQENBQwAAAAABgMAAAACAQEBAQ0DCQAAAAEGAwAAAAIBAQIGAQAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAArMAAAADrgAAAAAgAAAAVABhAGIAbABlAFMAdAB5AGwAZQBMAGkAZwBoAHQAOAABAQAAAAADfgAAAAQJAAAAAgEbAAQJAAAABAkAAAACAQoABAgAAAAECQAAAAIBGgAEBwAAAAQJAAAAAgEBAAQGAAAABAkAAAACAQsABAUAAAAECQAAAAIBBQAEBAAAAAQJAAAAAgESAAQDAAAABAkAAAACAQIABAIAAAAECQAAAAIBEAAEAQAAAAAmAgAAATIBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBCQMFzWXmMnOZ6T8LHAAAAAIXAAAAABIAAAABDQAAAAIBCQMFzWXmMnOZ6T8LGwAAAAMWAAAAAAEBAQYNAAAAAgEJAwUA/X/+P//PvwsbAAAAAxYAAAAAAQEBBg0AAAACAQkDBQD9f/4//8+/CzEAAAABEQAAAAUMAAAAAAYDAAAAAgEJAQENAxYAAAAAAQEBBg0AAAACAQkDBQD9f/4//8+/CzEAAAABEQAAAAAMAAAAAAYDAAAAAgEJAQENAxYAAAAAAQEBBg0AAAACAQkDBQD9f/4//8+/Cz8AAAABIgAAAAAMAAAAAAYDAAAAAgEJAQENBQwAAAAABgMAAAACAQkBAQ0DEwAAAAEGDQAAAAIBCQMFAP1//j//z78C6gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKXAAAAA5IAAAAAIAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATABpAGcAaAB0ADcAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAAAmAgAAATIBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBCAMFzWXmMnOZ6T8LHAAAAAIXAAAAABIAAAABDQAAAAIBCAMFzWXmMnOZ6T8LGwAAAAMWAAAAAAEBAQYNAAAAAgEIAwUA/X/+P//PvwsbAAAAAxYAAAAAAQEBBg0AAAACAQgDBQD9f/4//8+/CzEAAAABEQAAAAUMAAAAAAYDAAAAAgEIAQENAxYAAAAAAQEBBg0AAAACAQgDBQD9f/4//8+/CzEAAAABEQAAAAAMAAAAAAYDAAAAAgEIAQENAxYAAAAAAQEBBg0AAAACAQgDBQD9f/4//8+/Cz8AAAABIgAAAAAMAAAAAAYDAAAAAgEIAQENBQwAAAAABgMAAAACAQgBAQ0DEwAAAAEGDQAAAAIBCAMFAP1//j//z78C6gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKXAAAAA5IAAAAAIAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATABpAGcAaAB0ADYAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAAAmAgAAATIBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBBwMFzWXmMnOZ6T8LHAAAAAIXAAAAABIAAAABDQAAAAIBBwMFzWXmMnOZ6T8LGwAAAAMWAAAAAAEBAQYNAAAAAgEHAwUA/X/+P//PvwsbAAAAAxYAAAAAAQEBBg0AAAACAQcDBQD9f/4//8+/CzEAAAABEQAAAAUMAAAAAAYDAAAAAgEHAQENAxYAAAAAAQEBBg0AAAACAQcDBQD9f/4//8+/CzEAAAABEQAAAAAMAAAAAAYDAAAAAgEHAQENAxYAAAAAAQEBBg0AAAACAQcDBQD9f/4//8+/Cz8AAAABIgAAAAAMAAAAAAYDAAAAAgEHAQENBQwAAAAABgMAAAACAQcBAQ0DEwAAAAEGDQAAAAIBBwMFAP1//j//z78C6gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKXAAAAA5IAAAAAIAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATABpAGcAaAB0ADUAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAAAmAgAAATIBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBBgMFzWXmMnOZ6T8LHAAAAAIXAAAAABIAAAABDQAAAAIBBgMFzWXmMnOZ6T8LGwAAAAMWAAAAAAEBAQYNAAAAAgEGAwUA/X/+P//PvwsbAAAAAxYAAAAAAQEBBg0AAAACAQYDBQD9f/4//8+/CzEAAAABEQAAAAUMAAAAAAYDAAAAAgEGAQENAxYAAAAAAQEBBg0AAAACAQYDBQD9f/4//8+/CzEAAAABEQAAAAAMAAAAAAYDAAAAAgEGAQENAxYAAAAAAQEBBg0AAAACAQYDBQD9f/4//8+/Cz8AAAABIgAAAAAMAAAAAAYDAAAAAgEGAQENBQwAAAAABgMAAAACAQYBAQ0DEwAAAAEGDQAAAAIBBgMFAP1//j//z78C6gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKXAAAAA5IAAAAAIAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATABpAGcAaAB0ADQAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAAAmAgAAATIBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBBQMFzWXmMnOZ6T8LHAAAAAIXAAAAABIAAAABDQAAAAIBBQMFzWXmMnOZ6T8LGwAAAAMWAAAAAAEBAQYNAAAAAgEFAwUA/X/+P//PvwsbAAAAAxYAAAAAAQEBBg0AAAACAQUDBQD9f/4//8+/CzEAAAABEQAAAAUMAAAAAAYDAAAAAgEFAQENAxYAAAAAAQEBBg0AAAACAQUDBQD9f/4//8+/CzEAAAABEQAAAAAMAAAAAAYDAAAAAgEFAQENAxYAAAAAAQEBBg0AAAACAQUDBQD9f/4//8+/Cz8AAAABIgAAAAAMAAAAAAYDAAAAAgEFAQENBQwAAAAABgMAAAACAQUBAQ0DEwAAAAEGDQAAAAIBBQMFAP1//j//z78C6gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKXAAAAA5IAAAAAIAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATABpAGcAaAB0ADMAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAAAmAgAAATIBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBBAMFzWXmMnOZ6T8LHAAAAAIXAAAAABIAAAABDQAAAAIBBAMFzWXmMnOZ6T8LGwAAAAMWAAAAAAEBAQYNAAAAAgEEAwUA/X/+P//PvwsbAAAAAxYAAAAAAQEBBg0AAAACAQQDBQD9f/4//8+/CzEAAAABEQAAAAUMAAAAAAYDAAAAAgEEAQENAxYAAAAAAQEBBg0AAAACAQQDBQD9f/4//8+/CzEAAAABEQAAAAAMAAAAAAYDAAAAAgEEAQENAxYAAAAAAQEBBg0AAAACAQQDBQD9f/4//8+/Cz8AAAABIgAAAAAMAAAAAAYDAAAAAgEEAQENBQwAAAAABgMAAAACAQQBAQ0DEwAAAAEGDQAAAAIBBAMFAP1//j//z78C6gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKXAAAAA5IAAAAAIAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATABpAGcAaAB0ADIAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAAD0AQAAAQABAAALHAAAAAIXAAAAABIAAAABDQAAAAIBAAMFmsxMZiYzw78LHAAAAAIXAAAAABIAAAABDQAAAAIBAAMFmsxMZiYzw78LEQAAAAMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAFDAAAAAAGAwAAAAIBAQEBDQMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAAMAAAAAAYDAAAAAgEBAQENAwwAAAAAAQEBBgMAAAACAQELNQAAAAEiAAAAAAwAAAAABgMAAAACAQEBAQ0FDAAAAAAGAwAAAAIBAQEBDQMJAAAAAQYDAAAAAgEBAuoAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgAClwAAAAOSAAAAACAAAABUAGEAYgBsAGUAUwB0AHkAbABlAEwAaQBnAGgAdAAxAAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAA1AEAAAHgAAAACxwAAAACFwAAAAASAAAAAQ0AAAACAQgDBZrMTGYmM+M/CxwAAAACFwAAAAASAAAAAQ0AAAACAQgDBZrMTGYmM+M/CxEAAAADDAAAAAABAQEGAwAAAAIBAQsRAAAAAwwAAAAAAQEBBgMAAAACAQELJwAAAAERAAAABQwAAAAABgMAAAACAQEBAQQDDAAAAAABAQEGAwAAAAIBAQsgAAAAAg0AAAAACAAAAAEDAAAAAgEJAwkAAAABBgMAAAACAQALHAAAAAIXAAAAABIAAAABDQAAAAIBCAMFzWXmMnOZ6T8C6gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKXAAAAA5IAAAAAIAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUARABhAHIAawAxADEAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAADUAQAAAeAAAAALHAAAAAIXAAAAABIAAAABDQAAAAIBBgMFmsxMZiYz4z8LHAAAAAIXAAAAABIAAAABDQAAAAIBBgMFmsxMZiYz4z8LEQAAAAMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAFDAAAAAAGAwAAAAIBAQEBBAMMAAAAAAEBAQYDAAAAAgEBCyAAAAACDQAAAAAIAAAAAQMAAAACAQcDCQAAAAEGAwAAAAIBAAscAAAAAhcAAAAAEgAAAAENAAAAAgEGAwXNZeYyc5npPwLqAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApcAAAADkgAAAAAgAAAAVABhAGIAbABlAFMAdAB5AGwAZQBEAGEAcgBrADEAMAABAQAAAAADYgAAAAQJAAAAAgEbAAQHAAAABAkAAAACAQoABAYAAAAECQAAAAIBGgAEBQAAAAQJAAAAAgEBAAQEAAAABAkAAAACAQsABAMAAAAECQAAAAIBBQAEAgAAAAQJAAAAAgECAAQBAAAAANIBAAAB4AAAAAscAAAAAhcAAAAAEgAAAAENAAAAAgEEAwWazExmJjPjPwscAAAAAhcAAAAAEgAAAAENAAAAAgEEAwWazExmJjPjPwsRAAAAAwwAAAAAAQEBBgMAAAACAQELEQAAAAMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAUMAAAAAAYDAAAAAgEBAQEEAwwAAAAAAQEBBgMAAAACAQELIAAAAAINAAAAAAgAAAABAwAAAAIBBQMJAAAAAQYDAAAAAgEACxwAAAACFwAAAAASAAAAAQ0AAAACAQQDBc1l5jJzmek/AugAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgAClQAAAAOQAAAAAB4AAABUAGEAYgBsAGUAUwB0AHkAbABlAEQAYQByAGsAOQABAQAAAAADYgAAAAQJAAAAAgEbAAQHAAAABAkAAAACAQoABAYAAAAECQAAAAIBGgAEBQAAAAQJAAAAAgEBAAQEAAAABAkAAAACAQsABAMAAAAECQAAAAIBBQAEAgAAAAQJAAAAAgECAAQBAAAAANIBAAAB4AAAAAscAAAAAhcAAAAAEgAAAAENAAAAAgEAAwWzmFnMLGbWvwscAAAAAhcAAAAAEgAAAAENAAAAAgEAAwWzmFnMLGbWvwsRAAAAAwwAAAAAAQEBBgMAAAACAQELEQAAAAMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAUMAAAAAAYDAAAAAgEBAQEEAwwAAAAAAQEBBgMAAAACAQELIAAAAAINAAAAAAgAAAABAwAAAAIBAQMJAAAAAQYDAAAAAgEACxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/AugAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgAClQAAAAOQAAAAAB4AAABUAGEAYgBsAGUAUwB0AHkAbABlAEQAYQByAGsAOAABAQAAAAADYgAAAAQJAAAAAgEbAAQHAAAABAkAAAACAQoABAYAAAAECQAAAAIBGgAEBQAAAAQJAAAAAgEBAAQEAAAABAkAAAACAQsABAMAAAAECQAAAAIBBQAEAgAAAAQJAAAAAgECAAQBAAAAAG8CAAABfQEAAAscAAAAAhcAAAAAEgAAAAENAAAAAgEJAwUA/X/+P//PvwscAAAAAhcAAAAAEgAAAAENAAAAAgEJAwUA/X/+P//PvwtDAAAAAREAAAAEDAAAAAAGAwAAAAIBAAEBBgIXAAAAABIAAAABDQAAAAIBCQMFAP1//j//z78DDAAAAAABAQEGAwAAAAIBAAtDAAAAAREAAAACDAAAAAAGAwAAAAIBAAEBBgIXAAAAABIAAAABDQAAAAIBCQMFAP1//j//z78DDAAAAAABAQEGAwAAAAIBAAtDAAAAAREAAAAFDAAAAAAGAwAAAAIBAAEBBgIXAAAAABIAAAABDQAAAAIBCQMFAP9//7//378DDAAAAAABAQEGAwAAAAIBAAs5AAAAAREAAAAADAAAAAAGAwAAAAIBAAEBBgINAAAAAAgAAAABAwAAAAIBAQMMAAAAAAEBAQYDAAAAAgEACyAAAAACDQAAAAAIAAAAAQMAAAACAQkDCQAAAAEGAwAAAAIBAALoAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApUAAAADkAAAAAAeAAAAVABhAGIAbABlAFMAdAB5AGwAZQBEAGEAcgBrADcAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAABvAgAAAX0BAAALHAAAAAIXAAAAABIAAAABDQAAAAIBCAMFAP1//j//z78LHAAAAAIXAAAAABIAAAABDQAAAAIBCAMFAP1//j//z78LQwAAAAERAAAABAwAAAAABgMAAAACAQABAQYCFwAAAAASAAAAAQ0AAAACAQgDBQD9f/4//8+/AwwAAAAAAQEBBgMAAAACAQALQwAAAAERAAAAAgwAAAAABgMAAAACAQABAQYCFwAAAAASAAAAAQ0AAAACAQgDBQD9f/4//8+/AwwAAAAAAQEBBgMAAAACAQALQwAAAAERAAAABQwAAAAABgMAAAACAQABAQYCFwAAAAASAAAAAQ0AAAACAQgDBQD/f/+//9+/AwwAAAAAAQEBBgMAAAACAQALOQAAAAERAAAAAAwAAAAABgMAAAACAQABAQYCDQAAAAAIAAAAAQMAAAACAQEDDAAAAAABAQEGAwAAAAIBAAsgAAAAAg0AAAAACAAAAAEDAAAAAgEIAwkAAAABBgMAAAACAQAC6AAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKVAAAAA5AAAAAAHgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUARABhAHIAawA2AAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAbwIAAAF9AQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQcDBQD9f/4//8+/CxwAAAACFwAAAAASAAAAAQ0AAAACAQcDBQD9f/4//8+/C0MAAAABEQAAAAQMAAAAAAYDAAAAAgEAAQEGAhcAAAAAEgAAAAENAAAAAgEHAwUA/X/+P//PvwMMAAAAAAEBAQYDAAAAAgEAC0MAAAABEQAAAAIMAAAAAAYDAAAAAgEAAQEGAhcAAAAAEgAAAAENAAAAAgEHAwUA/X/+P//PvwMMAAAAAAEBAQYDAAAAAgEAC0MAAAABEQAAAAUMAAAAAAYDAAAAAgEAAQEGAhcAAAAAEgAAAAENAAAAAgEHAwUA/3//v//fvwMMAAAAAAEBAQYDAAAAAgEACzkAAAABEQAAAAAMAAAAAAYDAAAAAgEAAQEGAg0AAAAACAAAAAEDAAAAAgEBAwwAAAAAAQEBBgMAAAACAQALIAAAAAINAAAAAAgAAAABAwAAAAIBBwMJAAAAAQYDAAAAAgEAAugAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgAClQAAAAOQAAAAAB4AAABUAGEAYgBsAGUAUwB0AHkAbABlAEQAYQByAGsANQABAQAAAAADYgAAAAQJAAAAAgEbAAQHAAAABAkAAAACAQoABAYAAAAECQAAAAIBGgAEBQAAAAQJAAAAAgEBAAQEAAAABAkAAAACAQsABAMAAAAECQAAAAIBBQAEAgAAAAQJAAAAAgECAAQBAAAAAG8CAAABfQEAAAscAAAAAhcAAAAAEgAAAAENAAAAAgEGAwUA/X/+P//PvwscAAAAAhcAAAAAEgAAAAENAAAAAgEGAwUA/X/+P//PvwtDAAAAAREAAAAEDAAAAAAGAwAAAAIBAAEBBgIXAAAAABIAAAABDQAAAAIBBgMFAP1//j//z78DDAAAAAABAQEGAwAAAAIBAAtDAAAAAREAAAACDAAAAAAGAwAAAAIBAAEBBgIXAAAAABIAAAABDQAAAAIBBgMFAP1//j//z78DDAAAAAABAQEGAwAAAAIBAAtDAAAAAREAAAAFDAAAAAAGAwAAAAIBAAEBBgIXAAAAABIAAAABDQAAAAIBBgMFAP9//7//378DDAAAAAABAQEGAwAAAAIBAAs5AAAAAREAAAAADAAAAAAGAwAAAAIBAAEBBgINAAAAAAgAAAABAwAAAAIBAQMMAAAAAAEBAQYDAAAAAgEACyAAAAACDQAAAAAIAAAAAQMAAAACAQYDCQAAAAEGAwAAAAIBAALoAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApUAAAADkAAAAAAeAAAAVABhAGIAbABlAFMAdAB5AGwAZQBEAGEAcgBrADQAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAABvAgAAAX0BAAALHAAAAAIXAAAAABIAAAABDQAAAAIBBQMFAP1//j//z78LHAAAAAIXAAAAABIAAAABDQAAAAIBBQMFAP1//j//z78LQwAAAAERAAAABAwAAAAABgMAAAACAQABAQYCFwAAAAASAAAAAQ0AAAACAQUDBQD9f/4//8+/AwwAAAAAAQEBBgMAAAACAQALQwAAAAERAAAAAgwAAAAABgMAAAACAQABAQYCFwAAAAASAAAAAQ0AAAACAQUDBQD9f/4//8+/AwwAAAAAAQEBBgMAAAACAQALQwAAAAERAAAABQwAAAAABgMAAAACAQABAQYCFwAAAAASAAAAAQ0AAAACAQUDBQD/f/+//9+/AwwAAAAAAQEBBgMAAAACAQALOQAAAAERAAAAAAwAAAAABgMAAAACAQABAQYCDQAAAAAIAAAAAQMAAAACAQEDDAAAAAABAQEGAwAAAAIBAAsgAAAAAg0AAAAACAAAAAEDAAAAAgEFAwkAAAABBgMAAAACAQAC6AAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKVAAAAA5AAAAAAHgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUARABhAHIAawAzAAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAbwIAAAF9AQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQQDBQD9f/4//8+/CxwAAAACFwAAAAASAAAAAQ0AAAACAQQDBQD9f/4//8+/C0MAAAABEQAAAAQMAAAAAAYDAAAAAgEAAQEGAhcAAAAAEgAAAAENAAAAAgEEAwUA/X/+P//PvwMMAAAAAAEBAQYDAAAAAgEAC0MAAAABEQAAAAIMAAAAAAYDAAAAAgEAAQEGAhcAAAAAEgAAAAENAAAAAgEEAwUA/X/+P//PvwMMAAAAAAEBAQYDAAAAAgEAC0MAAAABEQAAAAUMAAAAAAYDAAAAAgEAAQEGAhcAAAAAEgAAAAENAAAAAgEEAwUA/3//v//fvwMMAAAAAAEBAQYDAAAAAgEACzkAAAABEQAAAAAMAAAAAAYDAAAAAgEAAQEGAg0AAAAACAAAAAEDAAAAAgEBAwwAAAAAAQEBBgMAAAACAQALIAAAAAINAAAAAAgAAAABAwAAAAIBBAMJAAAAAQYDAAAAAgEAAugAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgAClQAAAAOQAAAAAB4AAABUAGEAYgBsAGUAUwB0AHkAbABlAEQAYQByAGsAMgABAQAAAAADYgAAAAQJAAAAAgEbAAQHAAAABAkAAAACAQoABAYAAAAECQAAAAIBGgAEBQAAAAQJAAAAAgEBAAQEAAAABAkAAAACAQsABAMAAAAECQAAAAIBBQAEAgAAAAQJAAAAAgECAAQBAAAAAHkCAAABhwEAAAscAAAAAhcAAAAAEgAAAAENAAAAAgEBAwUA/X/+P//PPwscAAAAAhcAAAAAEgAAAAENAAAAAgEBAwUA/X/+P//PPwtDAAAAAREAAAAEDAAAAAAGAwAAAAIBAAEBBgIXAAAAABIAAAABDQAAAAIBAQMFAP1//j//zz8DDAAAAAABAQEGAwAAAAIBAAtDAAAAAREAAAACDAAAAAAGAwAAAAIBAAEBBgIXAAAAABIAAAABDQAAAAIBAQMFAP1//j//zz8DDAAAAAABAQEGAwAAAAIBAAtDAAAAAREAAAAFDAAAAAAGAwAAAAIBAAEBBgIXAAAAABIAAAABDQAAAAIBAQMFmsxMZiYzwz8DDAAAAAABAQEGAwAAAAIBAAs5AAAAAREAAAAADAAAAAAGAwAAAAIBAAEBBgINAAAAAAgAAAABAwAAAAIBAQMMAAAAAAEBAQYDAAAAAgEACyoAAAACFwAAAAASAAAAAQ0AAAACAQEDBeYyc5m5zNw/AwkAAAABBgMAAAACAQAC6AAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKVAAAAA5AAAAAAHgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUARABhAHIAawAxAAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAA="; var dstLen = sStyles.length; var pointer = g_memory.Alloc(dstLen); var stream = new FT_Stream2(pointer.data, dstLen); stream.obj = pointer.obj; var bcr = new Binary_CommonReader(stream); var oBinaryFileReader = new BinaryFileReader(""); oBinaryFileReader.getbase64DecodedData2(sStyles, 0, stream, 0); var oBinary_StylesTableReader = new Binary_StylesTableReader(stream, wb, [], []); var fReadStyle = function(type, length, oTableStyles, oOutputName) { var res = c_oSerConstants.ReadOk; if ( Types.Dxf == type ) { //потому что в presetTableStyles.xml в отличии от custom стилей, индексы начинаются с 1 oOutputName.dxfs.push(null); res = bcr.Read1(length, function(t,l){ return oBinary_StylesTableReader.ReadDxfs(t,l,oOutputName.dxfs); }); } else if ( Types.tableStyles == type ) { res = bcr.Read1(length, function(t,l){ return oBinary_StylesTableReader.ReadTableStyles(t,l, oTableStyles, oOutputName.customStyle); }); } else res = c_oSerConstants.ReadUnknown; return res; }; var fReadStyles = function(type, length, oOutput) { var res = c_oSerConstants.ReadOk; if ( Types.Style == type ) { var oTableStyles = new CTableStyles(); var oOutputName = {customStyle: {}, dxfs: []}; res = bcr.Read1(length, function(t,l){ return fReadStyle(t,l, oTableStyles, oOutputName); }); for(var i in oOutputName.customStyle) { var customStyle = oOutputName.customStyle[i]; var oNewStyle = customStyle.style; oBinary_StylesTableReader.initTableStyle(oNewStyle, customStyle.elements, oOutputName.dxfs); oOutput[oNewStyle.name] = oNewStyle; } } else res = c_oSerConstants.ReadUnknown; return res; }; var length = stream.GetULongLE(); var res = bcr.Read1(length, function(t,l){ return fReadStyles(t, l, oOutput); }); } function ReadDefCellStyles(wb, oOutput) { var Types = { Style : 0, BuiltinId : 1, Hidden : 2, CellStyle : 3, Xfs : 4, Font : 5, Fill : 6, Border : 7, NumFmts : 8 }; var sStyles = "2TEAAACdAAAAAQQAAAAAAAAAAyMAAAAABAAAAAAAAAAEDAAAAE4AbwByAG0AYQBsAAUEAAAAAAAAAAQYAAAABgQAAAAABwQAAAAACAQAAAAACQQAAAAABScAAAABBgMAAAACAQEEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGAAAAAAcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAACyAAAAAQQAAAAcAAAAAxwAAAAEDgAAAE4AZQB1AHQAcgBhAGwABQQAAAABAAAABCEAAAAAAQABAQAEAQAGBAAAAAAHBAIAAAAIBAEAAAAJBAAAAAAFKgAAAAEGBgAAAAAEAGWc/wQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYQAAAAAAsAAAABBgAAAAAEnOv//wcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAACqAAAAAQQAAAAbAAAAAxQAAAAEBgAAAEIAYQBkAAUEAAAAAQAAAAQhAAAAAAEAAQEABAEABgQAAAAABwQCAAAACAQBAAAACQQAAAAABSoAAAABBgYAAAAABAYAnP8EBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGEAAAAAALAAAAAQYAAAAABM7H//8HGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAArAAAAAEEAAAAGgAAAAMWAAAABAgAAABHAG8AbwBkAAUEAAAAAQAAAAQhAAAAAAEAAQEABAEABgQAAAAABwQCAAAACAQBAAAACQQAAAAABSoAAAABBgYAAAAABABhAP8EBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGEAAAAAALAAAAAQYAAAAABM7vxv8HGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAA5wAAAAEEAAAAFAAAAAMYAAAABAoAAABJAG4AcAB1AHQABQQAAAABAAAABB4AAAAAAQAEAQAGBAEAAAAHBAIAAAAIBAEAAAAJBAAAAAAFKgAAAAEGBgAAAAAEdj8//wQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYQAAAAAAsAAAABBgAAAAAEmcz//wdVAAAAAA8AAAAABgYAAAAABH9/f/8BAQ0BAAAAAAIPAAAAAAYGAAAAAAR/f3//AQENBA8AAAAABgYAAAAABH9/f/8BAQ0FDwAAAAAGBgAAAAAEf39//wEBDQDsAAAAAQQAAAAVAAAAAxoAAAAEDAAAAE8AdQB0AHAAdQB0AAUEAAAAAQAAAAQeAAAAAAEABAEABgQBAAAABwQCAAAACAQBAAAACQQAAAAABS0AAAAAAQEBBgYAAAAABD8/P/8EBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGEAAAAAALAAAAAQYAAAAABPLy8v8HVQAAAAAPAAAAAAYGAAAAAAQ/Pz//AQENAQAAAAACDwAAAAAGBgAAAAAEPz8//wEBDQQPAAAAAAYGAAAAAAQ/Pz//AQENBQ8AAAAABgYAAAAABD8/P/8BAQ0A9gAAAAEEAAAAFgAAAAMkAAAABBYAAABDAGEAbABjAHUAbABhAHQAaQBvAG4ABQQAAAABAAAABB4AAAAAAQAEAQAGBAEAAAAHBAIAAAAIBAEAAAAJBAAAAAAFLQAAAAABAQEGBgAAAAAEAH36/wQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYQAAAAAAsAAAABBgAAAAAE8vLy/wdVAAAAAA8AAAAABgYAAAAABH9/f/8BAQ0BAAAAAAIPAAAAAAYGAAAAAAR/f3//AQENBA8AAAAABgYAAAAABH9/f/8BAQ0FDwAAAAAGBgAAAAAEf39//wEBDQDxAAAAAQQAAAAXAAAAAyIAAAAEFAAAAEMAaABlAGMAawAgAEMAZQBsAGwABQQAAAABAAAABB4AAAAAAQAEAQAGBAEAAAAHBAIAAAAIBAEAAAAJBAAAAAAFKgAAAAABAQEGAwAAAAIBAAQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYQAAAAAAsAAAABBgAAAAAEpaWl/wdVAAAAAA8AAAAABgYAAAAABD8/P/8BAQQBAAAAAAIPAAAAAAYGAAAAAAQ/Pz//AQEEBA8AAAAABgYAAAAABD8/P/8BAQQFDwAAAAAGBgAAAAAEPz8//wEBBAC6AAAAAQQAAAA1AAAAAy4AAAAEIAAAAEUAeABwAGwAYQBuAGEAdABvAHIAeQAgAFQAZQB4AHQABQQAAAABAAAABCQAAAAAAQABAQACAQAEAQAGBAAAAAAHBAAAAAAIBAEAAAAJBAAAAAAFLQAAAAEGBgAAAAAEf39//wMBAQQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYAAAAABxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAOUAAAABBAAAAAoAAAADFgAAAAQIAAAATgBvAHQAZQAFBAAAAAEAAAAEIQAAAAABAAMBAAQBAAYEAQAAAAcEAgAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEBBAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABhAAAAAACwAAAAEGAAAAAATM////B1UAAAAADwAAAAAGBgAAAAAEsrKy/wEBDQEAAAAAAg8AAAAABgYAAAAABLKysv8BAQ0EDwAAAAAGBgAAAAAEsrKy/wEBDQUPAAAAAAYGAAAAAASysrL/AQENALkAAAABBAAAABgAAAADJAAAAAQWAAAATABpAG4AawBlAGQAIABDAGUAbABsAAUEAAAAAQAAAAQhAAAAAAEAAgEABAEABgQBAAAABwQAAAAACAQBAAAACQQAAAAABSoAAAABBgYAAAAABAB9+v8EBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGAAAAAAcoAAAAAA8AAAAABgYAAAAABAGA//8BAQQBAAAAAAIAAAAABAAAAAAFAAAAAACvAAAAAQQAAAALAAAAAyYAAAAEGAAAAFcAYQByAG4AaQBuAGcAIABUAGUAeAB0AAUEAAAAAQAAAAQkAAAAAAEAAQEAAgEABAEABgQAAAAABwQAAAAACAQBAAAACQQAAAAABSoAAAABBgYAAAAABAAA//8EBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGAAAAAAcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAACyAAAAAQQAAAAQAAAAAyAAAAAEEgAAAEgAZQBhAGQAaQBuAGcAIAAxAAUEAAAAAQAAAAQhAAAAAAEAAgEABAEABgQBAAAABwQAAAAACAQBAAAACQQAAAAABSoAAAAAAQEBBgMAAAACAQMEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAALkAGAAAAAAclAAAAAAwAAAAABgMAAAACAQQBAQwBAAAAAAIAAAAABAAAAAAFAAAAAAC8AAAAAQQAAAARAAAAAyAAAAAEEgAAAEgAZQBhAGQAaQBuAGcAIAAyAAUEAAAAAQAAAAQhAAAAAAEAAgEABAEABgQBAAAABwQAAAAACAQBAAAACQQAAAAABSoAAAAAAQEBBgMAAAACAQMEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAKkAGAAAAAAcvAAAAABYAAAAABg0AAAACAQQDBQD/f/+//98/AQEMAQAAAAACAAAAAAQAAAAABQAAAAAAvAAAAAEEAAAAEgAAAAMgAAAABBIAAABIAGUAYQBkAGkAbgBnACAAMwAFBAAAAAEAAAAEIQAAAAABAAIBAAQBAAYEAQAAAAcEAAAAAAgEAQAAAAkEAAAAAAUqAAAAAAEBAQYDAAAAAgEDBAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABgAAAAAHLwAAAAAWAAAAAAYNAAAAAgEEAwXNZGYyM5nZPwEBBgEAAAAAAgAAAAAEAAAAAAUAAAAAAKkAAAABBAAAABMAAAADIAAAAAQSAAAASABlAGEAZABpAG4AZwAgADQABQQAAAABAAAABCQAAAAAAQABAQACAQAEAQAGBAAAAAAHBAAAAAAIBAEAAAAJBAAAAAAFKgAAAAABAQEGAwAAAAIBAwQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYAAAAABxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAALYAAAABBAAAABkAAAADGAAAAAQKAAAAVABvAHQAYQBsAAUEAAAAAQAAAAQhAAAAAAEAAgEABAEABgQBAAAABwQAAAAACAQBAAAACQQAAAAABSoAAAAAAQEBBgMAAAACAQEEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGAAAAAAcxAAAAAAwAAAAABgMAAAACAQQBAQQBAAAAAAIAAAAABAAAAAAFDAAAAAAGAwAAAAIBBAEBDQChAAAAAQQAAAAPAAAAAxgAAAAECgAAAFQAaQB0AGwAZQAFBAAAAAEAAAAEJAAAAAABAAEBAAIBAAQBAAYEAAAAAAcEAAAAAAgEAQAAAAkEAAAAAAUqAAAAAAEBAQYDAAAAAgEDBAYOAAAAQwBhAG0AYgByAGkAYQAGBQAAAAAAADJABgAAAAAHGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAAwgAAAAEEAAAAHgAAAAMoAAAABBoAAAAyADAAJQAgAC0AIABBAGMAYwBlAG4AdAAxAAUEAAAAAQAAAAQhAAAAAAEAAQEABAEABgQAAAAABwQCAAAACAQBAAAACQQAAAAABScAAAABBgMAAAACAQEEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGFwAAAAASAAAAAQ0AAAACAQQDBc1l5jJzmek/BxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAMIAAAABBAAAACIAAAADKAAAAAQaAAAAMgAwACUAIAAtACAAQQBjAGMAZQBuAHQAMgAFBAAAAAEAAAAEIQAAAAABAAEBAAQBAAYEAAAAAAcEAgAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEBBAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABhcAAAAAEgAAAAENAAAAAgEFAwXNZeYyc5npPwcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAADCAAAAAQQAAAAmAAAAAygAAAAEGgAAADIAMAAlACAALQAgAEEAYwBjAGUAbgB0ADMABQQAAAABAAAABCEAAAAAAQABAQAEAQAGBAAAAAAHBAIAAAAIBAEAAAAJBAAAAAAFJwAAAAEGAwAAAAIBAQQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYXAAAAABIAAAABDQAAAAIBBgMFzWXmMnOZ6T8HGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAAwgAAAAEEAAAAKgAAAAMoAAAABBoAAAAyADAAJQAgAC0AIABBAGMAYwBlAG4AdAA0AAUEAAAAAQAAAAQhAAAAAAEAAQEABAEABgQAAAAABwQCAAAACAQBAAAACQQAAAAABScAAAABBgMAAAACAQEEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGFwAAAAASAAAAAQ0AAAACAQcDBc1l5jJzmek/BxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAMIAAAABBAAAAC4AAAADKAAAAAQaAAAAMgAwACUAIAAtACAAQQBjAGMAZQBuAHQANQAFBAAAAAEAAAAEIQAAAAABAAEBAAQBAAYEAAAAAAcEAgAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEBBAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABhcAAAAAEgAAAAENAAAAAgEIAwXNZeYyc5npPwcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAADCAAAAAQQAAAAyAAAAAygAAAAEGgAAADIAMAAlACAALQAgAEEAYwBjAGUAbgB0ADYABQQAAAABAAAABCEAAAAAAQABAQAEAQAGBAAAAAAHBAIAAAAIBAEAAAAJBAAAAAAFJwAAAAEGAwAAAAIBAQQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYXAAAAABIAAAABDQAAAAIBCQMFzWXmMnOZ6T8HGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAAwgAAAAEEAAAAHwAAAAMoAAAABBoAAAA0ADAAJQAgAC0AIABBAGMAYwBlAG4AdAAxAAUEAAAAAQAAAAQhAAAAAAEAAQEABAEABgQAAAAABwQCAAAACAQBAAAACQQAAAAABScAAAABBgMAAAACAQEEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGFwAAAAASAAAAAQ0AAAACAQQDBZrMTGYmM+M/BxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAMIAAAABBAAAACMAAAADKAAAAAQaAAAANAAwACUAIAAtACAAQQBjAGMAZQBuAHQAMgAFBAAAAAEAAAAEIQAAAAABAAEBAAQBAAYEAAAAAAcEAgAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEBBAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABhcAAAAAEgAAAAENAAAAAgEFAwWazExmJjPjPwcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAADCAAAAAQQAAAAnAAAAAygAAAAEGgAAADQAMAAlACAALQAgAEEAYwBjAGUAbgB0ADMABQQAAAABAAAABCEAAAAAAQABAQAEAQAGBAAAAAAHBAIAAAAIBAEAAAAJBAAAAAAFJwAAAAEGAwAAAAIBAQQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYXAAAAABIAAAABDQAAAAIBBgMFmsxMZiYz4z8HGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAAwgAAAAEEAAAAKwAAAAMoAAAABBoAAAA0ADAAJQAgAC0AIABBAGMAYwBlAG4AdAA0AAUEAAAAAQAAAAQhAAAAAAEAAQEABAEABgQAAAAABwQCAAAACAQBAAAACQQAAAAABScAAAABBgMAAAACAQEEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGFwAAAAASAAAAAQ0AAAACAQcDBZrMTGYmM+M/BxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAMIAAAABBAAAAC8AAAADKAAAAAQaAAAANAAwACUAIAAtACAAQQBjAGMAZQBuAHQANQAFBAAAAAEAAAAEIQAAAAABAAEBAAQBAAYEAAAAAAcEAgAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEBBAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABhcAAAAAEgAAAAENAAAAAgEIAwWazExmJjPjPwcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAADCAAAAAQQAAAAzAAAAAygAAAAEGgAAADQAMAAlACAALQAgAEEAYwBjAGUAbgB0ADYABQQAAAABAAAABCEAAAAAAQABAQAEAQAGBAAAAAAHBAIAAAAIBAEAAAAJBAAAAAAFJwAAAAEGAwAAAAIBAQQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYXAAAAABIAAAABDQAAAAIBCQMFmsxMZiYz4z8HGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAAxgAAAAEEAAAAIAAAAAMsAAAABB4AAAA2ADAAJQAgAC0AIABBAGMAYwBlAG4AdAAxACAAMgAFBAAAAAEAAAAEIQAAAAABAAEBAAQBAAYEAAAAAAcEAgAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEABAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABhcAAAAAEgAAAAENAAAAAgEEAwXNZGYyM5nZPwcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAADCAAAAAQQAAAAkAAAAAygAAAAEGgAAADYAMAAlACAALQAgAEEAYwBjAGUAbgB0ADIABQQAAAABAAAABCEAAAAAAQABAQAEAQAGBAAAAAAHBAIAAAAIBAEAAAAJBAAAAAAFJwAAAAEGAwAAAAIBAAQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYXAAAAABIAAAABDQAAAAIBBQMFzWRmMjOZ2T8HGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAAwgAAAAEEAAAAKAAAAAMoAAAABBoAAAA2ADAAJQAgAC0AIABBAGMAYwBlAG4AdAAzAAUEAAAAAQAAAAQhAAAAAAEAAQEABAEABgQAAAAABwQCAAAACAQBAAAACQQAAAAABScAAAABBgMAAAACAQAEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGFwAAAAASAAAAAQ0AAAACAQYDBc1kZjIzmdk/BxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAMIAAAABBAAAACwAAAADKAAAAAQaAAAANgAwACUAIAAtACAAQQBjAGMAZQBuAHQANAAFBAAAAAEAAAAEIQAAAAABAAEBAAQBAAYEAAAAAAcEAgAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEABAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABhcAAAAAEgAAAAENAAAAAgEHAwXNZGYyM5nZPwcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAADCAAAAAQQAAAAwAAAAAygAAAAEGgAAADYAMAAlACAALQAgAEEAYwBjAGUAbgB0ADUABQQAAAABAAAABCEAAAAAAQABAQAEAQAGBAAAAAAHBAIAAAAIBAEAAAAJBAAAAAAFJwAAAAEGAwAAAAIBAAQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYXAAAAABIAAAABDQAAAAIBCAMFzWRmMjOZ2T8HGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAAwgAAAAEEAAAANAAAAAMoAAAABBoAAAA2ADAAJQAgAC0AIABBAGMAYwBlAG4AdAA2AAUEAAAAAQAAAAQhAAAAAAEAAQEABAEABgQAAAAABwQCAAAACAQBAAAACQQAAAAABScAAAABBgMAAAACAQAEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGFwAAAAASAAAAAQ0AAAACAQkDBc1kZjIzmdk/BxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAKwAAAABBAAAAB0AAAADHAAAAAQOAAAAQQBjAGMAZQBuAHQAMQAFBAAAAAEAAAAEIQAAAAABAAEBAAQBAAYEAAAAAAcEAgAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEABAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABg0AAAAACAAAAAEDAAAAAgEEBxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAKwAAAABBAAAACEAAAADHAAAAAQOAAAAQQBjAGMAZQBuAHQAMgAFBAAAAAEAAAAEIQAAAAABAAEBAAQBAAYEAAAAAAcEAgAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEABAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABg0AAAAACAAAAAEDAAAAAgEFBxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAKMAAAADHAAAAAQOAAAAQQBjAGMAZQBuAHQAMwAFBAAAAAEAAAAEIQAAAAABAAEBAAQBAAYEAAAAAAcEAgAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEABAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABg0AAAAACAAAAAEDAAAAAgEGBxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAKwAAAABBAAAACkAAAADHAAAAAQOAAAAQQBjAGMAZQBuAHQANAAFBAAAAAEAAAAEIQAAAAABAAEBAAQBAAYEAAAAAAcEAgAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEABAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABg0AAAAACAAAAAEDAAAAAgEHBxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAKwAAAABBAAAAC0AAAADHAAAAAQOAAAAQQBjAGMAZQBuAHQANQAFBAAAAAEAAAAEIQAAAAABAAEBAAQBAAYEAAAAAAcEAgAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEABAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABg0AAAAACAAAAAEDAAAAAgEIBxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAKwAAAABBAAAADEAAAADHAAAAAQOAAAAQQBjAGMAZQBuAHQANgAFBAAAAAEAAAAEIQAAAAABAAEBAAQBAAYEAAAAAAcEAgAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEABAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABg0AAAAACAAAAAEDAAAAAgEJBxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAADcBAAABBAAAAAQAAAADJwAAAAAEAAAABAAAAAQQAAAAQwB1AHIAcgBlAG4AYwB5AAUEAAAAAQAAAAQkAAAAAAEAAQEAAgEAAwEABgQAAAAABwQAAAAACAQBAAAACQQsAAAABScAAAABBgMAAAACAQEEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGAAAAAAcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAAiFAAAACYAAAAAABnQAAABfACgAIgAkACIAKgAgACMALAAjACMAMAAuADAAMABfACkAOwBfACgAIgAkACIAKgAgAFwAKAAjACwAIwAjADAALgAwADAAXAApADsAXwAoACIAJAAiACoAIAAiAC0AIgA/AD8AXwApADsAXwAoAEAAXwApAAEELAAAAAAvAQAAAQQAAAAHAAAAAy8AAAAABAAAAAcAAAAEGAAAAEMAdQByAHIAZQBuAGMAeQAgAFsAMABdAAUEAAAAAQAAAAQkAAAAAAEAAQEAAgEAAwEABgQAAAAABwQAAAAACAQBAAAACQQqAAAABScAAAABBgMAAAACAQEEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGAAAAAAcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAAh1AAAACXAAAAAABmQAAABfACgAIgAkACIAKgAgACMALAAjACMAMABfACkAOwBfACgAIgAkACIAKgAgAFwAKAAjACwAIwAjADAAXAApADsAXwAoACIAJAAiACoAIAAiAC0AIgBfACkAOwBfACgAQABfACkAAQQqAAAAAKsAAAABBAAAAAUAAAADJQAAAAAEAAAABQAAAAQOAAAAUABlAHIAYwBlAG4AdAAFBAAAAAEAAAAEJAAAAAABAAEBAAIBAAMBAAYEAAAAAAcEAAAAAAgEAQAAAAkECQAAAAUnAAAAAQYDAAAAAgEBBAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABgAAAAAHGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAAHwEAAAEEAAAAAwAAAAMhAAAAAAQAAAADAAAABAoAAABDAG8AbQBtAGEABQQAAAABAAAABCQAAAAAAQABAQACAQADAQAGBAAAAAAHBAAAAAAIBAEAAAAJBCsAAAAFJwAAAAEGAwAAAAIBAQQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYAAAAABxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAACHMAAAAJbgAAAAAGYgAAAF8AKAAqACAAIwAsACMAIwAwAC4AMAAwAF8AKQA7AF8AKAAqACAAXAAoACMALAAjACMAMAAuADAAMABcACkAOwBfACgAKgAgACIALQAiAD8APwBfACkAOwBfACgAQABfACkAAQQrAAAAABcBAAABBAAAAAYAAAADKQAAAAAEAAAABgAAAAQSAAAAQwBvAG0AbQBhACAAWwAwAF0ABQQAAAABAAAABCQAAAAAAQABAQACAQADAQAGBAAAAAAHBAAAAAAIBAEAAAAJBCkAAAAFJwAAAAEGAwAAAAIBAQQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYAAAAABxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAACGMAAAAJXgAAAAAGUgAAAF8AKAAqACAAIwAsACMAIwAwAF8AKQA7AF8AKAAqACAAXAAoACMALAAjACMAMABcACkAOwBfACgAKgAgACIALQAiAF8AKQA7AF8AKABAAF8AKQABBCkAAAAAwwAAAAEEAAAAAQAAAAIBAAAAAQM0AAAAAAQAAAABAAAAAwQAAAAAAAAABBQAAABSAG8AdwBMAGUAdgBlAGwAXwAxAAUEAAAAAQAAAAQkAAAAAAEAAQEAAgEABAEABgQAAAAABwQAAAAACAQBAAAACQQAAAAABSoAAAAAAQEBBgMAAAACAQEEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGAAAAAAcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAADDAAAAAQQAAAABAAAAAgEAAAABAzQAAAAABAAAAAEAAAADBAAAAAEAAAAEFAAAAFIAbwB3AEwAZQB2AGUAbABfADIABQQAAAABAAAABCQAAAAAAQABAQACAQAEAQAGBAAAAAAHBAAAAAAIBAEAAAAJBAAAAAAFKgAAAAEGAwAAAAIBAQMBAQQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYAAAAABxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAMAAAAABBAAAAAEAAAACAQAAAAEDNAAAAAAEAAAAAQAAAAMEAAAAAgAAAAQUAAAAUgBvAHcATABlAHYAZQBsAF8AMwAFBAAAAAEAAAAEJAAAAAABAAEBAAIBAAQBAAYEAAAAAAcEAAAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEBBAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABgAAAAAHGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAAwAAAAAEEAAAAAQAAAAIBAAAAAQM0AAAAAAQAAAABAAAAAwQAAAADAAAABBQAAABSAG8AdwBMAGUAdgBlAGwAXwA0AAUEAAAAAQAAAAQkAAAAAAEAAQEAAgEABAEABgQAAAAABwQAAAAACAQBAAAACQQAAAAABScAAAABBgMAAAACAQEEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGAAAAAAcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAADAAAAAAQQAAAABAAAAAgEAAAABAzQAAAAABAAAAAEAAAADBAAAAAQAAAAEFAAAAFIAbwB3AEwAZQB2AGUAbABfADUABQQAAAABAAAABCQAAAAAAQABAQACAQAEAQAGBAAAAAAHBAAAAAAIBAEAAAAJBAAAAAAFJwAAAAEGAwAAAAIBAQQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYAAAAABxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAMAAAAABBAAAAAEAAAACAQAAAAEDNAAAAAAEAAAAAQAAAAMEAAAABQAAAAQUAAAAUgBvAHcATABlAHYAZQBsAF8ANgAFBAAAAAEAAAAEJAAAAAABAAEBAAIBAAQBAAYEAAAAAAcEAAAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEBBAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABgAAAAAHGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAAwAAAAAEEAAAAAQAAAAIBAAAAAQM0AAAAAAQAAAABAAAAAwQAAAAGAAAABBQAAABSAG8AdwBMAGUAdgBlAGwAXwA3AAUEAAAAAQAAAAQkAAAAAAEAAQEAAgEABAEABgQAAAAABwQAAAAACAQBAAAACQQAAAAABScAAAABBgMAAAACAQEEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGAAAAAAcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAADDAAAAAQQAAAACAAAAAgEAAAABAzQAAAAABAAAAAIAAAADBAAAAAAAAAAEFAAAAEMAbwBsAEwAZQB2AGUAbABfADEABQQAAAABAAAABCQAAAAAAQABAQACAQAEAQAGBAAAAAAHBAAAAAAIBAEAAAAJBAAAAAAFKgAAAAABAQEGAwAAAAIBAQQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYAAAAABxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAMMAAAABBAAAAAIAAAACAQAAAAEDNAAAAAAEAAAAAgAAAAMEAAAAAQAAAAQUAAAAQwBvAGwATABlAHYAZQBsAF8AMgAFBAAAAAEAAAAEJAAAAAABAAEBAAIBAAQBAAYEAAAAAAcEAAAAAAgEAQAAAAkEAAAAAAUqAAAAAQYDAAAAAgEBAwEBBAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABgAAAAAHGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAAwAAAAAEEAAAAAgAAAAIBAAAAAQM0AAAAAAQAAAACAAAAAwQAAAACAAAABBQAAABDAG8AbABMAGUAdgBlAGwAXwAzAAUEAAAAAQAAAAQkAAAAAAEAAQEAAgEABAEABgQAAAAABwQAAAAACAQBAAAACQQAAAAABScAAAABBgMAAAACAQEEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGAAAAAAcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAADAAAAAAQQAAAACAAAAAgEAAAABAzQAAAAABAAAAAIAAAADBAAAAAMAAAAEFAAAAEMAbwBsAEwAZQB2AGUAbABfADQABQQAAAABAAAABCQAAAAAAQABAQACAQAEAQAGBAAAAAAHBAAAAAAIBAEAAAAJBAAAAAAFJwAAAAEGAwAAAAIBAQQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYAAAAABxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAMAAAAABBAAAAAIAAAACAQAAAAEDNAAAAAAEAAAAAgAAAAMEAAAABAAAAAQUAAAAQwBvAGwATABlAHYAZQBsAF8ANQAFBAAAAAEAAAAEJAAAAAABAAEBAAIBAAQBAAYEAAAAAAcEAAAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEBBAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABgAAAAAHGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAAwAAAAAEEAAAAAgAAAAIBAAAAAQM0AAAAAAQAAAACAAAAAwQAAAAFAAAABBQAAABDAG8AbABMAGUAdgBlAGwAXwA2AAUEAAAAAQAAAAQkAAAAAAEAAQEAAgEABAEABgQAAAAABwQAAAAACAQBAAAACQQAAAAABScAAAABBgMAAAACAQEEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGAAAAAAcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAADAAAAAAQQAAAACAAAAAgEAAAABAzQAAAAABAAAAAIAAAADBAAAAAYAAAAEFAAAAEMAbwBsAEwAZQB2AGUAbABfADcABQQAAAABAAAABCQAAAAAAQABAQACAQAEAQAGBAAAAAAHBAAAAAAIBAEAAAAJBAAAAAAFJwAAAAEGAwAAAAIBAQQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYAAAAABxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAMEAAAABBAAAAAgAAAACAQAAAAEDKQAAAAAEAAAACAAAAAQSAAAASAB5AHAAZQByAGwAaQBuAGsABQQAAAABAAAABC0AAAAAAQABAQACAQAEAQAGBAAAAAAHBAAAAAAIBAEAAAAJBAAAAAANBgMAAAAHAQQFKgAAAAEGAwAAAAIBCgQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAcBAwYAAAAABxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAANMAAAABBAAAAAkAAAACAQAAAAEDOwAAAAAEAAAACQAAAAQkAAAARgBvAGwAbABvAHcAZQBkACAASAB5AHAAZQByAGwAaQBuAGsABQQAAAABAAAABC0AAAAAAQABAQACAQAEAQAGBAAAAAAHBAAAAAAIBAEAAAAJBAAAAAANBgMAAAAHAQQFKgAAAAEGAwAAAAIBCwQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAcBAwYAAAAABxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAA"; var dstLen = sStyles.length; var pointer = g_memory.Alloc(dstLen); var stream = new FT_Stream2(pointer.data, dstLen); stream.obj = pointer.obj; var bcr = new Binary_CommonReader(stream); var oBinaryFileReader = new BinaryFileReader(""); oBinaryFileReader.getbase64DecodedData2(sStyles, 0, stream, 0); var oBinary_StylesTableReader = new Binary_StylesTableReader(stream, wb, [], []); var length = stream.GetULongLE(); var fReadStyle = function(type, length, oCellStyle, oStyleObject) { var res = c_oSerConstants.ReadOk; if (Types.BuiltinId === type) { oCellStyle.BuiltinId = stream.GetULongLE(); } else if (Types.Hidden === type) { oCellStyle.Hidden = stream.GetBool(); } else if (Types.CellStyle === type) { res = bcr.Read1(length, function(t, l) { return oBinary_StylesTableReader.ReadCellStyle(t, l, oCellStyle); }); } else if (Types.Xfs === type) { oStyleObject.xfs = {ApplyAlignment: null, ApplyBorder: null, ApplyFill: null, ApplyFont: null, ApplyNumberFormat: null, BorderId: null, FillId: null, FontId: null, NumFmtId: null, QuotePrefix: null, Aligment: null, XfId: null}; res = bcr.Read2Spreadsheet(length, function (t, l) { return oBinary_StylesTableReader.ReadXfs(t, l, oStyleObject.xfs); }); } else if (Types.Font === type) { oStyleObject.font = new Font(); res = bcr.Read2Spreadsheet(length, function (t, l) { return oBinary_StylesTableReader.bssr.ReadRPr(t, l, oStyleObject.font); }); } else if (Types.Fill === type) { oStyleObject.fill = new Fill(); res = bcr.Read1(length, function (t, l) { return oBinary_StylesTableReader.ReadFill(t, l, oStyleObject.fill); }); } else if (Types.Border === type) { oStyleObject.border = new Border(); res = bcr.Read1(length, function (t, l) { return oBinary_StylesTableReader.ReadBorder(t, l, oStyleObject.border); }); } else if (Types.NumFmts === type) { res = bcr.Read1(length, function (t, l) { return oBinary_StylesTableReader.ReadNumFmts(t, l, oStyleObject.oNumFmts); }); } else res = c_oSerConstants.ReadUnknown; return res; }; var fReadStyles = function (type, length, oOutput) { var res = c_oSerConstants.ReadOk; var oStyleObject = {font: null, fill: null, border: null, oNumFmts: [], xfs: null}; if (Types.Style === type) { var oCellStyle = new CCellStyle(); res = bcr.Read1(length, function (t, l) { return fReadStyle(t,l, oCellStyle, oStyleObject); }); oCellStyle.xfs = new CellXfs(); // Border if (null !== oStyleObject.border) oCellStyle.xfs.border = oStyleObject.border.clone(); // Fill if (null !== oStyleObject.fill) oCellStyle.xfs.fill = oStyleObject.fill.clone(); // Font if (null !== oStyleObject.font) oCellStyle.xfs.font = oStyleObject.font.clone(); // NumFmt if (null !== oStyleObject.xfs.numid) { var oCurNum = oStyleObject.oNumFmts[oStyleObject.xfs.numid]; if(null != oCurNum) oCellStyle.xfs.num = oBinary_StylesTableReader.ParseNum(oCurNum, oStyleObject.oNumFmts); else oCellStyle.xfs.num = oBinary_StylesTableReader.ParseNum({id: oStyleObject.xfs.numid, f: null}, oStyleObject.oNumFmts); } // QuotePrefix if(null != oStyleObject.xfs.QuotePrefix) oCellStyle.xfs.QuotePrefix = oStyleObject.xfs.QuotePrefix; // align if(null != oStyleObject.xfs.align) oCellStyle.xfs.align = oStyleObject.xfs.align.clone(); // XfId if (null !== oStyleObject.xfs.XfId) oCellStyle.xfs.XfId = oStyleObject.xfs.XfId; // ApplyBorder (ToDo возможно это свойство должно быть в xfs) if (null !== oStyleObject.xfs.ApplyBorder) oCellStyle.ApplyBorder = oStyleObject.xfs.ApplyBorder; // ApplyFill (ToDo возможно это свойство должно быть в xfs) if (null !== oStyleObject.xfs.ApplyFill) oCellStyle.ApplyFill = oStyleObject.xfs.ApplyFill; // ApplyFont (ToDo возможно это свойство должно быть в xfs) if (null !== oStyleObject.xfs.ApplyFont) oCellStyle.ApplyFont = oStyleObject.xfs.ApplyFont; // ApplyNumberFormat (ToDo возможно это свойство должно быть в xfs) if (null !== oStyleObject.xfs.ApplyNumberFormat) oCellStyle.ApplyNumberFormat = oStyleObject.xfs.ApplyNumberFormat; oOutput.push(oCellStyle); } else res = c_oSerConstants.ReadUnknown; return res; }; var res = bcr.Read1(length, function (t, l) { return fReadStyles(t, l, oOutput); }); // Если нет стилей в документе, то добавим if (0 === wb.CellStyles.CustomStyles.length && 0 < oOutput.length) { wb.CellStyles.CustomStyles.push(oOutput[0].clone()); wb.CellStyles.CustomStyles[0].XfId = 0; } // Если XfId не задан, то определим его if (null == g_oDefaultXfId) { g_oDefaultXfId = 0; } }
Excel/model/Serialize.js
/** @enum */ var c_oSerFormat = { Version:2, //1.0.0.2 Signature: "XLSY" }; var g_nCurFileVersion = c_oSerFormat.Version; //dif: //Version:2 добавлены свойства колонок и строк CustomWidth, CustomHeight(раньше считались true) /** @enum */ var c_oSerTableTypes = { Other: 0, SharedStrings: 1, Styles: 2, Workbook: 3, Worksheets: 4, CalcChain: 5 }; /** @enum */ var c_oSerStylesTypes = { Borders: 0, Border: 1, CellXfs: 2, Xfs: 3, Fills: 4, Fill: 5, Fonts: 6, Font: 7, NumFmts: 8, NumFmt: 9, Dxfs: 10, Dxf: 11, TableStyles: 12, CellStyleXfs: 14, CellStyles: 15, CellStyle: 16 }; /** @enum */ var c_oSerBorderTypes = { Bottom: 0, Diagonal: 1, End: 2, Horizontal: 3, Start: 4, Top: 5, Vertical: 6, DiagonalDown: 7, DiagonalUp: 8, Outline: 9 }; /** @enum */ var c_oSerBorderPropTypes = { Color: 0, Style: 1 }; /** @enum */ var c_oSerXfsTypes = { ApplyAlignment: 0, ApplyBorder: 1, ApplyFill: 2, ApplyFont: 3, ApplyNumberFormat: 4, ApplyProtection: 5, BorderId: 6, FillId: 7, FontId: 8, NumFmtId: 9, PivotButton: 10, QuotePrefix: 11, XfId: 12, Aligment: 13, Protection: 14 }; /** @enum */ var c_oSerAligmentTypes = { Horizontal: 0, Indent: 1, JustifyLastLine: 2, ReadingOrder: 3, RelativeIndent: 4, ShrinkToFit: 5, TextRotation: 6, Vertical: 7, WrapText: 8 }; /** @enum */ var c_oSerFillTypes = { PatternFill: 0, PatternFillBgColor: 1 }; /** @enum */ var c_oSerFontTypes = { Bold: 0, Color: 1, Italic: 3, RFont: 4, Strike: 5, Sz: 6, Underline: 7, VertAlign: 8 }; /** @enum */ var c_oSerNumFmtTypes = { FormatCode: 0, NumFmtId: 1 }; /** @enum */ var c_oSerSharedStringTypes = { Si: 0, Run: 1, RPr: 2, Text: 3 }; /** @enum */ var c_oSerWorkbookTypes = { WorkbookPr: 0, BookViews: 1, WorkbookView: 2, DefinedNames: 3, DefinedName: 4 }; /** @enum */ var c_oSerWorkbookPrTypes = { Date1904: 0, DateCompatibility: 1 }; /** @enum */ var c_oSerWorkbookViewTypes = { ActiveTab: 0 }; /** @enum */ var c_oSerDefinedNameTypes = { Name: 0, Ref: 1, LocalSheetId: 2 }; /** @enum */ var c_oSerWorksheetsTypes = { Worksheet: 0, WorksheetProp: 1, Cols: 2, Col: 3, Dimension: 4, Hyperlinks: 5, Hyperlink: 6, MergeCells: 7, MergeCell: 8, SheetData: 9, Row: 10, SheetFormatPr: 11, Drawings: 12, Drawing: 13, PageMargins: 14, PageSetup: 15, PrintOptions: 16, Autofilter: 17, TableParts: 18, Comments: 19, Comment: 20, ConditionalFormatting: 21, SheetViews: 22, SheetView: 23 }; /** @enum */ var c_oSerWorksheetPropTypes = { Name: 0, SheetId: 1, State: 2 }; /** @enum */ var c_oSerWorksheetColTypes = { BestFit: 0, Hidden: 1, Max: 2, Min: 3, Style: 4, Width: 5, CustomWidth: 6 }; /** @enum */ var c_oSerHyperlinkTypes = { Ref: 0, Hyperlink: 1, Location: 2, Tooltip: 3 }; /** @enum */ var c_oSerSheetFormatPrTypes = { DefaultColWidth : 0, DefaultRowHeight : 1, BaseColWidth : 2 }; /** @enum */ var c_oSerRowTypes = { Row: 0, Style: 1, Height: 2, Hidden: 3, Cells: 4, Cell: 5, CustomHeight: 6 }; /** @enum */ var c_oSerCellTypes = { Ref: 0, Style: 1, Type: 2, Value: 3, Formula: 4 }; /** @enum */ var c_oSerFormulaTypes = { Aca: 0, Bx: 1, Ca: 2, Del1: 3, Del2: 4, Dt2D: 5, Dtr: 6, R1: 7, R2: 8, Ref: 9, Si: 10, T: 11, Text: 12 }; /** @enum */ var c_oSer_DrawingFromToType = { Col: 0, ColOff: 1, Row: 2, RowOff: 3 }; /** @enum */ var c_oSer_DrawingPosType = { X: 0, Y: 1 }; /** @enum */ var c_oSer_DrawingExtType = { Cx: 0, Cy: 1 }; /** @enum */ var c_oSer_OtherType = { Media: 0, MediaItem: 1, MediaId: 2, MediaSrc: 3, EmbeddedFonts: 4, Theme: 5 }; /** @enum */ var c_oSer_CalcChainType = { CalcChainItem: 0, Array: 1, SheetId: 2, DependencyLevel: 3, Ref: 4, ChildChain: 5, NewThread: 6 }; /** @enum */ var c_oSer_ColorObjectType = { Rgb: 0, Type: 1, Theme: 2, Tint: 3 }; /** @enum */ var c_oSer_ColorType = { Auto: 0 }; /** @enum */ var c_oSer_CalcChainType = { CalcChainItem: 0, Array: 1, SheetId: 2, DependencyLevel: 3, Ref: 4, ChildChain: 5, NewThread: 6 }; /** @enum */ var c_oSer_PageMargins = { Left: 0, Top: 1, Right: 2, Bottom: 3, Header: 4, Footer: 5 }; /** @enum */ var c_oSer_PageSetup = { Orientation: 0, PaperSize: 1 }; /** @enum */ var c_oSer_PrintOptions = { GridLines: 0, Headings: 1 }; /** @enum */ var c_oSer_TablePart = { Table:0, Ref:1, TotalsRowCount:2, DisplayName:3, AutoFilter:4, SortState:5, TableColumns:6, TableStyleInfo:7, HeaderRowCount:8 }; /** @enum */ var c_oSer_TableStyleInfo = { Name:0, ShowColumnStripes:1, ShowRowStripes:2, ShowFirstColumn:3, ShowLastColumn:4 }; /** @enum */ var c_oSer_TableColumns = { TableColumn:0, Name:1, DataDxfId:2, TotalsRowLabel:3, TotalsRowFunction:4, TotalsRowFormula:5, CalculatedColumnFormula:6 }; /** @enum */ var c_oSer_SortState = { Ref:0, CaseSensitive:1, SortConditions:2, SortCondition:3, ConditionRef:4, ConditionSortBy:5, ConditionDescending:6, ConditionDxfId:7 }; /** @enum */ var c_oSer_AutoFilter = { Ref:0, FilterColumns:1, FilterColumn:2, SortState:3 }; /** @enum */ var c_oSer_FilterColumn = { ColId:0, Filters:1, Filter:2, DateGroupItem:3, CustomFilters:4, ColorFilter:5, Top10:6, DynamicFilter: 7, HiddenButton: 8, ShowButton: 9, FiltersBlank: 10 }; /** @enum */ var c_oSer_Filter = { Val:0 }; /** @enum */ var c_oSer_DateGroupItem = { DateTimeGrouping:0, Day:1, Hour:2, Minute:3, Month:4, Second:5, Year:6 }; /** @enum */ var c_oSer_CustomFilters = { And:0, CustomFilters:1, CustomFilter:2, Operator:3, Val:4 }; /** @enum */ var c_oSer_DynamicFilter = { Type: 0, Val: 1, MaxVal: 2 }; /** @enum */ var c_oSer_ColorFilter = { CellColor:0, DxfId:1 }; /** @enum */ var c_oSer_Top10 = { FilterVal:0, Percent:1, Top:2, Val:3 }; /** @enum */ var c_oSer_Dxf = { Alignment:0, Border:1, Fill:2, Font:3, NumFmt:4 }; /** @enum */ var c_oSer_TableStyles = { DefaultTableStyle:0, DefaultPivotStyle:1, TableStyles: 2, TableStyle: 3 }; var c_oSer_TableStyle = { Name: 0, Pivot: 1, Table: 2, Elements: 3, Element: 4 }; var c_oSer_TableStyleElement = { DxfId: 0, Size: 1, Type: 2 }; var c_oSer_Comments = { Row: 0, Col: 1, CommentDatas : 2, CommentData : 3, Left: 4, LeftOffset: 5, Top: 6, TopOffset: 7, Right: 8, RightOffset: 9, Bottom: 10, BottomOffset: 11, LeftMM: 12, TopMM: 13, WidthMM: 14, HeightMM: 15, MoveWithCells: 16, SizeWithCells: 17 }; var c_oSer_CommentData = { Text : 0, Time : 1, UserId : 2, UserName : 3, QuoteText : 4, Solved : 5, Document : 6, Replies : 7, Reply : 8 }; var c_oSer_ConditionalFormatting = { Pivot : 0, SqRef : 1, ConditionalFormattingRule : 2 }; var c_oSer_ConditionalFormattingRule = { AboveAverage : 0, Bottom : 1, DxfId : 2, EqualAverage : 3, Operator : 4, Percent : 5, Priority : 6, Rank : 7, StdDev : 8, StopIfTrue : 9, Text : 10, TimePeriod : 11, Type : 12, ColorScale : 14, DataBar : 15, FormulaCF : 16, IconSet : 17 }; var c_oSer_ConditionalFormattingRuleColorScale = { CFVO : 0, Color : 1 }; var c_oSer_ConditionalFormattingDataBar = { CFVO : 0, Color : 1, MaxLength : 2, MinLength : 3, ShowValue : 4 }; var c_oSer_ConditionalFormattingIconSet = { CFVO : 0, IconSet : 1, Percent : 2, Reverse : 3, ShowValue : 4 }; var c_oSer_ConditionalFormattingValueObject = { Gte : 0, Type : 1, Val : 2 }; var c_oSer_SheetView = { ColorId : 0, DefaultGridColor : 1, RightToLeft : 2, ShowFormulas : 3, ShowGridLines : 4, ShowOutlineSymbols : 5, ShowRowColHeaders : 6, ShowRuler : 7, ShowWhiteSpace : 8, ShowZeros : 9, TabSelected : 10, TopLeftCell : 11, View : 12, WindowProtection : 13, WorkbookViewId : 14, ZoomScale : 15, ZoomScaleNormal : 16, ZoomScalePageLayoutView : 17, ZoomScaleSheetLayoutView : 18 }; var c_oSer_CellStyle = { BuiltinId : 0, CustomBuiltin : 1, Hidden : 2, ILevel : 3, Name : 4, XfId : 5 }; /** @enum */ var EBorderStyle = { borderstyleDashDot: 0, borderstyleDashDotDot: 1, borderstyleDashed: 2, borderstyleDotted: 3, borderstyleDouble: 4, borderstyleHair: 5, borderstyleMedium: 6, borderstyleMediumDashDot: 7, borderstyleMediumDashDotDot: 8, borderstyleMediumDashed: 9, borderstyleNone: 10, borderstyleSlantDashDot: 11, borderstyleThick: 12, borderstyleThin: 13 }; /** @enum */ var EUnderline = { underlineDouble: 0, underlineDoubleAccounting: 1, underlineNone: 2, underlineSingle: 3, underlineSingleAccounting: 4 }; /** @enum */ var EVerticalAlignRun = { verticalalignrunBaseline: 0, verticalalignrunSubscript: 1, verticalalignrunSuperscript: 2 }; /** @enum */ var ECellAnchorType = { cellanchorAbsolute: 0, cellanchorOneCell: 1, cellanchorTwoCell: 2 }; /** @enum */ var EVisibleType = { visibleHidden: 0, visibleVeryHidden: 1, visibleVisible: 2 }; /** @enum */ var EHorizontalAlignment = { horizontalalignmentCenter: 0, horizontalalignmentcenterContinuous: 1, horizontalalignmentDistributed: 2, horizontalalignmentFill: 3, horizontalalignmentGeneral: 4, horizontalalignmentJustify: 5, horizontalalignmentLeft: 6, horizontalalignmentRight: 7 }; /** @enum */ var EVerticalAlignment = { verticalalignmentBottom: 0, verticalalignmentCenter: 1, verticalalignmentDistributed: 2, verticalalignmentJustify: 3, verticalalignmentTop: 4 }; /** @enum */ var ECellTypeType = { celltypeBool: 0, celltypeDate: 1, celltypeError: 2, celltypeInlineStr: 3, celltypeNumber: 4, celltypeSharedString: 5, celltypeStr: 6 }; /** @enum */ var ECellFormulaType = { cellformulatypeArray: 0, cellformulatypeDataTable: 1, cellformulatypeNormal: 2, cellformulatypeShared: 3 }; /** @enum */ var EPageOrientation = { pageorientLandscape: 0, pageorientPortrait: 1 }; /** @enum */ var EPageSize = { pagesizeLetterPaper: 1, pagesizeLetterSmall: 2, pagesizeTabloidPaper: 3, pagesizeLedgerPaper: 4, pagesizeLegalPaper: 5, pagesizeStatementPaper: 6, pagesizeExecutivePaper: 7, pagesizeA3Paper: 8, pagesizeA4Paper: 9, pagesizeA4SmallPaper: 10, pagesizeA5Paper: 11, pagesizeB4Paper: 12, pagesizeB5Paper: 13, pagesizeFolioPaper: 14, pagesizeQuartoPaper: 15, pagesizeStandardPaper1: 16, pagesizeStandardPaper2: 17, pagesizeNotePaper: 18, pagesize9Envelope: 19, pagesize10Envelope: 20, pagesize11Envelope: 21, pagesize12Envelope: 22, pagesize14Envelope: 23, pagesizeCPaper: 24, pagesizeDPaper: 25, pagesizeEPaper: 26, pagesizeDLEnvelope: 27, pagesizeC5Envelope: 28, pagesizeC3Envelope: 29, pagesizeC4Envelope: 30, pagesizeC6Envelope: 31, pagesizeC65Envelope: 32, pagesizeB4Envelope: 33, pagesizeB5Envelope: 34, pagesizeB6Envelope: 35, pagesizeItalyEnvelope: 36, pagesizeMonarchEnvelope: 37, pagesize6_3_4Envelope: 38, pagesizeUSStandardFanfold: 39, pagesizeGermanStandardFanfold: 40, pagesizeGermanLegalFanfold: 41, pagesizeISOB4: 42, pagesizeJapaneseDoublePostcard: 43, pagesizeStandardPaper3: 44, pagesizeStandardPaper4: 45, pagesizeStandardPaper5: 46, pagesizeInviteEnvelope: 47, pagesizeLetterExtraPaper: 50, pagesizeLegalExtraPaper: 51, pagesizeTabloidExtraPaper: 52, pagesizeA4ExtraPaper: 53, pagesizeLetterTransversePaper: 54, pagesizeA4TransversePaper: 55, pagesizeLetterExtraTransversePaper: 56, pagesizeSuperA_SuperA_A4Paper: 57, pagesizeSuperB_SuperB_A3Paper: 58, pagesizeLetterPlusPaper: 59, pagesizeA4PlusPaper: 60, pagesizeA5TransversePaper: 61, pagesizeJISB5TransversePaper: 62, pagesizeA3ExtraPaper: 63, pagesizeA5ExtraPaper: 64, pagesizeISOB5ExtraPaper: 65, pagesizeA2Paper: 66, pagesizeA3TransversePaper: 67, pagesizeA3ExtraTransversePaper: 68 }; /** @enum */ var ETotalsRowFunction = { totalrowfunctionAverage: 1, totalrowfunctionCount: 2, totalrowfunctionCountNums: 3, totalrowfunctionCustom: 4, totalrowfunctionMax: 5, totalrowfunctionMin: 6, totalrowfunctionNone: 7, totalrowfunctionStdDev: 8, totalrowfunctionSum: 9, totalrowfunctionVar: 10 }; /** @enum */ var ESortBy = { sortbyCellColor: 1, sortbyFontColor: 2, sortbyIcon: 3, sortbyValue: 4 }; /** @enum */ var ECustomFilter = { customfilterEqual: 1, customfilterGreaterThan: 2, customfilterGreaterThanOrEqual: 3, customfilterLessThan: 4, customfilterLessThanOrEqual: 5, customfilterNotEqual: 6 }; /** @enum */ var EDateTimeGroup = { datetimegroupDay: 1, datetimegroupHour: 2, datetimegroupMinute: 3, datetimegroupMonth: 4, datetimegroupSecond: 5, datetimegroupYear: 6 }; /** @enum */ var ETableStyleType = { tablestyletypeBlankRow: 0, tablestyletypeFirstColumn: 1, tablestyletypeFirstColumnStripe: 2, tablestyletypeFirstColumnSubheading: 3, tablestyletypeFirstHeaderCell: 4, tablestyletypeFirstRowStripe: 5, tablestyletypeFirstRowSubheading: 6, tablestyletypeFirstSubtotalColumn: 7, tablestyletypeFirstSubtotalRow: 8, tablestyletypeFirstTotalCell: 9, tablestyletypeHeaderRow: 10, tablestyletypeLastColumn: 11, tablestyletypeLastHeaderCell: 12, tablestyletypeLastTotalCell: 13, tablestyletypePageFieldLabels: 14, tablestyletypePageFieldValues: 15, tablestyletypeSecondColumnStripe: 16, tablestyletypeSecondColumnSubheading: 17, tablestyletypeSecondRowStripe: 18, tablestyletypeSecondRowSubheading: 19, tablestyletypeSecondSubtotalColumn: 20, tablestyletypeSecondSubtotalRow: 21, tablestyletypeThirdColumnSubheading: 22, tablestyletypeThirdRowSubheading: 23, tablestyletypeThirdSubtotalColumn: 24, tablestyletypeThirdSubtotalRow: 25, tablestyletypeTotalRow: 26, tablestyletypeWholeTable: 27 }; /** @enum */ var EFontScheme = { fontschemeNone: 0, fontschemeMinor: 1, fontschemeMajor: 2 }; var DocumentPageSize = new function() { this.oSizes = [ {id:EPageSize.pagesizeLetterPaper, w_mm: 215.9, h_mm: 279.4}, {id:EPageSize.pagesizeLetterSmall, w_mm: 215.9, h_mm: 279.4}, {id:EPageSize.pagesizeTabloidPaper, w_mm: 279.4, h_mm: 431.7}, {id:EPageSize.pagesizeLedgerPaper, w_mm: 431.8, h_mm: 279.4}, {id:EPageSize.pagesizeLegalPaper, w_mm: 215.9, h_mm: 355.6}, {id:EPageSize.pagesizeStatementPaper, w_mm: 495.3, h_mm: 215.9}, {id:EPageSize.pagesizeExecutivePaper, w_mm: 184.2, h_mm: 266.7}, {id:EPageSize.pagesizeA3Paper, w_mm: 297, h_mm: 420.1}, {id:EPageSize.pagesizeA4Paper, w_mm: 210, h_mm: 297}, {id:EPageSize.pagesizeA4SmallPaper, w_mm: 210, h_mm: 297}, {id:EPageSize.pagesizeA5Paper, w_mm: 148.1, h_mm: 209.9}, {id:EPageSize.pagesizeB4Paper, w_mm: 250, h_mm: 353}, {id:EPageSize.pagesizeB5Paper, w_mm: 176, h_mm: 250.1}, {id:EPageSize.pagesizeFolioPaper, w_mm: 215.9, h_mm: 330.2}, {id:EPageSize.pagesizeQuartoPaper, w_mm: 215, h_mm: 275}, {id:EPageSize.pagesizeStandardPaper1, w_mm: 254, h_mm: 355.6}, {id:EPageSize.pagesizeStandardPaper2, w_mm: 279.4, h_mm: 431.8}, {id:EPageSize.pagesizeNotePaper, w_mm: 215.9, h_mm: 279.4}, {id:EPageSize.pagesize9Envelope, w_mm: 98.4, h_mm: 225.4}, {id:EPageSize.pagesize10Envelope, w_mm: 104.8, h_mm: 241.3}, {id:EPageSize.pagesize11Envelope, w_mm: 114.3, h_mm: 263.5}, {id:EPageSize.pagesize12Envelope, w_mm: 120.7, h_mm: 279.4}, {id:EPageSize.pagesize14Envelope, w_mm: 127, h_mm: 292.1}, {id:EPageSize.pagesizeCPaper, w_mm: 431.8, h_mm: 558.8}, {id:EPageSize.pagesizeDPaper, w_mm: 558.8, h_mm: 863.6}, {id:EPageSize.pagesizeEPaper, w_mm: 863.6, h_mm: 1117.6}, {id:EPageSize.pagesizeDLEnvelope, w_mm: 110.1, h_mm: 220.1}, {id:EPageSize.pagesizeC5Envelope, w_mm: 162, h_mm: 229}, {id:EPageSize.pagesizeC3Envelope, w_mm: 324, h_mm: 458}, {id:EPageSize.pagesizeC4Envelope, w_mm: 229, h_mm: 324}, {id:EPageSize.pagesizeC6Envelope, w_mm: 114, h_mm: 162}, {id:EPageSize.pagesizeC65Envelope, w_mm: 114, h_mm: 229}, {id:EPageSize.pagesizeB4Envelope, w_mm: 250, h_mm: 353}, {id:EPageSize.pagesizeB5Envelope, w_mm: 176, h_mm: 250}, {id:EPageSize.pagesizeB6Envelope, w_mm: 176, h_mm: 125}, {id:EPageSize.pagesizeItalyEnvelope, w_mm: 110, h_mm: 230}, {id:EPageSize.pagesizeMonarchEnvelope, w_mm: 98.4, h_mm: 190.5}, {id:EPageSize.pagesize6_3_4Envelope, w_mm: 92.1, h_mm: 165.1}, {id:EPageSize.pagesizeUSStandardFanfold, w_mm: 377.8, h_mm: 279.4}, {id:EPageSize.pagesizeGermanStandardFanfold, w_mm: 215.9, h_mm: 304.8}, {id:EPageSize.pagesizeGermanLegalFanfold, w_mm: 215.9, h_mm: 330.2}, {id:EPageSize.pagesizeISOB4, w_mm: 250, h_mm: 353}, {id:EPageSize.pagesizeJapaneseDoublePostcard, w_mm: 200, h_mm: 148}, {id:EPageSize.pagesizeStandardPaper3, w_mm: 228.6, h_mm: 279.4}, {id:EPageSize.pagesizeStandardPaper4, w_mm: 254, h_mm: 279.4}, {id:EPageSize.pagesizeStandardPaper5, w_mm: 381, h_mm: 279.4}, {id:EPageSize.pagesizeInviteEnvelope, w_mm: 220, h_mm: 220}, {id:EPageSize.pagesizeLetterExtraPaper, w_mm: 235.6, h_mm: 304.8}, {id:EPageSize.pagesizeLegalExtraPaper, w_mm: 235.6, h_mm: 381}, {id:EPageSize.pagesizeTabloidExtraPaper, w_mm: 296.9, h_mm: 457.2}, {id:EPageSize.pagesizeA4ExtraPaper, w_mm: 236, h_mm: 322}, {id:EPageSize.pagesizeLetterTransversePaper, w_mm: 210.2, h_mm: 279.4}, {id:EPageSize.pagesizeA4TransversePaper, w_mm: 210, h_mm: 297}, {id:EPageSize.pagesizeLetterExtraTransversePaper, w_mm: 235.6, h_mm: 304.8}, {id:EPageSize.pagesizeSuperA_SuperA_A4Paper, w_mm: 227, h_mm: 356}, {id:EPageSize.pagesizeSuperB_SuperB_A3Paper, w_mm: 305, h_mm: 487}, {id:EPageSize.pagesizeLetterPlusPaper, w_mm: 215.9, h_mm: 12.69}, {id:EPageSize.pagesizeA4PlusPaper, w_mm: 210, h_mm: 330}, {id:EPageSize.pagesizeA5TransversePaper, w_mm: 148, h_mm: 210}, {id:EPageSize.pagesizeJISB5TransversePaper, w_mm: 182, h_mm: 257}, {id:EPageSize.pagesizeA3ExtraPaper, w_mm: 322, h_mm: 445}, {id:EPageSize.pagesizeA5ExtraPaper, w_mm: 174, h_mm: 235}, {id:EPageSize.pagesizeISOB5ExtraPaper, w_mm: 201, h_mm: 276}, {id:EPageSize.pagesizeA2Paper, w_mm: 420, h_mm: 594}, {id:EPageSize.pagesizeA3TransversePaper, w_mm: 297, h_mm: 420}, {id:EPageSize.pagesizeA3ExtraTransversePaper, w_mm: 322, h_mm: 445} ]; this.getSizeByWH = function(widthMm, heightMm) { for( index in this.oSizes) { var item = this.oSizes[index]; if(widthMm == item.w_mm && heightMm == item.h_mm) return item; } return this.oSizes[8];//A4 }; this.getSizeById = function(id) { for( index in this.oSizes) { var item = this.oSizes[index]; if(id == item.id) return item; } return this.oSizes[8];//A4 }; }; function OpenColor() { this.rgb = null; this.auto = null; this.theme = null; this.tint = null; } var g_nodeAttributeStart = 0xFA; var g_nodeAttributeEnd = 0xFB; /** @constructor */ function BinaryTableWriter(memory, aDxfs) { this.memory = memory; this.aDxfs = aDxfs; this.bs = new BinaryCommonWriter(this.memory); this.Write = function(aTables) { var oThis = this; for(var i = 0, length = aTables.length; i < length; ++i) this.bs.WriteItem(c_oSer_TablePart.Table, function(){oThis.WriteTable(aTables[i]);}); } this.WriteTable = function(table) { var oThis = this; //Ref if(null != table.Ref) { this.memory.WriteByte(c_oSer_TablePart.Ref); this.memory.WriteString2(table.Ref); } //HeaderRowCount if(null != table.HeaderRowCount) this.bs.WriteItem(c_oSer_TablePart.HeaderRowCount, function(){oThis.memory.WriteLong(table.HeaderRowCount);}); //TotalsRowCount if(null != table.TotalsRowCount) this.bs.WriteItem(c_oSer_TablePart.TotalsRowCount, function(){oThis.memory.WriteLong(table.TotalsRowCount);}); //Display Name if(null != table.DisplayName) { this.memory.WriteByte(c_oSer_TablePart.DisplayName); this.memory.WriteString2(table.DisplayName); } //AutoFilter if(null != table.AutoFilter) this.bs.WriteItem(c_oSer_TablePart.AutoFilter, function(){oThis.WriteAutoFilter(table.AutoFilter);}); //SortState if(null != table.SortState) this.bs.WriteItem(c_oSer_TablePart.SortState, function(){oThis.WriteSortState(table.SortState);}); //TableColumns if(null != table.TableColumns) this.bs.WriteItem(c_oSer_TablePart.TableColumns, function(){oThis.WriteTableColumns(table.TableColumns);}); //TableStyleInfo if(null != table.TableStyleInfo) this.bs.WriteItem(c_oSer_TablePart.TableStyleInfo, function(){oThis.WriteTableStyleInfo(table.TableStyleInfo);}); } this.WriteAutoFilter = function(autofilter) { var oThis = this; //Ref if(null != autofilter.Ref) { this.memory.WriteByte(c_oSer_AutoFilter.Ref); this.memory.WriteString2(autofilter.Ref); } //FilterColumns if(null != autofilter.FilterColumns) this.bs.WriteItem(c_oSer_AutoFilter.FilterColumns, function(){oThis.WriteFilterColumns(autofilter.FilterColumns);}); //SortState if(null != autofilter.SortState) this.bs.WriteItem(c_oSer_AutoFilter.SortState, function(){oThis.WriteSortState(autofilter.SortState);}); } this.WriteFilterColumns = function(filterColumns) { var oThis = this; for(var i = 0, length = filterColumns.length; i < length; ++i) this.bs.WriteItem(c_oSer_AutoFilter.FilterColumn, function(){oThis.WriteFilterColumn(filterColumns[i]);}); } this.WriteFilterColumn = function(filterColumn) { var oThis = this; //ColId if(null != filterColumn.ColId) this.bs.WriteItem(c_oSer_FilterColumn.ColId, function(){oThis.memory.WriteLong(filterColumn.ColId);}); //Filters if(null != filterColumn.Filters) this.bs.WriteItem(c_oSer_FilterColumn.Filters, function(){oThis.WriteFilters(filterColumn.Filters);}); //CustomFilters if(null != filterColumn.CustomFiltersObj) this.bs.WriteItem(c_oSer_FilterColumn.CustomFilters, function(){oThis.WriteCustomFilters(filterColumn.CustomFiltersObj);}); //DynamicFilter if(null != filterColumn.DynamicFilter) this.bs.WriteItem(c_oSer_FilterColumn.DynamicFilter, function(){oThis.WriteDynamicFilter(filterColumn.DynamicFilter);}); //ColorFilter if(null != filterColumn.ColorFilter) this.bs.WriteItem(c_oSer_FilterColumn.ColorFilter, function(){oThis.WriteColorFilter(filterColumn.ColorFilter);}); //Top10 if(null != filterColumn.Top10) this.bs.WriteItem(c_oSer_FilterColumn.Top10, function(){oThis.WriteTop10(filterColumn.Top10);}); //ShowButton if(null != filterColumn.ShowButton) this.bs.WriteItem(c_oSer_FilterColumn.ShowButton, function(){oThis.memory.WriteBool(filterColumn.ShowButton);}); } this.WriteFilters = function(filters) { var oThis = this; if(null != filters.Values) { for(var i = 0, length = filters.Values.length; i < length; ++i) this.bs.WriteItem(c_oSer_FilterColumn.Filter, function(){oThis.WriteFilter(filters.Values[i]);}); } if(null != filters.Dates) { for(var i = 0, length = filters.Dates.length; i < length; ++i) this.bs.WriteItem(c_oSer_FilterColumn.DateGroupItem, function(){oThis.WriteDateGroupItem(filters.Dates[i]);}); } if(null != filters.Blank) this.bs.WriteItem(c_oSer_FilterColumn.FiltersBlank, function(){oThis.memory.WriteBool(filters.Blank);}); } this.WriteFilter = function(val) { var oThis = this; if(null != val) { this.memory.WriteByte(c_oSer_Filter.Val); this.memory.WriteString2(val); } } this.WriteDateGroupItem = function(dateGroupItem) { var oThis = this; if(null != dateGroupItem.DateTimeGrouping) { this.memory.WriteByte(c_oSer_DateGroupItem.DateTimeGrouping); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteByte(dateGroupItem.DateTimeGrouping); } if(null != dateGroupItem.Day) { this.memory.WriteByte(c_oSer_DateGroupItem.Day); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(dateGroupItem.Day); } if(null != dateGroupItem.Hour) { this.memory.WriteByte(c_oSer_DateGroupItem.Hour); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(dateGroupItem.Hour); } if(null != dateGroupItem.Minute) { this.memory.WriteByte(c_oSer_DateGroupItem.Minute); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(dateGroupItem.Minute); } if(null != dateGroupItem.Month) { this.memory.WriteByte(c_oSer_DateGroupItem.Month); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(dateGroupItem.Month); } if(null != dateGroupItem.Second) { this.memory.WriteByte(c_oSer_DateGroupItem.Second); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(dateGroupItem.Second); } if(null != dateGroupItem.Year) { this.memory.WriteByte(c_oSer_DateGroupItem.Year); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(dateGroupItem.Year); } } this.WriteCustomFilters = function(customFilters) { var oThis = this; if(null != customFilters.And) this.bs.WriteItem(c_oSer_CustomFilters.And, function(){oThis.memory.WriteBool(customFilters.And);}); if(null != customFilters.CustomFilters && customFilters.CustomFilters.length > 0) this.bs.WriteItem(c_oSer_CustomFilters.CustomFilters, function(){oThis.WriteCustomFiltersItems(customFilters.CustomFilters);}); } this.WriteCustomFiltersItems = function(aCustomFilters) { var oThis = this; for(var i = 0, length = aCustomFilters.length; i < length; ++i) this.bs.WriteItem(c_oSer_CustomFilters.CustomFilter, function(){oThis.WriteCustomFiltersItem(aCustomFilters[i]);}); } this.WriteCustomFiltersItem = function(customFilter) { var oThis = this; if(null != customFilter.Operator) { this.memory.WriteByte(c_oSer_CustomFilters.Operator); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteByte(customFilter.Operator); } if(null != customFilter.Val) { this.memory.WriteByte(c_oSer_CustomFilters.Val); this.memory.WriteByte(c_oSerPropLenType.Variable); this.memory.WriteString2(customFilter.Val); } } this.WriteDynamicFilter = function(dynamicFilter) { var oThis = this; if(null != dynamicFilter.Type) { this.memory.WriteByte(c_oSer_DynamicFilter.Type); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteByte(dynamicFilter.Type); } if(null != dynamicFilter.Val) { this.memory.WriteByte(c_oSer_DynamicFilter.Val); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(dynamicFilter.Val); } if(null != dynamicFilter.MaxVal) { this.memory.WriteByte(c_oSer_DynamicFilter.MaxVal); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(dynamicFilter.MaxVal); } } this.WriteColorFilter = function(colorFilter) { var oThis = this; if(null != colorFilter.CellColor) { this.memory.WriteByte(c_oSer_ColorFilter.CellColor); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(colorFilter.CellColor); } if(null != colorFilter.dxf) { this.memory.WriteByte(c_oSer_ColorFilter.DxfId); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(this.aDxfs.length); this.aDxfs.push(colorFilter.dxf); } } this.WriteTop10 = function(top10) { var oThis = this; if(null != top10.FilterVal) { this.memory.WriteByte(c_oSer_Top10.FilterVal); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(top10.FilterVal); } if(null != top10.Percent) { this.memory.WriteByte(c_oSer_Top10.Percent); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(top10.Percent); } if(null != top10.Top) { this.memory.WriteByte(c_oSer_Top10.Top); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(top10.Top); } if(null != top10.Val) { this.memory.WriteByte(c_oSer_Top10.Val); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(top10.Val); } } this.WriteSortState = function(sortState) { var oThis = this; if(null != sortState.Ref) { this.memory.WriteByte(c_oSer_SortState.Ref); this.memory.WriteString2(sortState.Ref); } if(null != sortState.CaseSensitive) this.bs.WriteItem(c_oSer_SortState.CaseSensitive, function(){oThis.memory.WriteBool(sortState.CaseSensitive);}); if(null != sortState.SortConditions) this.bs.WriteItem(c_oSer_SortState.SortConditions, function(){oThis.WriteSortConditions(sortState.SortConditions);}); } this.WriteSortConditions = function(sortConditions) { var oThis = this; for(var i = 0, length = sortConditions.length; i < length; ++i) this.bs.WriteItem(c_oSer_SortState.SortCondition, function(){oThis.WriteSortCondition(sortConditions[i]);}); } this.WriteSortCondition = function(sortCondition) { var oThis = this; if(null != sortCondition.Ref) { this.memory.WriteByte(c_oSer_SortState.ConditionRef); this.memory.WriteByte(c_oSerPropLenType.Variable); this.memory.WriteString2(sortCondition.Ref); } if(null != sortCondition.ConditionSortBy) { this.memory.WriteByte(c_oSer_SortState.ConditionSortBy); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteByte(sortCondition.ConditionSortBy); } if(null != sortCondition.ConditionDescending) { this.memory.WriteByte(c_oSer_SortState.ConditionDescending); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(sortCondition.ConditionDescending); } if(null != sortCondition.dxf) { this.memory.WriteByte(c_oSer_SortState.ConditionDxfId); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(this.aDxfs.length); this.aDxfs.push(sortCondition.dxf); } } this.WriteTableColumns = function(tableColumns) { var oThis = this; for(var i = 0, length = tableColumns.length; i < length; ++i) this.bs.WriteItem(c_oSer_TableColumns.TableColumn, function(){oThis.WriteTableColumn(tableColumns[i]);}); } this.WriteTableColumn = function(tableColumn) { var oThis = this; if(null != tableColumn.Name) { this.memory.WriteByte(c_oSer_TableColumns.Name); this.memory.WriteString2(tableColumn.Name); } if(null != tableColumn.TotalsRowLabel) { this.memory.WriteByte(c_oSer_TableColumns.TotalsRowLabel); this.memory.WriteString2(tableColumn.TotalsRowLabel); } if(null != tableColumn.TotalsRowFunction) this.bs.WriteItem(c_oSer_TableColumns.TotalsRowFunction, function(){oThis.memory.WriteByte(tableColumn.TotalsRowFunction);}); if(null != tableColumn.TotalsRowFormula) { this.memory.WriteByte(c_oSer_TableColumns.TotalsRowFormula); this.memory.WriteString2(tableColumn.TotalsRowFormula); } if(null != tableColumn.dxf) { this.bs.WriteItem(c_oSer_TableColumns.DataDxfId, function(){oThis.memory.WriteLong(oThis.aDxfs.length);}); this.aDxfs.push(tableColumn.dxf); } if(null != tableColumn.CalculatedColumnFormula) { this.memory.WriteByte(c_oSer_TableColumns.CalculatedColumnFormula); this.memory.WriteString2(tableColumn.CalculatedColumnFormula); } } this.WriteTableStyleInfo = function(tableStyleInfo) { var oThis = this; if(null != tableStyleInfo.Name) { this.memory.WriteByte(c_oSer_TableStyleInfo.Name); this.memory.WriteByte(c_oSerPropLenType.Variable); this.memory.WriteString2(tableStyleInfo.Name); } if(null != tableStyleInfo.ShowColumnStripes) { this.memory.WriteByte(c_oSer_TableStyleInfo.ShowColumnStripes); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(tableStyleInfo.ShowColumnStripes); } if(null != tableStyleInfo.ShowRowStripes) { this.memory.WriteByte(c_oSer_TableStyleInfo.ShowRowStripes); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(tableStyleInfo.ShowRowStripes); } if(null != tableStyleInfo.ShowFirstColumn) { this.memory.WriteByte(c_oSer_TableStyleInfo.ShowFirstColumn); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(tableStyleInfo.ShowFirstColumn); } if(null != tableStyleInfo.ShowLastColumn) { this.memory.WriteByte(c_oSer_TableStyleInfo.ShowLastColumn); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(tableStyleInfo.ShowLastColumn); } } } /** @constructor */ function BinarySharedStringsTableWriter(memory, oSharedStrings) { this.memory = memory; this.bs = new BinaryCommonWriter(this.memory); this.bsw = new BinaryStylesTableWriter(this.memory); this.oSharedStrings = oSharedStrings; this.Write = function() { var oThis = this; this.bs.WriteItemWithLength(function(){oThis.WriteSharedStringsContent();}); }; this.WriteSharedStringsContent = function() { var oThis = this; var aSharedStrings = new Array(); for(var i in this.oSharedStrings.strings) { var item = this.oSharedStrings.strings[i]; if(null != item.t) aSharedStrings[item.t.id] = {t: item.t.val}; if(null != item.a) { for(var j = 0, length2 = item.a.length; j < length2; ++j) { var oCurText = item.a[j]; aSharedStrings[oCurText.id] = {a: oCurText.val}; } } } for(var i = 0, length = aSharedStrings.length; i < length; ++i) { var si = aSharedStrings[i]; if(null != si) this.bs.WriteItem(c_oSerSharedStringTypes.Si, function(){oThis.WriteSi(si);}); } }; this.WriteSi = function(si) { var oThis = this; if(null != si.t) { this.memory.WriteByte(c_oSerSharedStringTypes.Text); this.memory.WriteString2(si.t); } else if(null != si.a) { for(var i = 0, length = si.a.length; i < length; ++i) { var run = si.a[i]; this.bs.WriteItem(c_oSerSharedStringTypes.Run, function(){oThis.WriteRun(run);}); } } }; this.WriteRun = function(run) { var oThis = this; if(null != run.format) this.bs.WriteItem(c_oSerSharedStringTypes.RPr, function(){oThis.bsw.WriteFont(run.format);}); if(null != run.text) { this.memory.WriteByte(c_oSerSharedStringTypes.Text); this.memory.WriteString2(run.text); } }; }; /** @constructor */ function BinaryStylesTableWriter(memory, wb, oBinaryWorksheetsTableWriter) { this.memory = memory; this.bs = new BinaryCommonWriter(this.memory); this.wb = wb; this.aDxfs = null; this.oXfsStylesMap = null; this.oXfsMap = null; this.oFontMap = null; this.oFillMap = null; this.oBorderMap = null; this.oNumMap = null; if(null != oBinaryWorksheetsTableWriter) { this.aDxfs = oBinaryWorksheetsTableWriter.aDxfs; this.oXfsStylesMap = oBinaryWorksheetsTableWriter.oXfsStylesMap; this.oXfsMap = oBinaryWorksheetsTableWriter.oXfsMap; this.oFontMap = oBinaryWorksheetsTableWriter.oFontMap; this.oFillMap = oBinaryWorksheetsTableWriter.oFillMap; this.oBorderMap = oBinaryWorksheetsTableWriter.oBorderMap; this.oNumMap = oBinaryWorksheetsTableWriter.oNumMap; } this.Write = function() { var oThis = this; this.bs.WriteItemWithLength(function(){oThis.WriteStylesContent();}); }; this.WriteStylesContent = function() { var oThis = this; var wb = this.wb; //borders this.bs.WriteItem(c_oSerStylesTypes.Borders, function(){oThis.WriteBorders();}); //fills this.bs.WriteItem(c_oSerStylesTypes.Fills, function(){oThis.WriteFills();}); //fonts this.bs.WriteItem(c_oSerStylesTypes.Fonts, function(){oThis.WriteFonts();}); //numfmts this.bs.WriteItem(c_oSerStylesTypes.NumFmts, function(){oThis.WriteNumFmts();}); //CellStyleXfs this.bs.WriteItem(c_oSerStylesTypes.CellStyleXfs, function(){oThis.WriteCellStyleXfs();}); //cellxfs this.bs.WriteItem(c_oSerStylesTypes.CellXfs, function(){oThis.WriteCellXfs();}); //CellStyles this.bs.WriteItem(c_oSerStylesTypes.CellStyles, function(){oThis.WriteCellStyles(wb.CellStyles.CustomStyles);}); if(null != wb.TableStyles) this.bs.WriteItem(c_oSerStylesTypes.TableStyles, function(){oThis.WriteTableStyles(wb.TableStyles);}); if(null != this.aDxfs && this.aDxfs.length > 0) this.bs.WriteItem(c_oSerStylesTypes.Dxfs, function(){oThis.WriteDxfs(oThis.aDxfs);}); }; this.WriteBorders = function() { var oThis = this; var aBorders = new Array(); for(var i in this.oBorderMap) { var elem = this.oBorderMap[i]; aBorders[elem.index] = elem.val; } for(var i = 0, length = aBorders.length; i < length; ++i) { var border = aBorders[i]; this.bs.WriteItem(c_oSerStylesTypes.Border, function(){oThis.WriteBorder(border.getDif(g_oDefaultBorderAbs));}); } }; this.WriteBorder = function(border) { if(null == border) return; var oThis = this; //Bottom if(null != border.b) this.bs.WriteItem(c_oSerBorderTypes.Bottom, function(){oThis.WriteBorderProp(border.b);}); //Diagonal if(null != border.d) this.bs.WriteItem(c_oSerBorderTypes.Diagonal, function(){oThis.WriteBorderProp(border.d);}); //End if(null != border.r) this.bs.WriteItem(c_oSerBorderTypes.End, function(){oThis.WriteBorderProp(border.r);}); //Horizontal if(null != border.h) this.bs.WriteItem(c_oSerBorderTypes.Horizontal, function(){oThis.WriteBorderProp(border.h);}); //Start if(null != border.l) this.bs.WriteItem(c_oSerBorderTypes.Start, function(){oThis.WriteBorderProp(border.l);}); //Top if(null != border.t) this.bs.WriteItem(c_oSerBorderTypes.Top, function(){oThis.WriteBorderProp(border.t);}); //Vertical if(null != border.v) this.bs.WriteItem(c_oSerBorderTypes.Vertical, function(){oThis.WriteBorderProp(border.v);}); //DiagonalDown if(null != border.dd) this.bs.WriteItem(c_oSerBorderTypes.DiagonalDown, function(){oThis.memory.WriteBool(border.dd);}); //DiagonalUp if(null != border.du) this.bs.WriteItem(c_oSerBorderTypes.DiagonalUp, function(){oThis.memory.WriteBool(border.du);}); }; this.WriteBorderProp = function(borderProp) { var oThis = this; if(null != borderProp.c) { this.memory.WriteByte(c_oSerBorderPropTypes.Color); this.memory.WriteByte(c_oSerPropLenType.Variable); this.bs.WriteItemWithLength(function(){oThis.bs.WriteColorSpreadsheet(borderProp.c);}); } if(null != borderProp.s) { var nStyle = EBorderStyle.borderstyleNone; switch(borderProp.s) { case "dashDot":nStyle = EBorderStyle.borderstyleDashDot;break; case "dashDotDot":nStyle = EBorderStyle.borderstyleDashDotDot;break; case "dashed":nStyle = EBorderStyle.borderstyleDashed;break; case "dotted":nStyle = EBorderStyle.borderstyleDotted;break; case "double":nStyle = EBorderStyle.borderstyleDouble;break; case "hair":nStyle = EBorderStyle.borderstyleHair;break; case "medium":nStyle = EBorderStyle.borderstyleMedium;break; case "mediumDashDot":nStyle = EBorderStyle.borderstyleMediumDashDot;break; case "mediumDashDotDot":nStyle = EBorderStyle.borderstyleMediumDashDotDot;break; case "mediumDashed":nStyle = EBorderStyle.borderstyleMediumDashed;break; case "none":nStyle = EBorderStyle.borderstyleNone;break; case "slantDashDot":nStyle = EBorderStyle.borderstyleSlantDashDot;break; case "thick":nStyle = EBorderStyle.borderstyleThick;break; case "thin":nStyle = EBorderStyle.borderstyleThin;break; } this.memory.WriteByte(c_oSerBorderPropTypes.Style); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteByte(nStyle); } }; this.WriteFills = function() { var oThis = this; var aFills = new Array(); for(var i in this.oFillMap) { var elem = this.oFillMap[i]; aFills[elem.index] = elem.val; } aFills[1] = aFills[0]; for(var i = 0, length = aFills.length; i < length; ++i) { var fill = aFills[i]; this.bs.WriteItem(c_oSerStylesTypes.Fill, function(){oThis.WriteFill(fill);}); } }; this.WriteFill = function(fill) { var oThis = this; this.bs.WriteItem(c_oSerFillTypes.PatternFill, function(){oThis.WritePatternFill(fill);}); }; this.WritePatternFill = function(fill) { var oThis = this; if(null != fill.bg) this.bs.WriteItem(c_oSerFillTypes.PatternFillBgColor, function(){oThis.bs.WriteColorSpreadsheet(fill.bg);}); }; this.WriteFonts = function() { var oThis = this; var aFonts = new Array(); for(var i in this.oFontMap) { var elem = this.oFontMap[i]; aFonts[elem.index] = elem.val; } for(var i = 0, length = aFonts.length; i < length; ++i) { var font = aFonts[i]; var fontMinimized = font.getDif(g_oDefaultFont); if(null == fontMinimized) fontMinimized = new Font(); if(null == fontMinimized.fn) fontMinimized.fn = g_oDefaultFont.fn; if(null == fontMinimized.fs) fontMinimized.fs = g_oDefaultFont.fs; if(null == fontMinimized.c) fontMinimized.c = g_oDefaultFont.c; this.bs.WriteItem(c_oSerStylesTypes.Font, function(){oThis.WriteFont(fontMinimized);}); } }; this.WriteFont = function(font) { var oThis = this; if(null != font.b) { this.memory.WriteByte(c_oSerFontTypes.Bold); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(font.b); } if(null != font.c) { this.memory.WriteByte(c_oSerFontTypes.Color); this.memory.WriteByte(c_oSerPropLenType.Variable); this.bs.WriteItemWithLength(function(){oThis.bs.WriteColorSpreadsheet(font.c);}); } if(null != font.i) { this.memory.WriteByte(c_oSerFontTypes.Italic); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(font.i); } if(null != font.fn) { this.memory.WriteByte(c_oSerFontTypes.RFont); this.memory.WriteByte(c_oSerPropLenType.Variable); this.memory.WriteString2(font.fn); } if(null != font.s) { this.memory.WriteByte(c_oSerFontTypes.Strike); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(font.s); } if(null != font.fs) { this.memory.WriteByte(c_oSerFontTypes.Sz); this.memory.WriteByte(c_oSerPropLenType.Double); //tood write double this.memory.WriteDouble2(font.fs); } if(null != font.u) { var nUnderline = EUnderline.underlineNone; switch(font.u) { case "double": nUnderline = EUnderline.underlineDouble;break; case "doubleAccounting": nUnderline = EUnderline.underlineDoubleAccounting;break; case "none": nUnderline = EUnderline.underlineNone;break; case "single": nUnderline = EUnderline.underlineSingle;break; case "singleAccounting": nUnderline = EUnderline.underlineSingleAccounting;break; } this.memory.WriteByte(c_oSerFontTypes.Underline); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteByte(nUnderline); } if(null != font.va) { var nVertAlign = EVerticalAlignRun.verticalalignrunBaseline; switch(font.va) { case "baseline": nVertAlign = EVerticalAlignRun.verticalalignrunBaseline;break; case "subscript": nVertAlign = EVerticalAlignRun.verticalalignrunSubscript;break; case "superscript": nVertAlign = EVerticalAlignRun.verticalalignrunSuperscript;break; } this.memory.WriteByte(c_oSerFontTypes.VertAlign); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteByte(nVertAlign); } }; this.WriteNumFmts = function() { var oThis = this; var index = 0; var aNums = new Array(); for(var i in this.oNumMap) { var num = this.oNumMap[i]; if(false == num.val.isEqual(g_oDefaultNumAbs)) this.bs.WriteItem(c_oSerStylesTypes.NumFmt, function(){oThis.WriteNum({id: num.index, f: num.val.f});}); } }; this.WriteNum = function(num) { if(null != num.f) { this.memory.WriteByte(c_oSerNumFmtTypes.FormatCode); this.memory.WriteByte(c_oSerPropLenType.Variable); this.memory.WriteString2(num.f); } if(null != num.id) { this.memory.WriteByte(c_oSerNumFmtTypes.NumFmtId); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(num.id); } }; this.WriteCellStyleXfs = function(cellStyles) { var oThis = this; for(var i = 0, length = this.oXfsStylesMap.length; i < length; ++i) { var cellStyleXfs = this.oXfsStylesMap[i]; this.bs.WriteItem(c_oSerStylesTypes.Xfs, function(){oThis.WriteXfs(cellStyleXfs);}); } }; this.WriteCellXfs = function() { var oThis = this; var aXfs = new Array(); for(var i in this.oXfsMap) { var elem = this.oXfsMap[i]; aXfs[elem.index] = elem.val; } for(var i = 0, length = aXfs.length; i < length; ++i) { var cellxfs = aXfs[i]; this.bs.WriteItem(c_oSerStylesTypes.Xfs, function(){oThis.WriteXfs(cellxfs);}); } }; this.WriteXfs = function(xfs) { var oThis = this; if(null != xfs.borderid) { if(0 != xfs.borderid) { this.memory.WriteByte(c_oSerXfsTypes.ApplyBorder); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(true); } this.memory.WriteByte(c_oSerXfsTypes.BorderId); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(xfs.borderid); } if(null != xfs.fillid) { if(0 != xfs.fillid) { this.memory.WriteByte(c_oSerXfsTypes.ApplyFill); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(true); } this.memory.WriteByte(c_oSerXfsTypes.FillId); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(xfs.fillid); } if(null != xfs.fontid) { if(0 != xfs.fontid) { this.memory.WriteByte(c_oSerXfsTypes.ApplyFont); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(true); } this.memory.WriteByte(c_oSerXfsTypes.FontId); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(xfs.fontid); } if(null != xfs.numid) { if(0 != xfs.numid) { this.memory.WriteByte(c_oSerXfsTypes.ApplyNumberFormat); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(true); } this.memory.WriteByte(c_oSerXfsTypes.NumFmtId); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(xfs.numid); } if(null != xfs.align) { var alignMinimized = xfs.align.getDif(g_oDefaultAlignAbs); if(null != alignMinimized) { this.memory.WriteByte(c_oSerXfsTypes.ApplyAlignment); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(true); this.memory.WriteByte(c_oSerXfsTypes.Aligment); this.memory.WriteByte(c_oSerPropLenType.Variable); this.bs.WriteItemWithLength(function(){oThis.WriteAlign(alignMinimized);}); } } if(null != xfs.QuotePrefix) { this.memory.WriteByte(c_oSerXfsTypes.QuotePrefix); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(xfs.QuotePrefix); } if(null != xfs.XfId) { this.memory.WriteByte(c_oSerXfsTypes.XfId); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(xfs.XfId); } }; this.WriteAlign = function(align) { if(null != align.hor) { var nHorizontalAlignment = EHorizontalAlignment.horizontalalignmentGeneral; switch(align.hor) { case "center" : nHorizontalAlignment = EHorizontalAlignment.horizontalalignmentCenter;break; case "justify" : nHorizontalAlignment = EHorizontalAlignment.horizontalalignmentJustify;break; case "none" : nHorizontalAlignment = EHorizontalAlignment.horizontalalignmentGeneral;break; case "left" : nHorizontalAlignment = EHorizontalAlignment.horizontalalignmentLeft;break; case "right" : nHorizontalAlignment = EHorizontalAlignment.horizontalalignmentRight;break; } this.memory.WriteByte(c_oSerAligmentTypes.Horizontal); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteByte(nHorizontalAlignment); } if(null != align.indent) { this.memory.WriteByte(c_oSerAligmentTypes.Indent); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(align.indent); } if(null != align.RelativeIndent) { this.memory.WriteByte(c_oSerAligmentTypes.RelativeIndent); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(align.RelativeIndent); } if(null != align.shrink) { this.memory.WriteByte(c_oSerAligmentTypes.ShrinkToFit); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(align.shrink); } if(null != align.angle) { this.memory.WriteByte(c_oSerAligmentTypes.TextRotation); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(align.angle); } if(null != align.ver) { var nVerticalAlignment = EHorizontalAlignment.horizontalalignmentGeneral; switch(align.ver) { case "bottom" : nVerticalAlignment = EVerticalAlignment.verticalalignmentBottom;break; case "center" : nVerticalAlignment = EVerticalAlignment.verticalalignmentCenter;break; case "distributed" : nVerticalAlignment = EVerticalAlignment.verticalalignmentDistributed;break; case "justify" : nVerticalAlignment = EVerticalAlignment.verticalalignmentJustify;break; case "top" : nVerticalAlignment = EVerticalAlignment.verticalalignmentTop;break; } this.memory.WriteByte(c_oSerAligmentTypes.Vertical); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteByte(nVerticalAlignment); } if(null != align.wrap) { this.memory.WriteByte(c_oSerAligmentTypes.WrapText); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(align.wrap); } }; this.WriteDxfs = function(Dxfs) { var oThis = this; for(var i = 0, length = Dxfs.length; i < length; ++i) this.bs.WriteItem(c_oSerStylesTypes.Dxf, function(){oThis.WriteDxf(Dxfs[i]);}); } this.WriteDxf = function(Dxf) { var oThis = this; if(null != Dxf.align) this.bs.WriteItem(c_oSer_Dxf.Alignment, function(){oThis.WriteAlign(Dxf.align);}); if(null != Dxf.border) this.bs.WriteItem(c_oSer_Dxf.Border, function(){oThis.WriteBorder(Dxf.border);}); if(null != Dxf.fill) this.bs.WriteItem(c_oSer_Dxf.Fill, function(){oThis.WriteFill(Dxf.fill);}); if(null != Dxf.font) this.bs.WriteItem(c_oSer_Dxf.Font, function(){oThis.WriteFont(Dxf.font);}); if(null != Dxf.numFmt) this.bs.WriteItem(c_oSer_Dxf.NumFmt, function(){oThis.WriteNum(Dxf.numFmt);}); }; this.WriteCellStyles = function (cellStyles) { var oThis = this; for(var i = 0, length = cellStyles.length; i < length; ++i) { var style = cellStyles[i]; this.bs.WriteItem(c_oSerStylesTypes.CellStyle, function(){oThis.WriteCellStyle(style);}); } }; this.WriteCellStyle = function (oCellStyle) { var oThis = this; if (null != oCellStyle.BuiltinId) this.bs.WriteItem(c_oSer_CellStyle.BuiltinId, function(){oThis.memory.WriteLong(oCellStyle.BuiltinId);}); if (null != oCellStyle.CustomBuiltin) this.bs.WriteItem(c_oSer_CellStyle.CustomBuiltin, function(){oThis.memory.WriteBool(oCellStyle.CustomBuiltin);}); if (null != oCellStyle.Hidden) this.bs.WriteItem(c_oSer_CellStyle.Hidden, function(){oThis.memory.WriteBool(oCellStyle.Hidden);}); if (null != oCellStyle.ILevel) this.bs.WriteItem(c_oSer_CellStyle.ILevel, function(){oThis.memory.WriteLong(oCellStyle.ILevel);}); if (null != oCellStyle.Name) { this.memory.WriteByte(c_oSer_CellStyle.Name); this.memory.WriteString2(oCellStyle.Name); } if (null != oCellStyle.XfId) this.bs.WriteItem(c_oSer_CellStyle.XfId, function(){oThis.memory.WriteLong(oCellStyle.XfId);}); }; this.WriteTableStyles = function(tableStyles) { var oThis = this; if(null != tableStyles.DefaultTableStyle) { this.memory.WriteByte(c_oSer_TableStyles.DefaultTableStyle); this.memory.WriteString2(tableStyles.DefaultTableStyle); } if(null != tableStyles.DefaultPivotStyle) { this.memory.WriteByte(c_oSer_TableStyles.DefaultPivotStyle); this.memory.WriteString2(tableStyles.DefaultPivotStyle); } var bEmptyCustom = true; for(var i in tableStyles.CustomStyles) { bEmptyCustom = false; break; } if(false == bEmptyCustom) { this.bs.WriteItem(c_oSer_TableStyles.TableStyles, function(){oThis.WriteTableCustomStyles(tableStyles.CustomStyles);}); } } this.WriteTableCustomStyles = function(customStyles) { var oThis = this; for(var i in customStyles) { var style = customStyles[i]; this.bs.WriteItem(c_oSer_TableStyles.TableStyle, function(){oThis.WriteTableCustomStyle(style);}); } } this.WriteTableCustomStyle = function(customStyle) { var oThis = this; if(null != customStyle.name) { this.memory.WriteByte(c_oSer_TableStyle.Name); this.memory.WriteString2(customStyle.name); } if(null != customStyle.pivot) this.bs.WriteItem(c_oSer_TableStyle.Pivot, function(){oThis.memory.WriteBool(customStyle.pivot);}); if(null != customStyle.table) this.bs.WriteItem(c_oSer_TableStyle.Table, function(){oThis.memory.WriteBool(customStyle.table);}); this.bs.WriteItem(c_oSer_TableStyle.Elements, function(){oThis.WriteTableCustomStyleElements(customStyle);}); } this.WriteTableCustomStyleElements = function(customStyle) { var oThis = this; if(null != customStyle.blankRow) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeBlankRow, customStyle.blankRow);}); if(null != customStyle.firstColumn) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeFirstColumn, customStyle.firstColumn);}); if(null != customStyle.firstColumnStripe) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeFirstColumnStripe, customStyle.firstColumnStripe);}); if(null != customStyle.firstColumnSubheading) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeFirstColumnSubheading, customStyle.firstColumnSubheading);}); if(null != customStyle.firstHeaderCell) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeFirstHeaderCell, customStyle.firstHeaderCell);}); if(null != customStyle.firstRowStripe) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeFirstRowStripe, customStyle.firstRowStripe);}); if(null != customStyle.firstRowSubheading) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeFirstRowSubheading, customStyle.firstRowSubheading);}); if(null != customStyle.firstSubtotalColumn) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeFirstSubtotalColumn, customStyle.firstSubtotalColumn);}); if(null != customStyle.firstSubtotalRow) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeFirstSubtotalRow, customStyle.firstSubtotalRow);}); if(null != customStyle.firstTotalCell) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeFirstTotalCell, customStyle.firstTotalCell);}); if(null != customStyle.headerRow) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeHeaderRow, customStyle.headerRow);}); if(null != customStyle.lastColumn) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeLastColumn, customStyle.lastColumn);}); if(null != customStyle.lastHeaderCell) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeLastHeaderCell, customStyle.lastHeaderCell);}); if(null != customStyle.lastTotalCell) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeLastTotalCell, customStyle.lastTotalCell);}); if(null != customStyle.pageFieldLabels) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypePageFieldLabels, customStyle.pageFieldLabels);}); if(null != customStyle.pageFieldValues) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypePageFieldValues, customStyle.pageFieldValues);}); if(null != customStyle.secondColumnStripe) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeSecondColumnStripe, customStyle.secondColumnStripe);}); if(null != customStyle.secondColumnSubheading) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeSecondColumnSubheading, customStyle.secondColumnSubheading);}); if(null != customStyle.secondRowStripe) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeSecondRowStripe, customStyle.secondRowStripe);}); if(null != customStyle.secondRowSubheading) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeSecondRowSubheading, customStyle.secondRowSubheading);}); if(null != customStyle.secondSubtotalColumn) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeSecondSubtotalColumn, customStyle.secondSubtotalColumn);}); if(null != customStyle.secondSubtotalRow) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeSecondSubtotalRow, customStyle.secondSubtotalRow);}); if(null != customStyle.thirdColumnSubheading) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeThirdColumnSubheading, customStyle.thirdColumnSubheading);}); if(null != customStyle.thirdRowSubheading) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeThirdRowSubheading, customStyle.thirdRowSubheading);}); if(null != customStyle.thirdSubtotalColumn) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeThirdSubtotalColumn, customStyle.thirdSubtotalColumn);}); if(null != customStyle.thirdSubtotalRow) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeThirdSubtotalRow, customStyle.thirdSubtotalRow);}); if(null != customStyle.totalRow) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeTotalRow, customStyle.totalRow);}); if(null != customStyle.wholeTable) this.bs.WriteItem(c_oSer_TableStyle.Element, function(){oThis.WriteTableCustomStyleElement(ETableStyleType.tablestyletypeWholeTable, customStyle.wholeTable);}); } this.WriteTableCustomStyleElement = function(type, customElement) { if(null != type) { this.memory.WriteByte(c_oSer_TableStyleElement.Type); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteByte(type); } if(null != customElement.size) { this.memory.WriteByte(c_oSer_TableStyleElement.Size); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(customElement.size); } if(null != customElement.dxf && null != this.aDxfs) { this.memory.WriteByte(c_oSer_TableStyleElement.DxfId); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(this.aDxfs.length); this.aDxfs.push(customElement.dxf); } } }; function BinaryWorkbookTableWriter(memory, wb) { this.memory = memory; this.bs = new BinaryCommonWriter(this.memory); this.wb = wb; this.Write = function() { var oThis = this; this.bs.WriteItemWithLength(function(){oThis.WriteWorkbookContent();}); }; this.WriteWorkbookContent = function() { var oThis = this; //WorkbookPr this.bs.WriteItem(c_oSerWorkbookTypes.WorkbookPr, function(){oThis.WriteWorkbookPr();}); //BookViews this.bs.WriteItem(c_oSerWorkbookTypes.BookViews, function(){oThis.WriteBookViews();}); //DefinedNames this.bs.WriteItem(c_oSerWorkbookTypes.DefinedNames, function(){oThis.WriteDefinedNames();}); }; this.WriteWorkbookPr = function() { var oWorkbookPr = this.wb.WorkbookPr; if(null != oWorkbookPr) { if(null != oWorkbookPr.Date1904) { this.memory.WriteByte(c_oSerBorderPropTypes.Date1904); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(oWorkbookPr.Date1904); } else if (null != oWorkbookPr.DateCompatibility) { this.memory.WriteByte(c_oSerBorderPropTypes.DateCompatibility); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(oWorkbookPr.DateCompatibility); } } }; this.WriteBookViews = function() { var oThis = this; this.bs.WriteItem(c_oSerWorkbookTypes.WorkbookView, function(){oThis.WriteWorkbookView();}); }; this.WriteWorkbookView = function() { if (null != this.wb.nActive) { this.memory.WriteByte( c_oSerWorkbookViewTypes.ActiveTab); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(this.wb.nActive); } }; this.WriteDefinedNames = function() { var oThis = this; //собираем все defined names в массив var allDefined = new Object(); if(null != this.wb.oRealDefinedNames) { for(var i in this.wb.oRealDefinedNames) { var oDefinedName = this.wb.oRealDefinedNames[i]; if(null == allDefined[oDefinedName.Name]) allDefined[oDefinedName.Name] = {global: oDefinedName, local: {}}; } } for(var i = 0, length = this.wb.aWorksheets.length; i < length; ++i) { var ws = this.wb.aWorksheets[i]; if(null != ws.DefinedNames) { for(var j in ws.DefinedNames) { var oDefinedName = ws.DefinedNames[j]; var elem = allDefined[oDefinedName.Name]; if(null == elem) { elem = {global: null, local: {}}; allDefined[oDefinedName.Name] = elem; } elem.local[i] = oDefinedName; } } } for(var i in allDefined) { var elem = allDefined[i]; for(var j in elem.local) { var localElem = elem.local[j]; var nLocalIndex = j - 0; if(null != localElem) this.bs.WriteItem(c_oSerWorkbookTypes.DefinedName, function(){oThis.WriteDefinedName(localElem, nLocalIndex);}); } if(null != elem.global) this.bs.WriteItem(c_oSerWorkbookTypes.DefinedName, function(){oThis.WriteDefinedName(elem.global);}); } }; this.WriteDefinedName = function(oDefinedName, LocalSheetId) { var oThis = this; if (null != oDefinedName.Name) { this.memory.WriteByte(c_oSerDefinedNameTypes.Name); this.memory.WriteString2(oDefinedName.Name); } if (null != oDefinedName.Ref) { this.memory.WriteByte(c_oSerDefinedNameTypes.Ref); this.memory.WriteString2(oDefinedName.Ref); } if (null != LocalSheetId) this.bs.WriteItem(c_oSerDefinedNameTypes.LocalSheetId, function(){oThis.memory.WriteLong(LocalSheetId);}); }; }; function BinaryWorksheetsTableWriter(memory, wb, oSharedStrings, oDrawings, aDxfs, aXfs, aFonts, aFills, aBorders, aNums, idWorksheet) { this.memory = memory; this.bs = new BinaryCommonWriter(this.memory); this.wb = wb; this.oSharedStrings = oSharedStrings; this.oDrawings = oDrawings; this.aDxfs = aDxfs; this.aXfs = aXfs; this.aFonts = aFonts; this.aFills = aFills; this.aBorders = aBorders; this.aNums = aNums; this.oXfsStylesMap = []; this.oXfsMap = new Object(); this.nXfsMapIndex = 0; this.oFontMap = new Object(); this.nFontMapIndex = 0; this.oFillMap = new Object(); this.nFillMapIndex = 0; this.oBorderMap = new Object(); this.nBorderMapIndex = 0; this.oNumMap = new Object(); this.nNumMapIndex = 0; this.oMerged = new Object(); this.oHyperlinks = new Object(); this.idWorksheet = idWorksheet; this.oAllColXfsId = null; this._getCrc32FromObjWithProperty = function(val) { return Asc.crc32(this._getStringFromObjWithProperty(val)); } this._getStringFromObjWithProperty = function(val) { var sRes = ""; if(val.getProperties) { var properties = val.getProperties(); for(var i in properties) { var oCurProp = val.getProperty(properties[i]); if(null != oCurProp && oCurProp.getProperties) sRes += this._getStringFromObjWithProperty(oCurProp); else sRes += oCurProp; } } return sRes; } this._prepeareStyles = function() { this.oFontMap[this._getStringFromObjWithProperty(g_oDefaultFont)] = {index: this.nFontMapIndex++, val: g_oDefaultFont}; this.oFillMap[this._getStringFromObjWithProperty(g_oDefaultFill)] = {index: this.nFillMapIndex++, val: g_oDefaultFill}; this.nFillMapIndex++; this.oBorderMap[this._getStringFromObjWithProperty(g_oDefaultBorder)] = {index: this.nBorderMapIndex++, val: g_oDefaultBorder}; this.nNumMapIndex = g_nNumsMaxId; var sAlign = "0"; var oAlign = null; if(false == g_oDefaultAlign.isEqual(g_oDefaultAlignAbs)) { oAlign = g_oDefaultAlign; sAlign = this._getStringFromObjWithProperty(g_oDefaultAlign); } this.prepareXfsStyles(); var xfs = {borderid: 0, fontid: 0, fillid: 0, numid: 0, align: oAlign, QuotePrefix: null}; this.oXfsMap["0|0|0|0|"+sAlign] = {index: this.nXfsMapIndex++, val: xfs}; }; this.Write = function() { var oThis = this; this._prepeareStyles(); this.bs.WriteItemWithLength(function(){oThis.WriteWorksheetsContent();}); }; this.WriteWorksheetsContent = function() { var oThis = this; for(var i = 0, length = this.wb.aWorksheets.length; i < length; ++i) { var ws = this.wb.aWorksheets[i]; this.oMerged = new Object(); this.oHyperlinks = new Object(); if(null == this.idWorksheet || this.idWorksheet == ws.getId()) this.bs.WriteItem(c_oSerWorksheetsTypes.Worksheet, function(){oThis.WriteWorksheet(ws, i);}); } }; this.WriteWorksheet = function(ws, index) { var oThis = this; this.bs.WriteItem(c_oSerWorksheetsTypes.WorksheetProp, function(){oThis.WriteWorksheetProp(ws, index);}); if(ws.aCols.length > 0 || null != ws.oAllCol) this.bs.WriteItem(c_oSerWorksheetsTypes.Cols, function(){oThis.WriteWorksheetCols(ws);}); this.bs.WriteItem(c_oSerWorksheetsTypes.SheetViews, function(){oThis.WriteSheetViews(ws);}); this.bs.WriteItem(c_oSerWorksheetsTypes.SheetFormatPr, function(){oThis.WriteSheetFormatPr(ws);}); if(null != ws.PagePrintOptions) { this.bs.WriteItem(c_oSerWorksheetsTypes.PageMargins, function(){oThis.WritePageMargins(ws.PagePrintOptions.asc_getPageMargins());}); this.bs.WriteItem(c_oSerWorksheetsTypes.PageSetup, function(){oThis.WritePageSetup(ws.PagePrintOptions.asc_getPageSetup());}); this.bs.WriteItem(c_oSerWorksheetsTypes.PrintOptions, function(){oThis.WritePrintOptions(ws.PagePrintOptions);}); } this.bs.WriteItem(c_oSerWorksheetsTypes.SheetData, function(){oThis.WriteSheetData(ws);}); this.bs.WriteItem(c_oSerWorksheetsTypes.Hyperlinks, function(){oThis.WriteHyperlinks();}); this.bs.WriteItem(c_oSerWorksheetsTypes.MergeCells, function(){oThis.WriteMergeCells();}); if ( ws.Drawings && (ws.Drawings.length) ) this.bs.WriteItem(c_oSerWorksheetsTypes.Drawings, function(){oThis.WriteDrawings(ws.Drawings);}); if(ws.aComments.length > 0 && ws.aCommentsCoords.length > 0) this.bs.WriteItem(c_oSerWorksheetsTypes.Comments, function(){oThis.WriteComments(ws.aComments, ws.aCommentsCoords);}); if(null != ws.AutoFilter) { var oBinaryTableWriter = new BinaryTableWriter(this.memory, this.aDxfs); this.bs.WriteItem(c_oSerWorksheetsTypes.Autofilter, function(){oBinaryTableWriter.WriteAutoFilter(ws.AutoFilter);}); } if(null != ws.TableParts && ws.TableParts.length > 0) { var oBinaryTableWriter = new BinaryTableWriter(this.memory, this.aDxfs); this.bs.WriteItem(c_oSerWorksheetsTypes.TableParts, function(){oBinaryTableWriter.Write(ws.TableParts);}); } }; this.WriteWorksheetProp = function(ws, index) { var oThis = this; //Name this.memory.WriteByte(c_oSerWorksheetPropTypes.Name); this.memory.WriteByte(c_oSerPropLenType.Variable); this.memory.WriteString2(ws.sName); //SheetId this.memory.WriteByte(c_oSerWorksheetPropTypes.SheetId); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(index + 1); //Hidden if(null != ws.bHidden) { this.memory.WriteByte(c_oSerWorksheetPropTypes.State); this.memory.WriteByte(c_oSerPropLenType.Byte); if(true == ws.bHidden) this.memory.WriteByte(EVisibleType.visibleHidden); else this.memory.WriteByte(EVisibleType.visibleVisible); } }; this.WriteWorksheetCols = function(ws) { var oThis = this; var aCols = ws.aCols; var oPrevCol = null; var nPrevIndexStart = null; var nPrevIndex = null; var aIndexes = new Array(); for(var i in aCols) aIndexes.push(i - 0); aIndexes.sort(fSortAscending); var fInitCol = function(col, nMin, nMax){ oThis.AddToMergedAndHyperlink(col); var oRes = {BestFit: col.BestFit, hd: col.hd, Max: nMax, Min: nMin, xfsid: null, width: col.width, CustomWidth: col.CustomWidth}; if(null == oRes.width) { if(null != ws.dDefaultColWidth) oRes.width = ws.dDefaultColWidth; else oRes.width = gc_dDefaultColWidthCharsAttribute; } if(null != col.xfs) oRes.xfsid = oThis.prepareXfs(col.xfs); return oRes; } var oAllCol = null; if(null != ws.oAllCol) { oAllCol = fInitCol(ws.oAllCol, 0, gc_nMaxCol0); this.oAllColXfsId = oAllCol.xfsid; } for(var i = 0 , length = aIndexes.length; i < length; ++i) { var nIndex = aIndexes[i]; var col = aCols[nIndex]; if(null != col) { if(false == col.isEmptyToSave()) { if(null != oAllCol && null == nPrevIndex && nIndex > 0) { oAllCol.Min = 1; oAllCol.Max = nIndex; this.bs.WriteItem(c_oSerWorksheetsTypes.Col, function(){oThis.WriteWorksheetCol(oAllCol);}); } if(null != nPrevIndex && (nPrevIndex + 1 != nIndex || false == oPrevCol.isEqual(col))) { var oColToWrite = fInitCol(oPrevCol, nPrevIndexStart + 1, nPrevIndex + 1); this.bs.WriteItem(c_oSerWorksheetsTypes.Col, function(){oThis.WriteWorksheetCol(oColToWrite);}); nPrevIndexStart = null; if(null != oAllCol && nPrevIndex + 1 != nIndex) { oAllCol.Min = nPrevIndex + 2; oAllCol.Max = nIndex; this.bs.WriteItem(c_oSerWorksheetsTypes.Col, function(){oThis.WriteWorksheetCol(oAllCol);}); } } oPrevCol = col; nPrevIndex = nIndex; if(null == nPrevIndexStart) nPrevIndexStart = nPrevIndex; } } } if(null != nPrevIndexStart && null != nPrevIndex && null != oPrevCol) { var oColToWrite = fInitCol(oPrevCol, nPrevIndexStart + 1, nPrevIndex + 1); this.bs.WriteItem(c_oSerWorksheetsTypes.Col, function(){oThis.WriteWorksheetCol(oColToWrite);}); } if(null != oAllCol) { if(null == nPrevIndex) { oAllCol.Min = 1; oAllCol.Max = gc_nMaxCol0 + 1; this.bs.WriteItem(c_oSerWorksheetsTypes.Col, function(){oThis.WriteWorksheetCol(oAllCol);}); } else if(gc_nMaxCol0 != nPrevIndex) { oAllCol.Min = nPrevIndex + 2; oAllCol.Max = gc_nMaxCol0 + 1; this.bs.WriteItem(c_oSerWorksheetsTypes.Col, function(){oThis.WriteWorksheetCol(oAllCol);}); } } }; this.WriteWorksheetCol = function(oCol) { if(null != oCol.BestFit) { this.memory.WriteByte(c_oSerWorksheetColTypes.BestFit); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(oCol.BestFit); } if(null != oCol.Hidden) { this.memory.WriteByte(c_oSerWorksheetColTypes.Hidden); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(oCol.Hidden); } if(null != oCol.Max) { this.memory.WriteByte(c_oSerWorksheetColTypes.Max); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(oCol.Max); } if(null != oCol.Min) { this.memory.WriteByte(c_oSerWorksheetColTypes.Min); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(oCol.Min); } if(null != oCol.xfsid) { this.memory.WriteByte(c_oSerWorksheetColTypes.Style); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(oCol.xfsid); } if(null != oCol.width) { this.memory.WriteByte(c_oSerWorksheetColTypes.Width); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(oCol.width); } if(null != oCol.CustomWidth) { this.memory.WriteByte(c_oSerWorksheetColTypes.CustomWidth); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(oCol.CustomWidth); } }; this.WriteSheetViews = function (ws) { var oThis = this; for (var i = 0, length = ws.sheetViews.length; i < length; ++i) { this.bs.WriteItem(c_oSerWorksheetsTypes.SheetView, function(){oThis.WriteSheetView(ws.sheetViews[i]);}); } }; this.WriteSheetView = function (oSheetView) { if (null !== oSheetView.showGridLines) { this.memory.WriteByte(c_oSer_SheetView.ShowGridLines); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(oSheetView.showGridLines); } if (null !== oSheetView.showRowColHeaders) { this.memory.WriteByte(c_oSer_SheetView.ShowRowColHeaders); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(oSheetView.showRowColHeaders); } }; this.WriteSheetFormatPr = function(ws) { if(null !== ws.dDefaultColWidth) { this.memory.WriteByte(c_oSerSheetFormatPrTypes.DefaultColWidth); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(ws.dDefaultColWidth); } if(null !== ws.dDefaultheight) { this.memory.WriteByte(c_oSerSheetFormatPrTypes.DefaultRowHeight); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(ws.dDefaultheight); } if (null !== ws.nBaseColWidth) { this.memory.WriteByte(c_oSerSheetFormatPrTypes.BaseColWidth); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(ws.nBaseColWidth); } }; this.WritePageMargins = function(oMargins) { //Left var dLeft = oMargins.asc_getLeft(); if(null != dLeft) { this.memory.WriteByte(c_oSer_PageMargins.Left); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(dLeft); } //Top var dTop = oMargins.asc_getTop(); if(null != dTop) { this.memory.WriteByte(c_oSer_PageMargins.Top); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(dTop); } //Right var dRight = oMargins.asc_getRight(); if(null != dRight) { this.memory.WriteByte(c_oSer_PageMargins.Right); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(dRight); } //Bottom var dBottom = oMargins.asc_getBottom(); if(null != dBottom) { this.memory.WriteByte(c_oSer_PageMargins.Bottom); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(dBottom); } this.memory.WriteByte(c_oSer_PageMargins.Header); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(12.7);//0.5inch this.memory.WriteByte(c_oSer_PageMargins.Footer); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(12.7);//0.5inch }; this.WritePageSetup = function(oPageSetup) { //Orientation var byteOrientation = oPageSetup.asc_getOrientation(); if(null != byteOrientation) { var byteFormatOrientation = null; switch(byteOrientation) { case c_oAscPageOrientation.PagePortrait: byteFormatOrientation = EPageOrientation.pageorientPortrait;break; case c_oAscPageOrientation.PageLandscape: byteFormatOrientation = EPageOrientation.pageorientLandscape;break; } if(null != byteFormatOrientation) { this.memory.WriteByte(c_oSer_PageSetup.Orientation); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteByte(byteFormatOrientation); } } //PageSize var dWidth = oPageSetup.asc_getWidth(); var dHeight = oPageSetup.asc_getHeight(); if(null != dWidth && null != dHeight) { var item = DocumentPageSize.getSizeByWH(dWidth, dHeight); this.memory.WriteByte(c_oSer_PageSetup.PaperSize); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteByte(item.id); } }; this.WritePrintOptions = function(oPrintOptions) { //GridLines var bGridLines = oPrintOptions.asc_getGridLines(); if(null != bGridLines) { this.memory.WriteByte(c_oSer_PrintOptions.GridLines); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(bGridLines); } //Headings var bHeadings = oPrintOptions.asc_getHeadings(); if(null != bHeadings) { this.memory.WriteByte(c_oSer_PrintOptions.Headings); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(bHeadings); } }; this.WriteHyperlinks = function() { var oThis = this; for(var i in this.oHyperlinks) { var hyp = this.oHyperlinks[i]; this.bs.WriteItem(c_oSerWorksheetsTypes.Hyperlink, function(){oThis.WriteHyperlink(hyp);}); } }; this.WriteHyperlink = function(oHyperlink) { if(null != oHyperlink.Ref) { this.memory.WriteByte(c_oSerHyperlinkTypes.Ref); this.memory.WriteString2(oHyperlink.Ref.getName()); } if(null != oHyperlink.Hyperlink) { this.memory.WriteByte(c_oSerHyperlinkTypes.Hyperlink); this.memory.WriteString2(oHyperlink.Hyperlink); } if(null != oHyperlink.Location) { this.memory.WriteByte(c_oSerHyperlinkTypes.Location); this.memory.WriteString2(oHyperlink.Location); } if(null != oHyperlink.Tooltip) { this.memory.WriteByte(c_oSerHyperlinkTypes.Tooltip); this.memory.WriteString2(oHyperlink.Tooltip); } }; this.WriteMergeCells = function() { var oThis = this; for(var i in this.oMerged) { this.memory.WriteByte(c_oSerWorksheetsTypes.MergeCell); this.memory.WriteString2(i); } }; this.WriteDrawings = function(aDrawings) { var oThis = this; for(var i = 0, length = aDrawings.length; i < length; ++i) { var oDrawing = aDrawings[i]; this.bs.WriteItem(c_oSerWorksheetsTypes.Drawing, function(){oThis.WriteDrawing(oDrawing);}); } }; this.WriteDrawing = function(oDrawing) { var oThis = this; if(null != oDrawing.Type) this.bs.WriteItem(c_oSer_DrawingType.Type, function(){oThis.memory.WriteByte(ECellAnchorType.cellanchorOneCell);}); if(null != oDrawing.from) this.bs.WriteItem(c_oSer_DrawingType.From, function(){oThis.WriteFromTo(oDrawing.from);}); if(null != oDrawing.to) this.bs.WriteItem(c_oSer_DrawingType.To, function(){oThis.WriteFromTo(oDrawing.to);}); // if(null != oDrawing.Pos) // this.bs.WriteItem(c_oSer_DrawingType.Pos, function(){oThis.WritePos(oDrawing.Pos);}); if(oDrawing.isChart()) { var oBinaryChartWriter = new BinaryChartWriter(this.memory); this.bs.WriteItem(c_oSer_DrawingType.GraphicFrame, function(){oBinaryChartWriter.Write(oDrawing.chart);}); } else { if ( (null != oDrawing.imageUrl) && ("" != oDrawing.imageUrl)) { if (window['scriptBridge']) { this.bs.WriteItem(c_oSer_DrawingType.Pic, function(){oThis.WritePic(oDrawing.imageUrl.replace(/^.*(\\|\/|\:)/, ''));}); } else { this.bs.WriteItem(c_oSer_DrawingType.Pic, function(){oThis.WritePic(oDrawing.imageUrl);}); } } } }; this.WriteFromTo = function(oFromTo) { if(null != oFromTo.col) { this.memory.WriteByte(c_oSer_DrawingFromToType.Col); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(oFromTo.col); } if(null != oFromTo.colOff) { this.memory.WriteByte(c_oSer_DrawingFromToType.ColOff); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(oFromTo.colOff); } if(null != oFromTo.row) { this.memory.WriteByte(c_oSer_DrawingFromToType.Row); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(oFromTo.row); } if(null != oFromTo.rowOff) { this.memory.WriteByte(c_oSer_DrawingFromToType.RowOff); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(oFromTo.rowOff); } }; this.WritePos = function(oPos) { if(null != oPos.X) { this.memory.WriteByte(c_oSer_DrawingPosType.X); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(oPos.X); } if(null != oPos.Y) { this.memory.WriteByte(c_oSer_DrawingPosType.Y); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(oPos.Y); } }; this.WritePic = function(oPic) { var oThis = this; if(null != oPic && "" != oPic) { var sSrc = oPic; var sLocalUrl = this.wb.sUrlPath + "media/"; if(0 == sSrc.indexOf(sLocalUrl)) sSrc = sSrc.substring(sLocalUrl.length); var nIndex = this.oDrawings.items[sSrc]; if(null == nIndex) { nIndex = this.oDrawings.length; this.oDrawings.items[sSrc] = nIndex; this.oDrawings.length++; } this.bs.WriteItem(c_oSer_DrawingType.PicSrc, function(){oThis.memory.WriteLong(nIndex);}); } }; this.WriteSheetData = function(ws) { var oThis = this; //сортируем Row по индексам var aIndexes = new Array(); for(var i in ws.aGCells) aIndexes.push(i - 0); aIndexes.sort(fSortAscending); for(var i = 0, length = aIndexes.length; i < length; ++i) { var row = ws.aGCells[aIndexes[i]]; if(null != row) { this.AddToMergedAndHyperlink(row); if(false == row.isEmptyToSave()) this.bs.WriteItem(c_oSerWorksheetsTypes.Row, function(){oThis.WriteRow(row);}); } } }; this.WriteRow = function(oRow) { var oThis = this; if(null != oRow.r) { this.memory.WriteByte(c_oSerRowTypes.Row); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(oRow.r); } if(null != oRow.xfs) { var nXfsId = this.prepareXfs(oRow.xfs); this.memory.WriteByte(c_oSerRowTypes.Style); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(nXfsId); } if(null != oRow.h) { this.memory.WriteByte(c_oSerRowTypes.Height); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(oRow.h); } if(null != oRow.CustomHeight) { this.memory.WriteByte(c_oSerRowTypes.CustomHeight); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(oRow.CustomHeight); } if(null != oRow.hd) { this.memory.WriteByte(c_oSerRowTypes.Hidden); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(oRow.hd); } this.memory.WriteByte(c_oSerRowTypes.Cells); this.memory.WriteByte(c_oSerPropLenType.Variable); this.bs.WriteItemWithLength(function(){oThis.WriteCells(oRow.c);}); }; this.WriteCells = function(aCells) { var oThis = this; var aIndexes = new Array(); for(var i in aCells) aIndexes.push(i - 0); aIndexes.sort(fSortAscending); for(var i = 0, length = aIndexes.length; i < length; ++i) { var cell = aCells[aIndexes[i]]; //готовим ячейку к записи var nXfsId = this.prepareXfs(cell.xfs); this.AddToMergedAndHyperlink(cell); if(0 != nXfsId || false == cell.isEmptyText() || null != cell.merged || cell.hyperlinks.length > 0) this.bs.WriteItem(c_oSerRowTypes.Cell, function(){oThis.WriteCell(cell, nXfsId);}); } }; this.prepareXfsStyles = function () { var styles = this.wb.CellStyles.CustomStyles; var xfs = null; for(var i = 0, length = styles.length; i < length; ++i) { xfs = styles[i].xfs; if (xfs) { var sStyle = this.prepareXfsStyle(xfs); var oXfs = {borderid: sStyle.borderid, fontid: sStyle.fontid, fillid: sStyle.fillid, numid: sStyle.numid, align: null, QuotePrefix: null, XfId: xfs.XfId}; if("0" != sStyle.align) oXfs.align = xfs.align; if(null != xfs.QuotePrefix) oXfs.QuotePrefix = xfs.QuotePrefix; this.oXfsStylesMap.push(oXfs); } } }; this.prepareXfsStyle = function(xfs) { var sStyle = {val: "", borderid: 0, fontid: 0, fillid: 0, numid: 0, align: "0"}; if(null != xfs) { if(null != xfs.font) { var sHash = this._getStringFromObjWithProperty(xfs.font); var elem = this.oFontMap[sHash]; if(null == elem) { sStyle.fontid = this.nFontMapIndex++; this.oFontMap[sHash] = {index: sStyle.fontid, val: xfs.font}; } else sStyle.fontid = elem.index; } sStyle.val += sStyle.fontid.toString(); if(null != xfs.fill) { var sHash = this._getStringFromObjWithProperty(xfs.fill); var elem = this.oFillMap[sHash]; if(null == elem) { sStyle.fillid = this.nFillMapIndex++; this.oFillMap[sHash] = {index: sStyle.fillid, val: xfs.fill}; } else sStyle.fillid = elem.index; } sStyle.val += "|" + sStyle.fillid.toString(); if(null != xfs.border) { var sHash = this._getStringFromObjWithProperty(xfs.border); var elem = this.oBorderMap[sHash]; if(null == elem) { sStyle.borderid = this.nBorderMapIndex++; this.oBorderMap[sHash] = {index: sStyle.borderid, val: xfs.border}; } else sStyle.borderid = elem.index; } sStyle.val += "|" + sStyle.borderid.toString(); if(null != xfs.num) { //стандартные форматы не записываем в map, на них можно ссылаться по id var nStandartId = aStandartNumFormatsId[xfs.num.f]; if(null == nStandartId) { var sHash = this._getStringFromObjWithProperty(xfs.num); var elem = this.oNumMap[sHash]; if(null == elem) { sStyle.numid = this.nNumMapIndex++; this.oNumMap[sHash] = {index: sStyle.numid, val: xfs.num}; } else sStyle.numid = elem.index; } else sStyle.numid = nStandartId; } sStyle.val += "|" + sStyle.numid.toString(); if(null != xfs.align && false == xfs.align.isEqual(g_oDefaultAlignAbs)) sStyle.align = this._getStringFromObjWithProperty(xfs.align); sStyle.val += "|" + sStyle.align; } return sStyle; }; this.prepareXfs = function(xfs) { var nXfsId = 0; if(null != xfs) { var sStyle = this.prepareXfsStyle(xfs); var oXfsMapObj = this.oXfsMap[sStyle.val]; if(null == oXfsMapObj) { nXfsId = this.nXfsMapIndex; var oXfs = {borderid: sStyle.borderid, fontid: sStyle.fontid, fillid: sStyle.fillid, numid: sStyle.numid, align: null, QuotePrefix: null, XfId: xfs.XfId}; if("0" != sStyle.align) oXfs.align = xfs.align; if(null != xfs.QuotePrefix) oXfs.QuotePrefix = xfs.QuotePrefix; this.oXfsMap[sStyle.val] = {index: this.nXfsMapIndex++, val: oXfs}; } else nXfsId = oXfsMapObj.index; } return nXfsId; }; this.AddToMergedAndHyperlink = function(container) { if(null != container.merged) this.oMerged[container.merged.getName()] = 1; if(null != container.hyperlinks) { for(var i = 0, length = container.hyperlinks.length; i < length; ++i) { var hyperlink = container.hyperlinks[i]; this.oHyperlinks[hyperlink.Ref.getName()] = hyperlink; } } } this.WriteCell = function(cell, nXfsId) { var oThis = this; if(null != cell.oId) { this.memory.WriteByte(c_oSerCellTypes.Ref); this.memory.WriteString2(cell.oId.getID()); } if(null != nXfsId) { this.bs.WriteItem(c_oSerCellTypes.Style, function(){oThis.memory.WriteLong(nXfsId);}); } var nCellType = cell.getType(); if(null != nCellType) { var nType = ECellTypeType.celltypeNumber; switch(nCellType) { case CellValueType.Bool: nType = ECellTypeType.celltypeBool; break; case CellValueType.Error: nType = ECellTypeType.celltypeError; break; case CellValueType.Number: nType = ECellTypeType.celltypeNumber; break; case CellValueType.String: nType = ECellTypeType.celltypeSharedString; break; } if(ECellTypeType.celltypeNumber != nType) this.bs.WriteItem(c_oSerCellTypes.Type, function(){oThis.memory.WriteByte(nType);}); } if(null != cell.sFormula) this.bs.WriteItem(c_oSerCellTypes.Formula, function(){oThis.WriteFormula(cell.sFormula, cell.sFormulaCA);}); if(null != cell.oValue && false == cell.oValue.isEmpty()) { var dValue = 0; if(CellValueType.Error == nCellType || CellValueType.String == nCellType) { var sText = ""; var aText = null; if(null != cell.oValue.text) sText = cell.oValue.text; else if(null != cell.oValue.multiText) { aText = cell.oValue.multiText; for(var i = 0, length = cell.oValue.multiText.length; i < length; ++i) sText += cell.oValue.multiText[i].text; } var item = this.oSharedStrings.strings[sText]; var bAddItem = false; if(null == item) { item = {t: null, a: []}; bAddItem = true; } if(null == aText) { if(null == item.t) { dValue = this.oSharedStrings.index++; item.t = {id: dValue, val: sText}; } else dValue = item.t.id; } else { var bFound = false; for(var i = 0, length = item.a.length; i < length; ++i) { var oCurItem = item.a[i]; if(oCurItem.val.length == aText.length) { var bEqual = true; for(var j = 0, length2 = aText.length; j < length2; ++j) { if(false == aText[j].isEqual(oCurItem.val[j])) { bEqual = false; break; } } if(bEqual) { bFound = true; dValue = oCurItem.id; break; } } } if(false == bFound) { dValue = this.oSharedStrings.index++; item.a.push({id: dValue, val: aText}); } } if(bAddItem) this.oSharedStrings.strings[sText] = item; } else { if(null != cell.oValue.number) dValue = cell.oValue.number; } this.bs.WriteItem(c_oSerCellTypes.Value, function(){oThis.memory.WriteDouble2(dValue);}); } }; this.WriteFormula = function(sFormula, sFormulaCA) { // if(null != oFormula.aca) // { // this.memory.WriteByte(c_oSerFormulaTypes.Aca); // this.memory.WriteByte(c_oSerPropLenType.Byte); // this.memory.WriteBool(oFormula.aca); // } // if(null != oFormula.bx) // { // this.memory.WriteByte(c_oSerFormulaTypes.Bx); // this.memory.WriteByte(c_oSerPropLenType.Byte); // this.memory.WriteBool(oFormula.bx); // } if(null != sFormulaCA) { this.memory.WriteByte(c_oSerFormulaTypes.Ca); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(sFormulaCA); } // if(null != oFormula.del1) // { // this.memory.WriteByte(c_oSerFormulaTypes.Del1); // this.memory.WriteByte(c_oSerPropLenType.Byte); // this.memory.WriteBool(oFormula.del1); // } // if(null != oFormula.del2) // { // this.memory.WriteByte(c_oSerFormulaTypes.Del2); // this.memory.WriteByte(c_oSerPropLenType.Byte); // this.memory.WriteBool(oFormula.del2); // } // if(null != oFormula.dt2d) // { // this.memory.WriteByte(c_oSerFormulaTypes.Dt2D); // this.memory.WriteByte(c_oSerPropLenType.Byte); // this.memory.WriteBool(oFormula.dt2d); // } // if(null != oFormula.dtr) // { // this.memory.WriteByte(c_oSerFormulaTypes.Dtr); // this.memory.WriteByte(c_oSerPropLenType.Byte); // this.memory.WriteBool(oFormula.dtr); // } // if(null != oFormula.r1) // { // this.memory.WriteByte(c_oSerFormulaTypes.R1); // this.memory.WriteByte(c_oSerPropLenType.Variable); // this.memory.WriteString2(oFormula.r1); // } // if(null != oFormula.r2) // { // this.memory.WriteByte(c_oSerFormulaTypes.R2); // this.memory.WriteByte(c_oSerPropLenType.Variable); // this.memory.WriteString2(oFormula.r2); // } // if(null != oFormula.ref) // { // this.memory.WriteByte(c_oSerFormulaTypes.Ref); // this.memory.WriteByte(c_oSerPropLenType.Variable); // this.memory.WriteString2(oFormula.ref); // } // if(null != oFormula.si) // { // this.memory.WriteByte(c_oSerFormulaTypes.Si); // this.memory.WriteByte(c_oSerPropLenType.Long); // this.memory.WriteLong(oFormula.si); // } // if(null != oFormula.t) // { // this.memory.WriteByte(c_oSerFormulaTypes.T); // this.memory.WriteByte(c_oSerPropLenType.Byte); // this.memory.WriteByte(oFormula.t); // } // if(null != oFormula.v) // { // this.memory.WriteByte(c_oSerFormulaTypes.Text); // this.memory.WriteByte(c_oSerPropLenType.Variable); // this.memory.WriteString2(oFormula.v); // } this.memory.WriteByte(c_oSerFormulaTypes.Text); this.memory.WriteByte(c_oSerPropLenType.Variable); this.memory.WriteString2(sFormula); }; this.WriteComments = function(aComments, aCommentsCoords) { var oThis = this; var oNewComments = new Object(); for(var i = 0, length = aComments.length; i < length; ++i) { var elem = aComments[i]; var nRow = elem.asc_getRow(); if(null == nRow) nRow = 0; var nCol = elem.asc_getCol(); if(null == nCol) nCol = 0; var row = oNewComments[nRow]; if(null == row) { row = new Object(); oNewComments[nRow] = row; } var comment = row[nCol]; if(null == comment) { comment = {data: new Array(), coord: null}; row[nCol] = comment; } comment.data.push(elem); } for(var i = 0, length = aCommentsCoords.length; i < length; ++i) { var elem = aCommentsCoords[i]; var nRow = elem.asc_getRow(); if(null == nRow) nRow = 0; var nCol = elem.asc_getCol(); if(null == nCol) nCol = 0; var row = oNewComments[nRow]; if(null == row) { row = new Object(); oNewComments[nRow] = row; } var comment = row[nCol]; if(null == comment) { comment = {data: new Array(), coord: null}; row[nCol] = comment; } comment.coord = elem; } for(var i in oNewComments) { var row = oNewComments[i]; for(var j in row) { var comment = row[j]; if(null == comment.coord || 0 == comment.data.length) continue; var coord = comment.coord; if(null == coord.asc_getLeft() || null == coord.asc_getTop() || null == coord.asc_getRight() || null == coord.asc_getBottom() || null == coord.asc_getLeftOffset() || null == coord.asc_getTopOffset() || null == coord.asc_getRightOffset() || null == coord.asc_getBottomOffset() || null == coord.asc_getLeftMM() || null == coord.asc_getTopMM() || null == coord.asc_getWidthMM() || null == coord.asc_getHeightMM()) continue; this.bs.WriteItem(c_oSerWorksheetsTypes.Comment, function(){oThis.WriteComment(comment);}); } } }; this.WriteComment = function(comment) { var oThis = this; this.memory.WriteByte(c_oSer_Comments.Row); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(comment.coord.asc_getRow()); this.memory.WriteByte(c_oSer_Comments.Col); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(comment.coord.asc_getCol()); this.memory.WriteByte(c_oSer_Comments.CommentDatas); this.memory.WriteByte(c_oSerPropLenType.Variable); this.bs.WriteItemWithLength(function(){oThis.WriteCommentDatas(comment.data);}); this.memory.WriteByte(c_oSer_Comments.Left); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(comment.coord.asc_getLeft()); this.memory.WriteByte(c_oSer_Comments.Top); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(comment.coord.asc_getTop()); this.memory.WriteByte(c_oSer_Comments.Right); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(comment.coord.asc_getRight()); this.memory.WriteByte(c_oSer_Comments.Bottom); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(comment.coord.asc_getBottom()); this.memory.WriteByte(c_oSer_Comments.LeftOffset); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(comment.coord.asc_getLeftOffset()); this.memory.WriteByte(c_oSer_Comments.TopOffset); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(comment.coord.asc_getTopOffset()); this.memory.WriteByte(c_oSer_Comments.RightOffset); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(comment.coord.asc_getRightOffset()); this.memory.WriteByte(c_oSer_Comments.BottomOffset); this.memory.WriteByte(c_oSerPropLenType.Long); this.memory.WriteLong(comment.coord.asc_getBottomOffset()); this.memory.WriteByte(c_oSer_Comments.LeftMM); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(comment.coord.asc_getLeftMM()); this.memory.WriteByte(c_oSer_Comments.TopMM); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(comment.coord.asc_getTopMM()); this.memory.WriteByte(c_oSer_Comments.WidthMM); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(comment.coord.asc_getWidthMM()); this.memory.WriteByte(c_oSer_Comments.HeightMM); this.memory.WriteByte(c_oSerPropLenType.Double); this.memory.WriteDouble2(comment.coord.asc_getHeightMM()); this.memory.WriteByte(c_oSer_Comments.MoveWithCells); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(comment.coord.asc_getMoveWithCells()); this.memory.WriteByte(c_oSer_Comments.SizeWithCells); this.memory.WriteByte(c_oSerPropLenType.Byte); this.memory.WriteBool(comment.coord.asc_getSizeWithCells()); }; this.WriteCommentDatas = function(aDatas) { var oThis = this; for(var i = 0, length = aDatas.length; i < length; ++i) this.bs.WriteItem( c_oSer_Comments.CommentData, function(){oThis.WriteCommentData(aDatas[i]);}); } this.WriteCommentData = function(oCommentData) { var oThis = this; var sText = oCommentData.asc_getText(); if(null != sText) { this.memory.WriteByte(c_oSer_CommentData.Text); this.memory.WriteString2(sText); } var sTime = oCommentData.asc_getTime(); if(null != sTime) { var oDate = new Date(sTime - 0); this.memory.WriteByte(c_oSer_CommentData.Time); this.memory.WriteString2(this.DateToISO8601(oDate)); } var sUserId = oCommentData.asc_getUserId(); if(null != sUserId) { this.memory.WriteByte(c_oSer_CommentData.UserId); this.memory.WriteString2(sUserId); } var sUserName = oCommentData.asc_getUserName(); if(null != sUserName) { this.memory.WriteByte(c_oSer_CommentData.UserName); this.memory.WriteString2(sUserName); } var sQuoteText = null; if(null != sQuoteText) { this.memory.WriteByte(c_oSer_CommentData.QuoteText); this.memory.WriteString2(sQuoteText); } var bSolved = null; if(null != bSolved) this.bs.WriteItem( c_oSer_CommentData.Solved, function(){oThis.memory.WriteBool(bSolved);}); var bDocumentFlag = oCommentData.asc_getDocumentFlag(); if(null != bDocumentFlag) this.bs.WriteItem( c_oSer_CommentData.Document, function(){oThis.memory.WriteBool(bDocumentFlag);}); var aReplies = oCommentData.aReplies; if(null != aReplies && aReplies.length > 0) this.bs.WriteItem( c_oSer_CommentData.Replies, function(){oThis.WriteReplies(aReplies);}); } this.DateToISO8601 = function(d) { function pad(n){return n < 10 ? '0' + n : n;} return d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate()) + 'T' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds())+'Z'; }; this.WriteReplies = function(aReplies) { var oThis = this; for(var i = 0, length = aReplies.length; i < length; ++i) this.bs.WriteItem( c_oSer_CommentData.Reply, function(){oThis.WriteCommentData(aReplies[i]);}); } }; /** @constructor */ function BinaryOtherTableWriter(memory, wb, oDrawings) { this.memory = memory; this.wb = wb; this.bs = new BinaryCommonWriter(this.memory); this.oDrawings = oDrawings; this.Write = function() { var oThis = this; this.bs.WriteItemWithLength(function(){oThis.WriteOtherContent();}); }; this.WriteOtherContent = function() { var oThis = this; //borders this.bs.WriteItem(c_oSer_OtherType.Media, function(){oThis.WriteMedia();}); this.bs.WriteItem(c_oSer_OtherType.Theme, function(){window.global_pptx_content_writer.WriteTheme(oThis.memory, oThis.wb.theme);}); }; this.WriteMedia = function() { var oThis = this; var aDrawings = new Array(this.oDrawings.length); for(var src in this.oDrawings.items) { var nIndex = this.oDrawings.items[src]; aDrawings[nIndex] = src; } for(var i = 0, length = aDrawings.length; i < length; ++i) { var src = aDrawings[i]; this.bs.WriteItem(c_oSer_OtherType.MediaItem, function(){oThis.WriteMediaItem(src, i);}); } }; this.WriteMediaItem = function(src, index) { var oThis = this; if(null != src) { this.memory.WriteByte(c_oSer_OtherType.MediaSrc); this.memory.WriteString2(src); } if(null != index) this.bs.WriteItem(c_oSer_OtherType.MediaId, function(){oThis.memory.WriteLong(index);}); }; }; /** @constructor */ function BinaryFileWriter(wb) { this.Memory = new CMemory(); this.wb = wb; this.nLastFilePos = 0; this.nRealTableCount = 0; this.bs = new BinaryCommonWriter(this.Memory); this.Write = function(idWorksheet) { //если idWorksheet не null, то надо серализовать только его. this.WriteMainTable(idWorksheet); return this.WriteFileHeader(this.Memory.GetCurPosition()) + this.Memory.GetBase64Memory(); } this.WriteFileHeader = function(nDataSize) { return c_oSerFormat.Signature + ";v" + c_oSerFormat.Version + ";" + nDataSize + ";"; } this.WriteMainTable = function(idWorksheet) { var nTableCount = 128;//Специально ставим большое число, чтобы не увеличивать его при добавлении очередной таблицы. this.nRealTableCount = 0;//Специально ставим большое число, чтобы не увеличивать его при добавлении очередной таблицы. var nStart = this.Memory.GetCurPosition(); //вычисляем с какой позиции можно писать таблицы var nmtItemSize = 5;//5 byte this.nLastFilePos = nStart + nTableCount * nmtItemSize; //Write mtLen this.Memory.WriteByte(0); var oSharedStrings = {index: 0, strings: new Object()}; var oDrawings = {length: 0, items: new Object()}; //Write SharedStrings var nSharedStringsPos = this.ReserveTable(c_oSerTableTypes.SharedStrings); //Write Styles var nStylesTablePos = this.ReserveTable(c_oSerTableTypes.Styles); //Workbook this.WriteTable(c_oSerTableTypes.Workbook, new BinaryWorkbookTableWriter(this.Memory, this.wb)); //Worksheets var aXfs = new Array(); var aFonts = new Array(); var aFills = new Array(); var aBorders = new Array(); var aNums = new Array(); var aDxfs = new Array(); var oBinaryWorksheetsTableWriter = new BinaryWorksheetsTableWriter(this.Memory, this.wb, oSharedStrings, oDrawings, aDxfs, aXfs, aFonts, aFills, aBorders, aNums, idWorksheet); this.WriteTable(c_oSerTableTypes.Worksheets, oBinaryWorksheetsTableWriter); //OtherTable this.WriteTable(c_oSerTableTypes.Other, new BinaryOtherTableWriter(this.Memory, this.wb, oDrawings)); //Write SharedStrings this.WriteReserved(new BinarySharedStringsTableWriter(this.Memory, oSharedStrings), nSharedStringsPos); //Write Styles this.WriteReserved(new BinaryStylesTableWriter(this.Memory, this.wb, oBinaryWorksheetsTableWriter), nStylesTablePos); //Пишем количество таблиц this.Memory.Seek(nStart); this.Memory.WriteByte(this.nRealTableCount); //seek в конец, потому что GetBase64Memory заканчивает запись на текущей позиции. this.Memory.Seek(this.nLastFilePos); } this.WriteTable = function(type, oTableSer) { //Write mtItem //Write mtiType this.Memory.WriteByte(type); //Write mtiOffBits this.Memory.WriteLong(this.nLastFilePos); //Write table //Запоминаем позицию в MainTable var nCurPos = this.Memory.GetCurPosition(); //Seek в свободную область this.Memory.Seek(this.nLastFilePos); oTableSer.Write(); //сдвигаем позицию куда можно следующую таблицу this.nLastFilePos = this.Memory.GetCurPosition(); //Seek вобратно в MainTable this.Memory.Seek(nCurPos); this.nRealTableCount++; } this.ReserveTable = function(type) { var res = 0; //Write mtItem //Write mtiType this.Memory.WriteByte(type); res = this.Memory.GetCurPosition(); //Write mtiOffBits this.Memory.WriteLong(this.nLastFilePos); return res; } this.WriteReserved = function(oTableSer, nPos) { this.Memory.Seek(nPos); this.Memory.WriteLong(this.nLastFilePos); //Write table //Запоминаем позицию в MainTable var nCurPos = this.Memory.GetCurPosition(); //Seek в свободную область this.Memory.Seek(this.nLastFilePos); oTableSer.Write(); //сдвигаем позицию куда можно следующую таблицу this.nLastFilePos = this.Memory.GetCurPosition(); //Seek вобратно в MainTable this.Memory.Seek(nCurPos); this.nRealTableCount++; } }; /** @constructor */ function Binary_TableReader(stream, ws, Dxfs) { this.stream = stream; this.ws = ws; this.Dxfs = Dxfs; this.bcr = new Binary_CommonReader(this.stream); this.Read = function(length, aTables) { var res = c_oSerConstants.ReadOk; var oThis = this; res = this.bcr.Read1(length, function(t,l){ return oThis.ReadTables(t,l, aTables); }); return res; }; this.ReadTables = function(type, length, aTables) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_TablePart.Table == type ) { var oNewTable = new Object(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadTable(t,l, oNewTable); }); if(null != oNewTable.Ref && null != oNewTable.DisplayName) this.ws.workbook.oNameGenerator.addTableName(oNewTable.DisplayName, this.ws, oNewTable.Ref); aTables.push(oNewTable); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadTable = function(type, length, oTable) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_TablePart.Ref == type ) oTable.Ref = this.stream.GetString2LE(length); else if ( c_oSer_TablePart.HeaderRowCount == type ) oTable.HeaderRowCount = this.stream.GetULongLE(); else if ( c_oSer_TablePart.TotalsRowCount == type ) oTable.TotalsRowCount = this.stream.GetULongLE(); else if ( c_oSer_TablePart.DisplayName == type ) oTable.DisplayName = this.stream.GetString2LE(length); else if ( c_oSer_TablePart.AutoFilter == type ) { oTable.AutoFilter = new Object(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadAutoFilter(t,l, oTable.AutoFilter); }); } else if ( c_oSer_TablePart.SortState == type ) { oTable.SortState = new Object(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadSortState(t,l, oTable.SortState); }); } else if ( c_oSer_TablePart.TableColumns == type ) { oTable.TableColumns = new Array(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadTableColumns(t,l, oTable.TableColumns); }); } else if ( c_oSer_TablePart.TableStyleInfo == type ) { oTable.TableStyleInfo = new Object(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadTableStyleInfo(t,l, oTable.TableStyleInfo); }); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadAutoFilter = function(type, length, oAutoFilter) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_AutoFilter.Ref == type ) oAutoFilter.Ref = this.stream.GetString2LE(length); else if ( c_oSer_AutoFilter.FilterColumns == type ) { oAutoFilter.FilterColumns = new Array(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadFilterColumns(t,l, oAutoFilter.FilterColumns); }); } else if ( c_oSer_AutoFilter.SortState == type ) { oAutoFilter.SortState = new Object(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadSortState(t,l, oAutoFilter.SortState); }); } else res = c_oSerConstants.ReadUnknown; return res; } this.ReadFilterColumns = function(type, length, aFilterColumns) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_AutoFilter.FilterColumn == type ) { var oFilterColumn = {ColId: null, Filters: null, CustomFiltersObj: null, DynamicFilter: null, ColorFilter: null, Top10: null, ShowButton: true}; res = this.bcr.Read1(length, function(t,l){ return oThis.ReadFilterColumn(t,l, oFilterColumn); }); aFilterColumns.push(oFilterColumn); } else res = c_oSerConstants.ReadUnknown; return res; } this.ReadFilterColumn = function(type, length, oFilterColumn) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_FilterColumn.ColId == type ) oFilterColumn.ColId = this.stream.GetULongLE(); else if ( c_oSer_FilterColumn.Filters == type ) { oFilterColumn.Filters = {Values: new Array(), Dates: new Array(), Blank: null}; res = this.bcr.Read1(length, function(t,l){ return oThis.ReadFilters(t,l, oFilterColumn.Filters); }); } else if ( c_oSer_FilterColumn.CustomFilters == type ) { oFilterColumn.CustomFiltersObj = new Object(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadCustomFilters(t,l, oFilterColumn.CustomFiltersObj); }); } else if ( c_oSer_FilterColumn.DynamicFilter == type ) { oFilterColumn.DynamicFilter = new Object(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadDynamicFilter(t,l, oFilterColumn.DynamicFilter); }); }else if ( c_oSer_FilterColumn.ColorFilter == type ) { oFilterColumn.ColorFilter = new Object(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadColorFilter(t,l, oFilterColumn.ColorFilter); }); } else if ( c_oSer_FilterColumn.Top10 == type ) { oFilterColumn.Top10 = new Object(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadTop10(t,l, oFilterColumn.Top10); }); } else if ( c_oSer_FilterColumn.HiddenButton == type ) oFilterColumn.ShowButton = !this.stream.GetBool(); else if ( c_oSer_FilterColumn.ShowButton == type ) oFilterColumn.ShowButton = this.stream.GetBool(); else res = c_oSerConstants.ReadUnknown; return res; } this.ReadFilters = function(type, length, oFilters) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_FilterColumn.Filter == type ) { var oFilterVal = new Object(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadFilter(t,l, oFilterVal); }); if(null != oFilterVal.Val) oFilters.Values.push(oFilterVal.Val); } else if ( c_oSer_FilterColumn.DateGroupItem == type ) { var oDateGroupItem = new Object(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadDateGroupItem(t,l, oDateGroupItem); }); oFilters.Dates.push(oDateGroupItem); } else if ( c_oSer_FilterColumn.FiltersBlank == type ) oFilters.Blank = this.stream.GetBool(); else res = c_oSerConstants.ReadUnknown; return res; } this.ReadFilter = function(type, length, oFilter) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_Filter.Val == type ) oFilter.Val = this.stream.GetString2LE(length); else res = c_oSerConstants.ReadUnknown; return res; } this.ReadDateGroupItem = function(type, length, oDateGroupItem) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_DateGroupItem.DateTimeGrouping == type ) oDateGroupItem.DateTimeGrouping = this.stream.GetUChar(); else if ( c_oSer_DateGroupItem.Day == type ) oDateGroupItem.Day = this.stream.GetULongLE(); else if ( c_oSer_DateGroupItem.Hour == type ) oDateGroupItem.Hour = this.stream.GetULongLE(); else if ( c_oSer_DateGroupItem.Minute == type ) oDateGroupItem.Minute = this.stream.GetULongLE(); else if ( c_oSer_DateGroupItem.Month == type ) oDateGroupItem.Month = this.stream.GetULongLE(); else if ( c_oSer_DateGroupItem.Second == type ) oDateGroupItem.Second = this.stream.GetULongLE(); else if ( c_oSer_DateGroupItem.Year == type ) oDateGroupItem.Year = this.stream.GetULongLE(); else res = c_oSerConstants.ReadUnknown; return res; } this.ReadCustomFilters = function(type, length, oCustomFilters) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_CustomFilters.And == type ) oCustomFilters.And = this.stream.GetBool(); else if ( c_oSer_CustomFilters.CustomFilters == type ) { oCustomFilters.CustomFilters = new Array(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadCustomFiltersItems(t,l, oCustomFilters.CustomFilters); }); } else res = c_oSerConstants.ReadUnknown; return res; } this.ReadCustomFiltersItems = function(type, length, aCustomFilters) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_CustomFilters.CustomFilter == type ) { var oCustomFiltersItem = new Object(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadCustomFiltersItem(t,l, oCustomFiltersItem); }); aCustomFilters.push(oCustomFiltersItem); } else res = c_oSerConstants.ReadUnknown; return res; } this.ReadCustomFiltersItem = function(type, length, oCustomFiltersItem) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_CustomFilters.Operator == type ) oCustomFiltersItem.Operator = this.stream.GetUChar(); else if ( c_oSer_CustomFilters.Val == type ) oCustomFiltersItem.Val = this.stream.GetString2LE(length); else res = c_oSerConstants.ReadUnknown; return res; } this.ReadDynamicFilter = function(type, length, oDynamicFilter) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_DynamicFilter.Type == type ) oDynamicFilter.Type = this.stream.GetUChar(); else if ( c_oSer_DynamicFilter.Val == type ) oDynamicFilter.Val = this.stream.GetDoubleLE(); else if ( c_oSer_DynamicFilter.MaxVal == type ) oDynamicFilter.MaxVal = this.stream.GetDoubleLE(); else res = c_oSerConstants.ReadUnknown; return res; } this.ReadColorFilter = function(type, length, oColorFilter) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_ColorFilter.CellColor == type ) oColorFilter.CellColor = this.stream.GetBool(); else if ( c_oSer_ColorFilter.DxfId == type ) { var DxfId = this.stream.GetULongLE(); var dxf = this.Dxfs[DxfId]; oColorFilter.dxf = dxf; } else res = c_oSerConstants.ReadUnknown; return res; } this.ReadTop10 = function(type, length, oTop10) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_Top10.FilterVal == type ) oTop10.FilterVal = this.stream.GetDoubleLE(); else if ( c_oSer_Top10.Percent == type ) oTop10.Percent = this.stream.GetBool(); else if ( c_oSer_Top10.Top == type ) oTop10.Top = this.stream.GetBool(); else if ( c_oSer_Top10.Val == type ) oTop10.Val = this.stream.GetDoubleLE(); else res = c_oSerConstants.ReadUnknown; return res; } this.ReadSortConditionContent = function(type, length, oSortCondition) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_SortState.ConditionRef == type ) oSortCondition.Ref = this.stream.GetString2LE(length); else if ( c_oSer_SortState.ConditionSortBy == type ) oSortCondition.ConditionSortBy = this.stream.GetUChar(); else if ( c_oSer_SortState.ConditionDescending == type ) oSortCondition.ConditionDescending = this.stream.GetBool(); else if ( c_oSer_SortState.ConditionDxfId == type ) { var DxfId = this.stream.GetULongLE(); var dxf = this.Dxfs[DxfId]; oSortCondition.dxf = dxf; } else res = c_oSerConstants.ReadUnknown; return res; } this.ReadSortCondition = function(type, length, aSortConditions) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_SortState.SortCondition == type ) { var oSortCondition = new Object(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadSortConditionContent(t,l, oSortCondition); }); aSortConditions.push(oSortCondition); } else res = c_oSerConstants.ReadUnknown; return res; } this.ReadSortState = function(type, length, oSortState) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_SortState.Ref == type ) oSortState.Ref = this.stream.GetString2LE(length); else if ( c_oSer_SortState.CaseSensitive == type ) oSortState.CaseSensitive = this.stream.GetBool(); else if ( c_oSer_SortState.SortConditions == type ) { oSortState.SortConditions = new Array(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadSortCondition(t,l, oSortState.SortConditions); }); } else res = c_oSerConstants.ReadUnknown; return res; } this.ReadTableColumn = function(type, length, oTableColumn) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_TableColumns.Name == type ) oTableColumn.Name = this.stream.GetString2LE(length); else if ( c_oSer_TableColumns.TotalsRowLabel == type ) oTableColumn.TotalsRowLabel = this.stream.GetString2LE(length); else if ( c_oSer_TableColumns.TotalsRowFunction == type ) oTableColumn.TotalsRowFunction = this.stream.GetUChar(); else if ( c_oSer_TableColumns.TotalsRowFormula == type ) oTableColumn.TotalsRowFormula = this.stream.GetString2LE(length); else if ( c_oSer_TableColumns.DataDxfId == type ) { var DxfId = this.stream.GetULongLE(); var dxf = this.Dxfs[DxfId]; oTableColumn.dxf = dxf; } else if ( c_oSer_TableColumns.CalculatedColumnFormula == type ) oTableColumn.CalculatedColumnFormula = this.stream.GetString2LE(length); else res = c_oSerConstants.ReadUnknown; return res; } this.ReadTableColumns = function(type, length, aTableColumns) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_TableColumns.TableColumn == type ) { var oTableColumn = new Object(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadTableColumn(t,l, oTableColumn); }); aTableColumns.push(oTableColumn); } else res = c_oSerConstants.ReadUnknown; return res; } this.ReadTableStyleInfo = function(type, length, oTableStyleInfo) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_TableStyleInfo.Name == type ) oTableStyleInfo.Name = this.stream.GetString2LE(length); else if ( c_oSer_TableStyleInfo.ShowColumnStripes == type ) oTableStyleInfo.ShowColumnStripes = this.stream.GetBool(); else if ( c_oSer_TableStyleInfo.ShowRowStripes == type ) oTableStyleInfo.ShowRowStripes = this.stream.GetBool(); else if ( c_oSer_TableStyleInfo.ShowFirstColumn == type ) oTableStyleInfo.ShowFirstColumn = this.stream.GetBool(); else if ( c_oSer_TableStyleInfo.ShowLastColumn == type ) oTableStyleInfo.ShowLastColumn = this.stream.GetBool(); else res = c_oSerConstants.ReadUnknown; return res; }; }; /** @constructor */ function Binary_SharedStringTableReader(stream, wb, aSharedStrings) { this.stream = stream; this.wb = wb; this.aSharedStrings = aSharedStrings; this.bcr = new Binary_CommonReader(this.stream); this.Read = function() { var oThis = this; return this.bcr.ReadTable(function(t, l){ return oThis.ReadSharedStringContent(t,l); }); }; this.ReadSharedStringContent = function(type, length) { var res = c_oSerConstants.ReadOk; if ( c_oSerSharedStringTypes.Si === type ) { var oThis = this; var Si = new CCellValue(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadSharedString(t,l,Si); }); if(null != this.aSharedStrings) this.aSharedStrings.push(Si); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadSharedString = function(type, length, Si) { var res = c_oSerConstants.ReadOk; if ( c_oSerSharedStringTypes.Run == type ) { var oThis = this; var oRun = new CCellValueMultiText(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadRun(t,l,oRun); }); if(null == Si.multiText) Si.multiText = new Array(); Si.multiText.push(oRun); } else if ( c_oSerSharedStringTypes.Text == type ) { if(null == Si.text) Si.text = ""; Si.text += this.stream.GetString2LE(length); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadRun = function(type, length, oRun) { var oThis = this; var res = c_oSerConstants.ReadOk; if ( c_oSerSharedStringTypes.RPr == type ) { if(null == oRun.format) oRun.format = new Font(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadRPr(t,l, oRun.format); }); } else if ( c_oSerSharedStringTypes.Text == type ) { if(null == oRun.text) oRun.text = ""; oRun.text += this.stream.GetString2LE(length); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadRPr = function(type, length, rPr) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerFontTypes.Bold == type ) rPr.b = this.stream.GetBool(); else if ( c_oSerFontTypes.Color == type ) { var color = new OpenColor(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.bcr.ReadColorSpreadsheet(t,l, color); }); if(null != color.theme) rPr.c = g_oColorManager.getThemeColor(color.theme, color.tint); else if(null != color.rgb) rPr.c = new RgbColor(0x00ffffff & color.rgb); } else if ( c_oSerFontTypes.Italic == type ) rPr.i = this.stream.GetBool(); else if ( c_oSerFontTypes.RFont == type ) rPr.fn = this.stream.GetString2LE(length); else if ( c_oSerFontTypes.Strike == type ) rPr.s = this.stream.GetBool(); else if ( c_oSerFontTypes.Sz == type ) rPr.fs = this.stream.GetDoubleLE(); else if ( c_oSerFontTypes.Underline == type ) { switch(this.stream.GetUChar()) { case EUnderline.underlineDouble: rPr.u = "double";break; case EUnderline.underlineDoubleAccounting: rPr.u = "doubleAccounting";break; case EUnderline.underlineNone: rPr.u = "none";break; case EUnderline.underlineSingle: rPr.u = "single";break; case EUnderline.underlineSingleAccounting: rPr.u = "singleAccounting";break; default: rPr.u = "none";break; } } else if ( c_oSerFontTypes.VertAlign == type ) { switch(this.stream.GetUChar()) { case EVerticalAlignRun.verticalalignrunBaseline: rPr.va = "baseline";break; case EVerticalAlignRun.verticalalignrunSubscript: rPr.va = "subscript";break; case EVerticalAlignRun.verticalalignrunSuperscript: rPr.va = "superscript";break; default: rPr.va = "baseline";break; } } else res = c_oSerConstants.ReadUnknown; return res; }; }; /** @constructor */ function Binary_StylesTableReader(stream, wb, aCellXfs, Dxfs) { this.stream = stream; this.wb = wb; this.oStyleManager = wb.oStyleManager; this.aCellXfs = aCellXfs; this.Dxfs = Dxfs; this.bcr = new Binary_CommonReader(this.stream); this.bssr = new Binary_SharedStringTableReader(this.stream, wb); this.Read = function() { var oThis = this; var oStyleObject = {aBorders: [], aFills: [], aFonts: [], oNumFmts: {}, aCellStyleXfs: [], aCellXfs: [], aCellStyles: [], oCustomTableStyles: {}}; var res = this.bcr.ReadTable(function (t, l) { return oThis.ReadStylesContent(t, l, oStyleObject); }); this.InitStyleManager(oStyleObject); return res; }; this.InitStyleManager = function (oStyleObject) { for(var i = 0, length = oStyleObject.aCellXfs.length; i < length; ++i) { var xfs = oStyleObject.aCellXfs[i]; var oNewXfs = new CellXfs(); if(null != xfs.borderid) { var border = oStyleObject.aBorders[xfs.borderid]; if(null != border) oNewXfs.border = border.clone(); } if(null != xfs.fillid) { var fill = oStyleObject.aFills[xfs.fillid]; if(null != fill) oNewXfs.fill = fill.clone(); } if(null != xfs.fontid) { var font = oStyleObject.aFonts[xfs.fontid]; if(null != font) oNewXfs.font = font.clone(); } if(null != xfs.numid) { var oCurNum = oStyleObject.oNumFmts[xfs.numid]; if(null != oCurNum) oNewXfs.num = this.ParseNum(oCurNum, oStyleObject.oNumFmts); else oNewXfs.num = this.ParseNum({id: xfs.numid, f: null}, oStyleObject.oNumFmts); } if(null != xfs.QuotePrefix) oNewXfs.QuotePrefix = xfs.QuotePrefix; if(null != xfs.align) oNewXfs.align = xfs.align.clone(); if (null !== xfs.XfId) oNewXfs.XfId = xfs.XfId; if(0 == this.aCellXfs.length) this.oStyleManager.init(oNewXfs); this.minimizeXfs(oNewXfs); this.aCellXfs.push(oNewXfs); } for (var nIndex in oStyleObject.aCellStyles) { if (!oStyleObject.aCellStyles.hasOwnProperty(nIndex)) continue; var oCellStyle = oStyleObject.aCellStyles[nIndex]; var oCellStyleXfs = oStyleObject.aCellStyleXfs[oCellStyle.XfId]; oCellStyle.xfs = new CellXfs(); // Border if (null != oCellStyleXfs.borderid) { var borderCellStyle = oStyleObject.aBorders[oCellStyleXfs.borderid]; if(null != borderCellStyle) oCellStyle.xfs.border = borderCellStyle.clone(); } // Fill if (null != oCellStyleXfs.fillid) { var fillCellStyle = oStyleObject.aFills[oCellStyleXfs.fillid]; if(null != fillCellStyle) oCellStyle.xfs.fill = fillCellStyle.clone(); } // Font if(null != oCellStyleXfs.fontid) { var fontCellStyle = oStyleObject.aFonts[oCellStyleXfs.fontid]; if(null != fontCellStyle) oCellStyle.xfs.font = fontCellStyle.clone(); } // NumFmt if(null != oCellStyleXfs.numid) { var oCurNumCellStyle = oStyleObject.oNumFmts[oCellStyleXfs.numid]; if(null != oCurNumCellStyle) oCellStyle.xfs.num = this.ParseNum(oCurNumCellStyle, oStyleObject.oNumFmts); else oCellStyle.xfs.num = this.ParseNum({id: oCellStyleXfs.numid, f: null}, oStyleObject.oNumFmts); } // QuotePrefix if(null != oCellStyleXfs.QuotePrefix) oCellStyle.xfs.QuotePrefix = oCellStyleXfs.QuotePrefix; // align if(null != oCellStyleXfs.align) oCellStyle.xfs.align = oCellStyleXfs.clone(); // XfId if (null !== oCellStyleXfs.XfId) oCellStyle.xfs.XfId = oCellStyleXfs.XfId; // ApplyBorder (ToDo возможно это свойство должно быть в xfs) if (null !== oCellStyleXfs.ApplyBorder) oCellStyle.ApplyBorder = oCellStyleXfs.ApplyBorder; // ApplyFill (ToDo возможно это свойство должно быть в xfs) if (null !== oCellStyleXfs.ApplyFill) oCellStyle.ApplyFill = oCellStyleXfs.ApplyFill; // ApplyFont (ToDo возможно это свойство должно быть в xfs) if (null !== oCellStyleXfs.ApplyFont) oCellStyle.ApplyFont = oCellStyleXfs.ApplyFont; // ApplyNumberFormat (ToDo возможно это свойство должно быть в xfs) if (null !== oCellStyleXfs.ApplyNumberFormat) oCellStyle.ApplyNumberFormat = oCellStyleXfs.ApplyNumberFormat; this.wb.CellStyles.CustomStyles[oCellStyle.XfId] = oCellStyle; } for(var i in oStyleObject.oCustomTableStyles) { var item = oStyleObject.oCustomTableStyles[i]; if(null != item) { var style = item.style; var elems = item.elements; this.initTableStyle(style, elems, this.Dxfs); this.wb.TableStyles.CustomStyles[i] = style; } } }; this.initTableStyle = function(style, elems, Dxfs) { for(var j = 0, length2 = elems.length; j < length2; ++j) { var elem = elems[j]; if(null != elem.DxfId) { var Dxf = Dxfs[elem.DxfId]; if(null != Dxf) { this.minimizeXfs(Dxf); var oTableStyleElement = new CTableStyleElement(); oTableStyleElement.dxf = Dxf; if(null != elem.Size) oTableStyleElement.size = elem.Size; switch(elem.Type) { case ETableStyleType.tablestyletypeBlankRow: style.blankRow = oTableStyleElement;break; case ETableStyleType.tablestyletypeFirstColumn: style.firstColumn = oTableStyleElement;break; case ETableStyleType.tablestyletypeFirstColumnStripe: style.firstColumnStripe = oTableStyleElement;break; case ETableStyleType.tablestyletypeFirstColumnSubheading: style.firstColumnSubheading = oTableStyleElement;break; case ETableStyleType.tablestyletypeFirstHeaderCell: style.firstHeaderCell = oTableStyleElement;break; case ETableStyleType.tablestyletypeFirstRowStripe: style.firstRowStripe = oTableStyleElement;break; case ETableStyleType.tablestyletypeFirstRowSubheading: style.firstRowSubheading = oTableStyleElement;break; case ETableStyleType.tablestyletypeFirstSubtotalColumn: style.firstSubtotalColumn = oTableStyleElement;break; case ETableStyleType.tablestyletypeFirstSubtotalRow: style.firstSubtotalRow = oTableStyleElement;break; case ETableStyleType.tablestyletypeFirstTotalCell: style.firstTotalCell = oTableStyleElement;break; case ETableStyleType.tablestyletypeHeaderRow: style.headerRow = oTableStyleElement;break; case ETableStyleType.tablestyletypeLastColumn: style.lastColumn = oTableStyleElement;break; case ETableStyleType.tablestyletypeLastHeaderCell: style.lastHeaderCell = oTableStyleElement;break; case ETableStyleType.tablestyletypeLastTotalCell: style.lastTotalCell = oTableStyleElement;break; case ETableStyleType.tablestyletypePageFieldLabels: style.pageFieldLabels = oTableStyleElement;break; case ETableStyleType.tablestyletypePageFieldValues: style.pageFieldValues = oTableStyleElement;break; case ETableStyleType.tablestyletypeSecondColumnStripe: style.secondColumnStripe = oTableStyleElement;break; case ETableStyleType.tablestyletypeSecondColumnSubheading: style.secondColumnSubheading = oTableStyleElement;break; case ETableStyleType.tablestyletypeSecondRowStripe: style.secondRowStripe = oTableStyleElement;break; case ETableStyleType.tablestyletypeSecondRowSubheading: style.secondRowSubheading = oTableStyleElement;break; case ETableStyleType.tablestyletypeSecondSubtotalColumn: style.secondSubtotalColumn = oTableStyleElement;break; case ETableStyleType.tablestyletypeSecondSubtotalRow: style.secondSubtotalRow = oTableStyleElement;break; case ETableStyleType.tablestyletypeThirdColumnSubheading: style.thirdColumnSubheading = oTableStyleElement;break; case ETableStyleType.tablestyletypeThirdRowSubheading: style.thirdRowSubheading = oTableStyleElement;break; case ETableStyleType.tablestyletypeThirdSubtotalColumn: style.thirdSubtotalColumn = oTableStyleElement;break; case ETableStyleType.tablestyletypeThirdSubtotalRow: style.thirdSubtotalRow = oTableStyleElement;break; case ETableStyleType.tablestyletypeTotalRow: style.totalRow = oTableStyleElement;break; case ETableStyleType.tablestyletypeWholeTable: style.wholeTable = oTableStyleElement;break; } } } } }; this.minimizeXfs = function(xfs) { if(null != xfs.border && g_oDefaultBorder.isEqual(xfs.border)) xfs.border = null; if(null != xfs.fill && g_oDefaultFill.isEqual(xfs.fill)) xfs.fill = null; if(null != xfs.font && g_oDefaultFont.isEqual(xfs.font)) xfs.font = null; if(null != xfs.num && g_oDefaultNum.isEqual(xfs.num)) xfs.num = null; if(null != xfs.align && g_oDefaultAlign.isEqual(xfs.align)) xfs.align = null; }; this.ParseNum = function(oNum, oNumFmts) { var oRes = null; var sFormat = null; if(null != oNum && null != oNum.f) sFormat = oNum.f; else { if(5 <= oNum.id && oNum.id <= 8) { //В спецификации нет стилей для чисел 5-8, экспериментально установлено, что это денежный формат, зависящий от локали. //Устанавливаем как в Engilsh(US) sFormat = "$#,##0.00_);[Red]($#,##0.00)"; } else { var sStandartNumFormat = aStandartNumFormats[oNum.id]; if(null != sStandartNumFormat) sFormat = sStandartNumFormat; } if(null == sFormat) sFormat = "General"; if(null != oNumFmts) oNumFmts[oNum.id] = {id:oNum.id, f: sFormat}; } if(null != sFormat && "General" != sFormat) { oRes = new Num(); oRes.f = sFormat; } return oRes; }; this.ReadStylesContent = function (type, length, oStyleObject) { var res = c_oSerConstants.ReadOk; var oThis = this; if (c_oSerStylesTypes.Borders === type) { res = this.bcr.Read1(length, function (t, l) { return oThis.ReadBorders(t, l, oStyleObject.aBorders); }); } else if (c_oSerStylesTypes.Fills === type) { res = this.bcr.Read1(length, function (t, l) { return oThis.ReadFills(t, l, oStyleObject.aFills); }); } else if (c_oSerStylesTypes.Fonts === type) { res = this.bcr.Read1(length, function (t, l) { return oThis.ReadFonts(t, l, oStyleObject.aFonts); }); } else if (c_oSerStylesTypes.NumFmts === type) { res = this.bcr.Read1(length, function (t, l) { return oThis.ReadNumFmts(t, l, oStyleObject.oNumFmts); }); } else if (c_oSerStylesTypes.CellStyleXfs === type) { res = this.bcr.Read1(length, function (t, l) { return oThis.ReadCellStyleXfs(t, l, oStyleObject.aCellStyleXfs); }); } else if (c_oSerStylesTypes.CellXfs === type) { res = this.bcr.Read1(length, function (t, l) { return oThis.ReadCellXfs(t,l, oStyleObject.aCellXfs); }); } else if (c_oSerStylesTypes.CellStyles === type) { res = this.bcr.Read1(length, function (t, l) { return oThis.ReadCellStyles(t, l, oStyleObject.aCellStyles); }); } else if (c_oSerStylesTypes.Dxfs === type) { res = this.bcr.Read1(length, function (t, l) { return oThis.ReadDxfs(t, l, oThis.Dxfs); }); } else if (c_oSerStylesTypes.TableStyles === type) { res = this.bcr.Read1(length, function (t, l){ return oThis.ReadTableStyles(t, l, oThis.wb.TableStyles, oStyleObject.oCustomTableStyles); }); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadBorders = function(type, length, aBorders) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerStylesTypes.Border == type ) { var oNewBorder = new Border(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadBorder(t,l,oNewBorder); }); aBorders.push(oNewBorder); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadBorder = function(type, length, oNewBorder) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerBorderTypes.Bottom == type ) { res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadBorderProp(t,l,oNewBorder.b); }); } else if ( c_oSerBorderTypes.Diagonal == type ) { res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadBorderProp(t,l,oNewBorder.d); }); } else if ( c_oSerBorderTypes.End == type ) { res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadBorderProp(t,l,oNewBorder.r); }); } else if ( c_oSerBorderTypes.Horizontal == type ) { res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadBorderProp(t,l,oNewBorder.ih); }); } else if ( c_oSerBorderTypes.Start == type ) { res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadBorderProp(t,l,oNewBorder.l); }); } else if ( c_oSerBorderTypes.Top == type ) { res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadBorderProp(t,l,oNewBorder.t); }); } else if ( c_oSerBorderTypes.Vertical == type ) { res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadBorderProp(t,l,oNewBorder.iv); }); } else if ( c_oSerBorderTypes.DiagonalDown == type ) { oNewBorder.dd = this.stream.GetBool(); } else if ( c_oSerBorderTypes.DiagonalUp == type ) { oNewBorder.du = this.stream.GetBool(); } // else if ( c_oSerBorderTypes.Outline == type ) // { // oNewBorder.outline = this.stream.GetBool(); // } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadBorderProp = function(type, length, oBorderProp) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerBorderPropTypes.Style == type ) { switch(this.stream.GetUChar()) { case EBorderStyle.borderstyleDashDot:oBorderProp.s = "dashDot";break; case EBorderStyle.borderstyleDashDotDot:oBorderProp.s = "dashDotDot";break; case EBorderStyle.borderstyleDashed:oBorderProp.s = "dashed";break; case EBorderStyle.borderstyleDotted:oBorderProp.s = "dotted";break; case EBorderStyle.borderstyleDouble:oBorderProp.s = "double";break; case EBorderStyle.borderstyleHair:oBorderProp.s = "hair";break; case EBorderStyle.borderstyleMedium:oBorderProp.s = "medium";break; case EBorderStyle.borderstyleMediumDashDot:oBorderProp.s = "mediumDashDot";break; case EBorderStyle.borderstyleMediumDashDotDot:oBorderProp.s = "mediumDashDotDot";break; case EBorderStyle.borderstyleMediumDashed:oBorderProp.s = "mediumDashed";break; case EBorderStyle.borderstyleNone:oBorderProp.s = "none";break; case EBorderStyle.borderstyleSlantDashDot:oBorderProp.s = "slantDashDot";break; case EBorderStyle.borderstyleThick:oBorderProp.s = "thick";break; case EBorderStyle.borderstyleThin:oBorderProp.s = "thin";break; default :oBorderProp.s = "none";break; } } else if ( c_oSerBorderPropTypes.Color == type ) { var color = new OpenColor(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.bcr.ReadColorSpreadsheet(t,l, color); }); if(null != color.theme) oBorderProp.c = g_oColorManager.getThemeColor(color.theme, color.tint); else if(null != color.rgb) oBorderProp.c = new RgbColor(0x00ffffff & color.rgb); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadCellStyleXfs = function (type, length, aCellStyleXfs) { var res = c_oSerConstants.ReadOk; var oThis = this; if (c_oSerStylesTypes.Xfs === type) { var oNewXfs = {ApplyAlignment: null, ApplyBorder: null, ApplyFill: null, ApplyFont: null, ApplyNumberFormat: null, BorderId: null, FillId: null, FontId: null, NumFmtId: null, QuotePrefix: null, Aligment: null}; res = this.bcr.Read2Spreadsheet(length, function (t, l) { return oThis.ReadXfs(t, l, oNewXfs); }); aCellStyleXfs.push(oNewXfs); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadCellXfs = function(type, length, aCellXfs) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerStylesTypes.Xfs == type ) { var oNewXfs = {ApplyAlignment: null, ApplyBorder: null, ApplyFill: null, ApplyFont: null, ApplyNumberFormat: null, BorderId: null, FillId: null, FontId: null, NumFmtId: null, QuotePrefix: null, Aligment: null, XfId: null}; res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadXfs(t,l,oNewXfs); }); aCellXfs.push(oNewXfs); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadXfs = function(type, length, oXfs) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerXfsTypes.ApplyAlignment == type ) oXfs.ApplyAlignment = this.stream.GetBool(); else if ( c_oSerXfsTypes.ApplyBorder == type ) oXfs.ApplyBorder = this.stream.GetBool(); else if ( c_oSerXfsTypes.ApplyFill == type ) oXfs.ApplyFill = this.stream.GetBool(); else if ( c_oSerXfsTypes.ApplyFont == type ) oXfs.ApplyFont = this.stream.GetBool(); else if ( c_oSerXfsTypes.ApplyNumberFormat == type ) oXfs.ApplyNumberFormat = this.stream.GetBool(); else if ( c_oSerXfsTypes.BorderId == type ) oXfs.borderid = this.stream.GetULongLE(); else if ( c_oSerXfsTypes.FillId == type ) oXfs.fillid = this.stream.GetULongLE(); else if ( c_oSerXfsTypes.FontId == type ) oXfs.fontid = this.stream.GetULongLE(); else if ( c_oSerXfsTypes.NumFmtId == type ) oXfs.numid = this.stream.GetULongLE(); else if ( c_oSerXfsTypes.QuotePrefix == type ) oXfs.QuotePrefix = this.stream.GetBool(); else if (c_oSerXfsTypes.XfId === type) oXfs.XfId = this.stream.GetULongLE(); else if ( c_oSerXfsTypes.Aligment == type ) { if(null == oXfs.Aligment) oXfs.align = new Align(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadAligment(t,l,oXfs.align); }); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadAligment = function(type, length, oAligment) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerAligmentTypes.Horizontal == type ) { switch(this.stream.GetUChar()) { case EHorizontalAlignment.horizontalalignmentCenter : oAligment.hor = "center";break; case EHorizontalAlignment.horizontalalignmentContinuous : oAligment.hor = "center";break; case EHorizontalAlignment.horizontalalignmentDistributed : oAligment.hor = "justify";break; case EHorizontalAlignment.horizontalalignmentFill : oAligment.hor = "justify";break; case EHorizontalAlignment.horizontalalignmentGeneral : oAligment.hor = "none";break; case EHorizontalAlignment.horizontalalignmentJustify : oAligment.hor = "justify";break; case EHorizontalAlignment.horizontalalignmentLeft : oAligment.hor = "left";break; case EHorizontalAlignment.horizontalalignmentRight : oAligment.hor = "right";break; } } else if ( c_oSerAligmentTypes.Indent == type ) oAligment.indent = this.stream.GetULongLE(); else if ( c_oSerAligmentTypes.RelativeIndent == type ) oAligment.RelativeIndent = this.stream.GetULongLE(); else if ( c_oSerAligmentTypes.ShrinkToFit == type ) oAligment.shrink = this.stream.GetBool(); else if ( c_oSerAligmentTypes.TextRotation == type ) oAligment.angle = this.stream.GetULongLE(); else if ( c_oSerAligmentTypes.Vertical == type ) { switch(this.stream.GetUChar()) { case EVerticalAlignment.verticalalignmentBottom : oAligment.ver = "bottom";break; case EVerticalAlignment.verticalalignmentCenter : oAligment.ver = "center";break; case EVerticalAlignment.verticalalignmentDistributed : oAligment.ver = "distributed";break; case EVerticalAlignment.verticalalignmentJustify : oAligment.ver = "justify";break; case EVerticalAlignment.verticalalignmentTop : oAligment.ver = "top";break; } } else if ( c_oSerAligmentTypes.WrapText == type ) oAligment.wrap= this.stream.GetBool(); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadFills = function(type, length, aFills) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerStylesTypes.Fill == type ) { var oNewFill = new Fill(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadFill(t,l,oNewFill); }); aFills.push(oNewFill); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadFill = function(type, length, oFill) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerFillTypes.PatternFill == type ) { res = this.bcr.Read1(length, function(t,l){ return oThis.ReadPatternFill(t,l,oFill); }); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadPatternFill = function(type, length, oFill) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerFillTypes.PatternFillBgColor == type ) { var color = new OpenColor(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.bcr.ReadColorSpreadsheet(t,l, color); }); if(null != color.theme) oFill.bg = g_oColorManager.getThemeColor(color.theme, color.tint); else if(null != color.rgb) oFill.bg = new RgbColor(0x00ffffff & color.rgb); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadFonts = function(type, length, aFonts) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerStylesTypes.Font == type ) { var oNewFont = new Font(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.bssr.ReadRPr(t,l,oNewFont); }); aFonts.push(oNewFont); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadNumFmts = function(type, length, oNumFmts) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerStylesTypes.NumFmt == type ) { var oNewNumFmt = {f: null, id: null}; res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadNumFmt(t,l,oNewNumFmt); }); if(null != oNewNumFmt.id && null != oNewNumFmt.f) oNumFmts[oNewNumFmt.id] = oNewNumFmt; } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadNumFmt = function(type, length, oNumFmt) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerNumFmtTypes.FormatCode == type ) { oNumFmt.f = this.stream.GetString2LE(length); } else if ( c_oSerNumFmtTypes.NumFmtId == type ) { oNumFmt.id = this.stream.GetULongLE();; } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadCellStyles = function (type, length, aCellStyles) { var res = c_oSerConstants.ReadOk; var oThis = this; var oCellStyle = null; if (c_oSerStylesTypes.CellStyle === type) { oCellStyle = new CCellStyle(); res = this.bcr.Read1(length, function (t, l) { return oThis.ReadCellStyle(t, l, oCellStyle); }); aCellStyles.push(oCellStyle); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadCellStyle = function (type, length, oCellStyle) { var res = c_oSerConstants.ReadOk; if (c_oSer_CellStyle.BuiltinId === type) oCellStyle.BuiltinId = this.stream.GetULongLE(); else if (c_oSer_CellStyle.CustomBuiltin === type) oCellStyle.CustomBuiltin = this.stream.GetBool(); else if (c_oSer_CellStyle.Hidden === type) oCellStyle.Hidden = this.stream.GetBool(); else if (c_oSer_CellStyle.ILevel === type) oCellStyle.ILevel = this.stream.GetULongLE(); else if (c_oSer_CellStyle.Name === type) oCellStyle.Name = this.stream.GetString2LE(length); else if (c_oSer_CellStyle.XfId === type) oCellStyle.XfId = this.stream.GetULongLE(); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadDxfs = function(type, length, aDxfs) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerStylesTypes.Dxf == type ) { var oDxf = new CellXfs(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadDxf(t,l,oDxf); }); aDxfs.push(oDxf); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadDxf = function(type, length, oDxf) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_Dxf.Alignment == type ) { oDxf.align = new Align(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadAligment(t,l,oDxf.align); }); } else if ( c_oSer_Dxf.Border == type ) { var oNewBorder = new Border(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadBorder(t,l,oNewBorder); }); oDxf.border = oNewBorder; } else if ( c_oSer_Dxf.Fill == type ) { var oNewFill = new Fill(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadFill(t,l,oNewFill); }); oDxf.fill = oNewFill; } else if ( c_oSer_Dxf.Font == type ) { var oNewFont = new Font(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.bssr.ReadRPr(t,l,oNewFont); }); oDxf.font = oNewFont; } else if ( c_oSer_Dxf.NumFmt == type ) { var oNewNumFmt = {f: null, id: null}; res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadNumFmt(t,l,oNewNumFmt); }); if(null != oNewNumFmt.id) oDxf.num = this.ParseNum({id: oNewNumFmt.id, f: null}, null); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadTableStyles = function(type, length, oTableStyles, oCustomStyles) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_TableStyles.DefaultTableStyle == type ) oTableStyles.DefaultTableStyle = this.stream.GetString2LE(length); else if ( c_oSer_TableStyles.DefaultPivotStyle == type ) oTableStyles.DefaultPivotStyle = this.stream.GetString2LE(length); else if ( c_oSer_TableStyles.TableStyles == type ) { res = this.bcr.Read1(length, function(t,l){ return oThis.ReadTableCustomStyles(t,l, oCustomStyles); }); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadTableCustomStyles = function(type, length, oCustomStyles) { var res = c_oSerConstants.ReadOk; var oThis = this; if (c_oSer_TableStyles.TableStyle === type) { var oNewStyle = new CTableStyle(); var aElements = new Array(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadTableCustomStyle(t,l, oNewStyle, aElements); }); if(null != oNewStyle.name && aElements.length > 0) oCustomStyles[oNewStyle.name] = {style : oNewStyle, elements: aElements}; } else res = c_oSerConstants.ReadUnknown; return res; } this.ReadTableCustomStyle = function(type, length, oNewStyle, aElements) { var res = c_oSerConstants.ReadOk; var oThis = this; if (c_oSer_TableStyle.Name === type) oNewStyle.name = this.stream.GetString2LE(length); else if (c_oSer_TableStyle.Pivot === type) oNewStyle.pivot = this.stream.GetBool(); else if (c_oSer_TableStyle.Table === type) oNewStyle.table = this.stream.GetBool(); else if (c_oSer_TableStyle.Elements === type) { res = this.bcr.Read1(length, function(t,l){ return oThis.ReadTableCustomStyleElements(t,l, aElements); }); } else res = c_oSerConstants.ReadUnknown; return res; } this.ReadTableCustomStyleElements = function(type, length, aElements) { var res = c_oSerConstants.ReadOk; var oThis = this; if (c_oSer_TableStyle.Element === type) { var oNewStyleElement = {Type: null, Size: null, DxfId: null}; res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadTableCustomStyleElement(t,l, oNewStyleElement); }); if(null != oNewStyleElement.Type && null != oNewStyleElement.DxfId) aElements.push(oNewStyleElement); } else res = c_oSerConstants.ReadUnknown; return res; } this.ReadTableCustomStyleElement = function(type, length, oNewStyleElement) { var res = c_oSerConstants.ReadOk; var oThis = this; if (c_oSer_TableStyleElement.Type === type) oNewStyleElement.Type = this.stream.GetUChar(); else if (c_oSer_TableStyleElement.Size === type) oNewStyleElement.Size = this.stream.GetULongLE(); else if (c_oSer_TableStyleElement.DxfId === type) oNewStyleElement.DxfId = this.stream.GetULongLE(); else res = c_oSerConstants.ReadUnknown; return res; } }; /** @constructor */ function Binary_WorkbookTableReader(stream, oWorkbook) { this.stream = stream; this.oWorkbook = oWorkbook; this.bcr = new Binary_CommonReader(this.stream); this.Read = function() { var oThis = this; return this.bcr.ReadTable(function(t, l){ return oThis.ReadWorkbookContent(t,l); }); }; this.ReadWorkbookContent = function(type, length) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerWorkbookTypes.WorkbookPr === type ) { if(null == this.oWorkbook.WorkbookPr) this.oWorkbook.WorkbookPr = new Object(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadWorkbookPr(t,l,oThis.oWorkbook.WorkbookPr); }); } else if ( c_oSerWorkbookTypes.BookViews === type ) { res = this.bcr.Read1(length, function(t,l){ return oThis.ReadBookViews(t,l); }); } else if ( c_oSerWorkbookTypes.DefinedNames === type ) { res = this.bcr.Read1(length, function(t,l){ return oThis.ReadDefinedNames(t,l); }); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadWorkbookPr = function(type, length, WorkbookPr) { var res = c_oSerConstants.ReadOk; if ( c_oSerWorkbookPrTypes.Date1904 == type ) { WorkbookPr.Date1904 = this.stream.GetBool(); g_bDate1904 = WorkbookPr.Date1904; c_DateCorrectConst = g_bDate1904?c_Date1904Const:c_Date1900Const; } else if ( c_oSerWorkbookPrTypes.DateCompatibility == type ) WorkbookPr.DateCompatibility = this.stream.GetBool(); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadBookViews = function(type, length) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerWorkbookTypes.WorkbookView == type ) { res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadWorkbookView(t,l); }); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadWorkbookView = function(type, length, BookViews) { var res = c_oSerConstants.ReadOk; if ( c_oSerWorkbookViewTypes.ActiveTab == type ) this.oWorkbook.nActive = this.stream.GetULongLE(); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadDefinedNames = function(type, length) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerWorkbookTypes.DefinedName == type ) { var oNewDefinedName = new DefinedName(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadDefinedName(t,l,oNewDefinedName); }); if(null != oNewDefinedName.Name && null != oNewDefinedName.Ref) { if(null != oNewDefinedName.LocalSheetId) { var ws = this.oWorkbook.aWorksheets[oNewDefinedName.LocalSheetId]; if(null != ws) { ws.DefinedNames[oNewDefinedName.Name] = oNewDefinedName; this.oWorkbook.oNameGenerator.addLocalDefinedName(oNewDefinedName); } } else { this.oWorkbook.oNameGenerator.addDefinedName(oNewDefinedName); this.oWorkbook.oRealDefinedNames[oNewDefinedName.Name] = oNewDefinedName; } } } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadDefinedName = function(type, length, oDefinedName) { var res = c_oSerConstants.ReadOk; if ( c_oSerDefinedNameTypes.Name == type ) oDefinedName.Name = this.stream.GetString2LE(length); else if ( c_oSerDefinedNameTypes.Ref == type ) oDefinedName.Ref = this.stream.GetString2LE(length); else if ( c_oSerDefinedNameTypes.LocalSheetId == type ) oDefinedName.LocalSheetId = this.stream.GetULongLE(); else res = c_oSerConstants.ReadUnknown; return res; }; }; /** @constructor */ function Binary_WorksheetTableReader(stream, wb, aSharedStrings, aCellXfs, Dxfs, oMediaArray) { this.stream = stream; this.wb = wb; this.aSharedStrings = aSharedStrings; this.oMediaArray = oMediaArray; this.aCellXfs = aCellXfs; this.Dxfs = Dxfs; this.bcr = new Binary_CommonReader(this.stream); this.aMerged = new Array(); this.aHyperlinks = new Array(); this.Read = function() { var oThis = this; return this.bcr.ReadTable(function(t, l){ return oThis.ReadWorksheetsContent(t,l); }); }; this.ReadWorksheetsContent = function(type, length) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerWorksheetsTypes.Worksheet === type ) { this.aMerged = new Array(); this.aHyperlinks = new Array(); var oNewWorksheet = new Woorksheet(this.wb, wb.aWorksheets.length, false); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadWorksheet(t,l, oNewWorksheet); }); //merged for(var i = 0, length = this.aMerged.length; i < length; ++i) { var range = oNewWorksheet.getRange2(this.aMerged[i]); if(null != range) range.mergeOpen(); } //hyperlinks for(var i = 0, length = this.aHyperlinks.length; i < length; ++i) { var hyperlink = this.aHyperlinks[i]; if (null !== hyperlink.Ref) hyperlink.Ref.setHyperlink(hyperlink, true); } oNewWorksheet.init(); this.wb.aWorksheets.push(oNewWorksheet); this.wb.aWorksheetsById[oNewWorksheet.getId()] = oNewWorksheet; } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadWorksheet = function(type, length, oWorksheet) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerWorksheetsTypes.WorksheetProp == type ) { res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadWorksheetProp(t,l, oWorksheet); }); } else if ( c_oSerWorksheetsTypes.Cols == type ) { var oConditionalFormatting = null; if(null == oWorksheet.Cols) oWorksheet.aCols = new Array(); var aTempCols = new Array(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadWorksheetCols(t,l, aTempCols, oWorksheet); }); var fInitCol = function(oFrom, oTo) { if(null != oFrom.BestFit) oTo.BestFit = oFrom.BestFit; if(null != oFrom.hd) oTo.hd = oFrom.hd; if(null != oFrom.xfs) oTo.xfs = oFrom.xfs.clone(); else if(null != oFrom.xfsid) { var xfs = oThis.aCellXfs[oFrom.xfsid]; if(null != xfs) { oFrom.xfs = xfs; oTo.xfs = xfs.clone(); } } if(null != oFrom.width) oTo.width = oFrom.width; if(null != oFrom.CustomWidth) oTo.CustomWidth = oFrom.CustomWidth; if(oTo.index + 1 > oWorksheet.nColsCount) oWorksheet.nColsCount = oTo.index + 1; } //если есть стиль последней колонки, назначаем его стилем всей таблицы и убираем из колонок var oAllCol = null; if(aTempCols.length > 0) { var oLast = aTempCols[aTempCols.length - 1]; if(gc_nMaxCol == oLast.Max) { oAllCol = oLast; oWorksheet.oAllCol = new Col(oWorksheet, 0); fInitCol(oAllCol, oWorksheet.oAllCol); } } for(var i = 0, length = aTempCols.length; i < length; ++i) { var elem = aTempCols[i]; if(null != oAllCol && elem.BestFit == oAllCol.BestFit && elem.hd == oAllCol.hd && elem.xfs == oAllCol.xfs && elem.width == oAllCol.width && elem.CustomWidth == oAllCol.CustomWidth) continue; if(null == elem.width) { elem.width = 0; elem.hd = true; } for(var j = elem.Min; j <= elem.Max; j++){ var oNewCol = new Col(oWorksheet, j - 1); fInitCol(elem, oNewCol); oWorksheet.aCols[oNewCol.index] = oNewCol; } } } else if ( c_oSerWorksheetsTypes.SheetFormatPr == type ) { res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadSheetFormatPr(t,l, oWorksheet); }); } else if ( c_oSerWorksheetsTypes.PageMargins == type ) { var oPageMargins = new Asc.asc_CPageMargins(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadPageMargins(t,l, oPageMargins); }); if(null == oWorksheet.PagePrintOptions) oWorksheet.PagePrintOptions = new Asc.asc_CPageOptions(); oWorksheet.PagePrintOptions.asc_setPageMargins(oPageMargins); } else if ( c_oSerWorksheetsTypes.PageSetup == type ) { var oPageSetup = new Asc.asc_CPageSetup(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadPageSetup(t,l, oPageSetup); }); if(null == oWorksheet.PagePrintOptions) oWorksheet.PagePrintOptions = new Asc.asc_CPageOptions(); oWorksheet.PagePrintOptions.asc_setPageSetup(oPageSetup); } else if ( c_oSerWorksheetsTypes.PrintOptions == type ) { if(null == oWorksheet.PagePrintOptions) oWorksheet.PagePrintOptions = new Asc.asc_CPageOptions(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadPrintOptions(t,l, oWorksheet.PagePrintOptions); }); } else if ( c_oSerWorksheetsTypes.Hyperlinks == type ) { res = this.bcr.Read1(length, function(t,l){ return oThis.ReadHyperlinks(t,l, oWorksheet); }); } else if ( c_oSerWorksheetsTypes.MergeCells == type ) { res = this.bcr.Read1(length, function(t,l){ return oThis.ReadMergeCells(t,l, oWorksheet); }); } else if ( c_oSerWorksheetsTypes.SheetData == type ) { res = this.bcr.Read1(length, function(t,l){ return oThis.ReadSheetData(t,l, oWorksheet); }); } else if ( c_oSerWorksheetsTypes.Drawings == type ) { res = this.bcr.Read1(length, function(t,l){ return oThis.ReadDrawings(t,l, oWorksheet.Drawings, oWorksheet.Id); }); } else if ( c_oSerWorksheetsTypes.Autofilter == type ) { var oBinary_TableReader = new Binary_TableReader(this.stream, oWorksheet, this.Dxfs); oWorksheet.AutoFilter = new Object(); res = this.bcr.Read1(length, function(t,l){ return oBinary_TableReader.ReadAutoFilter(t,l, oWorksheet.AutoFilter); }); } else if ( c_oSerWorksheetsTypes.TableParts == type ) { oWorksheet.TableParts = new Array(); var oBinary_TableReader = new Binary_TableReader(this.stream, oWorksheet, this.Dxfs); oBinary_TableReader.Read(length, oWorksheet.TableParts); } else if ( c_oSerWorksheetsTypes.Comments == type ) { res = this.bcr.Read1(length, function(t,l){ return oThis.ReadComments(t,l, oWorksheet); }); } else if (c_oSerWorksheetsTypes.ConditionalFormatting === type) { oConditionalFormatting = new Asc.CConditionalFormatting(); res = this.bcr.Read1(length, function (t, l) { return oThis.ReadConditionalFormatting(t, l, oConditionalFormatting, function (sRange) {return oWorksheet.getRange2(sRange);}); }); oWorksheet.aConditionalFormatting.push(oConditionalFormatting); } else if (c_oSerWorksheetsTypes.SheetViews === type) { res = this.bcr.Read1(length, function (t, l) { return oThis.ReadSheetViews(t, l, oWorksheet.sheetViews); }); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadWorksheetProp = function(type, length, oWorksheet) { var res = c_oSerConstants.ReadOk; if ( c_oSerWorksheetPropTypes.Name == type ) oWorksheet.sName = this.stream.GetString2LE(length); else if ( c_oSerWorksheetPropTypes.SheetId == type ) oWorksheet.nSheetId = this.stream.GetULongLE(); else if ( c_oSerWorksheetPropTypes.State == type ) { switch(this.stream.GetUChar()) { case EVisibleType.visibleHidden: oWorksheet.bHidden = true;break; case EVisibleType.visibleVeryHidden: oWorksheet.bHidden = true;break; case EVisibleType.visibleVisible: oWorksheet.bHidden = false;break; } } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadWorksheetCols = function(type, length, aTempCols, oWorksheet) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerWorksheetsTypes.Col == type ) { var oTempCol = {BestFit: null, hd: null, Max: null, Min: null, xfs: null, xfsid: null, width: null, CustomWidth: null}; res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadWorksheetCol(t,l, oTempCol); }); aTempCols.push(oTempCol); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadWorksheetCol = function(type, length, oCol) { var res = c_oSerConstants.ReadOk; if ( c_oSerWorksheetColTypes.BestFit == type ) oCol.BestFit = this.stream.GetBool(); else if ( c_oSerWorksheetColTypes.Hidden == type ) oCol.hd = this.stream.GetBool(); else if ( c_oSerWorksheetColTypes.Max == type ) oCol.Max = this.stream.GetULongLE(); else if ( c_oSerWorksheetColTypes.Min == type ) oCol.Min = this.stream.GetULongLE(); else if ( c_oSerWorksheetColTypes.Style == type ) oCol.xfsid = this.stream.GetULongLE(); else if ( c_oSerWorksheetColTypes.Width == type ) { oCol.width = this.stream.GetDoubleLE(); if(g_nCurFileVersion < 2) oCol.CustomWidth = 1; } else if ( c_oSerWorksheetColTypes.CustomWidth == type ) oCol.CustomWidth = this.stream.GetBool(); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadSheetFormatPr = function(type, length, oWorksheet) { var res = c_oSerConstants.ReadOk; if ( c_oSerSheetFormatPrTypes.DefaultColWidth == type ) oWorksheet.dDefaultColWidth = this.stream.GetDoubleLE(); else if ( c_oSerSheetFormatPrTypes.DefaultRowHeight == type ) oWorksheet.dDefaultheight = this.stream.GetDoubleLE(); else if (c_oSerSheetFormatPrTypes.BaseColWidth === type) oWorksheet.nBaseColWidth = this.stream.GetULongLE(); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadPageMargins = function(type, length, oPageMargins) { var res = c_oSerConstants.ReadOk; if ( c_oSer_PageMargins.Left == type ) oPageMargins.asc_setLeft(this.stream.GetDoubleLE()); else if ( c_oSer_PageMargins.Top == type ) oPageMargins.asc_setTop(this.stream.GetDoubleLE()); else if ( c_oSer_PageMargins.Right == type ) oPageMargins.asc_setRight(this.stream.GetDoubleLE()); else if ( c_oSer_PageMargins.Bottom == type ) oPageMargins.asc_setBottom(this.stream.GetDoubleLE()); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadPageSetup = function(type, length, oPageSetup) { var res = c_oSerConstants.ReadOk; if ( c_oSer_PageSetup.Orientation == type ) { var byteFormatOrientation = this.stream.GetUChar(); var byteOrientation = null; switch(byteFormatOrientation) { case EPageOrientation.pageorientPortrait: byteOrientation = c_oAscPageOrientation.PagePortrait;break; case EPageOrientation.pageorientLandscape: byteOrientation = c_oAscPageOrientation.PageLandscape;break; } if(null != byteOrientation) oPageSetup.asc_setOrientation(byteOrientation); } else if ( c_oSer_PageSetup.PaperSize == type ) { var bytePaperSize = this.stream.GetUChar(); var item = DocumentPageSize.getSizeById(bytePaperSize); oPageSetup.asc_setWidth(item.w_mm); oPageSetup.asc_setHeight(item.h_mm); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadPrintOptions = function(type, length, oPrintOptions) { var res = c_oSerConstants.ReadOk; if ( c_oSer_PrintOptions.GridLines == type ) oPrintOptions.asc_setGridLines(this.stream.GetBool()); else if ( c_oSer_PrintOptions.Headings == type ) oPrintOptions.asc_setHeadings(this.stream.GetBool()); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadHyperlinks = function(type, length, ws) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerWorksheetsTypes.Hyperlink == type ) { var oNewHyperlink = new Hyperlink(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadHyperlink(t,l, ws, oNewHyperlink); }); this.aHyperlinks.push(oNewHyperlink); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadHyperlink = function(type, length, ws, oHyperlink) { var res = c_oSerConstants.ReadOk; if ( c_oSerHyperlinkTypes.Ref == type ) oHyperlink.Ref = ws.getRange2(this.stream.GetString2LE(length)); else if ( c_oSerHyperlinkTypes.Hyperlink == type ) oHyperlink.Hyperlink = this.stream.GetString2LE(length); else if ( c_oSerHyperlinkTypes.Location == type ) oHyperlink.Location = this.stream.GetString2LE(length); else if ( c_oSerHyperlinkTypes.Tooltip == type ) oHyperlink.Tooltip = this.stream.GetString2LE(length); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadMergeCells = function(type, length, ws) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerWorksheetsTypes.MergeCell == type ) { this.aMerged.push(this.stream.GetString2LE(length)); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadSheetData = function(type, length, ws) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerWorksheetsTypes.Row == type ) { var oNewRow = new Row(ws); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadRow(t,l, oNewRow, ws); }); if(null != oNewRow.r) ws.aGCells[oNewRow.r - 1] = oNewRow; } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadRow = function(type, length, oRow, ws) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerRowTypes.Row == type ) { oRow.r = this.stream.GetULongLE(); oRow.index = oRow.r - 1; if(oRow.r > ws.nRowsCount) ws.nRowsCount = oRow.r; } else if ( c_oSerRowTypes.Style == type ) { var xfs = this.aCellXfs[this.stream.GetULongLE()]; if(null != xfs) oRow.xfs = xfs.clone(); } else if ( c_oSerRowTypes.Height == type ) { oRow.h = this.stream.GetDoubleLE(); if(g_nCurFileVersion < 2) oRow.CustomHeight = true; } else if ( c_oSerRowTypes.CustomHeight == type ) oRow.CustomHeight = this.stream.GetBool(); else if ( c_oSerRowTypes.Hidden == type ) oRow.hd = this.stream.GetBool(); else if ( c_oSerRowTypes.Cells == type ) { if(null == oRow.Cells) oRow.c = new Object(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadCells(t,l, ws, oRow.c); }); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadCells = function(type, length, ws, aCells) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerRowTypes.Cell == type ) { var oNewCell = new Cell(ws); var oCellVal = {val: null}; res = this.bcr.Read1(length, function(t,l){ return oThis.ReadCell(t,l, ws, oNewCell, oCellVal); }); if(null != oNewCell.oId) { var nCellCol = 0; //вычисляем nColsCount if(null != oNewCell) { var nCols = oNewCell.oId.getCol(); nCellCol = nCols - 1; if(nCols > ws.nColsCount) ws.nColsCount = nCols; } if(null != oCellVal.val) { var bText = false; if(CellValueType.String == oNewCell.oValue.type || CellValueType.Error == oNewCell.oValue.type) { var ss = this.aSharedStrings[oCellVal.val]; if(null != ss) { bText = true; var nType = oNewCell.oValue.type; oNewCell.oValue = ss.clone(oNewCell); oNewCell.oValue.type = nType; } } //todo убрать to string if(false == bText) oNewCell.oValue.number = oCellVal.val; } aCells[nCellCol] = oNewCell; } } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadCell = function(type, length, ws, oCell, oCellVal) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerCellTypes.Ref == type ) oCell.oId = new CellAddress(this.stream.GetString2LE(length)); else if( c_oSerCellTypes.Style == type ) { var nStyleIndex = this.stream.GetULongLE(); if(0 != nStyleIndex) { var xfs = this.aCellXfs[nStyleIndex]; if(null != xfs) oCell.xfs = xfs.clone(); } } else if( c_oSerCellTypes.Type == type ) { switch(this.stream.GetUChar()) { case ECellTypeType.celltypeBool: oCell.oValue.type = CellValueType.Bool;break; case ECellTypeType.celltypeError: oCell.oValue.type = CellValueType.Error;break; case ECellTypeType.celltypeNumber: oCell.oValue.type = CellValueType.Number;break; case ECellTypeType.celltypeSharedString: oCell.oValue.type = CellValueType.String;break; }; } else if( c_oSerCellTypes.Formula == type ) { if(null == oCell.oFormulaExt) oCell.oFormulaExt = {aca: null, bx: null, ca: null, del1: null, del2: null, dt2d: null, dtr: null, r1: null, r2: null, si: null, t: null, v: null}; res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadFormula(t,l, oCell.oFormulaExt); }); } else if( c_oSerCellTypes.Value == type ) { oCellVal.val = this.stream.GetDoubleLE(); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadFormula = function(type, length, oFormula) { var res = c_oSerConstants.ReadOk; if ( c_oSerFormulaTypes.Aca == type ) oFormula.aca = this.stream.GetBool(); else if ( c_oSerFormulaTypes.Bx == type ) oFormula.bx = this.stream.GetBool(); else if ( c_oSerFormulaTypes.Ca == type ) oFormula.ca = this.stream.GetBool(); else if ( c_oSerFormulaTypes.Del1 == type ) oFormula.del1 = this.stream.GetBool(); else if ( c_oSerFormulaTypes.Del2 == type ) oFormula.del2 = this.stream.GetBool(); else if ( c_oSerFormulaTypes.Dt2D == type ) oFormula.dt2d = this.stream.GetBool(); else if ( c_oSerFormulaTypes.Dtr == type ) oFormula.dtr = this.stream.GetBool(); else if ( c_oSerFormulaTypes.R1 == type ) oFormula.r1 = this.stream.GetString2LE(length); else if ( c_oSerFormulaTypes.R2 == type ) oFormula.r2 = this.stream.GetString2LE(length); else if ( c_oSerFormulaTypes.Ref == type ) oFormula.ref = this.stream.GetString2LE(length); else if ( c_oSerFormulaTypes.Si == type ) oFormula.si = this.stream.GetULongLE(); else if ( c_oSerFormulaTypes.T == type ) oFormula.t = this.stream.GetUChar(); else if ( c_oSerFormulaTypes.Text == type ) oFormula.v = this.stream.GetString2LE(length); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadDrawings = function(type, length, aDrawings, wsId) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerWorksheetsTypes.Drawing == type ) { var objectRender = new DrawingObjects(); var oFlags = {from: false, to: false, pos: false, ext: false}; var oNewDrawing = objectRender.createDrawingObject(); oNewDrawing.id = "sheet" + wsId + "_" + (aDrawings.length + 1); res = this.bcr.Read1(length, function(t, l) { return oThis.ReadDrawing(t, l, oNewDrawing, oFlags); }); if(false != oFlags.from && false != oFlags.to) oNewDrawing.Type = ECellAnchorType.cellanchorTwoCell; else if(false != oFlags.from && false != oFlags.ext) oNewDrawing.Type = ECellAnchorType.cellanchorOneCell; else if(false != oFlags.pos && false != oFlags.ext) oNewDrawing.Type = ECellAnchorType.cellanchorAbsolute; aDrawings.push(oNewDrawing); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadDrawing = function(type, length, oDrawing, oFlags) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_DrawingType.Type == type ) oDrawing.Type = this.stream.GetUChar(); else if ( c_oSer_DrawingType.From == type ) { oFlags.from = true; res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadFromTo(t,l, oDrawing.from); }); } else if ( c_oSer_DrawingType.To == type ) { oFlags.to = true; res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadFromTo(t,l, oDrawing.to); }); } else if ( c_oSer_DrawingType.Pos == type ) { oFlags.pos = true; if(null == oDrawing.Pos) oDrawing.Pos = new Object(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadPos(t,l, oDrawing.Pos); }); } else if ( c_oSer_DrawingType.Ext == type ) { oFlags.ext = true; res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadExt(t,l, oDrawing.ext); }); } else if ( c_oSer_DrawingType.Pic == type ) { oDrawing.image = new Image(); res = this.bcr.Read1(length, function(t,l){ //return oThis.ReadPic(t,l, oDrawing.Pic); return oThis.ReadPic(t,l, oDrawing); }); } else if ( c_oSer_DrawingType.GraphicFrame == type ) { var oBinary_ChartReader = new Binary_ChartReader(this.stream, oDrawing.chart); res = oBinary_ChartReader.Read(length); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadFromTo = function(type, length, oFromTo) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_DrawingFromToType.Col == type ) //oFromTo.Col = this.stream.GetULongLE(); oFromTo.col = this.stream.GetULongLE(); else if ( c_oSer_DrawingFromToType.ColOff == type ) //oFromTo.ColOff = this.stream.GetDoubleLE(); oFromTo.colOff = this.stream.GetDoubleLE(); else if ( c_oSer_DrawingFromToType.Row == type ) //oFromTo.Row = this.stream.GetULongLE(); oFromTo.row = this.stream.GetULongLE(); else if ( c_oSer_DrawingFromToType.RowOff == type ) //oFromTo.RowOff = this.stream.GetDoubleLE(); oFromTo.rowOff = this.stream.GetDoubleLE(); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadPos = function(type, length, oPos) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_DrawingPosType.X == type ) oPos.X = this.stream.GetDoubleLE(); else if ( c_oSer_DrawingPosType.Y == type ) oPos.Y = this.stream.GetDoubleLE(); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadExt = function(type, length, oExt) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_DrawingExtType.Cx == type ) oExt.cx = this.stream.GetDoubleLE(); else if ( c_oSer_DrawingExtType.Cy == type ) oExt.cy = this.stream.GetDoubleLE(); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadPic = function(type, length, oDrawing) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_DrawingType.PicSrc == type ) { var nIndex = this.stream.GetULongLE(); var src = this.oMediaArray[nIndex]; if(null != src) { if (window['scriptBridge']) { oDrawing.image.src = window['scriptBridge']['workPath']() + src; oDrawing.imageUrl = window['scriptBridge']['workPath']() + src; } else { oDrawing.image.src = src; oDrawing.imageUrl = src; } } } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadComments = function(type, length, oWorksheet) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSerWorksheetsTypes.Comment == type ) { var oCommentCoords = new Asc.asc_CCommentCoords(); var aCommentData = new Array(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadComment(t,l, oCommentCoords, aCommentData); }); //todo проверка for(var i = 0, length = aCommentData.length; i < length; ++i) { var elem = aCommentData[i]; elem.asc_putRow(oCommentCoords.asc_getRow()); elem.asc_putCol(oCommentCoords.asc_getCol()); elem.wsId = oWorksheet.Id; if (elem.asc_getDocumentFlag()) elem.nId = "doc_" + (oWorksheet.aComments.length + 1); else elem.nId = "sheet" + elem.wsId + "_" + (oWorksheet.aComments.length + 1); oWorksheet.aComments.push(elem); } oWorksheet.aCommentsCoords.push(oCommentCoords); } else res = c_oSerConstants.ReadUnknown; return res; } this.ReadComment = function(type, length, oCommentCoords, aCommentData) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_Comments.Row == type ) oCommentCoords.asc_setRow(this.stream.GetULongLE()); else if ( c_oSer_Comments.Col == type ) oCommentCoords.asc_setCol(this.stream.GetULongLE()); else if ( c_oSer_Comments.CommentDatas == type ) { res = this.bcr.Read1(length, function(t,l){ return oThis.ReadCommentDatas(t,l, aCommentData); }); } else if ( c_oSer_Comments.Left == type ) oCommentCoords.asc_setLeft(this.stream.GetULongLE()); else if ( c_oSer_Comments.LeftOffset == type ) oCommentCoords.asc_setLeftOffset(this.stream.GetULongLE()); else if ( c_oSer_Comments.Top == type ) oCommentCoords.asc_setTop(this.stream.GetULongLE()); else if ( c_oSer_Comments.TopOffset == type ) oCommentCoords.asc_setTopOffset(this.stream.GetULongLE()); else if ( c_oSer_Comments.Right == type ) oCommentCoords.asc_setRight(this.stream.GetULongLE()); else if ( c_oSer_Comments.RightOffset == type ) oCommentCoords.asc_setRightOffset(this.stream.GetULongLE()); else if ( c_oSer_Comments.Bottom == type ) oCommentCoords.asc_setBottom(this.stream.GetULongLE()); else if ( c_oSer_Comments.BottomOffset == type ) oCommentCoords.asc_setBottomOffset(this.stream.GetULongLE()); else if ( c_oSer_Comments.LeftMM == type ) oCommentCoords.asc_setLeftMM(this.stream.GetDoubleLE()); else if ( c_oSer_Comments.TopMM == type ) oCommentCoords.asc_setTopMM(this.stream.GetDoubleLE()); else if ( c_oSer_Comments.WidthMM == type ) oCommentCoords.asc_setWidthMM(this.stream.GetDoubleLE()); else if ( c_oSer_Comments.HeightMM == type ) oCommentCoords.asc_setHeightMM(this.stream.GetDoubleLE()); else if ( c_oSer_Comments.MoveWithCells == type ) oCommentCoords.asc_setMoveWithCells(this.stream.GetBool()); else if ( c_oSer_Comments.SizeWithCells == type ) oCommentCoords.asc_setSizeWithCells(this.stream.GetBool()); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadCommentDatas = function(type, length, aCommentData) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_Comments.CommentData === type ) { var oCommentData = new Asc.asc_CCommentData(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadCommentData(t,l,oCommentData); }); aCommentData.push(oCommentData); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadCommentData = function(type, length, oCommentData) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_CommentData.Text == type ) oCommentData.asc_putText(this.stream.GetString2LE(length)); else if ( c_oSer_CommentData.Time == type ) { var oDate = this.Iso8601ToDate(this.stream.GetString2LE(length)); if(null != oDate) oCommentData.asc_putTime(oDate.getTime() + ""); } else if ( c_oSer_CommentData.UserId == type ) oCommentData.asc_putUserId(this.stream.GetString2LE(length)); else if ( c_oSer_CommentData.UserName == type ) oCommentData.asc_putUserName(this.stream.GetString2LE(length)); else if ( c_oSer_CommentData.QuoteText == type ) { var sQuoteText = this.stream.GetString2LE(length); } else if ( c_oSer_CommentData.Replies == type ) { res = this.bcr.Read1(length, function(t,l){ return oThis.ReadReplies(t,l, oCommentData); }); } else if ( c_oSer_CommentData.Solved == type ) { var bSolved = this.stream.GetBool(); } else if ( c_oSer_CommentData.Document == type ) oCommentData.asc_putDocumentFlag(this.stream.GetBool()); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadConditionalFormatting = function (type, length, oConditionalFormatting, functionGetRange2) { var res = c_oSerConstants.ReadOk; var oThis = this; var oConditionalFormattingRule = null; if (c_oSer_ConditionalFormatting.Pivot === type) oConditionalFormatting.Pivot = this.stream.GetBool(); else if (c_oSer_ConditionalFormatting.SqRef === type) { oConditionalFormatting.SqRef = this.stream.GetString2LE(length); oConditionalFormatting.SqRefRange = functionGetRange2(oConditionalFormatting.SqRef); } else if (c_oSer_ConditionalFormatting.ConditionalFormattingRule === type) { oConditionalFormattingRule = new Asc.CConditionalFormattingRule(); res = this.bcr.Read1(length, function (t, l) { return oThis.ReadConditionalFormattingRule(t, l, oConditionalFormattingRule); }); oConditionalFormatting.aRules.push(oConditionalFormattingRule); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadConditionalFormattingRule = function (type, length, oConditionalFormattingRule) { var res = c_oSerConstants.ReadOk; var oThis = this; var oConditionalFormattingRuleElement = null; if (c_oSer_ConditionalFormattingRule.AboveAverage === type) oConditionalFormattingRule.AboveAverage = this.stream.GetBool(); else if (c_oSer_ConditionalFormattingRule.Bottom === type) oConditionalFormattingRule.Bottom = this.stream.GetBool(); else if (c_oSer_ConditionalFormattingRule.DxfId === type) { var DxfId = this.stream.GetULongLE(); var dxf = this.Dxfs[DxfId]; oConditionalFormattingRule.dxf = dxf; } else if (c_oSer_ConditionalFormattingRule.EqualAverage === type) oConditionalFormattingRule.EqualAverage = this.stream.GetBool(); else if (c_oSer_ConditionalFormattingRule.Operator === type) oConditionalFormattingRule.Operator = this.stream.GetString2LE(length); else if (c_oSer_ConditionalFormattingRule.Percent === type) oConditionalFormattingRule.Percent = this.stream.GetBool(); else if (c_oSer_ConditionalFormattingRule.Priority === type) oConditionalFormattingRule.Priority = this.stream.GetULongLE(); else if (c_oSer_ConditionalFormattingRule.Rank === type) oConditionalFormattingRule.Rank = this.stream.GetULongLE(); else if (c_oSer_ConditionalFormattingRule.StdDev === type) oConditionalFormattingRule.StdDev = this.stream.GetULongLE(); else if (c_oSer_ConditionalFormattingRule.StopIfTrue === type) oConditionalFormattingRule.StopIfTrue = this.stream.GetBool(); else if (c_oSer_ConditionalFormattingRule.Text === type) oConditionalFormattingRule.Text = this.stream.GetString2LE(length); else if (c_oSer_ConditionalFormattingRule.TimePeriod === type) oConditionalFormattingRule.TimePeriod = this.stream.GetString2LE(length); else if (c_oSer_ConditionalFormattingRule.Type === type) oConditionalFormattingRule.Type = this.stream.GetString2LE(length); else if (c_oSer_ConditionalFormattingRule.ColorScale === type) { oConditionalFormattingRuleElement = new Asc.CColorScale(); res = this.bcr.Read1(length, function (t, l) { return oThis.ReadColorScale(t, l, oConditionalFormattingRuleElement); }); oConditionalFormattingRule.aRuleElements.push(oConditionalFormattingRuleElement); } else if (c_oSer_ConditionalFormattingRule.DataBar === type) { oConditionalFormattingRuleElement = new Asc.CDataBar(); res = this.bcr.Read1(length, function (t, l) { return oThis.ReadDataBar(t, l, oConditionalFormattingRuleElement); }); oConditionalFormattingRule.aRuleElements.push(oConditionalFormattingRuleElement); } else if (c_oSer_ConditionalFormattingRule.FormulaCF === type) { oConditionalFormattingRuleElement = new Asc.CFormulaCF(); oConditionalFormattingRuleElement.Text = this.stream.GetString2LE(length); oConditionalFormattingRule.aRuleElements.push(oConditionalFormattingRuleElement); } else if (c_oSer_ConditionalFormattingRule.IconSet === type) { oConditionalFormattingRuleElement = new Asc.CIconSet(); res = this.bcr.Read1(length, function (t, l) { return oThis.ReadIconSet(t, l, oConditionalFormattingRuleElement); }); oConditionalFormattingRule.aRuleElements.push(oConditionalFormattingRuleElement); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadColorScale = function (type, length, oColorScale) { var res = c_oSerConstants.ReadOk; var oThis = this; var oObject = null; if (c_oSer_ConditionalFormattingRuleColorScale.CFVO === type) { oObject = new Asc.CConditionalFormatValueObject(); res = this.bcr.Read1(length, function (t, l) { return oThis.ReadCFVO(t, l, oObject); }); oColorScale.aCFVOs.push(oObject); } else if (c_oSer_ConditionalFormattingRuleColorScale.Color === type) { oObject = new OpenColor(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.bcr.ReadColorSpreadsheet(t,l, oObject); }); if(null != oObject.theme) oColorScale.aColors.push(g_oColorManager.getThemeColor(oObject.theme, oObject.tint)); else if(null != oObject.rgb) oColorScale.aColors.push(new RgbColor(0x00ffffff & oObject.rgb)); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadDataBar = function (type, length, oDataBar) { var res = c_oSerConstants.ReadOk; var oThis = this; var oObject = null; if (c_oSer_ConditionalFormattingDataBar.MaxLength === type) oDataBar.MaxLength = this.stream.GetULongLE(); else if (c_oSer_ConditionalFormattingDataBar.MinLength === type) oDataBar.MinLength = this.stream.GetULongLE(); else if (c_oSer_ConditionalFormattingDataBar.ShowValue === type) oDataBar.ShowValue = this.stream.GetBool(); else if (c_oSer_ConditionalFormattingDataBar.Color === type) { oObject = new OpenColor(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.bcr.ReadColorSpreadsheet(t,l, oObject); }); if(null != oObject.theme) oDataBar.Color = g_oColorManager.getThemeColor(oObject.theme, oObject.tint); else if(null != oObject.rgb) oDataBar.Color = new RgbColor(0x00ffffff & oObject.rgb); } else if (c_oSer_ConditionalFormattingDataBar.CFVO === type) { oObject = new Asc.CConditionalFormatValueObject(); res = this.bcr.Read1(length, function (t, l) { return oThis.ReadCFVO(t, l, oObject); }); oDataBar.aCFVOs.push(oObject); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadIconSet = function (type, length, oIconSet) { var res = c_oSerConstants.ReadOk; var oThis = this; var oObject = null; if (c_oSer_ConditionalFormattingIconSet.IconSet === type) oIconSet.IconSet = this.stream.GetString2LE(length); else if (c_oSer_ConditionalFormattingIconSet.Percent === type) oIconSet.Percent = this.stream.GetBool(); else if (c_oSer_ConditionalFormattingIconSet.Reverse === type) oIconSet.Reverse = this.stream.GetBool(); else if (c_oSer_ConditionalFormattingIconSet.ShowValue === type) oIconSet.ShowValue = this.stream.GetBool(); else if (c_oSer_ConditionalFormattingIconSet.CFVO === type) { oObject = new Asc.CConditionalFormatValueObject(); res = this.bcr.Read1(length, function (t, l) { return oThis.ReadCFVO(t, l, oObject); }); oIconSet.aCFVOs.push(oObject); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadCFVO = function (type, length, oCFVO) { var res = c_oSerConstants.ReadOk; if (c_oSer_ConditionalFormattingValueObject.Gte === type) oCFVO.Gte = this.stream.GetBool(); else if (c_oSer_ConditionalFormattingValueObject.Type === type) oCFVO.Type = this.stream.GetString2LE(length); else if (c_oSer_ConditionalFormattingValueObject.Val === type) oCFVO.Val = this.stream.GetString2LE(length); else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadSheetViews = function (type, length, aSheetViews) { var res = c_oSerConstants.ReadOk; var oThis = this; var oSheetView = null; if (c_oSerWorksheetsTypes.SheetView === type) { oSheetView = new Asc.asc_CSheetViewSettings(); res = this.bcr.Read1(length, function (t, l) { return oThis.ReadSheetView(t, l, oSheetView); }); aSheetViews.push(oSheetView); } return res; }; this.ReadSheetView = function (type, length, oSheetView) { var res = c_oSerConstants.ReadOk; if (c_oSer_SheetView.ShowGridLines === type) { oSheetView.showGridLines = this.stream.GetBool(); } else if (c_oSer_SheetView.ShowRowColHeaders === type) { oSheetView.showRowColHeaders = this.stream.GetBool(); } else res = c_oSerConstants.ReadUnknown; return res; }; this.Iso8601ToDate = function(sDate) { var numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ]; var minutesOffset = 0; if ((struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(sDate))) { // avoid NaN timestamps caused by “undefined” values being passed to Date.UTC for (var i = 0, k; (k = numericKeys[i]); ++i) { struct[k] = +struct[k] || 0; } // allow undefined days and months struct[2] = (+struct[2] || 1) - 1; struct[3] = +struct[3] || 1; if (struct[8] !== 'Z' && struct[9] !== undefined) { minutesOffset = struct[10] * 60 + struct[11]; if (struct[9] === '+') { minutesOffset = 0 - minutesOffset; } } return new Date(Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7])); } return null }; this.ReadReplies = function(type, length, oCommentData) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_CommentData.Reply === type ) { var oReplyData = new Asc.asc_CCommentData(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadCommentData(t,l,oReplyData); }); oCommentData.aReplies.push(oReplyData); } else res = c_oSerConstants.ReadUnknown; return res; }; }; /** @constructor */ function Binary_CalcChainTableReader(stream, aCalcChain) { this.stream = stream; this.aCalcChain = aCalcChain; this.bcr = new Binary_CommonReader(this.stream); this.Read = function() { var oThis = this; return this.bcr.ReadTable(function(t, l){ return oThis.ReadCalcChainContent(t,l); }); }; this.ReadCalcChainContent = function(type, length) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_CalcChainType.CalcChainItem === type ) { var oNewCalcChain = new Object(); res = this.bcr.Read2Spreadsheet(length, function(t,l){ return oThis.ReadCalcChain(t,l, oNewCalcChain); }); this.aCalcChain.push(oNewCalcChain); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadCalcChain = function(type, length, oCalcChain) { var res = c_oSerConstants.ReadOk; if ( c_oSer_CalcChainType.Array == type ) oCalcChain.Array = this.stream.GetBool(); else if ( c_oSer_CalcChainType.SheetId == type ) oCalcChain.SheetId = this.stream.GetULongLE(); else if ( c_oSer_CalcChainType.DependencyLevel == type ) oCalcChain.DependencyLevel = this.stream.GetBool(); else if ( c_oSer_CalcChainType.Ref == type ) oCalcChain.Ref = this.stream.GetString2LE(length); else if ( c_oSer_CalcChainType.ChildChain == type ) oCalcChain.ChildChain = this.stream.GetBool(); else if ( c_oSer_CalcChainType.NewThread == type ) oCalcChain.NewThread = this.stream.GetBool(); else res = c_oSerConstants.ReadUnknown; return res; }; }; /** @constructor */ function Binary_OtherTableReader(stream, oMedia, sUrlPath, wb) { this.stream = stream; this.oMedia = oMedia; this.sUrlPath = sUrlPath; this.wb = wb; this.bcr = new Binary_CommonReader(this.stream); this.Read = function() { var oThis = this; var oRes = this.bcr.ReadTable(function(t, l){ return oThis.ReadOtherContent(t,l); }); g_oColorManager.setTheme(this.wb.theme); g_oDefaultFont = g_oDefaultFontAbs = new Font(); g_oDefaultFill = g_oDefaultFillAbs = new Fill(); g_oDefaultBorder = g_oDefaultBorderAbs = new Border(); g_oDefaultNum = g_oDefaultNumAbs = new Num(); g_oDefaultAlign = g_oDefaultAlignAbs = new Align(); return oRes; }; this.ReadOtherContent = function(type, length) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_OtherType.Media === type ) { res = this.bcr.Read1(length, function(t,l){ return oThis.ReadMediaContent(t,l); }); } else if ( c_oSer_OtherType.EmbeddedFonts === type ) { var _count = this.stream.GetULongLE(); var _embedded_fonts = new Array(); for (var i = 0; i < _count; i++) { var _at = this.stream.GetUChar(); if (_at != g_nodeAttributeStart) break; var _f_i = new Object(); while (true) { _at = this.stream.GetUChar(); if (_at == g_nodeAttributeEnd) break; switch (_at) { case 0: { _f_i.Name = this.stream.GetString(); break; } case 1: { _f_i.Style = this.stream.GetULongLE(); break; } case 2: { _f_i.IsCut = this.stream.GetBool(); break; } case 3: { _f_i.IndexCut = this.stream.GetULongLE(); break; } default: break; } } _embedded_fonts.push(_f_i); } var api = this.wb.oApi; if(true == api.isUseEmbeddedCutFonts) { var font_cuts = api.FontLoader.embedded_cut_manager; font_cuts.Url = this.sUrlPath + "fonts/fonts.js"; font_cuts.init_cut_fonts(_embedded_fonts); font_cuts.bIsCutFontsUse = true; } } else if ( c_oSer_OtherType.Theme === type ) { this.wb.theme = window.global_pptx_content_loader.ReadTheme(this, this.stream); } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadMediaContent = function(type, length) { var res = c_oSerConstants.ReadOk; var oThis = this; if ( c_oSer_OtherType.MediaItem === type ) { var oNewMedia = new Object(); res = this.bcr.Read1(length, function(t,l){ return oThis.ReadMediaItem(t,l, oNewMedia); }); if(null != oNewMedia.id && null != oNewMedia.src) this.oMedia[oNewMedia.id] = oNewMedia.src; } else res = c_oSerConstants.ReadUnknown; return res; }; this.ReadMediaItem = function(type, length, oNewMedia) { var res = c_oSerConstants.ReadOk; if ( c_oSer_OtherType.MediaSrc === type ) { var src = this.stream.GetString2LE(length); if(0 != src.indexOf("http:") && 0 != src.indexOf("data:") && 0 != src.indexOf("https:") && 0 != src.indexOf("ftp:") && 0 != src.indexOf("file:")) oNewMedia.src = this.sUrlPath + "media/" + src; else oNewMedia.src = src; } else if ( c_oSer_OtherType.MediaId === type ) oNewMedia.id = this.stream.GetULongLE(); else res = c_oSerConstants.ReadUnknown; return res; }; }; /** @constructor */ function BinaryFileReader(sUrlPath) { this.stream; this.sUrlPath = sUrlPath; this.getbase64DecodedData = function(szSrc, stream) { var nType = 0; var index = c_oSerFormat.Signature.length; var version = ""; var dst_len = ""; while (true) { index++; var _c = szSrc.charCodeAt(index); if (_c == ";".charCodeAt(0)) { if(0 == nType) { nType = 1; continue; } else { index++; break; } } if(0 == nType) version += String.fromCharCode(_c); else dst_len += String.fromCharCode(_c); } var dstLen = parseInt(dst_len); var pointer = g_memory.Alloc(dstLen); stream = new FT_Stream2(pointer.data, dstLen); stream.obj = pointer.obj; this.getbase64DecodedData2(szSrc, index, stream, 0); if(version.length > 1) { var nTempVersion = version.substring(1) - 0; if(nTempVersion) g_nCurFileVersion = nTempVersion; } return stream; }; this.getbase64DecodedData2 = function(szSrc, szSrcOffset, stream, streamOffset) { var srcLen = szSrc.length; var nWritten = streamOffset; var dstPx = stream.data; var index = szSrcOffset; if (window.chrome) { while (index < srcLen) { var dwCurr = 0; var i; var nBits = 0; for (i=0; i<4; i++) { if (index >= srcLen) break; var nCh = DecodeBase64Char(szSrc.charCodeAt(index++)); if (nCh == -1) { i--; continue; } dwCurr <<= 6; dwCurr |= nCh; nBits += 6; } dwCurr <<= 24-nBits; var nLen = (nBits/8) | 0; for (i=0; i<nLen; i++) { dstPx[nWritten++] = ((dwCurr & 0x00ff0000) >>> 16); dwCurr <<= 8; } } } else { var p = b64_decode; while (index < srcLen) { var dwCurr = 0; var i; var nBits = 0; for (i=0; i<4; i++) { if (index >= srcLen) break; var nCh = p[szSrc.charCodeAt(index++)]; if (nCh == undefined) { i--; continue; } dwCurr <<= 6; dwCurr |= nCh; nBits += 6; } dwCurr <<= 24-nBits; var nLen = (nBits/8) | 0; for (i=0; i<nLen; i++) { dstPx[nWritten++] = ((dwCurr & 0x00ff0000) >>> 16); dwCurr <<= 8; } } } return nWritten; } this.Read = function(data, wb) { this.stream = this.getbase64DecodedData(data); History.TurnOff(); this.ReadFile(wb); ReadDefCellStyles(wb, wb.CellStyles.DefaultStyles); ReadDefTableStyles(wb, wb.TableStyles.DefaultStyles); wb.TableStyles.concatStyles(); History.TurnOn(); }; this.ReadFile = function(wb) { return this.ReadMainTable(wb); }; this.ReadMainTable = function(wb) { var res = c_oSerConstants.ReadOk; //mtLen res = this.stream.EnterFrame(1); if(c_oSerConstants.ReadOk != res) return res; var mtLen = this.stream.GetUChar(); var aSeekTable = new Array(); var nOtherTableOffset = null; var nSharedStringTableOffset = null; var nStyleTableOffset = null; var nWorkbookTableOffset = null; for(var i = 0; i < mtLen; ++i) { //mtItem res = this.stream.EnterFrame(5); if(c_oSerConstants.ReadOk != res) return res; var mtiType = this.stream.GetUChar(); var mtiOffBits = this.stream.GetULongLE(); if(c_oSerTableTypes.Other == mtiType) nOtherTableOffset = mtiOffBits; else if(c_oSerTableTypes.SharedStrings == mtiType) nSharedStringTableOffset = mtiOffBits; else if(c_oSerTableTypes.Styles == mtiType) nStyleTableOffset = mtiOffBits; else if(c_oSerTableTypes.Workbook == mtiType) nWorkbookTableOffset = mtiOffBits; else aSeekTable.push( {type: mtiType, offset: mtiOffBits} ); } var aSharedStrings = new Array(); var aCellXfs = new Array(); var aDxfs = new Array(); var oMediaArray = new Object(); wb.aWorksheets = new Array(); if(null != nOtherTableOffset) { res = this.stream.Seek(nOtherTableOffset); if(c_oSerConstants.ReadOk == res) res = (new Binary_OtherTableReader(this.stream, oMediaArray, this.sUrlPath, wb)).Read(); } if(null != nSharedStringTableOffset) { res = this.stream.Seek(nSharedStringTableOffset); if(c_oSerConstants.ReadOk == res) res = (new Binary_SharedStringTableReader(this.stream, wb, aSharedStrings)).Read(); } if(null != nStyleTableOffset) { res = this.stream.Seek(nStyleTableOffset); if(c_oSerConstants.ReadOk == res) res = (new Binary_StylesTableReader(this.stream, wb, aCellXfs, aDxfs)).Read(); } if(c_oSerConstants.ReadOk == res) { for(var i = 0; i < aSeekTable.length; ++i) { var seek = aSeekTable[i]; var mtiType = seek.type; var mtiOffBits = seek.offset; res = this.stream.Seek(mtiOffBits); if(c_oSerConstants.ReadOk != res) break; switch(mtiType) { // case c_oSerTableTypes.SharedStrings: // res = (new Binary_SharedStringTableReader(this.stream, aSharedStrings)).Read(); // break; // case c_oSerTableTypes.Styles: // res = (new Binary_StylesTableReader(this.stream, wb.oStyleManager, aCellXfs)).Read(); // break; // case c_oSerTableTypes.Workbook: // res = (new Binary_WorkbookTableReader(this.stream, wb)).Read(); // break; case c_oSerTableTypes.Worksheets: res = (new Binary_WorksheetTableReader(this.stream, wb, aSharedStrings, aCellXfs, aDxfs, oMediaArray)).Read(); break; case c_oSerTableTypes.CalcChain: res = (new Binary_CalcChainTableReader(this.stream, wb.calcChain)).Read(); break; // case c_oSerTableTypes.Other: // res = (new Binary_OtherTableReader(this.stream, oMediaArray)).Read(); // break; } if(c_oSerConstants.ReadOk != res) break; } } if(null != nWorkbookTableOffset) { res = this.stream.Seek(nWorkbookTableOffset); if(c_oSerConstants.ReadOk == res) res = (new Binary_WorkbookTableReader(this.stream, wb)).Read(); } wb.init(); return res; }; }; function CTableStyles() { this.DefaultTableStyle = "TableStyleMedium2"; this.DefaultPivotStyle = "PivotStyleLight16"; this.CustomStyles = new Object(); this.DefaultStyles = new Object(); this.AllStyles = new Object(); } CTableStyles.prototype = { concatStyles : function() { for(var i in this.DefaultStyles) this.AllStyles[i] = this.DefaultStyles[i]; for(var i in this.CustomStyles) this.AllStyles[i] = this.CustomStyles[i]; } } function CTableStyle() { this.name = null; this.pivot = true; this.table = true; this.compiled = null; this.blankRow = null; this.firstColumn = null; this.firstColumnStripe = null; this.firstColumnSubheading = null; this.firstHeaderCell = null; this.firstRowStripe = null; this.firstRowSubheading = null; this.firstSubtotalColumn = null; this.firstSubtotalRow = null; this.firstTotalCell = null; this.headerRow = null; this.lastColumn = null; this.lastHeaderCell = null; this.lastTotalCell = null; this.pageFieldLabels = null; this.pageFieldValues = null; this.secondColumnStripe = null; this.secondColumnSubheading = null; this.secondRowStripe = null; this.secondRowSubheading = null; this.secondSubtotalColumn = null; this.secondSubtotalRow = null; this.thirdColumnSubheading = null; this.thirdRowSubheading = null; this.thirdSubtotalColumn = null; this.thirdSubtotalRow = null; this.totalRow = null; this.wholeTable = null; } CTableStyle.prototype = { getStyle: function(bbox, rowIndex, colIndex, options, headerRowCount, totalsRowCount) { //todo есть проблемы при малых размерах таблиц var res = null; if(null == this.compiled) this._compile(); var styles = this._getOption(options, headerRowCount, totalsRowCount); if(headerRowCount > 0 && rowIndex == bbox.r1) { if(colIndex == bbox.c1) res = styles.headerLeftTop; else if(colIndex == bbox.c2) res = styles.headerRightTop; else res = styles.header; } else if(totalsRowCount > 0 && rowIndex == bbox.r2) { if(colIndex == bbox.c1) res = styles.totalLeftBottom; else if(colIndex == bbox.c2) res = styles.totalRightBottom; else res = styles.total; } else if(options.ShowFirstColumn && colIndex == bbox.c1) { if(rowIndex == bbox.r1 + headerRowCount) res = styles.leftTopFC; else if(rowIndex == bbox.r2 - totalsRowCount) { if(0 == (rowIndex - headerRowCount) % 2) res = styles.leftBottomRowBand1FC; else res = styles.leftBottomRowBand2FC; } else { if(0 == (rowIndex - headerRowCount) % 2) res = styles.leftRowBand1FC; else res = styles.leftRowBand2FC; } } else if(options.ShowLastColumn && colIndex == bbox.c2) { if(rowIndex == bbox.r1 + headerRowCount) { if(0 == colIndex % 2) res = styles.rightTopColBand1LC; else res = styles.rightTopColBand2LC; } else if(rowIndex == bbox.r2 - totalsRowCount) { if(0 == (rowIndex - headerRowCount) % 2) { if(0 == colIndex % 2) res = styles.rightRowBand1ColBand1LC; else res = styles.rightRowBand1ColBand2LC; } else { if(0 == colIndex % 2) res = styles.rightRowBand2ColBand1LC; else res = styles.rightRowBand2ColBand2LC; } } else { if(0 == (rowIndex - headerRowCount) % 2) { if(0 == colIndex % 2) res = styles.rightBottomRowBand1ColBand1LC; else res = styles.rightBottomRowBand1ColBand2LC; } else { if(0 == colIndex % 2) res = styles.rightBottomRowBand2ColBand1LC; else res = styles.rightBottomRowBand2ColBand2LC; } } } else if(options.ShowRowStripes || options.ShowColumnStripes) { if(rowIndex == bbox.r1 + headerRowCount) { if(colIndex == bbox.c1) res = styles.leftTop; else if(colIndex == bbox.c2) { if(0 == colIndex % 2) res = styles.rightTopColBand1; else res = styles.rightTopColBand2; } else { if(0 == colIndex % 2) res = styles.topColBand1; else res = styles.topColBand2; } } else if(rowIndex == bbox.r2 - totalsRowCount) { if(colIndex == bbox.c1) { if(0 == (rowIndex - headerRowCount) % 2) res = styles.leftBottomRowBand1; else res = styles.leftBottomRowBand2; } else if(colIndex == bbox.c2) { if(0 == (rowIndex - headerRowCount) % 2) { if(0 == colIndex % 2) res = styles.rightBottomRowBand1ColBand1; else res = styles.rightBottomRowBand1ColBand2; } else { if(0 == colIndex % 2) res = styles.rightBottomRowBand2ColBand1; else res = styles.rightBottomRowBand2ColBand2; } } else { if(0 == (rowIndex - headerRowCount) % 2) { if(0 == colIndex % 2) res = styles.bottomRowBand1ColBand1; else res = styles.bottomRowBand1ColBand2; } else { if(0 == colIndex % 2) res = styles.bottomRowBand2ColBand1; else res = styles.bottomRowBand2ColBand2; } } } else if(colIndex == bbox.c1) { if(0 == (rowIndex - headerRowCount) % 2) res = styles.leftRowBand1; else res = styles.leftRowBand2; } else if(colIndex == bbox.c2) { if(0 == (rowIndex - headerRowCount) % 2) { if(0 == colIndex % 2) res = styles.rightRowBand1ColBand1; else res = styles.rightRowBand1ColBand2; } else { if(0 == colIndex % 2) res = styles.rightRowBand2ColBand1; else res = styles.rightRowBand2ColBand2; } } else { if(0 == (rowIndex - headerRowCount) % 2) { if(0 == colIndex % 2) res = styles.innerRowBand1ColBand1; else res = styles.innerRowBand1ColBand2; } else { if(0 == colIndex % 2) res = styles.innerRowBand2ColBand1; else res = styles.innerRowBand2ColBand2; } } } else { if(rowIndex == bbox.r1 + headerRowCount) { if(colIndex == bbox.c1) res = styles.leftTop; else if(colIndex == bbox.c2) res = styles.rightTopColBand1; else res = styles.topColBand1; } else if(rowIndex == bbox.r2 - totalsRowCount) { if(colIndex == bbox.c1) res = styles.leftBottomRowBand1; else if(colIndex == bbox.c2) res = styles.rightBottomRowBand1ColBand1; else res = styles.bottomRowBand1ColBand1; } else if(colIndex == bbox.c1) res = styles.leftRowBand1; else if(colIndex == bbox.c2) res = styles.rightRowBand1ColBand1; else res = styles.innerRowBand1ColBand1; } return res; }, _getOption: function(options, headerRowCount, totalsRowCount) { var nBitMask = 0; if(options.ShowFirstColumn) nBitMask += 1; if(options.ShowLastColumn) nBitMask += 1 << 1; if(options.ShowRowStripes) nBitMask += 1 << 2; if(options.ShowColumnStripes) nBitMask += 1 << 3; if(headerRowCount > 0) nBitMask += 1 << 4; if(totalsRowCount > 0) nBitMask += 1 << 5; var styles = this.compiled.options[nBitMask]; if(null == styles) { var configs = { header: {header: true, top: true}, headerLeftTop: {header: true, left: true, top: true}, headerRightTop: {header: true, right: true, top: true}, total: {total: true, bottom: true}, totalLeftBottom: {total: true, left: true, bottom: true}, totalRightBottom: {total: true, right: true, bottom: true}, leftTop: {ShowRowStripes: true, ShowColumnStripes: true, left: true, top: true, RowBand1: true, ColBand1: true}, leftBottomRowBand1: {ShowRowStripes: true, ShowColumnStripes: true, left: true, bottom: true, RowBand1: true, ColBand1: true}, leftBottomRowBand2: {ShowRowStripes: true, ShowColumnStripes: true, left: true, bottom: true, RowBand2: true, ColBand1: true}, leftRowBand1: {ShowRowStripes: true, ShowColumnStripes: true, left: true, RowBand1: true, ColBand1: true}, leftRowBand2: {ShowRowStripes: true, ShowColumnStripes: true, left: true, RowBand2: true, ColBand1: true}, rightTopColBand1: {ShowRowStripes: true, ShowColumnStripes: true, right: true, top: true, RowBand1: true, ColBand1: true}, rightTopColBand2: {ShowRowStripes: true, ShowColumnStripes: true, right: true, top: true, RowBand1: true, ColBand2: true}, rightRowBand1ColBand1: {ShowRowStripes: true, ShowColumnStripes: true, right: true, RowBand1: true, ColBand1: true}, rightRowBand1ColBand2: {ShowRowStripes: true, ShowColumnStripes: true, right: true, RowBand1: true, ColBand2: true}, rightRowBand2ColBand1: {ShowRowStripes: true, ShowColumnStripes: true, right: true, RowBand2: true, ColBand1: true}, rightRowBand2ColBand2: {ShowRowStripes: true, ShowColumnStripes: true, right: true, RowBand2: true, ColBand2: true}, rightBottomRowBand1ColBand1: {ShowRowStripes: true, ShowColumnStripes: true, right: true, bottom: true, RowBand1: true, ColBand1: true}, rightBottomRowBand1ColBand2: {ShowRowStripes: true, ShowColumnStripes: true, right: true, bottom: true, RowBand1: true, ColBand2: true}, rightBottomRowBand2ColBand1: {ShowRowStripes: true, ShowColumnStripes: true, right: true, bottom: true, RowBand2: true, ColBand1: true}, rightBottomRowBand2ColBand2: {ShowRowStripes: true, ShowColumnStripes: true, right: true, bottom: true, RowBand2: true, ColBand2: true}, topColBand1: {ShowRowStripes: true, ShowColumnStripes: true, top: true, RowBand1: true, ColBand1: true}, topColBand2: {ShowRowStripes: true, ShowColumnStripes: true, top: true, RowBand1: true, ColBand2: true}, bottomRowBand1ColBand1: {ShowRowStripes: true, ShowColumnStripes: true, bottom: true, RowBand1: true, ColBand1: true}, bottomRowBand1ColBand2: {ShowRowStripes: true, ShowColumnStripes: true, bottom: true, RowBand1: true, ColBand2: true}, bottomRowBand2ColBand1: {ShowRowStripes: true, ShowColumnStripes: true, bottom: true, RowBand2: true, ColBand1: true}, bottomRowBand2ColBand2: {ShowRowStripes: true, ShowColumnStripes: true, bottom: true, RowBand2: true, ColBand2: true}, innerRowBand1ColBand1: {ShowRowStripes: true, ShowColumnStripes: true, RowBand1: true, ColBand1: true}, innerRowBand1ColBand2: {ShowRowStripes: true, ShowColumnStripes: true, RowBand1: true, ColBand2: true}, innerRowBand2ColBand1: {ShowRowStripes: true, ShowColumnStripes: true, RowBand2: true, ColBand1: true}, innerRowBand2ColBand2: {ShowRowStripes: true, ShowColumnStripes: true, RowBand2: true, ColBand2: true}, leftTopFC: {ShowFirstColumn: true, ShowRowStripes: true, ShowColumnStripes: true, left: true, top: true, RowBand1: true, ColBand1: true}, leftBottomRowBand1FC: {ShowFirstColumn: true, ShowRowStripes: true, ShowColumnStripes: true, left: true, bottom: true, RowBand1: true, ColBand1: true}, leftBottomRowBand2FC: {ShowFirstColumn: true, ShowRowStripes: true, ShowColumnStripes: true, left: true, bottom: true, RowBand2: true, ColBand1: true}, leftRowBand1FC: {ShowFirstColumn: true, ShowRowStripes: true, ShowColumnStripes: true, left: true, RowBand1: true, ColBand1: true}, leftRowBand2FC: {ShowFirstColumn: true, ShowRowStripes: true, ShowColumnStripes: true, left: true, RowBand2: true, ColBand1: true}, rightTopColBand1LC: {ShowLastColumn: true, ShowRowStripes: true, ShowColumnStripes: true, right: true, top: true, RowBand1: true, ColBand1: true}, rightTopColBand2LC: {ShowLastColumn: true, ShowRowStripes: true, ShowColumnStripes: true, right: true, top: true, RowBand1: true, ColBand2: true}, rightRowBand1ColBand1LC: {ShowLastColumn: true, ShowRowStripes: true, ShowColumnStripes: true, right: true, RowBand1: true, ColBand1: true}, rightRowBand1ColBand2LC: {ShowLastColumn: true, ShowRowStripes: true, ShowColumnStripes: true, right: true, RowBand1: true, ColBand2: true}, rightRowBand2ColBand1LC: {ShowLastColumn: true, ShowRowStripes: true, ShowColumnStripes: true, right: true, RowBand2: true, ColBand1: true}, rightRowBand2ColBand2LC: {ShowLastColumn: true, ShowRowStripes: true, ShowColumnStripes: true, right: true, RowBand2: true, ColBand2: true}, rightBottomRowBand1ColBand1LC: {ShowLastColumn: true, ShowRowStripes: true, ShowColumnStripes: true, right: true, bottom: true, RowBand1: true, ColBand1: true}, rightBottomRowBand1ColBand2LC: {ShowLastColumn: true, ShowRowStripes: true, ShowColumnStripes: true, right: true, bottom: true, RowBand1: true, ColBand2: true}, rightBottomRowBand2ColBand1LC: {ShowLastColumn: true, ShowRowStripes: true, ShowColumnStripes: true, right: true, bottom: true, RowBand2: true, ColBand1: true}, rightBottomRowBand2ColBand2LC: {ShowLastColumn: true, ShowRowStripes: true, ShowColumnStripes: true, right: true, bottom: true, RowBand2: true, ColBand2: true} } var styles = new Object(); for(var i in configs) { styles[i] = new CellXfs(); } this._compileOption(options, headerRowCount, totalsRowCount, styles, configs); this.compiled.options[nBitMask] = styles; } return styles; }, _compileSetBorder : function(inputDxf, outputDxf, bLeft, bTop, bRight, bBottom, bInnerHor, bInnerVer) { if(null != inputDxf && null != inputDxf.border) { var oCurBorder = inputDxf.border; var oNewBorder = new Border(); if(bLeft) oNewBorder.l = oCurBorder.l; else if(bInnerVer) oNewBorder.l = oCurBorder.iv; if(bTop) oNewBorder.t = oCurBorder.t; else if(bInnerHor) oNewBorder.t = oCurBorder.ih; if(bRight) oNewBorder.r = oCurBorder.r; else if(bInnerVer) oNewBorder.r = oCurBorder.iv; if(bBottom) oNewBorder.b = oCurBorder.b; else if(bInnerHor) oNewBorder.b = oCurBorder.ih; if(null == outputDxf.border) outputDxf.border = oNewBorder; else outputDxf.border = outputDxf.border.merge(oNewBorder); } }, _compileSetHeaderBorder : function(inputDxf, outputDxf, bHeader) { if(null != inputDxf && null != inputDxf.border) { var oCurBorder = inputDxf.border; var oNewBorder = new Border(); if(bHeader) oNewBorder.t = oCurBorder.b; else oNewBorder.b = oCurBorder.t; if(null == outputDxf.border) outputDxf.border = oNewBorder; else outputDxf.border = outputDxf.border.merge(oNewBorder); } }, _compileOption : function(options, headerRowCount, totalsRowCount, styles, configs) { for(var i in styles) { var xfs = styles[i]; var config = configs[i]; //заглушка для бордеров, чтобы при конфликте нижние бордеры не перекрывали бордеры заголовка if(headerRowCount > 0 && config.top && true != config.header) { if(options.ShowFirstColumn && null != this.firstHeaderCell && config.left) this._compileSetHeaderBorder(this.firstHeaderCell.dxf, xfs, true); else if(options.ShowLastColumn && null != this.lastHeaderCell && config.right) this._compileSetHeaderBorder(this.lastHeaderCell.dxf, xfs, true); if(null != this.headerRow) this._compileSetHeaderBorder(this.headerRow.dxf, xfs, true); } if(totalsRowCount > 0 && config.bottom && true != config.total) { if(options.ShowFirstColumn && null != this.firstTotalCell && config.left) this._compileSetHeaderBorder(this.firstTotalCell.dxf, xfs, false); else if(options.ShowLastColumn && null != this.lastTotalCell && config.right) this._compileSetHeaderBorder(this.lastTotalCell.dxf, xfs, false); if(null != this.totalRow) this._compileSetHeaderBorder(this.totalRow.dxf, xfs, false); } if(headerRowCount > 0 && config.header) { if(options.ShowFirstColumn && null != this.firstHeaderCell && config.left) xfs = xfs.merge(this.firstHeaderCell.dxf); if(options.ShowLastColumn && null != this.lastHeaderCell && config.right) xfs = xfs.merge(this.lastHeaderCell.dxf); if(null != this.headerRow) { xfs = xfs.merge(this.compiled.headerRow.dxf); //применяем бордер if(config.left) this._compileSetBorder(this.headerRow.dxf, xfs, true, true, false, true, false, true); else if(config.right) this._compileSetBorder(this.headerRow.dxf, xfs, false, true, true, true, false, true); else this._compileSetBorder(this.headerRow.dxf, xfs, false, true, false, true, false, true); } if(options.ShowFirstColumn && null != this.firstColumn && config.left) { xfs = xfs.merge(this.compiled.firstColumn.dxf); //применяем бордер this._compileSetBorder(this.firstColumn.dxf, xfs, true, true, true, false, true, false); } if(options.ShowLastColumn && null != this.lastColumn && config.right) { xfs = xfs.merge(this.compiled.lastColumn.dxf); //применяем бордер this._compileSetBorder(this.lastColumn.dxf, xfs, true, true, true, false, true, false); } } else if(totalsRowCount > 0 && config.total) { if(options.ShowFirstColumn && null != this.firstTotalCell && config.left) xfs = xfs.merge(this.firstTotalCell.dxf); if(options.ShowLastColumn && null != this.lastTotalCell && config.right) xfs = xfs.merge(this.lastTotalCell.dxf); if(null != this.totalRow) { xfs = xfs.merge(this.compiled.totalRow.dxf); //применяем бордер if(config.left) this._compileSetBorder(this.totalRow.dxf, xfs, true, true, false, true, false, true); else if(config.right) this._compileSetBorder(this.totalRow.dxf, xfs, false, true, true, true, false, true); else this._compileSetBorder(this.totalRow.dxf, xfs, false, true, false, true, false, true); } if(options.ShowFirstColumn && null != this.firstColumn && config.left) { xfs = xfs.merge(this.compiled.firstColumn.dxf); //применяем бордер this._compileSetBorder(this.firstColumn.dxf, xfs, true, false, true, true, true, false); } if(options.ShowLastColumn && null != this.lastColumn && config.right) { xfs = xfs.merge(this.compiled.lastColumn.dxf); //применяем бордер this._compileSetBorder(this.lastColumn.dxf, xfs, true, false, true, true, true, false); } } else { if(options.ShowFirstColumn && null != this.firstColumn && config.ShowFirstColumn) { xfs = xfs.merge(this.compiled.firstColumn.dxf); //применяем бордер if(config.left && config.top) { if(headerRowCount > 0) this._compileSetBorder(this.firstColumn.dxf, xfs, true, false, true, false, true, false); else this._compileSetBorder(this.firstColumn.dxf, xfs, true, true, true, false, true, false); } else if(config.left && config.bottom) { if(totalsRowCount > 0) this._compileSetBorder(this.firstColumn.dxf, xfs, true, false, true, false, true, false); else this._compileSetBorder(this.firstColumn.dxf, xfs, true, false, true, true, true, false); } else this._compileSetBorder(this.firstColumn.dxf, xfs, true, false, true, false, true, false); } else if(options.ShowLastColumn && null != this.lastColumn && config.ShowLastColumn) { xfs = xfs.merge(this.compiled.lastColumn.dxf); //применяем бордер if(config.right && config.top) { if(headerRowCount > 0) this._compileSetBorder(this.lastColumn.dxf, xfs, true, false, true, false, true, false); else this._compileSetBorder(this.lastColumn.dxf, xfs, true, true, true, false, true, false); } else if(config.right && config.bottom) { if(totalsRowCount > 0) this._compileSetBorder(this.lastColumn.dxf, xfs, true, false, true, false, true, false); else this._compileSetBorder(this.lastColumn.dxf, xfs, true, false, true, true, true, false); } else this._compileSetBorder(this.lastColumn.dxf, xfs, true, false, true, false, true, false); } if(options.ShowRowStripes && config.ShowRowStripes) { if(null != this.firstRowStripe && config.RowBand1) { xfs = xfs.merge(this.compiled.firstRowStripe.dxf); //применяем бордер if(config.left) this._compileSetBorder(this.firstRowStripe.dxf, xfs, true, true, false, true, false, true); else if(config.right) this._compileSetBorder(this.firstRowStripe.dxf, xfs, false, true, true, true, false, true); else this._compileSetBorder(this.firstRowStripe.dxf, xfs, false, true, false, true, false, true); } else if(null != this.secondRowStripe && config.RowBand2) { xfs = xfs.merge(this.compiled.secondRowStripe.dxf); //применяем бордер if(config.left) this._compileSetBorder(this.secondRowStripe.dxf, xfs, true, true, false, true, false, true); else if(config.right) this._compileSetBorder(this.secondRowStripe.dxf, xfs, false, true, true, true, false, true); else this._compileSetBorder(this.secondRowStripe.dxf, xfs, false, true, false, true, false, true); } } if(options.ShowColumnStripes && config.ShowRowStripes) { if(null != this.firstColumnStripe && config.ColBand1) { xfs = xfs.merge(this.compiled.firstColumnStripe.dxf); //применяем бордер if(config.top) this._compileSetBorder(this.firstColumnStripe.dxf, xfs, true, true, true, false, true, false); else if(config.bottom) this._compileSetBorder(this.firstColumnStripe.dxf, xfs, true, false, true, true, true, false); else this._compileSetBorder(this.firstColumnStripe.dxf, xfs, true, false, true, false, true, false); } else if(null != this.secondColumnStripe && config.ColBand2) { xfs = xfs.merge(this.compiled.secondColumnStripe.dxf); //применяем бордер if(config.top) this._compileSetBorder(this.secondColumnStripe.dxf, xfs, true, true, true, false, true, false); else if(config.bottom) this._compileSetBorder(this.secondColumnStripe.dxf, xfs, true, false, true, true, true, false); else this._compileSetBorder(this.secondColumnStripe.dxf, xfs, true, false, true, false, true, false); } } } if(null != this.wholeTable) { xfs = xfs.merge(this.compiled.wholeTable.dxf); //применяем бордер if(config.top) { if(headerRowCount > 0 && true != config.header) { if(config.left) this._compileSetBorder(this.wholeTable.dxf, xfs, true, false, false, false, true, true); else if(config.right) this._compileSetBorder(this.wholeTable.dxf, xfs, false, false, true, false, true, true); else this._compileSetBorder(this.wholeTable.dxf, xfs, false, false, false, false, true, true); } else { if(config.left) this._compileSetBorder(this.wholeTable.dxf, xfs, true, true, false, false, true, true); else if(config.right) this._compileSetBorder(this.wholeTable.dxf, xfs, false, true, true, false, true, true); else this._compileSetBorder(this.wholeTable.dxf, xfs, false, true, false, false, true, true); } } else if(config.bottom) { if(totalsRowCount > 0 && true != config.total) { if(config.left) this._compileSetBorder(this.wholeTable.dxf, xfs, true, false, false, false, true, true); else if(config.right) this._compileSetBorder(this.wholeTable.dxf, xfs, false, false, true, false, true, true); else this._compileSetBorder(this.wholeTable.dxf, xfs, false, false, false, false, true, true); } else { if(config.left) this._compileSetBorder(this.wholeTable.dxf, xfs, true, false, false, true, true, true); else if(config.right) this._compileSetBorder(this.wholeTable.dxf, xfs, false, false, true, true, true, true); else this._compileSetBorder(this.wholeTable.dxf, xfs, false, false, false, true, true, true); } } else if(config.left) this._compileSetBorder(this.wholeTable.dxf, xfs, true, false, false, false, true, true); else if(config.right) this._compileSetBorder(this.wholeTable.dxf, xfs, false, false, true, false, true, true); else this._compileSetBorder(this.wholeTable.dxf, xfs, false, false, false, false, true, true); } styles[i] = xfs; } }, _compile : function() { this.compiled = { options: new Object(), blankRow: null, firstColumn: null, firstColumnStripe: null, firstColumnSubheading: null, firstHeaderCell: null, firstRowStripe: null, firstRowSubheading: null, firstSubtotalColumn: null, firstSubtotalRow: null, firstTotalCell: null, headerRow: null, lastColumn: null, lastHeaderCell: null, lastTotalCell: null, pageFieldLabels: null, pageFieldValues: null, secondColumnStripe: null, secondColumnSubheading: null, secondRowStripe: null, secondRowSubheading: null, secondSubtotalColumn: null, secondSubtotalRow: null, thirdColumnSubheading: null, thirdRowSubheading: null, thirdSubtotalColumn: null, thirdSubtotalRow: null, totalRow: null, wholeTable: null } //копируем исходные стили только без border for(var i in this) { var elem = this[i]; if(null != elem && elem instanceof CTableStyleElement) { var oNewElem = new CTableStyleElement(); oNewElem.size = elem.size; oNewElem.dxf = elem.dxf.clone(); oNewElem.dxf.border = null; this.compiled[i] = oNewElem; } } } } function CTableStyleElement() { this.size = 1; this.dxf = null; } function ReadDefTableStyles(wb, oOutput) { var Types = { Style: 0, Dxf: 1, tableStyles: 2 }; var sStyles = "X4kAAAB+AgAAAYYBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBCQMFmsxMZiYz4z8LHAAAAAIXAAAAABIAAAABDQAAAAIBCQMFmsxMZiYz4z8LEQAAAAMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAFDAAAAAAGAwAAAAIBCQEBBgMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQvRAAAAAaIAAAAAFgAAAAAGDQAAAAIBCQMFzWRmMjOZ2T8BAQ0CFgAAAAAGDQAAAAIBCQMFzWRmMjOZ2T8BAQ0DFgAAAAAGDQAAAAIBCQMFzWRmMjOZ2T8BAQ0EFgAAAAAGDQAAAAIBCQMFzWRmMjOZ2T8BAQ0FFgAAAAAGDQAAAAIBCQMFzWRmMjOZ2T8BAQ0GFgAAAAAGDQAAAAIBCQMFzWRmMjOZ2T8BAQ0CFwAAAAASAAAAAQ0AAAACAQkDBc1l5jJzmek/AwkAAAABBgMAAAACAQEC7gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKbAAAAA5YAAAAAJAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AMgA4AAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAfgIAAAGGAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQgDBZrMTGYmM+M/CxwAAAACFwAAAAASAAAAAQ0AAAACAQgDBZrMTGYmM+M/CxEAAAADDAAAAAABAQEGAwAAAAIBAQsRAAAAAwwAAAAAAQEBBgMAAAACAQELJwAAAAERAAAABQwAAAAABgMAAAACAQgBAQYDDAAAAAABAQEGAwAAAAIBAQsRAAAAAwwAAAAAAQEBBgMAAAACAQEL0QAAAAGiAAAAABYAAAAABg0AAAACAQgDBc1kZjIzmdk/AQENAhYAAAAABg0AAAACAQgDBc1kZjIzmdk/AQENAxYAAAAABg0AAAACAQgDBc1kZjIzmdk/AQENBBYAAAAABg0AAAACAQgDBc1kZjIzmdk/AQENBRYAAAAABg0AAAACAQgDBc1kZjIzmdk/AQENBhYAAAAABg0AAAACAQgDBc1kZjIzmdk/AQENAhcAAAAAEgAAAAENAAAAAgEIAwXNZeYyc5npPwMJAAAAAQYDAAAAAgEBAu4AAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgACmwAAAAOWAAAAACQAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADIANwABAQAAAAADYgAAAAQJAAAAAgEbAAQHAAAABAkAAAACAQoABAYAAAAECQAAAAIBGgAEBQAAAAQJAAAAAgEBAAQEAAAABAkAAAACAQsABAMAAAAECQAAAAIBBQAEAgAAAAQJAAAAAgECAAQBAAAAAH4CAAABhgEAAAscAAAAAhcAAAAAEgAAAAENAAAAAgEHAwWazExmJjPjPwscAAAAAhcAAAAAEgAAAAENAAAAAgEHAwWazExmJjPjPwsRAAAAAwwAAAAAAQEBBgMAAAACAQELEQAAAAMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAUMAAAAAAYDAAAAAgEHAQEGAwwAAAAAAQEBBgMAAAACAQELEQAAAAMMAAAAAAEBAQYDAAAAAgEBC9EAAAABogAAAAAWAAAAAAYNAAAAAgEHAwXNZGYyM5nZPwEBDQIWAAAAAAYNAAAAAgEHAwXNZGYyM5nZPwEBDQMWAAAAAAYNAAAAAgEHAwXNZGYyM5nZPwEBDQQWAAAAAAYNAAAAAgEHAwXNZGYyM5nZPwEBDQUWAAAAAAYNAAAAAgEHAwXNZGYyM5nZPwEBDQYWAAAAAAYNAAAAAgEHAwXNZGYyM5nZPwEBDQIXAAAAABIAAAABDQAAAAIBBwMFzWXmMnOZ6T8DCQAAAAEGAwAAAAIBAQLuAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApsAAAADlgAAAAAkAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQAyADYAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAAB+AgAAAYYBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBBgMFmsxMZiYz4z8LHAAAAAIXAAAAABIAAAABDQAAAAIBBgMFmsxMZiYz4z8LEQAAAAMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAFDAAAAAAGAwAAAAIBBgEBBgMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQvRAAAAAaIAAAAAFgAAAAAGDQAAAAIBBgMFzWRmMjOZ2T8BAQ0CFgAAAAAGDQAAAAIBBgMFzWRmMjOZ2T8BAQ0DFgAAAAAGDQAAAAIBBgMFzWRmMjOZ2T8BAQ0EFgAAAAAGDQAAAAIBBgMFzWRmMjOZ2T8BAQ0FFgAAAAAGDQAAAAIBBgMFzWRmMjOZ2T8BAQ0GFgAAAAAGDQAAAAIBBgMFzWRmMjOZ2T8BAQ0CFwAAAAASAAAAAQ0AAAACAQYDBc1l5jJzmek/AwkAAAABBgMAAAACAQEC7gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKbAAAAA5YAAAAAJAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AMgA1AAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAfgIAAAGGAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQUDBZrMTGYmM+M/CxwAAAACFwAAAAASAAAAAQ0AAAACAQUDBZrMTGYmM+M/CxEAAAADDAAAAAABAQEGAwAAAAIBAQsRAAAAAwwAAAAAAQEBBgMAAAACAQELJwAAAAERAAAABQwAAAAABgMAAAACAQUBAQYDDAAAAAABAQEGAwAAAAIBAQsRAAAAAwwAAAAAAQEBBgMAAAACAQEL0QAAAAGiAAAAABYAAAAABg0AAAACAQUDBc1kZjIzmdk/AQENAhYAAAAABg0AAAACAQUDBc1kZjIzmdk/AQENAxYAAAAABg0AAAACAQUDBc1kZjIzmdk/AQENBBYAAAAABg0AAAACAQUDBc1kZjIzmdk/AQENBRYAAAAABg0AAAACAQUDBc1kZjIzmdk/AQENBhYAAAAABg0AAAACAQUDBc1kZjIzmdk/AQENAhcAAAAAEgAAAAENAAAAAgEFAwXNZeYyc5npPwMJAAAAAQYDAAAAAgEBAu4AAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgACmwAAAAOWAAAAACQAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADIANAABAQAAAAADYgAAAAQJAAAAAgEbAAQHAAAABAkAAAACAQoABAYAAAAECQAAAAIBGgAEBQAAAAQJAAAAAgEBAAQEAAAABAkAAAACAQsABAMAAAAECQAAAAIBBQAEAgAAAAQJAAAAAgECAAQBAAAAAH4CAAABhgEAAAscAAAAAhcAAAAAEgAAAAENAAAAAgEEAwWazExmJjPjPwscAAAAAhcAAAAAEgAAAAENAAAAAgEEAwWazExmJjPjPwsRAAAAAwwAAAAAAQEBBgMAAAACAQELEQAAAAMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAUMAAAAAAYDAAAAAgEEAQEGAwwAAAAAAQEBBgMAAAACAQELEQAAAAMMAAAAAAEBAQYDAAAAAgEBC9EAAAABogAAAAAWAAAAAAYNAAAAAgEEAwXNZGYyM5nZPwEBDQIWAAAAAAYNAAAAAgEEAwXNZGYyM5nZPwEBDQMWAAAAAAYNAAAAAgEEAwXNZGYyM5nZPwEBDQQWAAAAAAYNAAAAAgEEAwXNZGYyM5nZPwEBDQUWAAAAAAYNAAAAAgEEAwXNZGYyM5nZPwEBDQYWAAAAAAYNAAAAAgEEAwXNZGYyM5nZPwEBDQIXAAAAABIAAAABDQAAAAIBBAMFzWXmMnOZ6T8DCQAAAAEGAwAAAAIBAQLuAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApsAAAADlgAAAAAkAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQAyADMAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAABCAgAAAUoBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBAAMFs5hZzCxm1r8LHAAAAAIXAAAAABIAAAABDQAAAAIBAAMFs5hZzCxm1r8LEQAAAAMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAFDAAAAAAGAwAAAAIBAQEBBgMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQuVAAAAAWYAAAAADAAAAAAGAwAAAAIBAQEBDQIMAAAAAAYDAAAAAgEBAQENAwwAAAAABgMAAAACAQEBAQ0EDAAAAAAGAwAAAAIBAQEBDQUMAAAAAAYDAAAAAgEBAQENBgwAAAAABgMAAAACAQEBAQ0CFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/AwkAAAABBgMAAAACAQEC7gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKbAAAAA5YAAAAAJAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AMgAyAAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAHQIAAAElAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CyMAAAACDQAAAAAIAAAAAQMAAAACAQkDDAAAAAABAQEGAwAAAAIBAAsjAAAAAg0AAAAACAAAAAEDAAAAAgEJAwwAAAAAAQEBBgMAAAACAQALFgAAAAERAAAABQwAAAAABgMAAAACAQEBAQQLOQAAAAERAAAAAAwAAAAABgMAAAACAQEBAQYCDQAAAAAIAAAAAQMAAAACAQkDDAAAAAABAQEGAwAAAAIBAAs1AAAAASIAAAAADAAAAAAGAwAAAAIBAQEBBgUMAAAAAAYDAAAAAgEBAQEGAwkAAAABBgMAAAACAQEC7gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKbAAAAA5YAAAAAJAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AMgAxAAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAHQIAAAElAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CyMAAAACDQAAAAAIAAAAAQMAAAACAQgDDAAAAAABAQEGAwAAAAIBAAsjAAAAAg0AAAAACAAAAAEDAAAAAgEIAwwAAAAAAQEBBgMAAAACAQALFgAAAAERAAAABQwAAAAABgMAAAACAQEBAQQLOQAAAAERAAAAAAwAAAAABgMAAAACAQEBAQYCDQAAAAAIAAAAAQMAAAACAQgDDAAAAAABAQEGAwAAAAIBAAs1AAAAASIAAAAADAAAAAAGAwAAAAIBAQEBBgUMAAAAAAYDAAAAAgEBAQEGAwkAAAABBgMAAAACAQEC7gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKbAAAAA5YAAAAAJAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AMgAwAAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAHQIAAAElAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CyMAAAACDQAAAAAIAAAAAQMAAAACAQcDDAAAAAABAQEGAwAAAAIBAAsjAAAAAg0AAAAACAAAAAEDAAAAAgEHAwwAAAAAAQEBBgMAAAACAQALFgAAAAERAAAABQwAAAAABgMAAAACAQEBAQQLOQAAAAERAAAAAAwAAAAABgMAAAACAQEBAQYCDQAAAAAIAAAAAQMAAAACAQcDDAAAAAABAQEGAwAAAAIBAAs1AAAAASIAAAAADAAAAAAGAwAAAAIBAQEBBgUMAAAAAAYDAAAAAgEBAQEGAwkAAAABBgMAAAACAQEC7gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKbAAAAA5YAAAAAJAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AMQA5AAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAHQIAAAElAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CyMAAAACDQAAAAAIAAAAAQMAAAACAQYDDAAAAAABAQEGAwAAAAIBAAsjAAAAAg0AAAAACAAAAAEDAAAAAgEGAwwAAAAAAQEBBgMAAAACAQALFgAAAAERAAAABQwAAAAABgMAAAACAQEBAQQLOQAAAAERAAAAAAwAAAAABgMAAAACAQEBAQYCDQAAAAAIAAAAAQMAAAACAQYDDAAAAAABAQEGAwAAAAIBAAs1AAAAASIAAAAADAAAAAAGAwAAAAIBAQEBBgUMAAAAAAYDAAAAAgEBAQEGAwkAAAABBgMAAAACAQEC7gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKbAAAAA5YAAAAAJAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AMQA4AAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAHQIAAAElAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CyMAAAACDQAAAAAIAAAAAQMAAAACAQUDDAAAAAABAQEGAwAAAAIBAAsjAAAAAg0AAAAACAAAAAEDAAAAAgEFAwwAAAAAAQEBBgMAAAACAQALFgAAAAERAAAABQwAAAAABgMAAAACAQEBAQQLOQAAAAERAAAAAAwAAAAABgMAAAACAQEBAQYCDQAAAAAIAAAAAQMAAAACAQUDDAAAAAABAQEGAwAAAAIBAAs1AAAAASIAAAAADAAAAAAGAwAAAAIBAQEBBgUMAAAAAAYDAAAAAgEBAQEGAwkAAAABBgMAAAACAQEC7gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKbAAAAA5YAAAAAJAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AMQA3AAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAHQIAAAElAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CyMAAAACDQAAAAAIAAAAAQMAAAACAQQDDAAAAAABAQEGAwAAAAIBAAsjAAAAAg0AAAAACAAAAAEDAAAAAgEEAwwAAAAAAQEBBgMAAAACAQALFgAAAAERAAAABQwAAAAABgMAAAACAQEBAQQLOQAAAAERAAAAAAwAAAAABgMAAAACAQEBAQYCDQAAAAAIAAAAAQMAAAACAQQDDAAAAAABAQEGAwAAAAIBAAs1AAAAASIAAAAADAAAAAAGAwAAAAIBAQEBBgUMAAAAAAYDAAAAAgEBAQEGAwkAAAABBgMAAAACAQEC7gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKbAAAAA5YAAAAAJAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AMQA2AAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAYQIAAAFpAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CyMAAAACDQAAAAAIAAAAAQMAAAACAQEDDAAAAAABAQEGAwAAAAIBAAsjAAAAAg0AAAAACAAAAAEDAAAAAgEBAwwAAAAAAQEBBgMAAAACAQALFgAAAAERAAAABQwAAAAABgMAAAACAQEBAQQLOQAAAAERAAAAAAwAAAAABgMAAAACAQEBAQYCDQAAAAAIAAAAAQMAAAACAQEDDAAAAAABAQEGAwAAAAIBAAt5AAAAAWYAAAAADAAAAAAGAwAAAAIBAQEBBgIMAAAAAAYDAAAAAgEBAQENAwwAAAAABgMAAAACAQEBAQ0EDAAAAAAGAwAAAAIBAQEBDQUMAAAAAAYDAAAAAgEBAQEGBgwAAAAABgMAAAACAQEBAQ0DCQAAAAEGAwAAAAIBAQLuAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApsAAAADlgAAAAAkAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQAxADUAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAABcAgAAAWQBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBCQMFmsxMZiYz4z8LHAAAAAIXAAAAABIAAAABDQAAAAIBCQMFmsxMZiYz4z8LIwAAAAINAAAAAAgAAAABAwAAAAIBCQMMAAAAAAEBAQYDAAAAAgEACyMAAAACDQAAAAAIAAAAAQMAAAACAQkDDAAAAAABAQEGAwAAAAIBAAs5AAAAAREAAAAFDAAAAAAGAwAAAAIBAAEBDAINAAAAAAgAAAABAwAAAAIBCQMMAAAAAAEBAQYDAAAAAgEACzkAAAABEQAAAAAMAAAAAAYDAAAAAgEAAQEMAg0AAAAACAAAAAEDAAAAAgEJAwwAAAAAAQEBBgMAAAACAQALUQAAAAEiAAAAAwwAAAAABgMAAAACAQABAQ0GDAAAAAAGAwAAAAIBAAEBDQIXAAAAABIAAAABDQAAAAIBCQMFzWXmMnOZ6T8DCQAAAAEGAwAAAAIBAQLuAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApsAAAADlgAAAAAkAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQAxADQAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAABcAgAAAWQBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBCAMFmsxMZiYz4z8LHAAAAAIXAAAAABIAAAABDQAAAAIBCAMFmsxMZiYz4z8LIwAAAAINAAAAAAgAAAABAwAAAAIBCAMMAAAAAAEBAQYDAAAAAgEACyMAAAACDQAAAAAIAAAAAQMAAAACAQgDDAAAAAABAQEGAwAAAAIBAAs5AAAAAREAAAAFDAAAAAAGAwAAAAIBAAEBDAINAAAAAAgAAAABAwAAAAIBCAMMAAAAAAEBAQYDAAAAAgEACzkAAAABEQAAAAAMAAAAAAYDAAAAAgEAAQEMAg0AAAAACAAAAAEDAAAAAgEIAwwAAAAAAQEBBgMAAAACAQALUQAAAAEiAAAAAwwAAAAABgMAAAACAQABAQ0GDAAAAAAGAwAAAAIBAAEBDQIXAAAAABIAAAABDQAAAAIBCAMFzWXmMnOZ6T8DCQAAAAEGAwAAAAIBAQLuAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApsAAAADlgAAAAAkAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQAxADMAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAABcAgAAAWQBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBBwMFmsxMZiYz4z8LHAAAAAIXAAAAABIAAAABDQAAAAIBBwMFmsxMZiYz4z8LIwAAAAINAAAAAAgAAAABAwAAAAIBBwMMAAAAAAEBAQYDAAAAAgEACyMAAAACDQAAAAAIAAAAAQMAAAACAQcDDAAAAAABAQEGAwAAAAIBAAs5AAAAAREAAAAFDAAAAAAGAwAAAAIBAAEBDAINAAAAAAgAAAABAwAAAAIBBwMMAAAAAAEBAQYDAAAAAgEACzkAAAABEQAAAAAMAAAAAAYDAAAAAgEAAQEMAg0AAAAACAAAAAEDAAAAAgEHAwwAAAAAAQEBBgMAAAACAQALUQAAAAEiAAAAAwwAAAAABgMAAAACAQABAQ0GDAAAAAAGAwAAAAIBAAEBDQIXAAAAABIAAAABDQAAAAIBBwMFzWXmMnOZ6T8DCQAAAAEGAwAAAAIBAQLuAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApsAAAADlgAAAAAkAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQAxADIAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAABcAgAAAWQBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBBgMFmsxMZiYz4z8LHAAAAAIXAAAAABIAAAABDQAAAAIBBgMFmsxMZiYz4z8LIwAAAAINAAAAAAgAAAABAwAAAAIBBgMMAAAAAAEBAQYDAAAAAgEACyMAAAACDQAAAAAIAAAAAQMAAAACAQYDDAAAAAABAQEGAwAAAAIBAAs5AAAAAREAAAAFDAAAAAAGAwAAAAIBAAEBDAINAAAAAAgAAAABAwAAAAIBBgMMAAAAAAEBAQYDAAAAAgEACzkAAAABEQAAAAAMAAAAAAYDAAAAAgEAAQEMAg0AAAAACAAAAAEDAAAAAgEGAwwAAAAAAQEBBgMAAAACAQALUQAAAAEiAAAAAwwAAAAABgMAAAACAQABAQ0GDAAAAAAGAwAAAAIBAAEBDQIXAAAAABIAAAABDQAAAAIBBgMFzWXmMnOZ6T8DCQAAAAEGAwAAAAIBAQLuAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApsAAAADlgAAAAAkAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQAxADEAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAABcAgAAAWQBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBBQMFmsxMZiYz4z8LHAAAAAIXAAAAABIAAAABDQAAAAIBBQMFmsxMZiYz4z8LIwAAAAINAAAAAAgAAAABAwAAAAIBBQMMAAAAAAEBAQYDAAAAAgEACyMAAAACDQAAAAAIAAAAAQMAAAACAQUDDAAAAAABAQEGAwAAAAIBAAs5AAAAAREAAAAFDAAAAAAGAwAAAAIBAAEBDAINAAAAAAgAAAABAwAAAAIBBQMMAAAAAAEBAQYDAAAAAgEACzkAAAABEQAAAAAMAAAAAAYDAAAAAgEAAQEMAg0AAAAACAAAAAEDAAAAAgEFAwwAAAAAAQEBBgMAAAACAQALUQAAAAEiAAAAAwwAAAAABgMAAAACAQABAQ0GDAAAAAAGAwAAAAIBAAEBDQIXAAAAABIAAAABDQAAAAIBBQMFzWXmMnOZ6T8DCQAAAAEGAwAAAAIBAQLuAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApsAAAADlgAAAAAkAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQAxADAAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAABaAgAAAWQBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBBAMFmsxMZiYz4z8LHAAAAAIXAAAAABIAAAABDQAAAAIBBAMFmsxMZiYz4z8LIwAAAAINAAAAAAgAAAABAwAAAAIBBAMMAAAAAAEBAQYDAAAAAgEACyMAAAACDQAAAAAIAAAAAQMAAAACAQQDDAAAAAABAQEGAwAAAAIBAAs5AAAAAREAAAAFDAAAAAAGAwAAAAIBAAEBDAINAAAAAAgAAAABAwAAAAIBBAMMAAAAAAEBAQYDAAAAAgEACzkAAAABEQAAAAAMAAAAAAYDAAAAAgEAAQEMAg0AAAAACAAAAAEDAAAAAgEEAwwAAAAAAQEBBgMAAAACAQALUQAAAAEiAAAAAwwAAAAABgMAAAACAQABAQ0GDAAAAAAGAwAAAAIBAAEBDQIXAAAAABIAAAABDQAAAAIBBAMFzWXmMnOZ6T8DCQAAAAEGAwAAAAIBAQLsAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApkAAAADlAAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAWgIAAAFkAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQADBbOYWcwsZta/CxwAAAACFwAAAAASAAAAAQ0AAAACAQADBbOYWcwsZta/CyMAAAACDQAAAAAIAAAAAQMAAAACAQEDDAAAAAABAQEGAwAAAAIBAAsjAAAAAg0AAAAACAAAAAEDAAAAAgEBAwwAAAAAAQEBBgMAAAACAQALOQAAAAERAAAABQwAAAAABgMAAAACAQABAQwCDQAAAAAIAAAAAQMAAAACAQEDDAAAAAABAQEGAwAAAAIBAAs5AAAAAREAAAAADAAAAAAGAwAAAAIBAAEBDAINAAAAAAgAAAABAwAAAAIBAQMMAAAAAAEBAQYDAAAAAgEAC1EAAAABIgAAAAMMAAAAAAYDAAAAAgEAAQENBgwAAAAABgMAAAACAQABAQ0CFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/AwkAAAABBgMAAAACAQEC7AAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKZAAAAA5QAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOAABAQAAAAADYgAAAAQJAAAAAgEbAAQHAAAABAkAAAACAQoABAYAAAAECQAAAAIBGgAEBQAAAAQJAAAAAgEBAAQEAAAABAkAAAACAQsABAMAAAAECQAAAAIBBQAEAgAAAAQJAAAAAgECAAQBAAAAAFcCAAABYQEAAAscAAAAAhcAAAAAEgAAAAENAAAAAgEJAwXNZeYyc5npPwscAAAAAhcAAAAAEgAAAAENAAAAAgEJAwXNZeYyc5npPwsRAAAAAwwAAAAAAQEBBgMAAAACAQELEQAAAAMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAUMAAAAAAYDAAAAAgEJAQEEAwwAAAAAAQEBBgMAAAACAQELIwAAAAINAAAAAAgAAAABAwAAAAIBCQMMAAAAAAEBAQYDAAAAAgEAC5oAAAABhwAAAAAWAAAAAAYNAAAAAgEJAwXNZGYyM5nZPwEBDQIWAAAAAAYNAAAAAgEJAwXNZGYyM5nZPwEBDQMWAAAAAAYNAAAAAgEJAwXNZGYyM5nZPwEBDQQWAAAAAAYNAAAAAgEJAwXNZGYyM5nZPwEBDQUWAAAAAAYNAAAAAgEJAwXNZGYyM5nZPwEBDQMJAAAAAQYDAAAAAgEBAuwAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgACmQAAAAOUAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADcAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAABXAgAAAWEBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBCAMFzWXmMnOZ6T8LHAAAAAIXAAAAABIAAAABDQAAAAIBCAMFzWXmMnOZ6T8LEQAAAAMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAFDAAAAAAGAwAAAAIBCAEBBAMMAAAAAAEBAQYDAAAAAgEBCyMAAAACDQAAAAAIAAAAAQMAAAACAQgDDAAAAAABAQEGAwAAAAIBAAuaAAAAAYcAAAAAFgAAAAAGDQAAAAIBCAMFzWRmMjOZ2T8BAQ0CFgAAAAAGDQAAAAIBCAMFzWRmMjOZ2T8BAQ0DFgAAAAAGDQAAAAIBCAMFzWRmMjOZ2T8BAQ0EFgAAAAAGDQAAAAIBCAMFzWRmMjOZ2T8BAQ0FFgAAAAAGDQAAAAIBCAMFzWRmMjOZ2T8BAQ0DCQAAAAEGAwAAAAIBAQLsAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApkAAAADlAAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA2AAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAVwIAAAFhAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQcDBc1l5jJzmek/CxwAAAACFwAAAAASAAAAAQ0AAAACAQcDBc1l5jJzmek/CxEAAAADDAAAAAABAQEGAwAAAAIBAQsRAAAAAwwAAAAAAQEBBgMAAAACAQELJwAAAAERAAAABQwAAAAABgMAAAACAQcBAQQDDAAAAAABAQEGAwAAAAIBAQsjAAAAAg0AAAAACAAAAAEDAAAAAgEHAwwAAAAAAQEBBgMAAAACAQALmgAAAAGHAAAAABYAAAAABg0AAAACAQcDBc1kZjIzmdk/AQENAhYAAAAABg0AAAACAQcDBc1kZjIzmdk/AQENAxYAAAAABg0AAAACAQcDBc1kZjIzmdk/AQENBBYAAAAABg0AAAACAQcDBc1kZjIzmdk/AQENBRYAAAAABg0AAAACAQcDBc1kZjIzmdk/AQENAwkAAAABBgMAAAACAQEC7AAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKZAAAAA5QAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0ANQABAQAAAAADYgAAAAQJAAAAAgEbAAQHAAAABAkAAAACAQoABAYAAAAECQAAAAIBGgAEBQAAAAQJAAAAAgEBAAQEAAAABAkAAAACAQsABAMAAAAECQAAAAIBBQAEAgAAAAQJAAAAAgECAAQBAAAAAFcCAAABYQEAAAscAAAAAhcAAAAAEgAAAAENAAAAAgEGAwXNZeYyc5npPwscAAAAAhcAAAAAEgAAAAENAAAAAgEGAwXNZeYyc5npPwsRAAAAAwwAAAAAAQEBBgMAAAACAQELEQAAAAMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAUMAAAAAAYDAAAAAgEGAQEEAwwAAAAAAQEBBgMAAAACAQELIwAAAAINAAAAAAgAAAABAwAAAAIBBgMMAAAAAAEBAQYDAAAAAgEAC5oAAAABhwAAAAAWAAAAAAYNAAAAAgEGAwXNZGYyM5nZPwEBDQIWAAAAAAYNAAAAAgEGAwXNZGYyM5nZPwEBDQMWAAAAAAYNAAAAAgEGAwXNZGYyM5nZPwEBDQQWAAAAAAYNAAAAAgEGAwXNZGYyM5nZPwEBDQUWAAAAAAYNAAAAAgEGAwXNZGYyM5nZPwEBDQMJAAAAAQYDAAAAAgEBAuwAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgACmQAAAAOUAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADQAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAABXAgAAAWEBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBBQMFzWXmMnOZ6T8LHAAAAAIXAAAAABIAAAABDQAAAAIBBQMFzWXmMnOZ6T8LEQAAAAMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAFDAAAAAAGAwAAAAIBBQEBBAMMAAAAAAEBAQYDAAAAAgEBCyMAAAACDQAAAAAIAAAAAQMAAAACAQUDDAAAAAABAQEGAwAAAAIBAAuaAAAAAYcAAAAAFgAAAAAGDQAAAAIBBQMFzWRmMjOZ2T8BAQ0CFgAAAAAGDQAAAAIBBQMFzWRmMjOZ2T8BAQ0DFgAAAAAGDQAAAAIBBQMFzWRmMjOZ2T8BAQ0EFgAAAAAGDQAAAAIBBQMFzWRmMjOZ2T8BAQ0FFgAAAAAGDQAAAAIBBQMFzWRmMjOZ2T8BAQ0DCQAAAAEGAwAAAAIBAQLsAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApkAAAADlAAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQAzAAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAVwIAAAFhAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQQDBc1l5jJzmek/CxwAAAACFwAAAAASAAAAAQ0AAAACAQQDBc1l5jJzmek/CxEAAAADDAAAAAABAQEGAwAAAAIBAQsRAAAAAwwAAAAAAQEBBgMAAAACAQELJwAAAAERAAAABQwAAAAABgMAAAACAQQBAQQDDAAAAAABAQEGAwAAAAIBAQsjAAAAAg0AAAAACAAAAAEDAAAAAgEEAwwAAAAAAQEBBgMAAAACAQALmgAAAAGHAAAAABYAAAAABg0AAAACAQQDBc1kZjIzmdk/AQENAhYAAAAABg0AAAACAQQDBc1kZjIzmdk/AQENAxYAAAAABg0AAAACAQQDBc1kZjIzmdk/AQENBBYAAAAABg0AAAACAQQDBc1kZjIzmdk/AQENBRYAAAAABg0AAAACAQQDBc1kZjIzmdk/AQENAwkAAAABBgMAAAACAQEC7AAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKZAAAAA5QAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AMgABAQAAAAADYgAAAAQJAAAAAgEbAAQHAAAABAkAAAACAQoABAYAAAAECQAAAAIBGgAEBQAAAAQJAAAAAgEBAAQEAAAABAkAAAACAQsABAMAAAAECQAAAAIBBQAEAgAAAAQJAAAAAgECAAQBAAAAACUCAAABLwEAAAscAAAAAhcAAAAAEgAAAAENAAAAAgEAAwWazExmJjPDvwscAAAAAhcAAAAAEgAAAAENAAAAAgEAAwWazExmJjPDvwsRAAAAAwwAAAAAAQEBBgMAAAACAQELEQAAAAMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAUMAAAAAAYDAAAAAgEBAQEEAwwAAAAAAQEBBgMAAAACAQELIwAAAAINAAAAAAgAAAABAwAAAAIBAQMMAAAAAAEBAQYDAAAAAgEAC2gAAAABVQAAAAAMAAAAAAYDAAAAAgEBAQENAgwAAAAABgMAAAACAQEBAQ0DDAAAAAAGAwAAAAIBAQEBDQQMAAAAAAYDAAAAAgEBAQENBQwAAAAABgMAAAACAQEBAQ0DCQAAAAEGAwAAAAIBAQLsAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApkAAAADlAAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQAxAAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAOgIAAAFEAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQkDBc1l5jJzmek/CxwAAAACFwAAAAASAAAAAQ0AAAACAQkDBc1l5jJzmek/CxEAAAADDAAAAAABAQEGAwAAAAIBAQsRAAAAAwwAAAAAAQEBBgMAAAACAQELJwAAAAERAAAABQwAAAAABgMAAAACAQkBAQQDDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAADAAAAAAGAwAAAAIBCQEBBgMMAAAAAAEBAQYDAAAAAgEBC3kAAAABZgAAAAAMAAAAAAYDAAAAAgEJAQENAgwAAAAABgMAAAACAQkBAQ0DDAAAAAAGAwAAAAIBCQEBDQQMAAAAAAYDAAAAAgEJAQENBQwAAAAABgMAAAACAQkBAQ0GDAAAAAAGAwAAAAIBCQEBDQMJAAAAAQYDAAAAAgEBAuwAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgACmQAAAAOUAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAEwAaQBnAGgAdAAyADEAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAAA6AgAAAUQBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBCAMFzWXmMnOZ6T8LHAAAAAIXAAAAABIAAAABDQAAAAIBCAMFzWXmMnOZ6T8LEQAAAAMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAFDAAAAAAGAwAAAAIBCAEBBAMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAAMAAAAAAYDAAAAAgEIAQEGAwwAAAAAAQEBBgMAAAACAQELeQAAAAFmAAAAAAwAAAAABgMAAAACAQgBAQ0CDAAAAAAGAwAAAAIBCAEBDQMMAAAAAAYDAAAAAgEIAQENBAwAAAAABgMAAAACAQgBAQ0FDAAAAAAGAwAAAAIBCAEBDQYMAAAAAAYDAAAAAgEIAQENAwkAAAABBgMAAAACAQEC7AAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKZAAAAA5QAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATABpAGcAaAB0ADIAMAABAQAAAAADYgAAAAQJAAAAAgEbAAQHAAAABAkAAAACAQoABAYAAAAECQAAAAIBGgAEBQAAAAQJAAAAAgEBAAQEAAAABAkAAAACAQsABAMAAAAECQAAAAIBBQAEAgAAAAQJAAAAAgECAAQBAAAAADoCAAABRAEAAAscAAAAAhcAAAAAEgAAAAENAAAAAgEHAwXNZeYyc5npPwscAAAAAhcAAAAAEgAAAAENAAAAAgEHAwXNZeYyc5npPwsRAAAAAwwAAAAAAQEBBgMAAAACAQELEQAAAAMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAUMAAAAAAYDAAAAAgEHAQEEAwwAAAAAAQEBBgMAAAACAQELJwAAAAERAAAAAAwAAAAABgMAAAACAQcBAQYDDAAAAAABAQEGAwAAAAIBAQt5AAAAAWYAAAAADAAAAAAGAwAAAAIBBwEBDQIMAAAAAAYDAAAAAgEHAQENAwwAAAAABgMAAAACAQcBAQ0EDAAAAAAGAwAAAAIBBwEBDQUMAAAAAAYDAAAAAgEHAQENBgwAAAAABgMAAAACAQcBAQ0DCQAAAAEGAwAAAAIBAQLsAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApkAAAADlAAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA5AAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAOgIAAAFEAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQYDBc1l5jJzmek/CxwAAAACFwAAAAASAAAAAQ0AAAACAQYDBc1l5jJzmek/CxEAAAADDAAAAAABAQEGAwAAAAIBAQsRAAAAAwwAAAAAAQEBBgMAAAACAQELJwAAAAERAAAABQwAAAAABgMAAAACAQYBAQQDDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAADAAAAAAGAwAAAAIBBgEBBgMMAAAAAAEBAQYDAAAAAgEBC3kAAAABZgAAAAAMAAAAAAYDAAAAAgEGAQENAgwAAAAABgMAAAACAQYBAQ0DDAAAAAAGAwAAAAIBBgEBDQQMAAAAAAYDAAAAAgEGAQENBQwAAAAABgMAAAACAQYBAQ0GDAAAAAAGAwAAAAIBBgEBDQMJAAAAAQYDAAAAAgEBAuwAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgACmQAAAAOUAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAEwAaQBnAGgAdAAxADgAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAAA6AgAAAUQBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBBQMFzWXmMnOZ6T8LHAAAAAIXAAAAABIAAAABDQAAAAIBBQMFzWXmMnOZ6T8LEQAAAAMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAFDAAAAAAGAwAAAAIBBQEBBAMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAAMAAAAAAYDAAAAAgEFAQEGAwwAAAAAAQEBBgMAAAACAQELeQAAAAFmAAAAAAwAAAAABgMAAAACAQUBAQ0CDAAAAAAGAwAAAAIBBQEBDQMMAAAAAAYDAAAAAgEFAQENBAwAAAAABgMAAAACAQUBAQ0FDAAAAAAGAwAAAAIBBQEBDQYMAAAAAAYDAAAAAgEFAQENAwkAAAABBgMAAAACAQEC7AAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKZAAAAA5QAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATABpAGcAaAB0ADEANwABAQAAAAADYgAAAAQJAAAAAgEbAAQHAAAABAkAAAACAQoABAYAAAAECQAAAAIBGgAEBQAAAAQJAAAAAgEBAAQEAAAABAkAAAACAQsABAMAAAAECQAAAAIBBQAEAgAAAAQJAAAAAgECAAQBAAAAADoCAAABRAEAAAscAAAAAhcAAAAAEgAAAAENAAAAAgEEAwXNZeYyc5npPwscAAAAAhcAAAAAEgAAAAENAAAAAgEEAwXNZeYyc5npPwsRAAAAAwwAAAAAAQEBBgMAAAACAQELEQAAAAMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAUMAAAAAAYDAAAAAgEEAQEEAwwAAAAAAQEBBgMAAAACAQELJwAAAAERAAAAAAwAAAAABgMAAAACAQQBAQYDDAAAAAABAQEGAwAAAAIBAQt5AAAAAWYAAAAADAAAAAAGAwAAAAIBBAEBDQIMAAAAAAYDAAAAAgEEAQENAwwAAAAABgMAAAACAQQBAQ0EDAAAAAAGAwAAAAIBBAEBDQUMAAAAAAYDAAAAAgEEAQENBgwAAAAABgMAAAACAQQBAQ0DCQAAAAEGAwAAAAIBAQLsAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApkAAAADlAAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAOgIAAAFEAQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/CxEAAAADDAAAAAABAQEGAwAAAAIBAQsRAAAAAwwAAAAAAQEBBgMAAAACAQELJwAAAAERAAAABQwAAAAABgMAAAACAQEBAQQDDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAADAAAAAAGAwAAAAIBAQEBBgMMAAAAAAEBAQYDAAAAAgEBC3kAAAABZgAAAAAMAAAAAAYDAAAAAgEBAQENAgwAAAAABgMAAAACAQEBAQ0DDAAAAAAGAwAAAAIBAQEBDQQMAAAAAAYDAAAAAgEBAQENBQwAAAAABgMAAAACAQEBAQ0GDAAAAAAGAwAAAAIBAQEBDQMJAAAAAQYDAAAAAgEBAuwAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgACmQAAAAOUAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAEwAaQBnAGgAdAAxADUAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAABaAgAAAUgBAAALFgAAAAERAAAABAwAAAAABgMAAAACAQkBAQ0LFgAAAAERAAAABAwAAAAABgMAAAACAQkBAQ0LFgAAAAERAAAABQwAAAAABgMAAAACAQkBAQ0LFgAAAAERAAAABQwAAAAABgMAAAACAQkBAQ0LEQAAAAMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAFDAAAAAAGAwAAAAIBCQEBBAMMAAAAAAEBAQYDAAAAAgEBCyMAAAACDQAAAAAIAAAAAQMAAAACAQkDDAAAAAABAQEGAwAAAAIBAAtXAAAAAUQAAAAADAAAAAAGAwAAAAIBCQEBDQIMAAAAAAYDAAAAAgEJAQENBAwAAAAABgMAAAACAQkBAQ0FDAAAAAAGAwAAAAIBCQEBDQMJAAAAAQYDAAAAAgEBAggBAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgACtQAAAAOwAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAEwAaQBnAGgAdAAxADQAAQEAAAAAA34AAAAECQAAAAIBGwAECQAAAAQJAAAAAgEKAAQIAAAABAkAAAACARoABAcAAAAECQAAAAIBAQAEBgAAAAQJAAAAAgELAAQFAAAABAkAAAACAQUABAQAAAAECQAAAAIBEgAEAwAAAAQJAAAAAgECAAQCAAAABAkAAAACARAABAEAAAAAWgIAAAFIAQAACxYAAAABEQAAAAQMAAAAAAYDAAAAAgEIAQENCxYAAAABEQAAAAQMAAAAAAYDAAAAAgEIAQENCxYAAAABEQAAAAUMAAAAAAYDAAAAAgEIAQENCxYAAAABEQAAAAUMAAAAAAYDAAAAAgEIAQENCxEAAAADDAAAAAABAQEGAwAAAAIBAQsRAAAAAwwAAAAAAQEBBgMAAAACAQELJwAAAAERAAAABQwAAAAABgMAAAACAQgBAQQDDAAAAAABAQEGAwAAAAIBAQsjAAAAAg0AAAAACAAAAAEDAAAAAgEIAwwAAAAAAQEBBgMAAAACAQALVwAAAAFEAAAAAAwAAAAABgMAAAACAQgBAQ0CDAAAAAAGAwAAAAIBCAEBDQQMAAAAAAYDAAAAAgEIAQENBQwAAAAABgMAAAACAQgBAQ0DCQAAAAEGAwAAAAIBAQIIAQAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAArUAAAADsAAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBMAGkAZwBoAHQAMQAzAAEBAAAAAAN+AAAABAkAAAACARsABAkAAAAECQAAAAIBCgAECAAAAAQJAAAAAgEaAAQHAAAABAkAAAACAQEABAYAAAAECQAAAAIBCwAEBQAAAAQJAAAAAgEFAAQEAAAABAkAAAACARIABAMAAAAECQAAAAIBAgAEAgAAAAQJAAAAAgEQAAQBAAAAAFoCAAABSAEAAAsWAAAAAREAAAAEDAAAAAAGAwAAAAIBBwEBDQsWAAAAAREAAAAEDAAAAAAGAwAAAAIBBwEBDQsWAAAAAREAAAAFDAAAAAAGAwAAAAIBBwEBDQsWAAAAAREAAAAFDAAAAAAGAwAAAAIBBwEBDQsRAAAAAwwAAAAAAQEBBgMAAAACAQELEQAAAAMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAUMAAAAAAYDAAAAAgEHAQEEAwwAAAAAAQEBBgMAAAACAQELIwAAAAINAAAAAAgAAAABAwAAAAIBBwMMAAAAAAEBAQYDAAAAAgEAC1cAAAABRAAAAAAMAAAAAAYDAAAAAgEHAQENAgwAAAAABgMAAAACAQcBAQ0EDAAAAAAGAwAAAAIBBwEBDQUMAAAAAAYDAAAAAgEHAQENAwkAAAABBgMAAAACAQECCAEAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAK1AAAAA7AAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATABpAGcAaAB0ADEAMgABAQAAAAADfgAAAAQJAAAAAgEbAAQJAAAABAkAAAACAQoABAgAAAAECQAAAAIBGgAEBwAAAAQJAAAAAgEBAAQGAAAABAkAAAACAQsABAUAAAAECQAAAAIBBQAEBAAAAAQJAAAAAgESAAQDAAAABAkAAAACAQIABAIAAAAECQAAAAIBEAAEAQAAAABaAgAAAUgBAAALFgAAAAERAAAABAwAAAAABgMAAAACAQYBAQ0LFgAAAAERAAAABAwAAAAABgMAAAACAQYBAQ0LFgAAAAERAAAABQwAAAAABgMAAAACAQYBAQ0LFgAAAAERAAAABQwAAAAABgMAAAACAQYBAQ0LEQAAAAMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAFDAAAAAAGAwAAAAIBBgEBBAMMAAAAAAEBAQYDAAAAAgEBCyMAAAACDQAAAAAIAAAAAQMAAAACAQYDDAAAAAABAQEGAwAAAAIBAAtXAAAAAUQAAAAADAAAAAAGAwAAAAIBBgEBDQIMAAAAAAYDAAAAAgEGAQENBAwAAAAABgMAAAACAQYBAQ0FDAAAAAAGAwAAAAIBBgEBDQMJAAAAAQYDAAAAAgEBAggBAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgACtQAAAAOwAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAEwAaQBnAGgAdAAxADEAAQEAAAAAA34AAAAECQAAAAIBGwAECQAAAAQJAAAAAgEKAAQIAAAABAkAAAACARoABAcAAAAECQAAAAIBAQAEBgAAAAQJAAAAAgELAAQFAAAABAkAAAACAQUABAQAAAAECQAAAAIBEgAEAwAAAAQJAAAAAgECAAQCAAAABAkAAAACARAABAEAAAAAWgIAAAFIAQAACxYAAAABEQAAAAQMAAAAAAYDAAAAAgEFAQENCxYAAAABEQAAAAQMAAAAAAYDAAAAAgEFAQENCxYAAAABEQAAAAUMAAAAAAYDAAAAAgEFAQENCxYAAAABEQAAAAUMAAAAAAYDAAAAAgEFAQENCxEAAAADDAAAAAABAQEGAwAAAAIBAQsRAAAAAwwAAAAAAQEBBgMAAAACAQELJwAAAAERAAAABQwAAAAABgMAAAACAQUBAQQDDAAAAAABAQEGAwAAAAIBAQsjAAAAAg0AAAAACAAAAAEDAAAAAgEFAwwAAAAAAQEBBgMAAAACAQALVwAAAAFEAAAAAAwAAAAABgMAAAACAQUBAQ0CDAAAAAAGAwAAAAIBBQEBDQQMAAAAAAYDAAAAAgEFAQENBQwAAAAABgMAAAACAQUBAQ0DCQAAAAEGAwAAAAIBAQIIAQAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAArUAAAADsAAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBMAGkAZwBoAHQAMQAwAAEBAAAAAAN+AAAABAkAAAACARsABAkAAAAECQAAAAIBCgAECAAAAAQJAAAAAgEaAAQHAAAABAkAAAACAQEABAYAAAAECQAAAAIBCwAEBQAAAAQJAAAAAgEFAAQEAAAABAkAAAACARIABAMAAAAECQAAAAIBAgAEAgAAAAQJAAAAAgEQAAQBAAAAAFgCAAABSAEAAAsWAAAAAREAAAAEDAAAAAAGAwAAAAIBBAEBDQsWAAAAAREAAAAEDAAAAAAGAwAAAAIBBAEBDQsWAAAAAREAAAAFDAAAAAAGAwAAAAIBBAEBDQsWAAAAAREAAAAFDAAAAAAGAwAAAAIBBAEBDQsRAAAAAwwAAAAAAQEBBgMAAAACAQELEQAAAAMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAUMAAAAAAYDAAAAAgEEAQEEAwwAAAAAAQEBBgMAAAACAQELIwAAAAINAAAAAAgAAAABAwAAAAIBBAMMAAAAAAEBAQYDAAAAAgEAC1cAAAABRAAAAAAMAAAAAAYDAAAAAgEEAQENAgwAAAAABgMAAAACAQQBAQ0EDAAAAAAGAwAAAAIBBAEBDQUMAAAAAAYDAAAAAgEEAQENAwkAAAABBgMAAAACAQECBgEAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKzAAAAA64AAAAAIAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATABpAGcAaAB0ADkAAQEAAAAAA34AAAAECQAAAAIBGwAECQAAAAQJAAAAAgEKAAQIAAAABAkAAAACARoABAcAAAAECQAAAAIBAQAEBgAAAAQJAAAAAgELAAQFAAAABAkAAAACAQUABAQAAAAECQAAAAIBEgAEAwAAAAQJAAAAAgECAAQCAAAABAkAAAACARAABAEAAAAAWAIAAAFIAQAACxYAAAABEQAAAAQMAAAAAAYDAAAAAgEBAQENCxYAAAABEQAAAAQMAAAAAAYDAAAAAgEBAQENCxYAAAABEQAAAAUMAAAAAAYDAAAAAgEBAQENCxYAAAABEQAAAAUMAAAAAAYDAAAAAgEBAQENCxEAAAADDAAAAAABAQEGAwAAAAIBAQsRAAAAAwwAAAAAAQEBBgMAAAACAQELJwAAAAERAAAABQwAAAAABgMAAAACAQEBAQQDDAAAAAABAQEGAwAAAAIBAQsjAAAAAg0AAAAACAAAAAEDAAAAAgEBAwwAAAAAAQEBBgMAAAACAQALVwAAAAFEAAAAAAwAAAAABgMAAAACAQEBAQ0CDAAAAAAGAwAAAAIBAQEBDQQMAAAAAAYDAAAAAgEBAQENBQwAAAAABgMAAAACAQEBAQ0DCQAAAAEGAwAAAAIBAQIGAQAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAArMAAAADrgAAAAAgAAAAVABhAGIAbABlAFMAdAB5AGwAZQBMAGkAZwBoAHQAOAABAQAAAAADfgAAAAQJAAAAAgEbAAQJAAAABAkAAAACAQoABAgAAAAECQAAAAIBGgAEBwAAAAQJAAAAAgEBAAQGAAAABAkAAAACAQsABAUAAAAECQAAAAIBBQAEBAAAAAQJAAAAAgESAAQDAAAABAkAAAACAQIABAIAAAAECQAAAAIBEAAEAQAAAAAmAgAAATIBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBCQMFzWXmMnOZ6T8LHAAAAAIXAAAAABIAAAABDQAAAAIBCQMFzWXmMnOZ6T8LGwAAAAMWAAAAAAEBAQYNAAAAAgEJAwUA/X/+P//PvwsbAAAAAxYAAAAAAQEBBg0AAAACAQkDBQD9f/4//8+/CzEAAAABEQAAAAUMAAAAAAYDAAAAAgEJAQENAxYAAAAAAQEBBg0AAAACAQkDBQD9f/4//8+/CzEAAAABEQAAAAAMAAAAAAYDAAAAAgEJAQENAxYAAAAAAQEBBg0AAAACAQkDBQD9f/4//8+/Cz8AAAABIgAAAAAMAAAAAAYDAAAAAgEJAQENBQwAAAAABgMAAAACAQkBAQ0DEwAAAAEGDQAAAAIBCQMFAP1//j//z78C6gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKXAAAAA5IAAAAAIAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATABpAGcAaAB0ADcAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAAAmAgAAATIBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBCAMFzWXmMnOZ6T8LHAAAAAIXAAAAABIAAAABDQAAAAIBCAMFzWXmMnOZ6T8LGwAAAAMWAAAAAAEBAQYNAAAAAgEIAwUA/X/+P//PvwsbAAAAAxYAAAAAAQEBBg0AAAACAQgDBQD9f/4//8+/CzEAAAABEQAAAAUMAAAAAAYDAAAAAgEIAQENAxYAAAAAAQEBBg0AAAACAQgDBQD9f/4//8+/CzEAAAABEQAAAAAMAAAAAAYDAAAAAgEIAQENAxYAAAAAAQEBBg0AAAACAQgDBQD9f/4//8+/Cz8AAAABIgAAAAAMAAAAAAYDAAAAAgEIAQENBQwAAAAABgMAAAACAQgBAQ0DEwAAAAEGDQAAAAIBCAMFAP1//j//z78C6gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKXAAAAA5IAAAAAIAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATABpAGcAaAB0ADYAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAAAmAgAAATIBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBBwMFzWXmMnOZ6T8LHAAAAAIXAAAAABIAAAABDQAAAAIBBwMFzWXmMnOZ6T8LGwAAAAMWAAAAAAEBAQYNAAAAAgEHAwUA/X/+P//PvwsbAAAAAxYAAAAAAQEBBg0AAAACAQcDBQD9f/4//8+/CzEAAAABEQAAAAUMAAAAAAYDAAAAAgEHAQENAxYAAAAAAQEBBg0AAAACAQcDBQD9f/4//8+/CzEAAAABEQAAAAAMAAAAAAYDAAAAAgEHAQENAxYAAAAAAQEBBg0AAAACAQcDBQD9f/4//8+/Cz8AAAABIgAAAAAMAAAAAAYDAAAAAgEHAQENBQwAAAAABgMAAAACAQcBAQ0DEwAAAAEGDQAAAAIBBwMFAP1//j//z78C6gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKXAAAAA5IAAAAAIAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATABpAGcAaAB0ADUAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAAAmAgAAATIBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBBgMFzWXmMnOZ6T8LHAAAAAIXAAAAABIAAAABDQAAAAIBBgMFzWXmMnOZ6T8LGwAAAAMWAAAAAAEBAQYNAAAAAgEGAwUA/X/+P//PvwsbAAAAAxYAAAAAAQEBBg0AAAACAQYDBQD9f/4//8+/CzEAAAABEQAAAAUMAAAAAAYDAAAAAgEGAQENAxYAAAAAAQEBBg0AAAACAQYDBQD9f/4//8+/CzEAAAABEQAAAAAMAAAAAAYDAAAAAgEGAQENAxYAAAAAAQEBBg0AAAACAQYDBQD9f/4//8+/Cz8AAAABIgAAAAAMAAAAAAYDAAAAAgEGAQENBQwAAAAABgMAAAACAQYBAQ0DEwAAAAEGDQAAAAIBBgMFAP1//j//z78C6gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKXAAAAA5IAAAAAIAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATABpAGcAaAB0ADQAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAAAmAgAAATIBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBBQMFzWXmMnOZ6T8LHAAAAAIXAAAAABIAAAABDQAAAAIBBQMFzWXmMnOZ6T8LGwAAAAMWAAAAAAEBAQYNAAAAAgEFAwUA/X/+P//PvwsbAAAAAxYAAAAAAQEBBg0AAAACAQUDBQD9f/4//8+/CzEAAAABEQAAAAUMAAAAAAYDAAAAAgEFAQENAxYAAAAAAQEBBg0AAAACAQUDBQD9f/4//8+/CzEAAAABEQAAAAAMAAAAAAYDAAAAAgEFAQENAxYAAAAAAQEBBg0AAAACAQUDBQD9f/4//8+/Cz8AAAABIgAAAAAMAAAAAAYDAAAAAgEFAQENBQwAAAAABgMAAAACAQUBAQ0DEwAAAAEGDQAAAAIBBQMFAP1//j//z78C6gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKXAAAAA5IAAAAAIAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATABpAGcAaAB0ADMAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAAAmAgAAATIBAAALHAAAAAIXAAAAABIAAAABDQAAAAIBBAMFzWXmMnOZ6T8LHAAAAAIXAAAAABIAAAABDQAAAAIBBAMFzWXmMnOZ6T8LGwAAAAMWAAAAAAEBAQYNAAAAAgEEAwUA/X/+P//PvwsbAAAAAxYAAAAAAQEBBg0AAAACAQQDBQD9f/4//8+/CzEAAAABEQAAAAUMAAAAAAYDAAAAAgEEAQENAxYAAAAAAQEBBg0AAAACAQQDBQD9f/4//8+/CzEAAAABEQAAAAAMAAAAAAYDAAAAAgEEAQENAxYAAAAAAQEBBg0AAAACAQQDBQD9f/4//8+/Cz8AAAABIgAAAAAMAAAAAAYDAAAAAgEEAQENBQwAAAAABgMAAAACAQQBAQ0DEwAAAAEGDQAAAAIBBAMFAP1//j//z78C6gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKXAAAAA5IAAAAAIAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATABpAGcAaAB0ADIAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAAD0AQAAAQABAAALHAAAAAIXAAAAABIAAAABDQAAAAIBAAMFmsxMZiYzw78LHAAAAAIXAAAAABIAAAABDQAAAAIBAAMFmsxMZiYzw78LEQAAAAMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAFDAAAAAAGAwAAAAIBAQEBDQMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAAMAAAAAAYDAAAAAgEBAQENAwwAAAAAAQEBBgMAAAACAQELNQAAAAEiAAAAAAwAAAAABgMAAAACAQEBAQ0FDAAAAAAGAwAAAAIBAQEBDQMJAAAAAQYDAAAAAgEBAuoAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgAClwAAAAOSAAAAACAAAABUAGEAYgBsAGUAUwB0AHkAbABlAEwAaQBnAGgAdAAxAAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAA1AEAAAHgAAAACxwAAAACFwAAAAASAAAAAQ0AAAACAQgDBZrMTGYmM+M/CxwAAAACFwAAAAASAAAAAQ0AAAACAQgDBZrMTGYmM+M/CxEAAAADDAAAAAABAQEGAwAAAAIBAQsRAAAAAwwAAAAAAQEBBgMAAAACAQELJwAAAAERAAAABQwAAAAABgMAAAACAQEBAQQDDAAAAAABAQEGAwAAAAIBAQsgAAAAAg0AAAAACAAAAAEDAAAAAgEJAwkAAAABBgMAAAACAQALHAAAAAIXAAAAABIAAAABDQAAAAIBCAMFzWXmMnOZ6T8C6gAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKXAAAAA5IAAAAAIAAAAFQAYQBiAGwAZQBTAHQAeQBsAGUARABhAHIAawAxADEAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAADUAQAAAeAAAAALHAAAAAIXAAAAABIAAAABDQAAAAIBBgMFmsxMZiYz4z8LHAAAAAIXAAAAABIAAAABDQAAAAIBBgMFmsxMZiYz4z8LEQAAAAMMAAAAAAEBAQYDAAAAAgEBCxEAAAADDAAAAAABAQEGAwAAAAIBAQsnAAAAAREAAAAFDAAAAAAGAwAAAAIBAQEBBAMMAAAAAAEBAQYDAAAAAgEBCyAAAAACDQAAAAAIAAAAAQMAAAACAQcDCQAAAAEGAwAAAAIBAAscAAAAAhcAAAAAEgAAAAENAAAAAgEGAwXNZeYyc5npPwLqAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApcAAAADkgAAAAAgAAAAVABhAGIAbABlAFMAdAB5AGwAZQBEAGEAcgBrADEAMAABAQAAAAADYgAAAAQJAAAAAgEbAAQHAAAABAkAAAACAQoABAYAAAAECQAAAAIBGgAEBQAAAAQJAAAAAgEBAAQEAAAABAkAAAACAQsABAMAAAAECQAAAAIBBQAEAgAAAAQJAAAAAgECAAQBAAAAANIBAAAB4AAAAAscAAAAAhcAAAAAEgAAAAENAAAAAgEEAwWazExmJjPjPwscAAAAAhcAAAAAEgAAAAENAAAAAgEEAwWazExmJjPjPwsRAAAAAwwAAAAAAQEBBgMAAAACAQELEQAAAAMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAUMAAAAAAYDAAAAAgEBAQEEAwwAAAAAAQEBBgMAAAACAQELIAAAAAINAAAAAAgAAAABAwAAAAIBBQMJAAAAAQYDAAAAAgEACxwAAAACFwAAAAASAAAAAQ0AAAACAQQDBc1l5jJzmek/AugAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgAClQAAAAOQAAAAAB4AAABUAGEAYgBsAGUAUwB0AHkAbABlAEQAYQByAGsAOQABAQAAAAADYgAAAAQJAAAAAgEbAAQHAAAABAkAAAACAQoABAYAAAAECQAAAAIBGgAEBQAAAAQJAAAAAgEBAAQEAAAABAkAAAACAQsABAMAAAAECQAAAAIBBQAEAgAAAAQJAAAAAgECAAQBAAAAANIBAAAB4AAAAAscAAAAAhcAAAAAEgAAAAENAAAAAgEAAwWzmFnMLGbWvwscAAAAAhcAAAAAEgAAAAENAAAAAgEAAwWzmFnMLGbWvwsRAAAAAwwAAAAAAQEBBgMAAAACAQELEQAAAAMMAAAAAAEBAQYDAAAAAgEBCycAAAABEQAAAAUMAAAAAAYDAAAAAgEBAQEEAwwAAAAAAQEBBgMAAAACAQELIAAAAAINAAAAAAgAAAABAwAAAAIBAQMJAAAAAQYDAAAAAgEACxwAAAACFwAAAAASAAAAAQ0AAAACAQADBZrMTGYmM8O/AugAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgAClQAAAAOQAAAAAB4AAABUAGEAYgBsAGUAUwB0AHkAbABlAEQAYQByAGsAOAABAQAAAAADYgAAAAQJAAAAAgEbAAQHAAAABAkAAAACAQoABAYAAAAECQAAAAIBGgAEBQAAAAQJAAAAAgEBAAQEAAAABAkAAAACAQsABAMAAAAECQAAAAIBBQAEAgAAAAQJAAAAAgECAAQBAAAAAG8CAAABfQEAAAscAAAAAhcAAAAAEgAAAAENAAAAAgEJAwUA/X/+P//PvwscAAAAAhcAAAAAEgAAAAENAAAAAgEJAwUA/X/+P//PvwtDAAAAAREAAAAEDAAAAAAGAwAAAAIBAAEBBgIXAAAAABIAAAABDQAAAAIBCQMFAP1//j//z78DDAAAAAABAQEGAwAAAAIBAAtDAAAAAREAAAACDAAAAAAGAwAAAAIBAAEBBgIXAAAAABIAAAABDQAAAAIBCQMFAP1//j//z78DDAAAAAABAQEGAwAAAAIBAAtDAAAAAREAAAAFDAAAAAAGAwAAAAIBAAEBBgIXAAAAABIAAAABDQAAAAIBCQMFAP9//7//378DDAAAAAABAQEGAwAAAAIBAAs5AAAAAREAAAAADAAAAAAGAwAAAAIBAAEBBgINAAAAAAgAAAABAwAAAAIBAQMMAAAAAAEBAQYDAAAAAgEACyAAAAACDQAAAAAIAAAAAQMAAAACAQkDCQAAAAEGAwAAAAIBAALoAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApUAAAADkAAAAAAeAAAAVABhAGIAbABlAFMAdAB5AGwAZQBEAGEAcgBrADcAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAABvAgAAAX0BAAALHAAAAAIXAAAAABIAAAABDQAAAAIBCAMFAP1//j//z78LHAAAAAIXAAAAABIAAAABDQAAAAIBCAMFAP1//j//z78LQwAAAAERAAAABAwAAAAABgMAAAACAQABAQYCFwAAAAASAAAAAQ0AAAACAQgDBQD9f/4//8+/AwwAAAAAAQEBBgMAAAACAQALQwAAAAERAAAAAgwAAAAABgMAAAACAQABAQYCFwAAAAASAAAAAQ0AAAACAQgDBQD9f/4//8+/AwwAAAAAAQEBBgMAAAACAQALQwAAAAERAAAABQwAAAAABgMAAAACAQABAQYCFwAAAAASAAAAAQ0AAAACAQgDBQD/f/+//9+/AwwAAAAAAQEBBgMAAAACAQALOQAAAAERAAAAAAwAAAAABgMAAAACAQABAQYCDQAAAAAIAAAAAQMAAAACAQEDDAAAAAABAQEGAwAAAAIBAAsgAAAAAg0AAAAACAAAAAEDAAAAAgEIAwkAAAABBgMAAAACAQAC6AAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKVAAAAA5AAAAAAHgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUARABhAHIAawA2AAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAbwIAAAF9AQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQcDBQD9f/4//8+/CxwAAAACFwAAAAASAAAAAQ0AAAACAQcDBQD9f/4//8+/C0MAAAABEQAAAAQMAAAAAAYDAAAAAgEAAQEGAhcAAAAAEgAAAAENAAAAAgEHAwUA/X/+P//PvwMMAAAAAAEBAQYDAAAAAgEAC0MAAAABEQAAAAIMAAAAAAYDAAAAAgEAAQEGAhcAAAAAEgAAAAENAAAAAgEHAwUA/X/+P//PvwMMAAAAAAEBAQYDAAAAAgEAC0MAAAABEQAAAAUMAAAAAAYDAAAAAgEAAQEGAhcAAAAAEgAAAAENAAAAAgEHAwUA/3//v//fvwMMAAAAAAEBAQYDAAAAAgEACzkAAAABEQAAAAAMAAAAAAYDAAAAAgEAAQEGAg0AAAAACAAAAAEDAAAAAgEBAwwAAAAAAQEBBgMAAAACAQALIAAAAAINAAAAAAgAAAABAwAAAAIBBwMJAAAAAQYDAAAAAgEAAugAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgAClQAAAAOQAAAAAB4AAABUAGEAYgBsAGUAUwB0AHkAbABlAEQAYQByAGsANQABAQAAAAADYgAAAAQJAAAAAgEbAAQHAAAABAkAAAACAQoABAYAAAAECQAAAAIBGgAEBQAAAAQJAAAAAgEBAAQEAAAABAkAAAACAQsABAMAAAAECQAAAAIBBQAEAgAAAAQJAAAAAgECAAQBAAAAAG8CAAABfQEAAAscAAAAAhcAAAAAEgAAAAENAAAAAgEGAwUA/X/+P//PvwscAAAAAhcAAAAAEgAAAAENAAAAAgEGAwUA/X/+P//PvwtDAAAAAREAAAAEDAAAAAAGAwAAAAIBAAEBBgIXAAAAABIAAAABDQAAAAIBBgMFAP1//j//z78DDAAAAAABAQEGAwAAAAIBAAtDAAAAAREAAAACDAAAAAAGAwAAAAIBAAEBBgIXAAAAABIAAAABDQAAAAIBBgMFAP1//j//z78DDAAAAAABAQEGAwAAAAIBAAtDAAAAAREAAAAFDAAAAAAGAwAAAAIBAAEBBgIXAAAAABIAAAABDQAAAAIBBgMFAP9//7//378DDAAAAAABAQEGAwAAAAIBAAs5AAAAAREAAAAADAAAAAAGAwAAAAIBAAEBBgINAAAAAAgAAAABAwAAAAIBAQMMAAAAAAEBAQYDAAAAAgEACyAAAAACDQAAAAAIAAAAAQMAAAACAQYDCQAAAAEGAwAAAAIBAALoAAAAACIAAABUAGEAYgBsAGUAUwB0AHkAbABlAE0AZQBkAGkAdQBtADkAASIAAABQAGkAdgBvAHQAUwB0AHkAbABlAEwAaQBnAGgAdAAxADYAApUAAAADkAAAAAAeAAAAVABhAGIAbABlAFMAdAB5AGwAZQBEAGEAcgBrADQAAQEAAAAAA2IAAAAECQAAAAIBGwAEBwAAAAQJAAAAAgEKAAQGAAAABAkAAAACARoABAUAAAAECQAAAAIBAQAEBAAAAAQJAAAAAgELAAQDAAAABAkAAAACAQUABAIAAAAECQAAAAIBAgAEAQAAAABvAgAAAX0BAAALHAAAAAIXAAAAABIAAAABDQAAAAIBBQMFAP1//j//z78LHAAAAAIXAAAAABIAAAABDQAAAAIBBQMFAP1//j//z78LQwAAAAERAAAABAwAAAAABgMAAAACAQABAQYCFwAAAAASAAAAAQ0AAAACAQUDBQD9f/4//8+/AwwAAAAAAQEBBgMAAAACAQALQwAAAAERAAAAAgwAAAAABgMAAAACAQABAQYCFwAAAAASAAAAAQ0AAAACAQUDBQD9f/4//8+/AwwAAAAAAQEBBgMAAAACAQALQwAAAAERAAAABQwAAAAABgMAAAACAQABAQYCFwAAAAASAAAAAQ0AAAACAQUDBQD/f/+//9+/AwwAAAAAAQEBBgMAAAACAQALOQAAAAERAAAAAAwAAAAABgMAAAACAQABAQYCDQAAAAAIAAAAAQMAAAACAQEDDAAAAAABAQEGAwAAAAIBAAsgAAAAAg0AAAAACAAAAAEDAAAAAgEFAwkAAAABBgMAAAACAQAC6AAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKVAAAAA5AAAAAAHgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUARABhAHIAawAzAAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAAAbwIAAAF9AQAACxwAAAACFwAAAAASAAAAAQ0AAAACAQQDBQD9f/4//8+/CxwAAAACFwAAAAASAAAAAQ0AAAACAQQDBQD9f/4//8+/C0MAAAABEQAAAAQMAAAAAAYDAAAAAgEAAQEGAhcAAAAAEgAAAAENAAAAAgEEAwUA/X/+P//PvwMMAAAAAAEBAQYDAAAAAgEAC0MAAAABEQAAAAIMAAAAAAYDAAAAAgEAAQEGAhcAAAAAEgAAAAENAAAAAgEEAwUA/X/+P//PvwMMAAAAAAEBAQYDAAAAAgEAC0MAAAABEQAAAAUMAAAAAAYDAAAAAgEAAQEGAhcAAAAAEgAAAAENAAAAAgEEAwUA/3//v//fvwMMAAAAAAEBAQYDAAAAAgEACzkAAAABEQAAAAAMAAAAAAYDAAAAAgEAAQEGAg0AAAAACAAAAAEDAAAAAgEBAwwAAAAAAQEBBgMAAAACAQALIAAAAAINAAAAAAgAAAABAwAAAAIBBAMJAAAAAQYDAAAAAgEAAugAAAAAIgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUATQBlAGQAaQB1AG0AOQABIgAAAFAAaQB2AG8AdABTAHQAeQBsAGUATABpAGcAaAB0ADEANgAClQAAAAOQAAAAAB4AAABUAGEAYgBsAGUAUwB0AHkAbABlAEQAYQByAGsAMgABAQAAAAADYgAAAAQJAAAAAgEbAAQHAAAABAkAAAACAQoABAYAAAAECQAAAAIBGgAEBQAAAAQJAAAAAgEBAAQEAAAABAkAAAACAQsABAMAAAAECQAAAAIBBQAEAgAAAAQJAAAAAgECAAQBAAAAAHkCAAABhwEAAAscAAAAAhcAAAAAEgAAAAENAAAAAgEBAwUA/X/+P//PPwscAAAAAhcAAAAAEgAAAAENAAAAAgEBAwUA/X/+P//PPwtDAAAAAREAAAAEDAAAAAAGAwAAAAIBAAEBBgIXAAAAABIAAAABDQAAAAIBAQMFAP1//j//zz8DDAAAAAABAQEGAwAAAAIBAAtDAAAAAREAAAACDAAAAAAGAwAAAAIBAAEBBgIXAAAAABIAAAABDQAAAAIBAQMFAP1//j//zz8DDAAAAAABAQEGAwAAAAIBAAtDAAAAAREAAAAFDAAAAAAGAwAAAAIBAAEBBgIXAAAAABIAAAABDQAAAAIBAQMFmsxMZiYzwz8DDAAAAAABAQEGAwAAAAIBAAs5AAAAAREAAAAADAAAAAAGAwAAAAIBAAEBBgINAAAAAAgAAAABAwAAAAIBAQMMAAAAAAEBAQYDAAAAAgEACyoAAAACFwAAAAASAAAAAQ0AAAACAQEDBeYyc5m5zNw/AwkAAAABBgMAAAACAQAC6AAAAAAiAAAAVABhAGIAbABlAFMAdAB5AGwAZQBNAGUAZABpAHUAbQA5AAEiAAAAUABpAHYAbwB0AFMAdAB5AGwAZQBMAGkAZwBoAHQAMQA2AAKVAAAAA5AAAAAAHgAAAFQAYQBiAGwAZQBTAHQAeQBsAGUARABhAHIAawAxAAEBAAAAAANiAAAABAkAAAACARsABAcAAAAECQAAAAIBCgAEBgAAAAQJAAAAAgEaAAQFAAAABAkAAAACAQEABAQAAAAECQAAAAIBCwAEAwAAAAQJAAAAAgEFAAQCAAAABAkAAAACAQIABAEAAAA="; var dstLen = sStyles.length; var pointer = g_memory.Alloc(dstLen); var stream = new FT_Stream2(pointer.data, dstLen); stream.obj = pointer.obj; var bcr = new Binary_CommonReader(stream); var oBinaryFileReader = new BinaryFileReader(""); oBinaryFileReader.getbase64DecodedData2(sStyles, 0, stream, 0); var oBinary_StylesTableReader = new Binary_StylesTableReader(stream, wb, [], []); var fReadStyle = function(type, length, oTableStyles, oOutputName) { var res = c_oSerConstants.ReadOk; if ( Types.Dxf == type ) { //потому что в presetTableStyles.xml в отличии от custom стилей, индексы начинаются с 1 oOutputName.dxfs.push(null); res = bcr.Read1(length, function(t,l){ return oBinary_StylesTableReader.ReadDxfs(t,l,oOutputName.dxfs); }); } else if ( Types.tableStyles == type ) { res = bcr.Read1(length, function(t,l){ return oBinary_StylesTableReader.ReadTableStyles(t,l, oTableStyles, oOutputName.customStyle); }); } else res = c_oSerConstants.ReadUnknown; return res; }; var fReadStyles = function(type, length, oOutput) { var res = c_oSerConstants.ReadOk; if ( Types.Style == type ) { var oTableStyles = new CTableStyles(); var oOutputName = {customStyle: {}, dxfs: []}; res = bcr.Read1(length, function(t,l){ return fReadStyle(t,l, oTableStyles, oOutputName); }); for(var i in oOutputName.customStyle) { var customStyle = oOutputName.customStyle[i]; var oNewStyle = customStyle.style; oBinary_StylesTableReader.initTableStyle(oNewStyle, customStyle.elements, oOutputName.dxfs); oOutput[oNewStyle.name] = oNewStyle; } } else res = c_oSerConstants.ReadUnknown; return res; }; var length = stream.GetULongLE(); var res = bcr.Read1(length, function(t,l){ return fReadStyles(t, l, oOutput); }); } function ReadDefCellStyles(wb, oOutput) { var Types = { Style : 0, BuiltinId : 1, Hidden : 2, CellStyle : 3, Xfs : 4, Font : 5, Fill : 6, Border : 7, NumFmts : 8 }; var sStyles = "2TEAAACdAAAAAQQAAAAAAAAAAyMAAAAABAAAAAAAAAAEDAAAAE4AbwByAG0AYQBsAAUEAAAAAAAAAAQYAAAABgQAAAAABwQAAAAACAQAAAAACQQAAAAABScAAAABBgMAAAACAQEEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGAAAAAAcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAACyAAAAAQQAAAAcAAAAAxwAAAAEDgAAAE4AZQB1AHQAcgBhAGwABQQAAAABAAAABCEAAAAAAQABAQAEAQAGBAAAAAAHBAIAAAAIBAEAAAAJBAAAAAAFKgAAAAEGBgAAAAAEAGWc/wQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYQAAAAAAsAAAABBgAAAAAEnOv//wcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAACqAAAAAQQAAAAbAAAAAxQAAAAEBgAAAEIAYQBkAAUEAAAAAQAAAAQhAAAAAAEAAQEABAEABgQAAAAABwQCAAAACAQBAAAACQQAAAAABSoAAAABBgYAAAAABAYAnP8EBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGEAAAAAALAAAAAQYAAAAABM7H//8HGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAArAAAAAEEAAAAGgAAAAMWAAAABAgAAABHAG8AbwBkAAUEAAAAAQAAAAQhAAAAAAEAAQEABAEABgQAAAAABwQCAAAACAQBAAAACQQAAAAABSoAAAABBgYAAAAABABhAP8EBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGEAAAAAALAAAAAQYAAAAABM7vxv8HGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAA5wAAAAEEAAAAFAAAAAMYAAAABAoAAABJAG4AcAB1AHQABQQAAAABAAAABB4AAAAAAQAEAQAGBAEAAAAHBAIAAAAIBAEAAAAJBAAAAAAFKgAAAAEGBgAAAAAEdj8//wQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYQAAAAAAsAAAABBgAAAAAEmcz//wdVAAAAAA8AAAAABgYAAAAABH9/f/8BAQ0BAAAAAAIPAAAAAAYGAAAAAAR/f3//AQENBA8AAAAABgYAAAAABH9/f/8BAQ0FDwAAAAAGBgAAAAAEf39//wEBDQDsAAAAAQQAAAAVAAAAAxoAAAAEDAAAAE8AdQB0AHAAdQB0AAUEAAAAAQAAAAQeAAAAAAEABAEABgQBAAAABwQCAAAACAQBAAAACQQAAAAABS0AAAAAAQEBBgYAAAAABD8/P/8EBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGEAAAAAALAAAAAQYAAAAABPLy8v8HVQAAAAAPAAAAAAYGAAAAAAQ/Pz//AQENAQAAAAACDwAAAAAGBgAAAAAEPz8//wEBDQQPAAAAAAYGAAAAAAQ/Pz//AQENBQ8AAAAABgYAAAAABD8/P/8BAQ0A9gAAAAEEAAAAFgAAAAMkAAAABBYAAABDAGEAbABjAHUAbABhAHQAaQBvAG4ABQQAAAABAAAABB4AAAAAAQAEAQAGBAEAAAAHBAIAAAAIBAEAAAAJBAAAAAAFLQAAAAABAQEGBgAAAAAEAH36/wQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYQAAAAAAsAAAABBgAAAAAE8vLy/wdVAAAAAA8AAAAABgYAAAAABH9/f/8BAQ0BAAAAAAIPAAAAAAYGAAAAAAR/f3//AQENBA8AAAAABgYAAAAABH9/f/8BAQ0FDwAAAAAGBgAAAAAEf39//wEBDQDxAAAAAQQAAAAXAAAAAyIAAAAEFAAAAEMAaABlAGMAawAgAEMAZQBsAGwABQQAAAABAAAABB4AAAAAAQAEAQAGBAEAAAAHBAIAAAAIBAEAAAAJBAAAAAAFKgAAAAABAQEGAwAAAAIBAAQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYQAAAAAAsAAAABBgAAAAAEpaWl/wdVAAAAAA8AAAAABgYAAAAABD8/P/8BAQQBAAAAAAIPAAAAAAYGAAAAAAQ/Pz//AQEEBA8AAAAABgYAAAAABD8/P/8BAQQFDwAAAAAGBgAAAAAEPz8//wEBBAC6AAAAAQQAAAA1AAAAAy4AAAAEIAAAAEUAeABwAGwAYQBuAGEAdABvAHIAeQAgAFQAZQB4AHQABQQAAAABAAAABCQAAAAAAQABAQACAQAEAQAGBAAAAAAHBAAAAAAIBAEAAAAJBAAAAAAFLQAAAAEGBgAAAAAEf39//wMBAQQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYAAAAABxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAOUAAAABBAAAAAoAAAADFgAAAAQIAAAATgBvAHQAZQAFBAAAAAEAAAAEIQAAAAABAAMBAAQBAAYEAQAAAAcEAgAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEBBAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABhAAAAAACwAAAAEGAAAAAATM////B1UAAAAADwAAAAAGBgAAAAAEsrKy/wEBDQEAAAAAAg8AAAAABgYAAAAABLKysv8BAQ0EDwAAAAAGBgAAAAAEsrKy/wEBDQUPAAAAAAYGAAAAAASysrL/AQENALkAAAABBAAAABgAAAADJAAAAAQWAAAATABpAG4AawBlAGQAIABDAGUAbABsAAUEAAAAAQAAAAQhAAAAAAEAAgEABAEABgQBAAAABwQAAAAACAQBAAAACQQAAAAABSoAAAABBgYAAAAABAB9+v8EBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGAAAAAAcoAAAAAA8AAAAABgYAAAAABAGA//8BAQQBAAAAAAIAAAAABAAAAAAFAAAAAACvAAAAAQQAAAALAAAAAyYAAAAEGAAAAFcAYQByAG4AaQBuAGcAIABUAGUAeAB0AAUEAAAAAQAAAAQkAAAAAAEAAQEAAgEABAEABgQAAAAABwQAAAAACAQBAAAACQQAAAAABSoAAAABBgYAAAAABAAA//8EBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGAAAAAAcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAACyAAAAAQQAAAAQAAAAAyAAAAAEEgAAAEgAZQBhAGQAaQBuAGcAIAAxAAUEAAAAAQAAAAQhAAAAAAEAAgEABAEABgQBAAAABwQAAAAACAQBAAAACQQAAAAABSoAAAAAAQEBBgMAAAACAQMEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAALkAGAAAAAAclAAAAAAwAAAAABgMAAAACAQQBAQwBAAAAAAIAAAAABAAAAAAFAAAAAAC8AAAAAQQAAAARAAAAAyAAAAAEEgAAAEgAZQBhAGQAaQBuAGcAIAAyAAUEAAAAAQAAAAQhAAAAAAEAAgEABAEABgQBAAAABwQAAAAACAQBAAAACQQAAAAABSoAAAAAAQEBBgMAAAACAQMEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAKkAGAAAAAAcvAAAAABYAAAAABg0AAAACAQQDBQD/f/+//98/AQEMAQAAAAACAAAAAAQAAAAABQAAAAAAvAAAAAEEAAAAEgAAAAMgAAAABBIAAABIAGUAYQBkAGkAbgBnACAAMwAFBAAAAAEAAAAEIQAAAAABAAIBAAQBAAYEAQAAAAcEAAAAAAgEAQAAAAkEAAAAAAUqAAAAAAEBAQYDAAAAAgEDBAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABgAAAAAHLwAAAAAWAAAAAAYNAAAAAgEEAwXNZGYyM5nZPwEBBgEAAAAAAgAAAAAEAAAAAAUAAAAAAKkAAAABBAAAABMAAAADIAAAAAQSAAAASABlAGEAZABpAG4AZwAgADQABQQAAAABAAAABCQAAAAAAQABAQACAQAEAQAGBAAAAAAHBAAAAAAIBAEAAAAJBAAAAAAFKgAAAAABAQEGAwAAAAIBAwQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYAAAAABxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAALYAAAABBAAAABkAAAADGAAAAAQKAAAAVABvAHQAYQBsAAUEAAAAAQAAAAQhAAAAAAEAAgEABAEABgQBAAAABwQAAAAACAQBAAAACQQAAAAABSoAAAAAAQEBBgMAAAACAQEEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGAAAAAAcxAAAAAAwAAAAABgMAAAACAQQBAQQBAAAAAAIAAAAABAAAAAAFDAAAAAAGAwAAAAIBBAEBDQChAAAAAQQAAAAPAAAAAxgAAAAECgAAAFQAaQB0AGwAZQAFBAAAAAEAAAAEJAAAAAABAAEBAAIBAAQBAAYEAAAAAAcEAAAAAAgEAQAAAAkEAAAAAAUqAAAAAAEBAQYDAAAAAgEDBAYOAAAAQwBhAG0AYgByAGkAYQAGBQAAAAAAADJABgAAAAAHGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAAwgAAAAEEAAAAHgAAAAMoAAAABBoAAAAyADAAJQAgAC0AIABBAGMAYwBlAG4AdAAxAAUEAAAAAQAAAAQhAAAAAAEAAQEABAEABgQAAAAABwQCAAAACAQBAAAACQQAAAAABScAAAABBgMAAAACAQEEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGFwAAAAASAAAAAQ0AAAACAQQDBc1l5jJzmek/BxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAMIAAAABBAAAACIAAAADKAAAAAQaAAAAMgAwACUAIAAtACAAQQBjAGMAZQBuAHQAMgAFBAAAAAEAAAAEIQAAAAABAAEBAAQBAAYEAAAAAAcEAgAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEBBAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABhcAAAAAEgAAAAENAAAAAgEFAwXNZeYyc5npPwcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAADCAAAAAQQAAAAmAAAAAygAAAAEGgAAADIAMAAlACAALQAgAEEAYwBjAGUAbgB0ADMABQQAAAABAAAABCEAAAAAAQABAQAEAQAGBAAAAAAHBAIAAAAIBAEAAAAJBAAAAAAFJwAAAAEGAwAAAAIBAQQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYXAAAAABIAAAABDQAAAAIBBgMFzWXmMnOZ6T8HGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAAwgAAAAEEAAAAKgAAAAMoAAAABBoAAAAyADAAJQAgAC0AIABBAGMAYwBlAG4AdAA0AAUEAAAAAQAAAAQhAAAAAAEAAQEABAEABgQAAAAABwQCAAAACAQBAAAACQQAAAAABScAAAABBgMAAAACAQEEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGFwAAAAASAAAAAQ0AAAACAQcDBc1l5jJzmek/BxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAMIAAAABBAAAAC4AAAADKAAAAAQaAAAAMgAwACUAIAAtACAAQQBjAGMAZQBuAHQANQAFBAAAAAEAAAAEIQAAAAABAAEBAAQBAAYEAAAAAAcEAgAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEBBAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABhcAAAAAEgAAAAENAAAAAgEIAwXNZeYyc5npPwcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAADCAAAAAQQAAAAyAAAAAygAAAAEGgAAADIAMAAlACAALQAgAEEAYwBjAGUAbgB0ADYABQQAAAABAAAABCEAAAAAAQABAQAEAQAGBAAAAAAHBAIAAAAIBAEAAAAJBAAAAAAFJwAAAAEGAwAAAAIBAQQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYXAAAAABIAAAABDQAAAAIBCQMFzWXmMnOZ6T8HGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAAwgAAAAEEAAAAHwAAAAMoAAAABBoAAAA0ADAAJQAgAC0AIABBAGMAYwBlAG4AdAAxAAUEAAAAAQAAAAQhAAAAAAEAAQEABAEABgQAAAAABwQCAAAACAQBAAAACQQAAAAABScAAAABBgMAAAACAQEEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGFwAAAAASAAAAAQ0AAAACAQQDBZrMTGYmM+M/BxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAMIAAAABBAAAACMAAAADKAAAAAQaAAAANAAwACUAIAAtACAAQQBjAGMAZQBuAHQAMgAFBAAAAAEAAAAEIQAAAAABAAEBAAQBAAYEAAAAAAcEAgAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEBBAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABhcAAAAAEgAAAAENAAAAAgEFAwWazExmJjPjPwcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAADCAAAAAQQAAAAnAAAAAygAAAAEGgAAADQAMAAlACAALQAgAEEAYwBjAGUAbgB0ADMABQQAAAABAAAABCEAAAAAAQABAQAEAQAGBAAAAAAHBAIAAAAIBAEAAAAJBAAAAAAFJwAAAAEGAwAAAAIBAQQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYXAAAAABIAAAABDQAAAAIBBgMFmsxMZiYz4z8HGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAAwgAAAAEEAAAAKwAAAAMoAAAABBoAAAA0ADAAJQAgAC0AIABBAGMAYwBlAG4AdAA0AAUEAAAAAQAAAAQhAAAAAAEAAQEABAEABgQAAAAABwQCAAAACAQBAAAACQQAAAAABScAAAABBgMAAAACAQEEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGFwAAAAASAAAAAQ0AAAACAQcDBZrMTGYmM+M/BxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAMIAAAABBAAAAC8AAAADKAAAAAQaAAAANAAwACUAIAAtACAAQQBjAGMAZQBuAHQANQAFBAAAAAEAAAAEIQAAAAABAAEBAAQBAAYEAAAAAAcEAgAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEBBAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABhcAAAAAEgAAAAENAAAAAgEIAwWazExmJjPjPwcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAADCAAAAAQQAAAAzAAAAAygAAAAEGgAAADQAMAAlACAALQAgAEEAYwBjAGUAbgB0ADYABQQAAAABAAAABCEAAAAAAQABAQAEAQAGBAAAAAAHBAIAAAAIBAEAAAAJBAAAAAAFJwAAAAEGAwAAAAIBAQQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYXAAAAABIAAAABDQAAAAIBCQMFmsxMZiYz4z8HGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAAxgAAAAEEAAAAIAAAAAMsAAAABB4AAAA2ADAAJQAgAC0AIABBAGMAYwBlAG4AdAAxACAAMgAFBAAAAAEAAAAEIQAAAAABAAEBAAQBAAYEAAAAAAcEAgAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEABAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABhcAAAAAEgAAAAENAAAAAgEEAwXNZGYyM5nZPwcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAADCAAAAAQQAAAAkAAAAAygAAAAEGgAAADYAMAAlACAALQAgAEEAYwBjAGUAbgB0ADIABQQAAAABAAAABCEAAAAAAQABAQAEAQAGBAAAAAAHBAIAAAAIBAEAAAAJBAAAAAAFJwAAAAEGAwAAAAIBAAQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYXAAAAABIAAAABDQAAAAIBBQMFzWRmMjOZ2T8HGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAAwgAAAAEEAAAAKAAAAAMoAAAABBoAAAA2ADAAJQAgAC0AIABBAGMAYwBlAG4AdAAzAAUEAAAAAQAAAAQhAAAAAAEAAQEABAEABgQAAAAABwQCAAAACAQBAAAACQQAAAAABScAAAABBgMAAAACAQAEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGFwAAAAASAAAAAQ0AAAACAQYDBc1kZjIzmdk/BxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAMIAAAABBAAAACwAAAADKAAAAAQaAAAANgAwACUAIAAtACAAQQBjAGMAZQBuAHQANAAFBAAAAAEAAAAEIQAAAAABAAEBAAQBAAYEAAAAAAcEAgAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEABAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABhcAAAAAEgAAAAENAAAAAgEHAwXNZGYyM5nZPwcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAADCAAAAAQQAAAAwAAAAAygAAAAEGgAAADYAMAAlACAALQAgAEEAYwBjAGUAbgB0ADUABQQAAAABAAAABCEAAAAAAQABAQAEAQAGBAAAAAAHBAIAAAAIBAEAAAAJBAAAAAAFJwAAAAEGAwAAAAIBAAQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYXAAAAABIAAAABDQAAAAIBCAMFzWRmMjOZ2T8HGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAAwgAAAAEEAAAANAAAAAMoAAAABBoAAAA2ADAAJQAgAC0AIABBAGMAYwBlAG4AdAA2AAUEAAAAAQAAAAQhAAAAAAEAAQEABAEABgQAAAAABwQCAAAACAQBAAAACQQAAAAABScAAAABBgMAAAACAQAEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGFwAAAAASAAAAAQ0AAAACAQkDBc1kZjIzmdk/BxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAKwAAAABBAAAAB0AAAADHAAAAAQOAAAAQQBjAGMAZQBuAHQAMQAFBAAAAAEAAAAEIQAAAAABAAEBAAQBAAYEAAAAAAcEAgAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEABAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABg0AAAAACAAAAAEDAAAAAgEEBxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAKwAAAABBAAAACEAAAADHAAAAAQOAAAAQQBjAGMAZQBuAHQAMgAFBAAAAAEAAAAEIQAAAAABAAEBAAQBAAYEAAAAAAcEAgAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEABAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABg0AAAAACAAAAAEDAAAAAgEFBxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAKMAAAADHAAAAAQOAAAAQQBjAGMAZQBuAHQAMwAFBAAAAAEAAAAEIQAAAAABAAEBAAQBAAYEAAAAAAcEAgAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEABAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABg0AAAAACAAAAAEDAAAAAgEGBxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAKwAAAABBAAAACkAAAADHAAAAAQOAAAAQQBjAGMAZQBuAHQANAAFBAAAAAEAAAAEIQAAAAABAAEBAAQBAAYEAAAAAAcEAgAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEABAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABg0AAAAACAAAAAEDAAAAAgEHBxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAKwAAAABBAAAAC0AAAADHAAAAAQOAAAAQQBjAGMAZQBuAHQANQAFBAAAAAEAAAAEIQAAAAABAAEBAAQBAAYEAAAAAAcEAgAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEABAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABg0AAAAACAAAAAEDAAAAAgEIBxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAKwAAAABBAAAADEAAAADHAAAAAQOAAAAQQBjAGMAZQBuAHQANgAFBAAAAAEAAAAEIQAAAAABAAEBAAQBAAYEAAAAAAcEAgAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEABAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABg0AAAAACAAAAAEDAAAAAgEJBxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAADcBAAABBAAAAAQAAAADJwAAAAAEAAAABAAAAAQQAAAAQwB1AHIAcgBlAG4AYwB5AAUEAAAAAQAAAAQkAAAAAAEAAQEAAgEAAwEABgQAAAAABwQAAAAACAQBAAAACQQsAAAABScAAAABBgMAAAACAQEEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGAAAAAAcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAAiFAAAACYAAAAAABnQAAABfACgAIgAkACIAKgAgACMALAAjACMAMAAuADAAMABfACkAOwBfACgAIgAkACIAKgAgAFwAKAAjACwAIwAjADAALgAwADAAXAApADsAXwAoACIAJAAiACoAIAAiAC0AIgA/AD8AXwApADsAXwAoAEAAXwApAAEELAAAAAAvAQAAAQQAAAAHAAAAAy8AAAAABAAAAAcAAAAEGAAAAEMAdQByAHIAZQBuAGMAeQAgAFsAMABdAAUEAAAAAQAAAAQkAAAAAAEAAQEAAgEAAwEABgQAAAAABwQAAAAACAQBAAAACQQqAAAABScAAAABBgMAAAACAQEEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGAAAAAAcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAAh1AAAACXAAAAAABmQAAABfACgAIgAkACIAKgAgACMALAAjACMAMABfACkAOwBfACgAIgAkACIAKgAgAFwAKAAjACwAIwAjADAAXAApADsAXwAoACIAJAAiACoAIAAiAC0AIgBfACkAOwBfACgAQABfACkAAQQqAAAAAKsAAAABBAAAAAUAAAADJQAAAAAEAAAABQAAAAQOAAAAUABlAHIAYwBlAG4AdAAFBAAAAAEAAAAEJAAAAAABAAEBAAIBAAMBAAYEAAAAAAcEAAAAAAgEAQAAAAkECQAAAAUnAAAAAQYDAAAAAgEBBAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABgAAAAAHGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAAHwEAAAEEAAAAAwAAAAMhAAAAAAQAAAADAAAABAoAAABDAG8AbQBtAGEABQQAAAABAAAABCQAAAAAAQABAQACAQADAQAGBAAAAAAHBAAAAAAIBAEAAAAJBCsAAAAFJwAAAAEGAwAAAAIBAQQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYAAAAABxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAACHMAAAAJbgAAAAAGYgAAAF8AKAAqACAAIwAsACMAIwAwAC4AMAAwAF8AKQA7AF8AKAAqACAAXAAoACMALAAjACMAMAAuADAAMABcACkAOwBfACgAKgAgACIALQAiAD8APwBfACkAOwBfACgAQABfACkAAQQrAAAAABcBAAABBAAAAAYAAAADKQAAAAAEAAAABgAAAAQSAAAAQwBvAG0AbQBhACAAWwAwAF0ABQQAAAABAAAABCQAAAAAAQABAQACAQADAQAGBAAAAAAHBAAAAAAIBAEAAAAJBCkAAAAFJwAAAAEGAwAAAAIBAQQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYAAAAABxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAACGMAAAAJXgAAAAAGUgAAAF8AKAAqACAAIwAsACMAIwAwAF8AKQA7AF8AKAAqACAAXAAoACMALAAjACMAMABcACkAOwBfACgAKgAgACIALQAiAF8AKQA7AF8AKABAAF8AKQABBCkAAAAAwwAAAAEEAAAAAQAAAAIBAAAAAQM0AAAAAAQAAAABAAAAAwQAAAAAAAAABBQAAABSAG8AdwBMAGUAdgBlAGwAXwAxAAUEAAAAAQAAAAQkAAAAAAEAAQEAAgEABAEABgQAAAAABwQAAAAACAQBAAAACQQAAAAABSoAAAAAAQEBBgMAAAACAQEEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGAAAAAAcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAADDAAAAAQQAAAABAAAAAgEAAAABAzQAAAAABAAAAAEAAAADBAAAAAEAAAAEFAAAAFIAbwB3AEwAZQB2AGUAbABfADIABQQAAAABAAAABCQAAAAAAQABAQACAQAEAQAGBAAAAAAHBAAAAAAIBAEAAAAJBAAAAAAFKgAAAAEGAwAAAAIBAQMBAQQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYAAAAABxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAMAAAAABBAAAAAEAAAACAQAAAAEDNAAAAAAEAAAAAQAAAAMEAAAAAgAAAAQUAAAAUgBvAHcATABlAHYAZQBsAF8AMwAFBAAAAAEAAAAEJAAAAAABAAEBAAIBAAQBAAYEAAAAAAcEAAAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEBBAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABgAAAAAHGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAAwAAAAAEEAAAAAQAAAAIBAAAAAQM0AAAAAAQAAAABAAAAAwQAAAADAAAABBQAAABSAG8AdwBMAGUAdgBlAGwAXwA0AAUEAAAAAQAAAAQkAAAAAAEAAQEAAgEABAEABgQAAAAABwQAAAAACAQBAAAACQQAAAAABScAAAABBgMAAAACAQEEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGAAAAAAcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAADAAAAAAQQAAAABAAAAAgEAAAABAzQAAAAABAAAAAEAAAADBAAAAAQAAAAEFAAAAFIAbwB3AEwAZQB2AGUAbABfADUABQQAAAABAAAABCQAAAAAAQABAQACAQAEAQAGBAAAAAAHBAAAAAAIBAEAAAAJBAAAAAAFJwAAAAEGAwAAAAIBAQQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYAAAAABxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAMAAAAABBAAAAAEAAAACAQAAAAEDNAAAAAAEAAAAAQAAAAMEAAAABQAAAAQUAAAAUgBvAHcATABlAHYAZQBsAF8ANgAFBAAAAAEAAAAEJAAAAAABAAEBAAIBAAQBAAYEAAAAAAcEAAAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEBBAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABgAAAAAHGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAAwAAAAAEEAAAAAQAAAAIBAAAAAQM0AAAAAAQAAAABAAAAAwQAAAAGAAAABBQAAABSAG8AdwBMAGUAdgBlAGwAXwA3AAUEAAAAAQAAAAQkAAAAAAEAAQEAAgEABAEABgQAAAAABwQAAAAACAQBAAAACQQAAAAABScAAAABBgMAAAACAQEEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGAAAAAAcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAADDAAAAAQQAAAACAAAAAgEAAAABAzQAAAAABAAAAAIAAAADBAAAAAAAAAAEFAAAAEMAbwBsAEwAZQB2AGUAbABfADEABQQAAAABAAAABCQAAAAAAQABAQACAQAEAQAGBAAAAAAHBAAAAAAIBAEAAAAJBAAAAAAFKgAAAAABAQEGAwAAAAIBAQQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYAAAAABxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAMMAAAABBAAAAAIAAAACAQAAAAEDNAAAAAAEAAAAAgAAAAMEAAAAAQAAAAQUAAAAQwBvAGwATABlAHYAZQBsAF8AMgAFBAAAAAEAAAAEJAAAAAABAAEBAAIBAAQBAAYEAAAAAAcEAAAAAAgEAQAAAAkEAAAAAAUqAAAAAQYDAAAAAgEBAwEBBAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABgAAAAAHGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAAwAAAAAEEAAAAAgAAAAIBAAAAAQM0AAAAAAQAAAACAAAAAwQAAAACAAAABBQAAABDAG8AbABMAGUAdgBlAGwAXwAzAAUEAAAAAQAAAAQkAAAAAAEAAQEAAgEABAEABgQAAAAABwQAAAAACAQBAAAACQQAAAAABScAAAABBgMAAAACAQEEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGAAAAAAcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAADAAAAAAQQAAAACAAAAAgEAAAABAzQAAAAABAAAAAIAAAADBAAAAAMAAAAEFAAAAEMAbwBsAEwAZQB2AGUAbABfADQABQQAAAABAAAABCQAAAAAAQABAQACAQAEAQAGBAAAAAAHBAAAAAAIBAEAAAAJBAAAAAAFJwAAAAEGAwAAAAIBAQQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYAAAAABxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAMAAAAABBAAAAAIAAAACAQAAAAEDNAAAAAAEAAAAAgAAAAMEAAAABAAAAAQUAAAAQwBvAGwATABlAHYAZQBsAF8ANQAFBAAAAAEAAAAEJAAAAAABAAEBAAIBAAQBAAYEAAAAAAcEAAAAAAgEAQAAAAkEAAAAAAUnAAAAAQYDAAAAAgEBBAYOAAAAQwBhAGwAaQBiAHIAaQAGBQAAAAAAACZABgAAAAAHGQAAAAAAAAAAAQAAAAACAAAAAAQAAAAABQAAAAAAwAAAAAEEAAAAAgAAAAIBAAAAAQM0AAAAAAQAAAACAAAAAwQAAAAFAAAABBQAAABDAG8AbABMAGUAdgBlAGwAXwA2AAUEAAAAAQAAAAQkAAAAAAEAAQEAAgEABAEABgQAAAAABwQAAAAACAQBAAAACQQAAAAABScAAAABBgMAAAACAQEEBg4AAABDAGEAbABpAGIAcgBpAAYFAAAAAAAAJkAGAAAAAAcZAAAAAAAAAAABAAAAAAIAAAAABAAAAAAFAAAAAADAAAAAAQQAAAACAAAAAgEAAAABAzQAAAAABAAAAAIAAAADBAAAAAYAAAAEFAAAAEMAbwBsAEwAZQB2AGUAbABfADcABQQAAAABAAAABCQAAAAAAQABAQACAQAEAQAGBAAAAAAHBAAAAAAIBAEAAAAJBAAAAAAFJwAAAAEGAwAAAAIBAQQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAYAAAAABxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAAMEAAAABBAAAAAgAAAACAQAAAAEDKQAAAAAEAAAACAAAAAQSAAAASAB5AHAAZQByAGwAaQBuAGsABQQAAAABAAAABC0AAAAAAQABAQACAQAEAQAGBAAAAAAHBAAAAAAIBAEAAAAJBAAAAAANBgMAAAAHAQQFKgAAAAEGAwAAAAIBCgQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAcBAwYAAAAABxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAAANMAAAABBAAAAAkAAAACAQAAAAEDOwAAAAAEAAAACQAAAAQkAAAARgBvAGwAbABvAHcAZQBkACAASAB5AHAAZQByAGwAaQBuAGsABQQAAAABAAAABC0AAAAAAQABAQACAQAEAQAGBAAAAAAHBAAAAAAIBAEAAAAJBAAAAAANBgMAAAAHAQQFKgAAAAEGAwAAAAIBCwQGDgAAAEMAYQBsAGkAYgByAGkABgUAAAAAAAAmQAcBAwYAAAAABxkAAAAAAAAAAAEAAAAAAgAAAAAEAAAAAAUAAAAA"; var dstLen = sStyles.length; var pointer = g_memory.Alloc(dstLen); var stream = new FT_Stream2(pointer.data, dstLen); stream.obj = pointer.obj; var bcr = new Binary_CommonReader(stream); var oBinaryFileReader = new BinaryFileReader(""); oBinaryFileReader.getbase64DecodedData2(sStyles, 0, stream, 0); var oBinary_StylesTableReader = new Binary_StylesTableReader(stream, wb, [], []); var length = stream.GetULongLE(); var fReadStyle = function(type, length, oCellStyle, oStyleObject) { var res = c_oSerConstants.ReadOk; if (Types.BuiltinId === type) { oCellStyle.BuiltinId = stream.GetULongLE(); } else if (Types.Hidden === type) { oCellStyle.Hidden = stream.GetBool(); } else if (Types.CellStyle === type) { res = bcr.Read1(length, function(t, l) { return oBinary_StylesTableReader.ReadCellStyle(t, l, oCellStyle); }); } else if (Types.Xfs === type) { oStyleObject.xfs = {ApplyAlignment: null, ApplyBorder: null, ApplyFill: null, ApplyFont: null, ApplyNumberFormat: null, BorderId: null, FillId: null, FontId: null, NumFmtId: null, QuotePrefix: null, Aligment: null, XfId: null}; res = bcr.Read2Spreadsheet(length, function (t, l) { return oBinary_StylesTableReader.ReadXfs(t, l, oStyleObject.xfs); }); } else if (Types.Font === type) { oStyleObject.font = new Font(); res = bcr.Read2Spreadsheet(length, function (t, l) { return oBinary_StylesTableReader.bssr.ReadRPr(t, l, oStyleObject.font); }); } else if (Types.Fill === type) { oStyleObject.fill = new Fill(); res = bcr.Read1(length, function (t, l) { return oBinary_StylesTableReader.ReadFill(t, l, oStyleObject.fill); }); } else if (Types.Border === type) { oStyleObject.border = new Border(); res = bcr.Read1(length, function (t, l) { return oBinary_StylesTableReader.ReadBorder(t, l, oStyleObject.border); }); } else if (Types.NumFmts === type) { res = bcr.Read1(length, function (t, l) { return oBinary_StylesTableReader.ReadNumFmts(t, l, oStyleObject.oNumFmts); }); } else res = c_oSerConstants.ReadUnknown; return res; }; var fReadStyles = function (type, length, oOutput) { var res = c_oSerConstants.ReadOk; var oStyleObject = {font: null, fill: null, border: null, oNumFmts: [], xfs: null}; if (Types.Style === type) { var oCellStyle = new CCellStyle(); res = bcr.Read1(length, function (t, l) { return fReadStyle(t,l, oCellStyle, oStyleObject); }); oCellStyle.xfs = new CellXfs(); // Border if (null !== oStyleObject.border) oCellStyle.xfs.border = oStyleObject.border.clone(); // Fill if (null !== oStyleObject.fill) oCellStyle.xfs.fill = oStyleObject.fill.clone(); // Font if (null !== oStyleObject.font) oCellStyle.xfs.font = oStyleObject.font.clone(); // NumFmt if (null !== oStyleObject.xfs.numid) { var oCurNum = oStyleObject.oNumFmts[oStyleObject.xfs.numid]; if(null != oCurNum) oCellStyle.xfs.num = oBinary_StylesTableReader.ParseNum(oCurNum, oStyleObject.oNumFmts); else oCellStyle.xfs.num = oBinary_StylesTableReader.ParseNum({id: oStyleObject.xfs.numid, f: null}, oStyleObject.oNumFmts); } // QuotePrefix if(null != oStyleObject.xfs.QuotePrefix) oCellStyle.xfs.QuotePrefix = oStyleObject.xfs.QuotePrefix; // align if(null != oStyleObject.xfs.align) oCellStyle.xfs.align = oStyleObject.xfs.align.clone(); // XfId if (null !== oStyleObject.xfs.XfId) oCellStyle.xfs.XfId = oStyleObject.xfs.XfId; // ApplyBorder (ToDo возможно это свойство должно быть в xfs) if (null !== oStyleObject.xfs.ApplyBorder) oCellStyle.ApplyBorder = oStyleObject.xfs.ApplyBorder; // ApplyFill (ToDo возможно это свойство должно быть в xfs) if (null !== oStyleObject.xfs.ApplyFill) oCellStyle.ApplyFill = oStyleObject.xfs.ApplyFill; // ApplyFont (ToDo возможно это свойство должно быть в xfs) if (null !== oStyleObject.xfs.ApplyFont) oCellStyle.ApplyFont = oStyleObject.xfs.ApplyFont; // ApplyNumberFormat (ToDo возможно это свойство должно быть в xfs) if (null !== oStyleObject.xfs.ApplyNumberFormat) oCellStyle.ApplyNumberFormat = oStyleObject.xfs.ApplyNumberFormat; oOutput.push(oCellStyle); } else res = c_oSerConstants.ReadUnknown; return res; }; var res = bcr.Read1(length, function (t, l) { return fReadStyles(t, l, oOutput); }); // Если нет стилей в документе, то добавим if (0 === wb.CellStyles.CustomStyles.length && 0 < oOutput.length) { wb.CellStyles.CustomStyles.push(oOutput[0].clone()); wb.CellStyles.CustomStyles[0].XfId = 0; } // Если XfId не задан, то определим его if (null == g_oDefaultXfId) { g_oDefaultXfId = 0; } }
git-svn-id: svn://192.168.3.15/activex/AVS/Sources/TeamlabOffice/trunk/OfficeWeb@48309 954022d7-b5bf-4e40-9824-e11837661b57
Excel/model/Serialize.js
<ide><path>xcel/model/Serialize.js <ide> oCellStyle.xfs.QuotePrefix = oCellStyleXfs.QuotePrefix; <ide> // align <ide> if(null != oCellStyleXfs.align) <del> oCellStyle.xfs.align = oCellStyleXfs.clone(); <add> oCellStyle.xfs.align = oCellStyleXfs.align.clone(); <ide> // XfId <ide> if (null !== oCellStyleXfs.XfId) <ide> oCellStyle.xfs.XfId = oCellStyleXfs.XfId;
Java
apache-2.0
cd556b9172e6e7f287c92674a6c4d6fdcada8593
0
Tarensaror/monoblog,Tarensaror/monoblog,Tarensaror/monoblog,Tarensaror/monoblog
package de.hska.lkit.demo.web.redis.repo; import javax.annotation.PostConstruct; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.connection.RedisZSetCommands.Range; import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.ListOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SetOperations; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.ZSetOperations; import org.springframework.data.redis.support.atomic.RedisAtomicLong; import org.springframework.stereotype.Repository; import java.util.UUID; import de.hska.lkit.demo.web.redis.model.UUIDSession; @Repository public class UUIDSessionRepo { private static String KEY_PREFIX_SESSION = "session:"; private static String KEY_PREFIX_USER = "user:"; private static String KEY_PREFIX_NAME = "name:"; private StringRedisTemplate stringRedisTemplate; private RedisTemplate<String, Object> redisTemplate; private HashOperations<String, String, String> srt_hashOps; private SetOperations<String, String> srt_setOps; private ZSetOperations<String, String> srt_zSetOps; @Resource(name="redisTemplate") private HashOperations<String, String, UUIDSession> rt_hashOps; @Autowired public UUIDSessionRepo(RedisTemplate<String, Object> redisTemplate, StringRedisTemplate stringRedisTemplate) { this.redisTemplate = redisTemplate; this.stringRedisTemplate = stringRedisTemplate; } @PostConstruct private void init() { srt_hashOps = stringRedisTemplate.opsForHash(); srt_setOps = stringRedisTemplate.opsForSet(); srt_zSetOps = stringRedisTemplate.opsForZSet(); } public String login(String name, String password) { UUIDSession uuid = new UUIDSession(); uuid.setName(name); uuid.setPassword(password); if (isCorrectLogin(uuid)) { uuid.setUUID(rollUUID()); saveSession(uuid); return uuid.getUUID(); } else { return null; } } public void saveSession(UUIDSession uuid) { /* TODO DB eintrag des Hashs */ String key = KEY_PREFIX_SESSION + uuid.getUUID(); srt_hashOps.put(key, "userid", uuid.getUserID()); //DEBUG System.out.println("I Put the session to key: " + key + " and i wrote " + uuid.getUserID()); } private String rollUUID() { String temp = UUID.randomUUID().toString(); while(isExistingUUID(temp)) { temp = UUID.randomUUID().toString(); } return temp; } public boolean isExistingUUID(String uuid) { // KEY_PREFIX_SESSION + uuid, String StringRedisTemplate foo = new StringRedisTemplate(stringRedisTemplate.getConnectionFactory()); foo.getConnectionFactory(); foo.afterPropertiesSet(); String value = foo.opsForValue().get(KEY_PREFIX_SESSION + uuid); if(foo.hasKey(KEY_PREFIX_SESSION + uuid)) { return false; } else { return true; } } private boolean isCorrectLogin(UUIDSession uuid) { UUIDSession temp = new UUIDSession(); StringRedisTemplate foo = new StringRedisTemplate(stringRedisTemplate.getConnectionFactory()); uuid.setUserID(foo.opsForValue().get(KEY_PREFIX_NAME + uuid.getName())); temp.setName(srt_hashOps.get(KEY_PREFIX_USER + uuid.getUserID(), "name")); temp.setPassword(srt_hashOps.get(KEY_PREFIX_USER + uuid.getUserID(), "password")); if( (temp.getName().equals(uuid.getName())) && (temp.getPassword().equals(uuid.getPassword()))) { return true; } else { return false; } } private boolean isExistingUser(String name) { StringRedisTemplate foo = new StringRedisTemplate(); if(foo.hasKey(foo.opsForValue().get(KEY_PREFIX_NAME + name))) { return false; } else { return true; } } }
spring-web-demo/src/main/java/de/hska/lkit/demo/web/redis/repo/UUIDSessionRepo.java
package de.hska.lkit.demo.web.redis.repo; import javax.annotation.PostConstruct; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.connection.RedisZSetCommands.Range; import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.ListOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SetOperations; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.ZSetOperations; import org.springframework.data.redis.support.atomic.RedisAtomicLong; import org.springframework.stereotype.Repository; import java.util.UUID; import de.hska.lkit.demo.web.redis.model.UUIDSession; @Repository public class UUIDSessionRepo { private static String KEY_PREFIX_SESSION = "session:"; private static String KEY_PREFIX_USER = "user:"; private static String KEY_PREFIX_NAME = "name:"; private StringRedisTemplate stringRedisTemplate; private RedisTemplate<String, Object> redisTemplate; private HashOperations<String, String, String> srt_hashOps; private SetOperations<String, String> srt_setOps; private ZSetOperations<String, String> srt_zSetOps; @Resource(name="redisTemplate") private HashOperations<String, String, UUIDSession> rt_hashOps; @Autowired public UUIDSessionRepo(RedisTemplate<String, Object> redisTemplate, StringRedisTemplate stringRedisTemplate) { this.redisTemplate = redisTemplate; this.stringRedisTemplate = stringRedisTemplate; } @PostConstruct private void init() { srt_hashOps = stringRedisTemplate.opsForHash(); srt_setOps = stringRedisTemplate.opsForSet(); srt_zSetOps = stringRedisTemplate.opsForZSet(); } public String login(String name, String password) { UUIDSession uuid = new UUIDSession(); uuid.setName(name); uuid.setPassword(password); if (isCorrectLogin(uuid)) { uuid.setUUID(rollUUID()); saveSession(uuid); return uuid.getUUID(); } else { return null; } } public void saveSession(UUIDSession uuid) { /* TODO DB eintrag des Hashs */ String key = KEY_PREFIX_SESSION + uuid.getUUID(); srt_hashOps.put(key, "userid", uuid.getUserID()); //DEBUG System.out.println("I Put the session to key: " + key + " and i wrote " + uuid.getUserID()); } private String rollUUID() { String temp = UUID.randomUUID().toString(); while(isExistingUUID(temp)) { temp = UUID.randomUUID().toString(); } return temp; } public boolean isExistingUUID(String uuid) { // KEY_PREFIX_SESSION + uuid, String StringRedisTemplate foo = new StringRedisTemplate(); String value = foo.opsForValue().get(KEY_PREFIX_SESSION + uuid); if(foo.hasKey(KEY_PREFIX_SESSION + uuid)) { return false; } else { return true; } } private boolean isCorrectLogin(UUIDSession uuid) { UUIDSession temp = new UUIDSession(); StringRedisTemplate foo = new StringRedisTemplate(); uuid.setUserID(foo.opsForValue().get(KEY_PREFIX_NAME + uuid.getName())); temp.setName(srt_hashOps.get(KEY_PREFIX_USER + uuid.getUserID(), "name")); temp.setPassword(srt_hashOps.get(KEY_PREFIX_USER + uuid.getUserID(), "password")); if( (temp.getName().equals(uuid.getName())) && (temp.getPassword().equals(uuid.getPassword()))) { return true; } else { return false; } } private boolean isExistingUser(String name) { if(stringRedisTemplate.hasKey(KEY_PREFIX_NAME + name)) { return true; } else { return false; } } }
nihongo desu
spring-web-demo/src/main/java/de/hska/lkit/demo/web/redis/repo/UUIDSessionRepo.java
nihongo desu
<ide><path>pring-web-demo/src/main/java/de/hska/lkit/demo/web/redis/repo/UUIDSessionRepo.java <ide> public boolean isExistingUUID(String uuid) { <ide> // KEY_PREFIX_SESSION + uuid, String <ide> <del> StringRedisTemplate foo = new StringRedisTemplate(); <add> StringRedisTemplate foo = new StringRedisTemplate(stringRedisTemplate.getConnectionFactory()); <add> <add> foo.getConnectionFactory(); <add> foo.afterPropertiesSet(); <add> <ide> String value = foo.opsForValue().get(KEY_PREFIX_SESSION + uuid); <ide> <ide> <ide> <ide> UUIDSession temp = new UUIDSession(); <ide> <del> StringRedisTemplate foo = new StringRedisTemplate(); <add> StringRedisTemplate foo = new StringRedisTemplate(stringRedisTemplate.getConnectionFactory()); <add> <ide> uuid.setUserID(foo.opsForValue().get(KEY_PREFIX_NAME + uuid.getName())); <ide> <ide> temp.setName(srt_hashOps.get(KEY_PREFIX_USER + uuid.getUserID(), "name")); <ide> <ide> private boolean isExistingUser(String name) { <ide> <del> if(stringRedisTemplate.hasKey(KEY_PREFIX_NAME + name)) { <del> return true; <add> StringRedisTemplate foo = new StringRedisTemplate(); <add> <add> <add> <add> if(foo.hasKey(foo.opsForValue().get(KEY_PREFIX_NAME + name))) { <add> return false; <ide> } else { <del> return false; <add> return true; <ide> } <del> } <add> } <ide> }
Java
apache-2.0
318adc583870549cae3478e58d9e250214f467fa
0
linkedin/gobblin,chavdar/gobblin-1,linkedin/gobblin,ibuenros/gobblin,ibuenros/gobblin,arjun4084346/gobblin,jinhyukchang/gobblin,shirshanka/gobblin,ydailinkedin/gobblin-1,ydailinkedin/gobblin-1,ydailinkedin/gobblin-1,arjun4084346/gobblin,ydailinkedin/gobblin-1,ydai1124/gobblin-1,sahilTakiar/gobblin,jack-moseley/gobblin,shirshanka/gobblin,aditya1105/gobblin,ibuenros/gobblin,linkedin/gobblin,mwol/gobblin,jinhyukchang/gobblin,linkedin/gobblin,aditya1105/gobblin,aditya1105/gobblin,mwol/gobblin,chavdar/gobblin-1,jinhyukchang/gobblin,ibuenros/gobblin,jack-moseley/gobblin,pcadabam/gobblin,lbendig/gobblin,lbendig/gobblin,pcadabam/gobblin,arjun4084346/gobblin,abti/gobblin,jenniferzheng/gobblin,ydai1124/gobblin-1,mwol/gobblin,aditya1105/gobblin,lbendig/gobblin,jenniferzheng/gobblin,jenniferzheng/gobblin,aditya1105/gobblin,jinhyukchang/gobblin,linkedin/gobblin,abti/gobblin,arjun4084346/gobblin,ydai1124/gobblin-1,aditya1105/gobblin,pcadabam/gobblin,sahilTakiar/gobblin,jenniferzheng/gobblin,abti/gobblin,jenniferzheng/gobblin,ydailinkedin/gobblin-1,shirshanka/gobblin,lbendig/gobblin,jinhyukchang/gobblin,jack-moseley/gobblin,jenniferzheng/gobblin,ydai1124/gobblin-1,sahilTakiar/gobblin,pcadabam/gobblin,ibuenros/gobblin,sahilTakiar/gobblin,chavdar/gobblin-1,sahilTakiar/gobblin,abti/gobblin,ydai1124/gobblin-1,arjun4084346/gobblin,pcadabam/gobblin,pcadabam/gobblin,lbendig/gobblin,chavdar/gobblin-1,jack-moseley/gobblin,jack-moseley/gobblin,mwol/gobblin,jinhyukchang/gobblin,linkedin/gobblin,mwol/gobblin,sahilTakiar/gobblin,abti/gobblin,chavdar/gobblin-1,ibuenros/gobblin,abti/gobblin,chavdar/gobblin-1,shirshanka/gobblin,shirshanka/gobblin,mwol/gobblin,lbendig/gobblin,ydai1124/gobblin-1
/* * Copyright (C) 2014-2016 LinkedIn Corp. 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. */ package gobblin.scheduler; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.nio.file.Files; import java.util.Properties; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.base.Function; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.common.util.concurrent.ServiceManager; import gobblin.configuration.ConfigurationKeys; import gobblin.testing.AssertWithBackoff; /** * Unit tests for the job configuration file monitor in {@link gobblin.scheduler.JobScheduler}. * * @author Yinan Li */ @Test(groups = {"gobblin.scheduler"}) public class JobConfigFileMonitorTest { private static final String JOB_CONFIG_FILE_DIR = "gobblin-test/resource/job-conf"; private String jobConfigDir; private ServiceManager serviceManager; private JobScheduler jobScheduler; private File newJobConfigFile; private class GetNumScheduledJobs implements Function<Void, Integer> { @Override public Integer apply(Void input) { return JobConfigFileMonitorTest.this.jobScheduler.getScheduledJobs().size(); } } @BeforeClass public void setUp() throws Exception { this.jobConfigDir = Files.createTempDirectory(String.format("gobblin-test_%s_job-conf", this.getClass().getSimpleName())) .toString(); FileUtils.forceDeleteOnExit(new File(this.jobConfigDir)); FileUtils.copyDirectory(new File(JOB_CONFIG_FILE_DIR), new File(jobConfigDir)); Properties properties = new Properties(); try (Reader schedulerPropsReader = new FileReader("gobblin-test/resource/gobblin.test.properties")) { properties.load(schedulerPropsReader); } properties.setProperty(ConfigurationKeys.JOB_CONFIG_FILE_DIR_KEY, jobConfigDir); properties.setProperty(ConfigurationKeys.JOB_CONFIG_FILE_GENERAL_PATH_KEY, jobConfigDir); properties.setProperty(ConfigurationKeys.JOB_CONFIG_FILE_MONITOR_POLLING_INTERVAL_KEY, "1000"); properties.setProperty(ConfigurationKeys.METRICS_ENABLED_KEY, "false"); SchedulerService quartzService = new SchedulerService(new Properties()); this.jobScheduler = new JobScheduler(properties, quartzService); this.serviceManager = new ServiceManager(Lists.newArrayList(quartzService, this.jobScheduler)); this.serviceManager.startAsync().awaitHealthy(10, TimeUnit.SECONDS);; } @Test public void testAddNewJobConfigFile() throws Exception { final Logger log = LoggerFactory.getLogger("testAddNewJobConfigFile"); log.info("testAddNewJobConfigFile: start"); AssertWithBackoff assertWithBackoff = AssertWithBackoff.create().logger(log).timeoutMs(15000); assertWithBackoff.assertEquals(new GetNumScheduledJobs(), 3, "3 scheduled jobs"); /* Set a time gap, to let the monitor recognize the "3-file" status as old status, so that new added file can be discovered */ Thread.sleep(1000); // Create a new job configuration file by making a copy of an existing // one and giving a different job name Properties jobProps = new Properties(); jobProps.load(new FileReader(new File(this.jobConfigDir, "GobblinTest1.pull"))); jobProps.setProperty(ConfigurationKeys.JOB_NAME_KEY, "Gobblin-test-new"); this.newJobConfigFile = new File(this.jobConfigDir, "Gobblin-test-new.pull"); jobProps.store(new FileWriter(this.newJobConfigFile), null); assertWithBackoff.assertEquals(new GetNumScheduledJobs(), 4, "4 scheduled jobs"); Set<String> jobNames = Sets.newHashSet(this.jobScheduler.getScheduledJobs()); Set<String> expectedJobNames = ImmutableSet.<String>builder() .add("GobblinTest1", "GobblinTest2", "GobblinTest3", "Gobblin-test-new") .build(); Assert.assertEquals(jobNames, expectedJobNames); log.info("testAddNewJobConfigFile: end"); } @Test(dependsOnMethods = {"testAddNewJobConfigFile"}) public void testChangeJobConfigFile() throws Exception { final Logger log = LoggerFactory.getLogger("testChangeJobConfigFile"); log.info("testChangeJobConfigFile: start"); Assert.assertEquals(this.jobScheduler.getScheduledJobs().size(), 4); // Make a change to the new job configuration file Properties jobProps = new Properties(); jobProps.load(new FileReader(this.newJobConfigFile)); jobProps.setProperty(ConfigurationKeys.JOB_COMMIT_POLICY_KEY, "partial"); jobProps.setProperty(ConfigurationKeys.JOB_NAME_KEY, "Gobblin-test-new2"); jobProps.store(new FileWriter(this.newJobConfigFile), null); AssertWithBackoff.create() .logger(log) .timeoutMs(30000) .assertEquals(new GetNumScheduledJobs(), 4, "4 scheduled jobs"); final Set<String> expectedJobNames = ImmutableSet.<String>builder() .add("GobblinTest1", "GobblinTest2", "GobblinTest3", "Gobblin-test-new2") .build(); AssertWithBackoff.create() .logger(log) .timeoutMs(30000) .assertEquals(new Function<Void, Set<String>>() { @Override public Set<String> apply(Void input) { return Sets.newHashSet(JobConfigFileMonitorTest.this.jobScheduler.getScheduledJobs()); } }, expectedJobNames, "Job change detected"); log.info("testChangeJobConfigFile: end"); } @Test(dependsOnMethods = {"testChangeJobConfigFile"}) public void testUnscheduleJob() throws Exception { final Logger log = LoggerFactory.getLogger("testUnscheduleJob"); log.info("testUnscheduleJob: start"); Assert.assertEquals(this.jobScheduler.getScheduledJobs().size(), 4); // Disable the new job by setting job.disabled=true Properties jobProps = new Properties(); jobProps.load(new FileReader(this.newJobConfigFile)); jobProps.setProperty(ConfigurationKeys.JOB_DISABLED_KEY, "true"); jobProps.store(new FileWriter(this.newJobConfigFile), null); AssertWithBackoff.create() .logger(log) .timeoutMs(7500) .assertEquals(new GetNumScheduledJobs(), 3, "3 scheduled jobs"); Set<String> jobNames = Sets.newHashSet(this.jobScheduler.getScheduledJobs()); Assert.assertEquals(jobNames.size(), 3); Assert.assertTrue(jobNames.contains("GobblinTest1")); Assert.assertTrue(jobNames.contains("GobblinTest2")); Assert.assertTrue(jobNames.contains("GobblinTest3")); log.info("testUnscheduleJob: end"); } @AfterClass public void tearDown() throws TimeoutException, IOException { if (jobConfigDir != null) { FileUtils.forceDelete(new File(jobConfigDir)); } this.serviceManager.stopAsync().awaitStopped(30, TimeUnit.SECONDS); } }
gobblin-runtime/src/test/java/gobblin/scheduler/JobConfigFileMonitorTest.java
/* * Copyright (C) 2014-2016 LinkedIn Corp. 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. */ package gobblin.scheduler; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.nio.file.Files; import java.util.Properties; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.base.Function; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.common.util.concurrent.ServiceManager; import gobblin.configuration.ConfigurationKeys; import gobblin.testing.AssertWithBackoff; /** * Unit tests for the job configuration file monitor in {@link gobblin.scheduler.JobScheduler}. * * @author Yinan Li */ @Test(groups = {"gobblin.scheduler"}) public class JobConfigFileMonitorTest { private static final String JOB_CONFIG_FILE_DIR = "gobblin-test/resource/job-conf"; private String jobConfigDir; private ServiceManager serviceManager; private JobScheduler jobScheduler; private File newJobConfigFile; private class GetNumScheduledJobs implements Function<Void, Integer> { @Override public Integer apply(Void input) { return JobConfigFileMonitorTest.this.jobScheduler.getScheduledJobs().size(); } } @BeforeClass public void setUp() throws Exception { this.jobConfigDir = Files.createTempDirectory(String.format("gobblin-test_%s_job-conf", this.getClass().getSimpleName())) .toString(); FileUtils.forceDeleteOnExit(new File(this.jobConfigDir)); FileUtils.copyDirectory(new File(JOB_CONFIG_FILE_DIR), new File(jobConfigDir)); Properties properties = new Properties(); try (Reader schedulerPropsReader = new FileReader("gobblin-test/resource/gobblin.test.properties")) { properties.load(schedulerPropsReader); } properties.setProperty(ConfigurationKeys.JOB_CONFIG_FILE_DIR_KEY, jobConfigDir); properties.setProperty(ConfigurationKeys.JOB_CONFIG_FILE_GENERAL_PATH_KEY, jobConfigDir); properties.setProperty(ConfigurationKeys.JOB_CONFIG_FILE_MONITOR_POLLING_INTERVAL_KEY, "1000"); properties.setProperty(ConfigurationKeys.METRICS_ENABLED_KEY, "false"); SchedulerService quartzService = new SchedulerService(new Properties()); this.jobScheduler = new JobScheduler(properties, quartzService); this.serviceManager = new ServiceManager(Lists.newArrayList(quartzService, this.jobScheduler)); this.serviceManager.startAsync().awaitHealthy(10, TimeUnit.SECONDS);; } @Test public void testAddNewJobConfigFile() throws Exception { final Logger log = LoggerFactory.getLogger("testAddNewJobConfigFile"); log.info("testAddNewJobConfigFile: start"); AssertWithBackoff assertWithBackoff = AssertWithBackoff.create().logger(log).timeoutMs(15000); assertWithBackoff.assertEquals(new GetNumScheduledJobs(), 3, "3 scheduled jobs"); /* Set a time gap, to let the monitor recognize the "3-file" status as old status, so that new added file can be discovered */ Thread.sleep(1000); // Create a new job configuration file by making a copy of an existing // one and giving a different job name Properties jobProps = new Properties(); jobProps.load(new FileReader(new File(this.jobConfigDir, "GobblinTest1.pull"))); jobProps.setProperty(ConfigurationKeys.JOB_NAME_KEY, "Gobblin-test-new"); this.newJobConfigFile = new File(this.jobConfigDir, "Gobblin-test-new.pull"); jobProps.store(new FileWriter(this.newJobConfigFile), null); assertWithBackoff.assertEquals(new GetNumScheduledJobs(), 4, "4 scheduled jobs"); Set<String> jobNames = Sets.newHashSet(this.jobScheduler.getScheduledJobs()); Set<String> expectedJobNames = ImmutableSet.<String>builder() .add("GobblinTest1", "GobblinTest2", "GobblinTest3", "Gobblin-test-new") .build(); Assert.assertEquals(jobNames, expectedJobNames); log.info("testAddNewJobConfigFile: end"); } @Test(dependsOnMethods = {"testAddNewJobConfigFile"}) public void testChangeJobConfigFile() throws Exception { final Logger log = LoggerFactory.getLogger("testChangeJobConfigFile"); log.info("testChangeJobConfigFile: start"); Assert.assertEquals(this.jobScheduler.getScheduledJobs().size(), 4); // Make a change to the new job configuration file Properties jobProps = new Properties(); jobProps.load(new FileReader(this.newJobConfigFile)); jobProps.setProperty(ConfigurationKeys.JOB_COMMIT_POLICY_KEY, "partial"); jobProps.setProperty(ConfigurationKeys.JOB_NAME_KEY, "Gobblin-test-new2"); jobProps.store(new FileWriter(this.newJobConfigFile), null); AssertWithBackoff.create() .logger(log) .timeoutMs(30000) .assertEquals(new GetNumScheduledJobs(), 4, "4 scheduled jobs"); final Set<String> expectedJobNames = ImmutableSet.<String>builder() .add("GobblinTest1", "GobblinTest2", "GobblinTest3", "Gobblin-test-new2") .build(); AssertWithBackoff.create() .logger(log) .timeoutMs(30000) .assertEquals(new Function<Void, Set<String>>() { @Override public Set<String> apply(Void input) { return Sets.newHashSet(JobConfigFileMonitorTest.this.jobScheduler.getScheduledJobs()); } }, expectedJobNames, "Job change detected"); log.info("testChangeJobConfigFile: end"); } @Test(dependsOnMethods = {"testChangeJobConfigFile"}) public void testUnscheduleJob() throws Exception { final Logger log = LoggerFactory.getLogger("testUnscheduleJob"); log.info("testUnscheduleJob: start"); Assert.assertEquals(this.jobScheduler.getScheduledJobs().size(), 4); // Disable the new job by setting job.disabled=true Properties jobProps = new Properties(); jobProps.load(new FileReader(this.newJobConfigFile)); jobProps.setProperty(ConfigurationKeys.JOB_DISABLED_KEY, "true"); jobProps.store(new FileWriter(this.newJobConfigFile), null); AssertWithBackoff.create() .logger(log) .timeoutMs(7500) .assertEquals(new GetNumScheduledJobs(), 3, "3 scheduled jobs"); Set<String> jobNames = Sets.newHashSet(this.jobScheduler.getScheduledJobs()); Assert.assertEquals(jobNames.size(), 3); Assert.assertTrue(jobNames.contains("GobblinTest1")); Assert.assertTrue(jobNames.contains("GobblinTest2")); Assert.assertTrue(jobNames.contains("GobblinTest3")); log.info("testUnscheduleJob: end"); } @AfterClass public void tearDown() throws TimeoutException, IOException { if (jobConfigDir != null) { FileUtils.forceDelete(new File(jobConfigDir)); } this.serviceManager.stopAsync().awaitStopped(10, TimeUnit.SECONDS); } }
Increase timeout for service manager stop. (#1445)
gobblin-runtime/src/test/java/gobblin/scheduler/JobConfigFileMonitorTest.java
Increase timeout for service manager stop. (#1445)
<ide><path>obblin-runtime/src/test/java/gobblin/scheduler/JobConfigFileMonitorTest.java <ide> if (jobConfigDir != null) { <ide> FileUtils.forceDelete(new File(jobConfigDir)); <ide> } <del> this.serviceManager.stopAsync().awaitStopped(10, TimeUnit.SECONDS); <add> this.serviceManager.stopAsync().awaitStopped(30, TimeUnit.SECONDS); <ide> } <ide> }
Java
apache-2.0
fd5d5c2f6d755086b3d3081925f2bf86b92db9c0
0
yahoo/pulsar,yahoo/pulsar,yahoo/pulsar,merlimat/pulsar,merlimat/pulsar,massakam/pulsar,merlimat/pulsar,yahoo/pulsar,massakam/pulsar,merlimat/pulsar,yahoo/pulsar,massakam/pulsar,yahoo/pulsar,massakam/pulsar,merlimat/pulsar,merlimat/pulsar,massakam/pulsar,massakam/pulsar
/** * 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.pulsar.broker; import com.google.common.collect.Sets; import io.netty.util.internal.PlatformDependent; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Properties; import java.util.Set; import java.util.concurrent.TimeUnit; import lombok.Getter; import lombok.Setter; import org.apache.bookkeeper.client.api.DigestType; import org.apache.pulsar.broker.authorization.PulsarAuthorizationProvider; import org.apache.pulsar.common.protocol.Commands; import org.apache.pulsar.common.configuration.Category; import org.apache.pulsar.common.configuration.FieldContext; import org.apache.pulsar.common.configuration.PulsarConfiguration; import org.apache.pulsar.common.policies.data.BacklogQuota; import org.apache.pulsar.common.sasl.SaslConstants; /** * Pulsar service configuration object. */ @Getter @Setter public class ServiceConfiguration implements PulsarConfiguration { @Category private static final String CATEGORY_SERVER = "Server"; @Category private static final String CATEGORY_STORAGE_BK = "Storage (BookKeeper)"; @Category private static final String CATEGORY_STORAGE_ML = "Storage (Managed Ledger)"; @Category private static final String CATEGORY_STORAGE_OFFLOADING = "Storage (Ledger Offloading)"; @Category private static final String CATEGORY_POLICIES = "Policies"; @Category private static final String CATEGORY_WEBSOCKET = "WebSocket"; @Category private static final String CATEGORY_SCHEMA = "Schema"; @Category private static final String CATEGORY_METRICS = "Metrics"; @Category private static final String CATEGORY_REPLICATION = "Replication"; @Category private static final String CATEGORY_LOAD_BALANCER = "Load Balancer"; @Category private static final String CATEGORY_FUNCTIONS = "Functions"; @Category private static final String CATEGORY_TLS = "TLS"; @Category private static final String CATEGORY_AUTHENTICATION = "Authentication"; @Category private static final String CATEGORY_AUTHORIZATION = "Authorization"; @Category private static final String CATEGORY_TOKEN_AUTH = "Token Authentication Provider"; @Category private static final String CATEGORY_SASL_AUTH = "SASL Authentication Provider"; @Category private static final String CATEGORY_HTTP = "HTTP"; /***** --- pulsar configuration --- ****/ @FieldContext( category = CATEGORY_SERVER, required = true, doc = "The Zookeeper quorum connection string (as a comma-separated list)" ) private String zookeeperServers; @Deprecated @FieldContext( category = CATEGORY_SERVER, required = false, deprecated = true, doc = "Global Zookeeper quorum connection string (as a comma-separated list)." + " Deprecated in favor of using `configurationStoreServers`" ) private String globalZookeeperServers; @FieldContext( category = CATEGORY_SERVER, required = false, doc = "Configuration store connection string (as a comma-separated list)" ) private String configurationStoreServers; @FieldContext( category = CATEGORY_SERVER, doc = "The port for serving binary protobuf requests" ) private Optional<Integer> brokerServicePort = Optional.of(6650); @FieldContext( category = CATEGORY_SERVER, doc = "The port for serving tls secured binary protobuf requests" ) private Optional<Integer> brokerServicePortTls = Optional.empty(); @FieldContext( category = CATEGORY_SERVER, doc = "The port for serving http requests" ) private Optional<Integer> webServicePort = Optional.of(8080); @FieldContext( category = CATEGORY_SERVER, doc = "The port for serving https requests" ) private Optional<Integer> webServicePortTls = Optional.empty(); @FieldContext( category = CATEGORY_SERVER, doc = "Hostname or IP address the service binds on" ) private String bindAddress = "0.0.0.0"; @FieldContext( category = CATEGORY_SERVER, doc = "Hostname or IP address the service advertises to the outside world." + " If not set, the value of `InetAddress.getLocalHost().getHostname()` is used." ) private String advertisedAddress; @FieldContext( category = CATEGORY_SERVER, doc = "Number of threads to use for Netty IO." + " Default is set to `2 * Runtime.getRuntime().availableProcessors()`" ) private int numIOThreads = 2 * Runtime.getRuntime().availableProcessors(); @FieldContext( category = CATEGORY_SERVER, doc = "Number of threads to use for HTTP requests processing" + " Default is set to `2 * Runtime.getRuntime().availableProcessors()`" ) // Use at least 8 threads to avoid having Jetty go into threads starving and // having the possibility of getting into a deadlock where a Jetty thread is // waiting for another HTTP call to complete in same thread. private int numHttpServerThreads = Math.max(8, 2 * Runtime.getRuntime().availableProcessors()); @FieldContext(category = CATEGORY_SERVER, doc = "Whether to enable the delayed delivery for messages.") private boolean delayedDeliveryEnabled = true; @FieldContext(category = CATEGORY_SERVER, doc = "Class name of the factory that implements the delayed deliver tracker") private String delayedDeliveryTrackerFactoryClassName = "org.apache.pulsar.broker.delayed.InMemoryDelayedDeliveryTrackerFactory"; @FieldContext(category = CATEGORY_SERVER, doc = "Control the tick time for when retrying on delayed delivery, " + " affecting the accuracy of the delivery time compared to the scheduled time. Default is 1 second.") private long delayedDeliveryTickTimeMillis = 1000; @FieldContext( category = CATEGORY_WEBSOCKET, doc = "Enable the WebSocket API service in broker" ) private boolean webSocketServiceEnabled = false; @FieldContext( category = CATEGORY_WEBSOCKET, doc = "Flag indicates whether to run broker in standalone mode" ) private boolean isRunningStandalone = false; @FieldContext( category = CATEGORY_SERVER, required = true, doc = "Name of the cluster to which this broker belongs to" ) private String clusterName; @FieldContext( category = CATEGORY_SERVER, dynamic = true, doc = "Enable cluster's failure-domain which can distribute brokers into logical region" ) private boolean failureDomainsEnabled = false; @FieldContext( category = CATEGORY_SERVER, doc = "ZooKeeper session timeout in milliseconds" ) private long zooKeeperSessionTimeoutMillis = 30000; @FieldContext( category = CATEGORY_SERVER, doc = "ZooKeeper operation timeout in seconds" ) private int zooKeeperOperationTimeoutSeconds = 30; @FieldContext( category = CATEGORY_SERVER, dynamic = true, doc = "Time to wait for broker graceful shutdown. After this time elapses, the process will be killed" ) private long brokerShutdownTimeoutMs = 60000; @FieldContext( category = CATEGORY_POLICIES, doc = "Enable backlog quota check. Enforces actions on topic when the quota is reached" ) private boolean backlogQuotaCheckEnabled = true; @FieldContext( category = CATEGORY_POLICIES, doc = "How often to check for topics that have reached the quota." + " It only takes effects when `backlogQuotaCheckEnabled` is true" ) private int backlogQuotaCheckIntervalInSeconds = 60; @FieldContext( category = CATEGORY_POLICIES, doc = "Default per-topic backlog quota limit, less than 0 means no limitation. default is -1." + " Increase it if you want to allow larger msg backlog" ) private long backlogQuotaDefaultLimitGB = -1; @FieldContext( category = CATEGORY_POLICIES, doc = "Default backlog quota retention policy. Default is producer_request_hold\n\n" + "'producer_request_hold' Policy which holds producer's send request until the" + "resource becomes available (or holding times out)\n" + "'producer_exception' Policy which throws javax.jms.ResourceAllocationException to the producer\n" + "'consumer_backlog_eviction' Policy which evicts the oldest message from the slowest consumer's backlog" ) private BacklogQuota.RetentionPolicy backlogQuotaDefaultRetentionPolicy = BacklogQuota.RetentionPolicy.producer_request_hold; @FieldContext( category = CATEGORY_POLICIES, doc = "Default ttl for namespaces if ttl is not already configured at namespace policies. " + "(disable default-ttl with value 0)" ) private int ttlDurationDefaultInSeconds = 0; @FieldContext( category = CATEGORY_POLICIES, doc = "Enable the deletion of inactive topics" ) private boolean brokerDeleteInactiveTopicsEnabled = true; @FieldContext( category = CATEGORY_POLICIES, doc = "How often to check for inactive topics" ) private long brokerDeleteInactiveTopicsFrequencySeconds = 60; @FieldContext( category = CATEGORY_POLICIES, doc = "How frequently to proactively check and purge expired messages" ) private int messageExpiryCheckIntervalInMinutes = 5; @FieldContext( category = CATEGORY_POLICIES, doc = "How long to delay rewinding cursor and dispatching messages when active consumer is changed" ) private int activeConsumerFailoverDelayTimeMillis = 1000; @FieldContext( category = CATEGORY_POLICIES, doc = "How long to delete inactive subscriptions from last consuming." + " When it is 0, inactive subscriptions are not deleted automatically" ) private long subscriptionExpirationTimeMinutes = 0; @FieldContext( category = CATEGORY_POLICIES, dynamic = true, doc = "Enable subscription message redelivery tracker to send redelivery " + "count to consumer (default is enabled)" ) private boolean subscriptionRedeliveryTrackerEnabled = true; @FieldContext( category = CATEGORY_POLICIES, doc = "How frequently to proactively check and purge expired subscription" ) private long subscriptionExpiryCheckIntervalInMinutes = 5; @FieldContext( category = CATEGORY_POLICIES, dynamic = true, doc = "Enable Key_Shared subscription (default is enabled)" ) private boolean subscriptionKeySharedEnable = true; @FieldContext( category = CATEGORY_POLICIES, doc = "Set the default behavior for message deduplication in the broker.\n\n" + "This can be overridden per-namespace. If enabled, broker will reject" + " messages that were already stored in the topic" ) private boolean brokerDeduplicationEnabled = false; @FieldContext( category = CATEGORY_POLICIES, doc = "Maximum number of producer information that it's going to be persisted for deduplication purposes" ) private int brokerDeduplicationMaxNumberOfProducers = 10000; @FieldContext( category = CATEGORY_POLICIES, doc = "Number of entries after which a dedup info snapshot is taken.\n\n" + "A bigger interval will lead to less snapshots being taken though it would" + " increase the topic recovery time, when the entries published after the" + " snapshot need to be replayed" ) private int brokerDeduplicationEntriesInterval = 1000; @FieldContext( category = CATEGORY_POLICIES, doc = "Time of inactivity after which the broker will discard the deduplication information" + " relative to a disconnected producer. Default is 6 hours.") private int brokerDeduplicationProducerInactivityTimeoutMinutes = 360; @FieldContext( category = CATEGORY_POLICIES, doc = "When a namespace is created without specifying the number of bundle, this" + " value will be used as the default") private int defaultNumberOfNamespaceBundles = 4; @FieldContext( category = CATEGORY_SERVER, dynamic = true, doc = "Enable check for minimum allowed client library version" ) private boolean clientLibraryVersionCheckEnabled = false; @FieldContext( category = CATEGORY_SERVER, doc = "Path for the file used to determine the rotation status for the broker" + " when responding to service discovery health checks") private String statusFilePath; @FieldContext( category = CATEGORY_POLICIES, doc = "Max number of unacknowledged messages allowed to receive messages by a consumer on" + " a shared subscription.\n\n Broker will stop sending messages to consumer once," + " this limit reaches until consumer starts acknowledging messages back and unack count" + " reaches to `maxUnackedMessagesPerConsumer/2`. Using a value of 0, it is disabling " + " unackedMessage-limit check and consumer can receive messages without any restriction") private int maxUnackedMessagesPerConsumer = 50000; @FieldContext( category = CATEGORY_POLICIES, doc = "Max number of unacknowledged messages allowed per shared subscription. \n\n" + " Broker will stop dispatching messages to all consumers of the subscription once this " + " limit reaches until consumer starts acknowledging messages back and unack count reaches" + " to `limit/2`. Using a value of 0, is disabling unackedMessage-limit check and dispatcher" + " can dispatch messages without any restriction") private int maxUnackedMessagesPerSubscription = 4 * 50000; @FieldContext( category = CATEGORY_POLICIES, doc = "Max number of unacknowledged messages allowed per broker. \n\n" + " Once this limit reaches, broker will stop dispatching messages to all shared subscription " + " which has higher number of unack messages until subscriptions start acknowledging messages " + " back and unack count reaches to `limit/2`. Using a value of 0, is disabling unackedMessage-limit" + " check and broker doesn't block dispatchers") private int maxUnackedMessagesPerBroker = 0; @FieldContext( category = CATEGORY_POLICIES, doc = "Once broker reaches maxUnackedMessagesPerBroker limit, it blocks subscriptions which has higher " + " unacked messages than this percentage limit and subscription will not receive any new messages " + " until that subscription acks back `limit/2` messages") private double maxUnackedMessagesPerSubscriptionOnBrokerBlocked = 0.16; @FieldContext( category = CATEGORY_POLICIES, dynamic = true, doc = "Too many subscribe requests from a consumer can cause broker rewinding consumer cursors " + " and loading data from bookies, hence causing high network bandwidth usage When the positive" + " value is set, broker will throttle the subscribe requests for one consumer. Otherwise, the" + " throttling will be disabled. The default value of this setting is 0 - throttling is disabled.") private int subscribeThrottlingRatePerConsumer = 0; @FieldContext( minValue = 1, dynamic = true, category = CATEGORY_POLICIES, doc = "Rate period for {subscribeThrottlingRatePerConsumer}. Default is 30s." ) private int subscribeRatePeriodPerConsumerInSecond = 30; @FieldContext( dynamic = true, category = CATEGORY_POLICIES, doc = "Default number of message dispatching throttling-limit for every topic. \n\n" + "Using a value of 0, is disabling default message dispatch-throttling") private int dispatchThrottlingRatePerTopicInMsg = 0; @FieldContext( dynamic = true, category = CATEGORY_POLICIES, doc = "Default number of message-bytes dispatching throttling-limit for every topic. \n\n" + "Using a value of 0, is disabling default message-byte dispatch-throttling") private long dispatchThrottlingRatePerTopicInByte = 0; @FieldContext( dynamic = true, category = CATEGORY_POLICIES, doc = "Default number of message dispatching throttling-limit for a subscription. \n\n" + "Using a value of 0, is disabling default message dispatch-throttling.") private int dispatchThrottlingRatePerSubscriptionInMsg = 0; @FieldContext( dynamic = true, category = CATEGORY_POLICIES, doc = "Default number of message-bytes dispatching throttling-limit for a subscription. \n\n" + "Using a value of 0, is disabling default message-byte dispatch-throttling.") private long dispatchThrottlingRatePerSubscriptionInByte = 0; @FieldContext( dynamic = true, category = CATEGORY_POLICIES, doc = "Default number of message dispatching throttling-limit for every replicator in replication. \n\n" + "Using a value of 0, is disabling replication message dispatch-throttling") private int dispatchThrottlingRatePerReplicatorInMsg = 0; @FieldContext( dynamic = true, category = CATEGORY_POLICIES, doc = "Default number of message-bytes dispatching throttling-limit for every replicator in replication. \n\n" + "Using a value of 0, is disabling replication message-byte dispatch-throttling") private long dispatchThrottlingRatePerReplicatorInByte = 0; @FieldContext( dynamic = true, category = CATEGORY_POLICIES, doc = "Default dispatch-throttling is disabled for consumers which already caught-up with" + " published messages and don't have backlog. This enables dispatch-throttling for " + " non-backlog consumers as well.") private boolean dispatchThrottlingOnNonBacklogConsumerEnabled = false; // <-- dispatcher read settings --> @FieldContext( dynamic = true, category = CATEGORY_SERVER, doc = "Max number of entries to read from bookkeeper. By default it is 100 entries." ) private int dispatcherMaxReadBatchSize = 100; @FieldContext( dynamic = true, category = CATEGORY_SERVER, doc = "Min number of entries to read from bookkeeper. By default it is 1 entries." + "When there is an error occurred on reading entries from bookkeeper, the broker" + " will backoff the batch size to this minimum number." ) private int dispatcherMinReadBatchSize = 1; @FieldContext( dynamic = true, category = CATEGORY_SERVER, doc = "Max number of entries to dispatch for a shared subscription. By default it is 20 entries." ) private int dispatcherMaxRoundRobinBatchSize = 20; @FieldContext( dynamic = true, category = CATEGORY_SERVER, doc = "Max number of concurrent lookup request broker allows to throttle heavy incoming lookup traffic") private int maxConcurrentLookupRequest = 50000; @FieldContext( dynamic = true, category = CATEGORY_SERVER, doc = "Max number of concurrent topic loading request broker allows to control number of zk-operations" ) private int maxConcurrentTopicLoadRequest = 5000; @FieldContext( category = CATEGORY_SERVER, doc = "Max concurrent non-persistent message can be processed per connection") private int maxConcurrentNonPersistentMessagePerConnection = 1000; @FieldContext( category = CATEGORY_SERVER, doc = "Number of worker threads to serve non-persistent topic") private int numWorkerThreadsForNonPersistentTopic = Runtime.getRuntime().availableProcessors();; @FieldContext( category = CATEGORY_SERVER, doc = "Enable broker to load persistent topics" ) private boolean enablePersistentTopics = true; @FieldContext( category = CATEGORY_SERVER, doc = "Enable broker to load non-persistent topics" ) private boolean enableNonPersistentTopics = true; @FieldContext( category = CATEGORY_SERVER, doc = "Enable to run bookie along with broker" ) private boolean enableRunBookieTogether = false; @FieldContext( category = CATEGORY_SERVER, doc = "Enable to run bookie autorecovery along with broker" ) private boolean enableRunBookieAutoRecoveryTogether = false; @FieldContext( category = CATEGORY_SERVER, doc = "Max number of producers allowed to connect to topic. \n\nOnce this limit reaches," + " Broker will reject new producers until the number of connected producers decrease." + " Using a value of 0, is disabling maxProducersPerTopic-limit check.") private int maxProducersPerTopic = 0; @FieldContext( category = CATEGORY_SERVER, doc = "Max number of consumers allowed to connect to topic. \n\nOnce this limit reaches," + " Broker will reject new consumers until the number of connected consumers decrease." + " Using a value of 0, is disabling maxConsumersPerTopic-limit check.") private int maxConsumersPerTopic = 0; @FieldContext( category = CATEGORY_SERVER, doc = "Max number of consumers allowed to connect to subscription. \n\nOnce this limit reaches," + " Broker will reject new consumers until the number of connected consumers decrease." + " Using a value of 0, is disabling maxConsumersPerSubscription-limit check.") private int maxConsumersPerSubscription = 0; @FieldContext( category = CATEGORY_SERVER, doc = "Max size of messages.", maxValue = Integer.MAX_VALUE - Commands.MESSAGE_SIZE_FRAME_PADDING) private int maxMessageSize = Commands.DEFAULT_MAX_MESSAGE_SIZE; @FieldContext( category = CATEGORY_SERVER, doc = "Enable tracking of replicated subscriptions state across clusters.") private boolean enableReplicatedSubscriptions = true; @FieldContext( category = CATEGORY_SERVER, doc = "Frequency of snapshots for replicated subscriptions tracking.") private int replicatedSubscriptionsSnapshotFrequencyMillis = 1_000; @FieldContext( category = CATEGORY_SERVER, doc = "Timeout for building a consistent snapshot for tracking replicated subscriptions state. ") private int replicatedSubscriptionsSnapshotTimeoutSeconds = 30; @FieldContext( category = CATEGORY_SERVER, doc = "Max number of snapshot to be cached per subscription.") private int replicatedSubscriptionsSnapshotMaxCachedPerSubscription = 10; /***** --- TLS --- ****/ @FieldContext( category = CATEGORY_TLS, doc = "Enable TLS" ) @Deprecated private boolean tlsEnabled = false; @FieldContext( category = CATEGORY_TLS, doc = "Tls cert refresh duration in seconds (set 0 to check on every new connection)" ) private long tlsCertRefreshCheckDurationSec = 300; @FieldContext( category = CATEGORY_TLS, doc = "Path for the TLS certificate file" ) private String tlsCertificateFilePath; @FieldContext( category = CATEGORY_TLS, doc = "Path for the TLS private key file" ) private String tlsKeyFilePath; @FieldContext( category = CATEGORY_TLS, doc = "Path for the trusted TLS certificate file" ) private String tlsTrustCertsFilePath = ""; @FieldContext( category = CATEGORY_TLS, doc = "Accept untrusted TLS certificate from client" ) private boolean tlsAllowInsecureConnection = false; @FieldContext( category = CATEGORY_TLS, doc = "Specify the tls protocols the broker will use to negotiate during TLS Handshake.\n\n" + "Example:- [TLSv1.2, TLSv1.1, TLSv1]" ) private Set<String> tlsProtocols = Sets.newTreeSet(); @FieldContext( category = CATEGORY_TLS, doc = "Specify the tls cipher the broker will use to negotiate during TLS Handshake.\n\n" + "Example:- [TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256]" ) private Set<String> tlsCiphers = Sets.newTreeSet(); @FieldContext( category = CATEGORY_TLS, doc = "Specify whether Client certificates are required for TLS Reject.\n" + "the Connection if the Client Certificate is not trusted") private boolean tlsRequireTrustedClientCertOnConnect = false; /***** --- Authentication --- ****/ @FieldContext( category = CATEGORY_AUTHENTICATION, doc = "Enable authentication" ) private boolean authenticationEnabled = false; @FieldContext( category = CATEGORY_AUTHENTICATION, doc = "Autentication provider name list, which is a list of class names" ) private Set<String> authenticationProviders = Sets.newTreeSet(); @FieldContext( category = CATEGORY_AUTHORIZATION, doc = "Enforce authorization" ) private boolean authorizationEnabled = false; @FieldContext( category = CATEGORY_AUTHORIZATION, doc = "Authorization provider fully qualified class-name" ) private String authorizationProvider = PulsarAuthorizationProvider.class.getName(); @FieldContext( category = CATEGORY_AUTHORIZATION, dynamic = true, doc = "Role names that are treated as `super-user`, meaning they will be able to" + " do all admin operations and publish/consume from all topics" ) private Set<String> superUserRoles = Sets.newTreeSet(); @FieldContext( category = CATEGORY_AUTHORIZATION, doc = "Role names that are treated as `proxy roles`. \n\nIf the broker sees" + " a request with role as proxyRoles - it will demand to see the original" + " client role or certificate.") private Set<String> proxyRoles = Sets.newTreeSet(); @FieldContext( category = CATEGORY_AUTHORIZATION, doc = "If this flag is set then the broker authenticates the original Auth data" + " else it just accepts the originalPrincipal and authorizes it (if required)") private boolean authenticateOriginalAuthData = false; @FieldContext( category = CATEGORY_AUTHORIZATION, doc = "Allow wildcard matching in authorization\n\n" + "(wildcard matching only applicable if wildcard-char: * presents at first" + " or last position eg: *.pulsar.service, pulsar.service.*)") private boolean authorizationAllowWildcardsMatching = false; @FieldContext( category = CATEGORY_AUTHENTICATION, dynamic = true, doc = "Authentication settings of the broker itself. \n\nUsed when the broker connects" + " to other brokers, either in same or other clusters. Default uses plugin which disables authentication" ) private String brokerClientAuthenticationPlugin = "org.apache.pulsar.client.impl.auth.AuthenticationDisabled"; @FieldContext( category = CATEGORY_AUTHENTICATION, dynamic = true, doc = "Authentication parameters of the authentication plugin the broker is using to connect to other brokers" ) private String brokerClientAuthenticationParameters = ""; @FieldContext( category = CATEGORY_AUTHENTICATION, doc = "Path for the trusted TLS certificate file for outgoing connection to a server (broker)") private String brokerClientTrustCertsFilePath = ""; @FieldContext( category = CATEGORY_AUTHORIZATION, doc = "When this parameter is not empty, unauthenticated users perform as anonymousUserRole" ) private String anonymousUserRole = null; @FieldContext( category = CATEGORY_SASL_AUTH, doc = "This is a regexp, which limits the range of possible ids which can connect to the Broker using SASL.\n" + " Default value is: \".*pulsar.*\", so only clients whose id contains 'pulsar' are allowed to connect." ) private String saslJaasClientAllowedIds = SaslConstants.JAAS_CLIENT_ALLOWED_IDS_DEFAULT; @FieldContext( category = CATEGORY_SASL_AUTH, doc = "Service Principal, for login context name. Default value is \"Broker\"." ) private String saslJaasServerSectionName = SaslConstants.JAAS_DEFAULT_BROKER_SECTION_NAME; @FieldContext( category = CATEGORY_SASL_AUTH, doc = "kerberos kinit command." ) private String kinitCommand = "/usr/bin/kinit"; /**** --- BookKeeper Client --- ****/ @FieldContext( category = CATEGORY_STORAGE_BK, doc = "Authentication plugin to use when connecting to bookies" ) private String bookkeeperClientAuthenticationPlugin; @FieldContext( category = CATEGORY_STORAGE_BK, doc = "BookKeeper auth plugin implementatation specifics parameters name and values" ) private String bookkeeperClientAuthenticationParametersName; @FieldContext( category = CATEGORY_STORAGE_BK, doc = "Parameters for bookkeeper auth plugin" ) private String bookkeeperClientAuthenticationParameters; @FieldContext( category = CATEGORY_STORAGE_BK, doc = "Timeout for BK add / read operations" ) private long bookkeeperClientTimeoutInSeconds = 30; @FieldContext( category = CATEGORY_STORAGE_BK, doc = "Speculative reads are initiated if a read request doesn't complete within" + " a certain time Using a value of 0, is disabling the speculative reads") private int bookkeeperClientSpeculativeReadTimeoutInMillis = 0; @FieldContext( category = CATEGORY_STORAGE_BK, doc = "Use older Bookkeeper wire protocol with bookie" ) private boolean bookkeeperUseV2WireProtocol = true; @FieldContext( category = CATEGORY_STORAGE_BK, doc = "Enable bookies health check. \n\n Bookies that have more than the configured" + " number of failure within the interval will be quarantined for some time." + " During this period, new ledgers won't be created on these bookies") private boolean bookkeeperClientHealthCheckEnabled = true; @FieldContext( category = CATEGORY_STORAGE_BK, doc = "Bookies health check interval in seconds" ) private long bookkeeperClientHealthCheckIntervalSeconds = 60; @FieldContext( category = CATEGORY_STORAGE_BK, doc = "Bookies health check error threshold per check interval" ) private long bookkeeperClientHealthCheckErrorThresholdPerInterval = 5; @FieldContext( category = CATEGORY_STORAGE_BK, doc = "Bookie health check quarantined time in seconds" ) private long bookkeeperClientHealthCheckQuarantineTimeInSeconds = 1800; @FieldContext( category = CATEGORY_STORAGE_BK, doc = "Enable rack-aware bookie selection policy. \n\nBK will chose bookies from" + " different racks when forming a new bookie ensemble") private boolean bookkeeperClientRackawarePolicyEnabled = true; @FieldContext( category = CATEGORY_STORAGE_BK, doc = "Enable region-aware bookie selection policy. \n\nBK will chose bookies from" + " different regions and racks when forming a new bookie ensemble") private boolean bookkeeperClientRegionawarePolicyEnabled = false; @FieldContext( category = CATEGORY_STORAGE_BK, doc = "Enable/disable reordering read sequence on reading entries") private boolean bookkeeperClientReorderReadSequenceEnabled = false; @FieldContext( category = CATEGORY_STORAGE_BK, required = false, doc = "Enable bookie isolation by specifying a list of bookie groups to choose from. \n\n" + "Any bookie outside the specified groups will not be used by the broker") private String bookkeeperClientIsolationGroups; @FieldContext( category = CATEGORY_STORAGE_BK, required = false, doc = "Enable bookie secondary-isolation group if bookkeeperClientIsolationGroups doesn't have enough bookie available." ) private String bookkeeperClientSecondaryIsolationGroups; @FieldContext(category = CATEGORY_STORAGE_BK, doc = "Enable/disable having read operations for a ledger to be sticky to " + "a single bookie.\n" + "If this flag is enabled, the client will use one single bookie (by " + "preference) to read all entries for a ledger.") private boolean bookkeeperEnableStickyReads = true; /**** --- Managed Ledger --- ****/ @FieldContext( minValue = 1, category = CATEGORY_STORAGE_ML, doc = "Number of bookies to use when creating a ledger" ) private int managedLedgerDefaultEnsembleSize = 1; @FieldContext( minValue = 1, category = CATEGORY_STORAGE_ML, doc = "Number of copies to store for each message" ) private int managedLedgerDefaultWriteQuorum = 1; @FieldContext( minValue = 1, category = CATEGORY_STORAGE_ML, doc = "Number of guaranteed copies (acks to wait before write is complete)" ) private int managedLedgerDefaultAckQuorum = 1; // // @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Default type of checksum to use when writing to BookKeeper. \n\nDefault is `CRC32C`." + " Other possible options are `CRC32`, `MAC` or `DUMMY` (no checksum)." ) private DigestType managedLedgerDigestType = DigestType.CRC32C; @FieldContext( minValue = 1, category = CATEGORY_STORAGE_ML, doc = "Max number of bookies to use when creating a ledger" ) private int managedLedgerMaxEnsembleSize = 5; @FieldContext( minValue = 1, category = CATEGORY_STORAGE_ML, doc = "Max number of copies to store for each message" ) private int managedLedgerMaxWriteQuorum = 5; @FieldContext( minValue = 1, category = CATEGORY_STORAGE_ML, doc = "Max number of guaranteed copies (acks to wait before write is complete)" ) private int managedLedgerMaxAckQuorum = 5; @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Amount of memory to use for caching data payload in managed ledger. \n\nThis" + " memory is allocated from JVM direct memory and it's shared across all the topics" + " running in the same broker. By default, uses 1/5th of available direct memory") private int managedLedgerCacheSizeMB = Math.max(64, (int) (PlatformDependent.maxDirectMemory() / 5 / (1024 * 1024))); @FieldContext(category = CATEGORY_STORAGE_ML, doc = "Whether we should make a copy of the entry payloads when inserting in cache") private boolean managedLedgerCacheCopyEntries = false; @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Threshold to which bring down the cache level when eviction is triggered" ) private double managedLedgerCacheEvictionWatermark = 0.9f; @FieldContext(category = CATEGORY_STORAGE_ML, doc = "Configure the cache eviction frequency for the managed ledger cache. Default is 100/s") private double managedLedgerCacheEvictionFrequency = 100.0; @FieldContext(category = CATEGORY_STORAGE_ML, doc = "All entries that have stayed in cache for more than the configured time, will be evicted") private long managedLedgerCacheEvictionTimeThresholdMillis = 1000; @FieldContext(category = CATEGORY_STORAGE_ML, doc = "Configure the threshold (in number of entries) from where a cursor should be considered 'backlogged'" + " and thus should be set as inactive.") private long managedLedgerCursorBackloggedThreshold = 1000; @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Rate limit the amount of writes per second generated by consumer acking the messages" ) private double managedLedgerDefaultMarkDeleteRateLimit = 1.0; @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Allow automated creation of non-partition topics if set to true (default value)." ) private boolean allowAutoTopicCreation = true; @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Number of threads to be used for managed ledger tasks dispatching" ) private int managedLedgerNumWorkerThreads = Runtime.getRuntime().availableProcessors(); @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Number of threads to be used for managed ledger scheduled tasks" ) private int managedLedgerNumSchedulerThreads = Runtime.getRuntime().availableProcessors(); @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Max number of entries to append to a ledger before triggering a rollover.\n\n" + "A ledger rollover is triggered on these conditions Either the max" + " rollover time has been reached or max entries have been written to the" + " ledged and at least min-time has passed") private int managedLedgerMaxEntriesPerLedger = 50000; @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Minimum time between ledger rollover for a topic" ) private int managedLedgerMinLedgerRolloverTimeMinutes = 10; @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Maximum time before forcing a ledger rollover for a topic" ) private int managedLedgerMaxLedgerRolloverTimeMinutes = 240; @FieldContext( category = CATEGORY_STORAGE_OFFLOADING, doc = "Delay between a ledger being successfully offloaded to long term storage," + " and the ledger being deleted from bookkeeper" ) private long managedLedgerOffloadDeletionLagMs = TimeUnit.HOURS.toMillis(4); @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Max number of entries to append to a cursor ledger" ) private int managedLedgerCursorMaxEntriesPerLedger = 50000; @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Max time before triggering a rollover on a cursor ledger" ) private int managedLedgerCursorRolloverTimeInSeconds = 14400; @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Max number of `acknowledgment holes` that are going to be persistently stored.\n\n" + "When acknowledging out of order, a consumer will leave holes that are supposed" + " to be quickly filled by acking all the messages. The information of which" + " messages are acknowledged is persisted by compressing in `ranges` of messages" + " that were acknowledged. After the max number of ranges is reached, the information" + " will only be tracked in memory and messages will be redelivered in case of" + " crashes.") private int managedLedgerMaxUnackedRangesToPersist = 10000; @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Max number of `acknowledgment holes` that can be stored in Zookeeper.\n\n" + "If number of unack message range is higher than this limit then broker will persist" + " unacked ranges into bookkeeper to avoid additional data overhead into zookeeper.") private int managedLedgerMaxUnackedRangesToPersistInZooKeeper = 1000; @FieldContext( category = CATEGORY_STORAGE_OFFLOADING, doc = "Use Open Range-Set to cache unacked messages (it is memory efficient but it can take more cpu)" ) private boolean managedLedgerUnackedRangesOpenCacheSetEnabled = true; @FieldContext( dynamic = true, category = CATEGORY_STORAGE_ML, doc = "Skip reading non-recoverable/unreadable data-ledger under managed-ledger's list.\n\n" + " It helps when data-ledgers gets corrupted at bookkeeper and managed-cursor is stuck at that ledger." ) private boolean autoSkipNonRecoverableData = false; @FieldContext( category = CATEGORY_STORAGE_ML, doc = "operation timeout while updating managed-ledger metadata." ) private long managedLedgerMetadataOperationsTimeoutSeconds = 60; @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Read entries timeout when broker tries to read messages from bookkeeper " + "(0 to disable it)" ) private long managedLedgerReadEntryTimeoutSeconds = 0; @FieldContext(category = CATEGORY_STORAGE_ML, doc = "Add entry timeout when broker tries to publish message to bookkeeper.(0 to disable it)") private long managedLedgerAddEntryTimeoutSeconds = 0; /*** --- Load balancer --- ****/ @FieldContext( category = CATEGORY_LOAD_BALANCER, doc = "Enable load balancer" ) private boolean loadBalancerEnabled = true; @Deprecated @FieldContext( category = CATEGORY_LOAD_BALANCER, deprecated = true, doc = "load placement strategy[weightedRandomSelection/leastLoadedServer] (only used by SimpleLoadManagerImpl)" ) private String loadBalancerPlacementStrategy = "leastLoadedServer"; // weighted random selection @FieldContext( dynamic = true, category = CATEGORY_LOAD_BALANCER, doc = "Percentage of change to trigger load report update" ) private int loadBalancerReportUpdateThresholdPercentage = 10; @FieldContext( dynamic = true, category = CATEGORY_LOAD_BALANCER, doc = "maximum interval to update load report" ) private int loadBalancerReportUpdateMaxIntervalMinutes = 15; @FieldContext( category = CATEGORY_LOAD_BALANCER, doc = "Frequency of report to collect, in minutes" ) private int loadBalancerHostUsageCheckIntervalMinutes = 1; @FieldContext( dynamic = true, category = CATEGORY_LOAD_BALANCER, doc = "Enable/disable automatic bundle unloading for load-shedding" ) private boolean loadBalancerSheddingEnabled = true; @FieldContext( category = CATEGORY_LOAD_BALANCER, doc = "Load shedding interval. \n\nBroker periodically checks whether some traffic" + " should be offload from some over-loaded broker to other under-loaded brokers" ) private int loadBalancerSheddingIntervalMinutes = 1; @FieldContext( category = CATEGORY_LOAD_BALANCER, doc = "Prevent the same topics to be shed and moved to other broker more that" + " once within this timeframe" ) private long loadBalancerSheddingGracePeriodMinutes = 30; @FieldContext( category = CATEGORY_LOAD_BALANCER, deprecated = true, doc = "Usage threshold to determine a broker as under-loaded (only used by SimpleLoadManagerImpl)" ) @Deprecated private int loadBalancerBrokerUnderloadedThresholdPercentage = 50; @FieldContext( dynamic = true, category = CATEGORY_LOAD_BALANCER, doc = "Usage threshold to allocate max number of topics to broker" ) private int loadBalancerBrokerMaxTopics = 50000; @FieldContext( dynamic = true, category = CATEGORY_LOAD_BALANCER, doc = "Usage threshold to determine a broker as over-loaded" ) private int loadBalancerBrokerOverloadedThresholdPercentage = 85; @FieldContext( category = CATEGORY_LOAD_BALANCER, doc = "Interval to flush dynamic resource quota to ZooKeeper" ) private int loadBalancerResourceQuotaUpdateIntervalMinutes = 15; @Deprecated @FieldContext( category = CATEGORY_LOAD_BALANCER, deprecated = true, doc = "Usage threshold to determine a broker is having just right level of load" + " (only used by SimpleLoadManagerImpl)" ) private int loadBalancerBrokerComfortLoadLevelPercentage = 65; @FieldContext( dynamic = true, category = CATEGORY_LOAD_BALANCER, doc = "enable/disable automatic namespace bundle split" ) private boolean loadBalancerAutoBundleSplitEnabled = true; @FieldContext( dynamic = true, category = CATEGORY_LOAD_BALANCER, doc = "enable/disable automatic unloading of split bundles" ) private boolean loadBalancerAutoUnloadSplitBundlesEnabled = true; @FieldContext( category = CATEGORY_LOAD_BALANCER, doc = "maximum topics in a bundle, otherwise bundle split will be triggered" ) private int loadBalancerNamespaceBundleMaxTopics = 1000; @FieldContext( category = CATEGORY_LOAD_BALANCER, doc = "maximum sessions (producers + consumers) in a bundle, otherwise bundle split will be triggered" ) private int loadBalancerNamespaceBundleMaxSessions = 1000; @FieldContext( category = CATEGORY_LOAD_BALANCER, doc = "maximum msgRate (in + out) in a bundle, otherwise bundle split will be triggered" ) private int loadBalancerNamespaceBundleMaxMsgRate = 30000; @FieldContext( category = CATEGORY_LOAD_BALANCER, doc = "maximum bandwidth (in + out) in a bundle, otherwise bundle split will be triggered" ) private int loadBalancerNamespaceBundleMaxBandwidthMbytes = 100; @FieldContext( category = CATEGORY_LOAD_BALANCER, doc = "maximum number of bundles in a namespace" ) private int loadBalancerNamespaceMaximumBundles = 128; @FieldContext( dynamic = true, category = CATEGORY_LOAD_BALANCER, doc = "Name of load manager to use" ) private String loadManagerClassName = "org.apache.pulsar.broker.loadbalance.impl.ModularLoadManagerImpl"; @FieldContext( category = CATEGORY_LOAD_BALANCER, doc = "Option to override the auto-detected network interfaces max speed" ) private Double loadBalancerOverrideBrokerNicSpeedGbps; /**** --- Replication --- ****/ @FieldContext( category = CATEGORY_REPLICATION, doc = "Enable replication metrics" ) private boolean replicationMetricsEnabled = false; @FieldContext( category = CATEGORY_REPLICATION, doc = "Max number of connections to open for each broker in a remote cluster.\n\n" + "More connections host-to-host lead to better throughput over high-latency links" ) private int replicationConnectionsPerBroker = 16; @FieldContext( required = false, category = CATEGORY_REPLICATION, doc = "replicator prefix used for replicator producer name and cursor name" ) private String replicatorPrefix = "pulsar.repl"; @FieldContext( category = CATEGORY_REPLICATION, doc = "Replicator producer queue size" ) private int replicationProducerQueueSize = 1000; @Deprecated @FieldContext( category = CATEGORY_REPLICATION, deprecated = true, doc = "@deprecated - Use brokerClientTlsEnabled instead." ) private boolean replicationTlsEnabled = false; @FieldContext( category = CATEGORY_REPLICATION, dynamic = true, doc = "Enable TLS when talking with other brokers in the same cluster (admin operation)" + " or different clusters (replication)" ) private boolean brokerClientTlsEnabled = false; @FieldContext( category = CATEGORY_POLICIES, doc = "Default message retention time" ) private int defaultRetentionTimeInMinutes = 0; @FieldContext( category = CATEGORY_POLICIES, doc = "Default retention size" ) private int defaultRetentionSizeInMB = 0; @FieldContext( category = CATEGORY_SERVER, doc = "How often to check pulsar connection is still alive" ) private int keepAliveIntervalSeconds = 30; @FieldContext( category = CATEGORY_POLICIES, doc = "How often broker checks for inactive topics to be deleted (topics with no subscriptions and no one connected)" ) private int brokerServicePurgeInactiveFrequencyInSeconds = 60; @FieldContext( category = CATEGORY_SERVER, doc = "A comma-separated list of namespaces to bootstrap" ) private List<String> bootstrapNamespaces = new ArrayList<String>(); private Properties properties = new Properties(); @FieldContext( dynamic = true, category = CATEGORY_SERVER, doc = "If true, (and ModularLoadManagerImpl is being used), the load manager will attempt to " + "use only brokers running the latest software version (to minimize impact to bundles)" ) private boolean preferLaterVersions = false; @FieldContext( category = CATEGORY_SERVER, doc = "Interval between checks to see if topics with compaction policies need to be compacted" ) private int brokerServiceCompactionMonitorIntervalInSeconds = 60; @FieldContext( category = CATEGORY_SCHEMA, doc = "Enforce schema validation on following cases:\n\n" + " - if a producer without a schema attempts to produce to a topic with schema, the producer will be\n" + " failed to connect. PLEASE be carefully on using this, since non-java clients don't support schema.\n" + " if you enable this setting, it will cause non-java clients failed to produce." ) private boolean isSchemaValidationEnforced = false; @FieldContext( category = CATEGORY_SCHEMA, doc = "The schema storage implementation used by this broker" ) private String schemaRegistryStorageClassName = "org.apache.pulsar.broker.service.schema.BookkeeperSchemaStorageFactory"; @FieldContext( category = CATEGORY_SCHEMA, doc = "The list compatibility checkers to be used in schema registry" ) private Set<String> schemaRegistryCompatibilityCheckers = Sets.newHashSet( "org.apache.pulsar.broker.service.schema.JsonSchemaCompatibilityCheck", "org.apache.pulsar.broker.service.schema.AvroSchemaCompatibilityCheck" ); /**** --- WebSocket --- ****/ @FieldContext( category = CATEGORY_WEBSOCKET, doc = "Number of IO threads in Pulsar Client used in WebSocket proxy" ) private int webSocketNumIoThreads = Runtime.getRuntime().availableProcessors(); @FieldContext( category = CATEGORY_WEBSOCKET, doc = "Number of connections per Broker in Pulsar Client used in WebSocket proxy" ) private int webSocketConnectionsPerBroker = Runtime.getRuntime().availableProcessors(); @FieldContext( category = CATEGORY_WEBSOCKET, doc = "Time in milliseconds that idle WebSocket session times out" ) private int webSocketSessionIdleTimeoutMillis = 300000; /**** --- Metrics --- ****/ @FieldContext( category = CATEGORY_METRICS, doc = "If true, export topic level metrics otherwise namespace level" ) private boolean exposeTopicLevelMetricsInPrometheus = true; @FieldContext( category = CATEGORY_METRICS, doc = "If true, export consumer level metrics otherwise namespace level" ) private boolean exposeConsumerLevelMetricsInPrometheus = false; @FieldContext( category = CATEGORY_METRICS, doc = "Classname of Pluggable JVM GC metrics logger that can log GC specific metrics") private String jvmGCMetricsLoggerClassName; /**** --- Functions --- ****/ @FieldContext( category = CATEGORY_FUNCTIONS, doc = "Flag indicates enabling or disabling function worker on brokers" ) private boolean functionsWorkerEnabled = false; /**** --- Broker Web Stats --- ****/ @FieldContext( category = CATEGORY_METRICS, doc = "If true, export publisher stats when returning topics stats from the admin rest api" ) private boolean exposePublisherStats = true; @FieldContext( category = CATEGORY_METRICS, doc = "Stats update frequency in seconds" ) private int statsUpdateFrequencyInSecs = 60; @FieldContext( category = CATEGORY_METRICS, doc = "Stats update initial delay in seconds" ) private int statsUpdateInitialDelayInSecs = 60; /**** --- Ledger Offloading --- ****/ /**** * NOTES: all implementation related settings should be put in implementation package. * only common settings like driver name, io threads can be added here. ****/ @FieldContext( category = CATEGORY_STORAGE_OFFLOADING, doc = "The directory to locate offloaders" ) private String offloadersDirectory = "./offloaders"; @FieldContext( category = CATEGORY_STORAGE_OFFLOADING, doc = "Driver to use to offload old data to long term storage" ) private String managedLedgerOffloadDriver = null; @FieldContext( category = CATEGORY_STORAGE_OFFLOADING, doc = "Maximum number of thread pool threads for ledger offloading" ) private int managedLedgerOffloadMaxThreads = 2; /** * @deprecated See {@link #getConfigurationStoreServers} */ @Deprecated public String getGlobalZookeeperServers() { if (this.globalZookeeperServers == null || this.globalZookeeperServers.isEmpty()) { // If the configuration is not set, assuming that the globalZK is not enabled and all data is in the same // ZooKeeper cluster return this.getZookeeperServers(); } return globalZookeeperServers; } /** * @deprecated See {@link #setConfigurationStoreServers(String)} */ @Deprecated public void setGlobalZookeeperServers(String globalZookeeperServers) { this.globalZookeeperServers = globalZookeeperServers; } public String getConfigurationStoreServers() { if (this.configurationStoreServers == null || this.configurationStoreServers.isEmpty()) { // If the configuration is not set, assuming that all data is in the same as globalZK cluster return this.getGlobalZookeeperServers(); } return configurationStoreServers; } public void setConfigurationStoreServers(String configurationStoreServers) { this.configurationStoreServers = configurationStoreServers; } public Object getProperty(String key) { return properties.get(key); } @Override public Properties getProperties() { return properties; } @Override public void setProperties(Properties properties) { this.properties = properties; } public Optional<Double> getLoadBalancerOverrideBrokerNicSpeedGbps() { return Optional.ofNullable(loadBalancerOverrideBrokerNicSpeedGbps); } public int getBookkeeperHealthCheckIntervalSec() { return (int) bookkeeperClientHealthCheckIntervalSeconds; } public Optional<Integer> getBrokerServicePort() { return brokerServicePort; } public Optional<Integer> getBrokerServicePortTls() { return brokerServicePortTls; } public Optional<Integer> getWebServicePort() { return webServicePort; } public Optional<Integer> getWebServicePortTls() { return webServicePortTls; } }
pulsar-broker-common/src/main/java/org/apache/pulsar/broker/ServiceConfiguration.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.pulsar.broker; import com.google.common.collect.Sets; import io.netty.util.internal.PlatformDependent; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Properties; import java.util.Set; import java.util.concurrent.TimeUnit; import lombok.Getter; import lombok.Setter; import org.apache.bookkeeper.client.api.DigestType; import org.apache.pulsar.broker.authorization.PulsarAuthorizationProvider; import org.apache.pulsar.common.protocol.Commands; import org.apache.pulsar.common.configuration.Category; import org.apache.pulsar.common.configuration.FieldContext; import org.apache.pulsar.common.configuration.PulsarConfiguration; import org.apache.pulsar.common.policies.data.BacklogQuota; import org.apache.pulsar.common.sasl.SaslConstants; /** * Pulsar service configuration object. */ @Getter @Setter public class ServiceConfiguration implements PulsarConfiguration { @Category private static final String CATEGORY_SERVER = "Server"; @Category private static final String CATEGORY_STORAGE_BK = "Storage (BookKeeper)"; @Category private static final String CATEGORY_STORAGE_ML = "Storage (Managed Ledger)"; @Category private static final String CATEGORY_STORAGE_OFFLOADING = "Storage (Ledger Offloading)"; @Category private static final String CATEGORY_POLICIES = "Policies"; @Category private static final String CATEGORY_WEBSOCKET = "WebSocket"; @Category private static final String CATEGORY_SCHEMA = "Schema"; @Category private static final String CATEGORY_METRICS = "Metrics"; @Category private static final String CATEGORY_REPLICATION = "Replication"; @Category private static final String CATEGORY_LOAD_BALANCER = "Load Balancer"; @Category private static final String CATEGORY_FUNCTIONS = "Functions"; @Category private static final String CATEGORY_TLS = "TLS"; @Category private static final String CATEGORY_AUTHENTICATION = "Authentication"; @Category private static final String CATEGORY_AUTHORIZATION = "Authorization"; @Category private static final String CATEGORY_TOKEN_AUTH = "Token Authentication Provider"; @Category private static final String CATEGORY_SASL_AUTH = "SASL Authentication Provider"; @Category private static final String CATEGORY_HTTP = "HTTP"; /***** --- pulsar configuration --- ****/ @FieldContext( category = CATEGORY_SERVER, required = true, doc = "The Zookeeper quorum connection string (as a comma-separated list)" ) private String zookeeperServers; @Deprecated @FieldContext( category = CATEGORY_SERVER, required = false, deprecated = true, doc = "Global Zookeeper quorum connection string (as a comma-separated list)." + " Deprecated in favor of using `configurationStoreServers`" ) private String globalZookeeperServers; @FieldContext( category = CATEGORY_SERVER, required = false, doc = "Configuration store connection string (as a comma-separated list)" ) private String configurationStoreServers; @FieldContext( category = CATEGORY_SERVER, doc = "The port for serving binary protobuf requests" ) private Optional<Integer> brokerServicePort = Optional.of(6650); @FieldContext( category = CATEGORY_SERVER, doc = "The port for serving tls secured binary protobuf requests" ) private Optional<Integer> brokerServicePortTls = Optional.empty(); @FieldContext( category = CATEGORY_SERVER, doc = "The port for serving http requests" ) private Optional<Integer> webServicePort = Optional.of(8080); @FieldContext( category = CATEGORY_SERVER, doc = "The port for serving https requests" ) private Optional<Integer> webServicePortTls = Optional.empty(); @FieldContext( category = CATEGORY_SERVER, doc = "Hostname or IP address the service binds on" ) private String bindAddress = "0.0.0.0"; @FieldContext( category = CATEGORY_SERVER, doc = "Hostname or IP address the service advertises to the outside world." + " If not set, the value of `InetAddress.getLocalHost().getHostname()` is used." ) private String advertisedAddress; @FieldContext( category = CATEGORY_SERVER, doc = "Number of threads to use for Netty IO." + " Default is set to `2 * Runtime.getRuntime().availableProcessors()`" ) private int numIOThreads = 2 * Runtime.getRuntime().availableProcessors(); @FieldContext( category = CATEGORY_SERVER, doc = "Number of threads to use for HTTP requests processing" + " Default is set to `2 * Runtime.getRuntime().availableProcessors()`" ) // Use at least 8 threads to avoid having Jetty go into threads starving and // having the possibility of getting into a deadlock where a Jetty thread is // waiting for another HTTP call to complete in same thread. private int numHttpServerThreads = Math.max(8, 2 * Runtime.getRuntime().availableProcessors()); @FieldContext(category = CATEGORY_SERVER, doc = "Whether to enable the delayed delivery for messages.") private boolean delayedDeliveryEnabled = true; @FieldContext(category = CATEGORY_SERVER, doc = "Class name of the factory that implements the delayed deliver tracker") private String delayedDeliveryTrackerFactoryClassName = "org.apache.pulsar.broker.delayed.InMemoryDelayedDeliveryTrackerFactory"; @FieldContext(category = CATEGORY_SERVER, doc = "Control the tick time for when retrying on delayed delivery, " + " affecting the accuracy of the delivery time compared to the scheduled time. Default is 1 second.") private long delayedDeliveryTickTimeMillis = 1000; @FieldContext( category = CATEGORY_WEBSOCKET, doc = "Enable the WebSocket API service in broker" ) private boolean webSocketServiceEnabled = false; @FieldContext( category = CATEGORY_WEBSOCKET, doc = "Flag indicates whether to run broker in standalone mode" ) private boolean isRunningStandalone = false; @FieldContext( category = CATEGORY_SERVER, required = true, doc = "Name of the cluster to which this broker belongs to" ) private String clusterName; @FieldContext( category = CATEGORY_SERVER, dynamic = true, doc = "Enable cluster's failure-domain which can distribute brokers into logical region" ) private boolean failureDomainsEnabled = false; @FieldContext( category = CATEGORY_SERVER, doc = "ZooKeeper session timeout in milliseconds" ) private long zooKeeperSessionTimeoutMillis = 30000; @FieldContext( category = CATEGORY_SERVER, doc = "ZooKeeper operation timeout in seconds" ) private int zooKeeperOperationTimeoutSeconds = 30; @FieldContext( category = CATEGORY_SERVER, dynamic = true, doc = "Time to wait for broker graceful shutdown. After this time elapses, the process will be killed" ) private long brokerShutdownTimeoutMs = 60000; @FieldContext( category = CATEGORY_POLICIES, doc = "Enable backlog quota check. Enforces actions on topic when the quota is reached" ) private boolean backlogQuotaCheckEnabled = true; @FieldContext( category = CATEGORY_POLICIES, doc = "How often to check for topics that have reached the quota." + " It only takes effects when `backlogQuotaCheckEnabled` is true" ) private int backlogQuotaCheckIntervalInSeconds = 60; @FieldContext( category = CATEGORY_POLICIES, doc = "Default per-topic backlog quota limit, less than 0 means no limitation. default is -1." + " Increase it if you want to allow larger msg backlog" ) private long backlogQuotaDefaultLimitGB = -1; @FieldContext( category = CATEGORY_POLICIES, doc = "Default backlog quota retention policy. Default is producer_request_hold\n\n" + "'producer_request_hold' Policy which holds producer's send request until the" + "resource becomes available (or holding times out)\n" + "'producer_exception' Policy which throws javax.jms.ResourceAllocationException to the producer\n" + "'consumer_backlog_eviction' Policy which evicts the oldest message from the slowest consumer's backlog" ) private BacklogQuota.RetentionPolicy backlogQuotaDefaultRetentionPolicy = BacklogQuota.RetentionPolicy.producer_request_hold; @FieldContext( category = CATEGORY_POLICIES, doc = "Default ttl for namespaces if ttl is not already configured at namespace policies. " + "(disable default-ttl with value 0)" ) private int ttlDurationDefaultInSeconds = 0; @FieldContext( category = CATEGORY_POLICIES, doc = "Enable the deletion of inactive topics" ) private boolean brokerDeleteInactiveTopicsEnabled = true; @FieldContext( category = CATEGORY_POLICIES, doc = "How often to check for inactive topics" ) private long brokerDeleteInactiveTopicsFrequencySeconds = 60; @FieldContext( category = CATEGORY_POLICIES, doc = "How frequently to proactively check and purge expired messages" ) private int messageExpiryCheckIntervalInMinutes = 5; @FieldContext( category = CATEGORY_POLICIES, doc = "How long to delay rewinding cursor and dispatching messages when active consumer is changed" ) private int activeConsumerFailoverDelayTimeMillis = 1000; @FieldContext( category = CATEGORY_POLICIES, doc = "How long to delete inactive subscriptions from last consuming." + " When it is 0, inactive subscriptions are not deleted automatically" ) private long subscriptionExpirationTimeMinutes = 0; @FieldContext( category = CATEGORY_POLICIES, dynamic = true, doc = "Enable subscription message redelivery tracker to send redelivery " + "count to consumer (default is enabled)" ) private boolean subscriptionRedeliveryTrackerEnabled = true; @FieldContext( category = CATEGORY_POLICIES, doc = "How frequently to proactively check and purge expired subscription" ) private long subscriptionExpiryCheckIntervalInMinutes = 5; @FieldContext( category = CATEGORY_POLICIES, dynamic = true, doc = "Enable Key_Shared subscription (default is enabled)" ) private boolean subscriptionKeySharedEnable = true; @FieldContext( category = CATEGORY_POLICIES, doc = "Set the default behavior for message deduplication in the broker.\n\n" + "This can be overridden per-namespace. If enabled, broker will reject" + " messages that were already stored in the topic" ) private boolean brokerDeduplicationEnabled = false; @FieldContext( category = CATEGORY_POLICIES, doc = "Maximum number of producer information that it's going to be persisted for deduplication purposes" ) private int brokerDeduplicationMaxNumberOfProducers = 10000; @FieldContext( category = CATEGORY_POLICIES, doc = "Number of entries after which a dedup info snapshot is taken.\n\n" + "A bigger interval will lead to less snapshots being taken though it would" + " increase the topic recovery time, when the entries published after the" + " snapshot need to be replayed" ) private int brokerDeduplicationEntriesInterval = 1000; @FieldContext( category = CATEGORY_POLICIES, doc = "Time of inactivity after which the broker will discard the deduplication information" + " relative to a disconnected producer. Default is 6 hours.") private int brokerDeduplicationProducerInactivityTimeoutMinutes = 360; @FieldContext( category = CATEGORY_POLICIES, doc = "When a namespace is created without specifying the number of bundle, this" + " value will be used as the default") private int defaultNumberOfNamespaceBundles = 4; @FieldContext( category = CATEGORY_SERVER, dynamic = true, doc = "Enable check for minimum allowed client library version" ) private boolean clientLibraryVersionCheckEnabled = false; @FieldContext( category = CATEGORY_SERVER, doc = "Path for the file used to determine the rotation status for the broker" + " when responding to service discovery health checks") private String statusFilePath; @FieldContext( category = CATEGORY_POLICIES, doc = "Max number of unacknowledged messages allowed to receive messages by a consumer on" + " a shared subscription.\n\n Broker will stop sending messages to consumer once," + " this limit reaches until consumer starts acknowledging messages back and unack count" + " reaches to `maxUnackedMessagesPerConsumer/2`. Using a value of 0, it is disabling " + " unackedMessage-limit check and consumer can receive messages without any restriction") private int maxUnackedMessagesPerConsumer = 50000; @FieldContext( category = CATEGORY_POLICIES, doc = "Max number of unacknowledged messages allowed per shared subscription. \n\n" + " Broker will stop dispatching messages to all consumers of the subscription once this " + " limit reaches until consumer starts acknowledging messages back and unack count reaches" + " to `limit/2`. Using a value of 0, is disabling unackedMessage-limit check and dispatcher" + " can dispatch messages without any restriction") private int maxUnackedMessagesPerSubscription = 4 * 50000; @FieldContext( category = CATEGORY_POLICIES, doc = "Max number of unacknowledged messages allowed per broker. \n\n" + " Once this limit reaches, broker will stop dispatching messages to all shared subscription " + " which has higher number of unack messages until subscriptions start acknowledging messages " + " back and unack count reaches to `limit/2`. Using a value of 0, is disabling unackedMessage-limit" + " check and broker doesn't block dispatchers") private int maxUnackedMessagesPerBroker = 0; @FieldContext( category = CATEGORY_POLICIES, doc = "Once broker reaches maxUnackedMessagesPerBroker limit, it blocks subscriptions which has higher " + " unacked messages than this percentage limit and subscription will not receive any new messages " + " until that subscription acks back `limit/2` messages") private double maxUnackedMessagesPerSubscriptionOnBrokerBlocked = 0.16; @FieldContext( category = CATEGORY_POLICIES, dynamic = true, doc = "Too many subscribe requests from a consumer can cause broker rewinding consumer cursors " + " and loading data from bookies, hence causing high network bandwidth usage When the positive" + " value is set, broker will throttle the subscribe requests for one consumer. Otherwise, the" + " throttling will be disabled. The default value of this setting is 0 - throttling is disabled.") private int subscribeThrottlingRatePerConsumer = 0; @FieldContext( minValue = 1, dynamic = true, category = CATEGORY_POLICIES, doc = "Rate period for {subscribeThrottlingRatePerConsumer}. Default is 30s." ) private int subscribeRatePeriodPerConsumerInSecond = 30; @FieldContext( dynamic = true, category = CATEGORY_POLICIES, doc = "Default number of message dispatching throttling-limit for every topic. \n\n" + "Using a value of 0, is disabling default message dispatch-throttling") private int dispatchThrottlingRatePerTopicInMsg = 0; @FieldContext( dynamic = true, category = CATEGORY_POLICIES, doc = "Default number of message-bytes dispatching throttling-limit for every topic. \n\n" + "Using a value of 0, is disabling default message-byte dispatch-throttling") private long dispatchThrottlingRatePerTopicInByte = 0; @FieldContext( dynamic = true, category = CATEGORY_POLICIES, doc = "Default number of message dispatching throttling-limit for a subscription. \n\n" + "Using a value of 0, is disabling default message dispatch-throttling.") private int dispatchThrottlingRatePerSubscriptionInMsg = 0; @FieldContext( dynamic = true, category = CATEGORY_POLICIES, doc = "Default number of message-bytes dispatching throttling-limit for a subscription. \n\n" + "Using a value of 0, is disabling default message-byte dispatch-throttling.") private long dispatchThrottlingRatePerSubscriptionInByte = 0; @FieldContext( dynamic = true, category = CATEGORY_POLICIES, doc = "Default number of message dispatching throttling-limit for every replicator in replication. \n\n" + "Using a value of 0, is disabling replication message dispatch-throttling") private int dispatchThrottlingRatePerReplicatorInMsg = 0; @FieldContext( dynamic = true, category = CATEGORY_POLICIES, doc = "Default number of message-bytes dispatching throttling-limit for every replicator in replication. \n\n" + "Using a value of 0, is disabling replication message-byte dispatch-throttling") private long dispatchThrottlingRatePerReplicatorInByte = 0; @FieldContext( dynamic = true, category = CATEGORY_POLICIES, doc = "Default dispatch-throttling is disabled for consumers which already caught-up with" + " published messages and don't have backlog. This enables dispatch-throttling for " + " non-backlog consumers as well.") private boolean dispatchThrottlingOnNonBacklogConsumerEnabled = false; // <-- dispatcher read settings --> @FieldContext( dynamic = true, category = CATEGORY_SERVER, doc = "Max number of entries to read from bookkeeper. By default it is 100 entries." ) private int dispatcherMaxReadBatchSize = 100; @FieldContext( dynamic = true, category = CATEGORY_SERVER, doc = "Min number of entries to read from bookkeeper. By default it is 1 entries." + "When there is an error occurred on reading entries from bookkeeper, the broker" + " will backoff the batch size to this minimum number." ) private int dispatcherMinReadBatchSize = 1; @FieldContext( dynamic = true, category = CATEGORY_SERVER, doc = "Max number of entries to dispatch for a shared subscription. By default it is 20 entries." ) private int dispatcherMaxRoundRobinBatchSize = 20; @FieldContext( dynamic = true, category = CATEGORY_SERVER, doc = "Max number of concurrent lookup request broker allows to throttle heavy incoming lookup traffic") private int maxConcurrentLookupRequest = 50000; @FieldContext( dynamic = true, category = CATEGORY_SERVER, doc = "Max number of concurrent topic loading request broker allows to control number of zk-operations" ) private int maxConcurrentTopicLoadRequest = 5000; @FieldContext( category = CATEGORY_SERVER, doc = "Max concurrent non-persistent message can be processed per connection") private int maxConcurrentNonPersistentMessagePerConnection = 1000; @FieldContext( category = CATEGORY_SERVER, doc = "Number of worker threads to serve non-persistent topic") private int numWorkerThreadsForNonPersistentTopic = Runtime.getRuntime().availableProcessors();; @FieldContext( category = CATEGORY_SERVER, doc = "Enable broker to load persistent topics" ) private boolean enablePersistentTopics = true; @FieldContext( category = CATEGORY_SERVER, doc = "Enable broker to load non-persistent topics" ) private boolean enableNonPersistentTopics = true; @FieldContext( category = CATEGORY_SERVER, doc = "Enable to run bookie along with broker" ) private boolean enableRunBookieTogether = false; @FieldContext( category = CATEGORY_SERVER, doc = "Enable to run bookie autorecovery along with broker" ) private boolean enableRunBookieAutoRecoveryTogether = false; @FieldContext( category = CATEGORY_SERVER, doc = "Max number of producers allowed to connect to topic. \n\nOnce this limit reaches," + " Broker will reject new producers until the number of connected producers decrease." + " Using a value of 0, is disabling maxProducersPerTopic-limit check.") private int maxProducersPerTopic = 0; @FieldContext( category = CATEGORY_SERVER, doc = "Max number of consumers allowed to connect to topic. \n\nOnce this limit reaches," + " Broker will reject new consumers until the number of connected consumers decrease." + " Using a value of 0, is disabling maxConsumersPerTopic-limit check.") private int maxConsumersPerTopic = 0; @FieldContext( category = CATEGORY_SERVER, doc = "Max number of consumers allowed to connect to subscription. \n\nOnce this limit reaches," + " Broker will reject new consumers until the number of connected consumers decrease." + " Using a value of 0, is disabling maxConsumersPerSubscription-limit check.") private int maxConsumersPerSubscription = 0; @FieldContext( category = CATEGORY_SERVER, doc = "Max size of messages.", maxValue = Integer.MAX_VALUE - Commands.MESSAGE_SIZE_FRAME_PADDING) private int maxMessageSize = Commands.DEFAULT_MAX_MESSAGE_SIZE; @FieldContext( category = CATEGORY_SERVER, doc = "Enable tracking of replicated subscriptions state across clusters.") private boolean enableReplicatedSubscriptions = true; @FieldContext( category = CATEGORY_SERVER, doc = "Frequency of snapshots for replicated subscriptions tracking.") private int replicatedSubscriptionsSnapshotFrequencyMillis = 1_000; @FieldContext( category = CATEGORY_SERVER, doc = "Timeout for building a consistent snapshot for tracking replicated subscriptions state. ") private int replicatedSubscriptionsSnapshotTimeoutSeconds = 30; @FieldContext( category = CATEGORY_SERVER, doc = "Max number of snapshot to be cached per subscription.") private int replicatedSubscriptionsSnapshotMaxCachedPerSubscription = 10; /***** --- TLS --- ****/ @FieldContext( category = CATEGORY_TLS, doc = "Enable TLS" ) @Deprecated private boolean tlsEnabled = false; @FieldContext( category = CATEGORY_TLS, doc = "Tls cert refresh duration in seconds (set 0 to check on every new connection)" ) private long tlsCertRefreshCheckDurationSec = 300; @FieldContext( category = CATEGORY_TLS, doc = "Path for the TLS certificate file" ) private String tlsCertificateFilePath; @FieldContext( category = CATEGORY_TLS, doc = "Path for the TLS private key file" ) private String tlsKeyFilePath; @FieldContext( category = CATEGORY_TLS, doc = "Path for the trusted TLS certificate file" ) private String tlsTrustCertsFilePath = ""; @FieldContext( category = CATEGORY_TLS, doc = "Accept untrusted TLS certificate from client" ) private boolean tlsAllowInsecureConnection = false; @FieldContext( category = CATEGORY_TLS, doc = "Specify the tls protocols the broker will use to negotiate during TLS Handshake.\n\n" + "Example:- [TLSv1.2, TLSv1.1, TLSv1]" ) private Set<String> tlsProtocols = Sets.newTreeSet(); @FieldContext( category = CATEGORY_TLS, doc = "Specify the tls cipher the broker will use to negotiate during TLS Handshake.\n\n" + "Example:- [TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256]" ) private Set<String> tlsCiphers = Sets.newTreeSet(); @FieldContext( category = CATEGORY_TLS, doc = "Specify whether Client certificates are required for TLS Reject.\n" + "the Connection if the Client Certificate is not trusted") private boolean tlsRequireTrustedClientCertOnConnect = false; /***** --- Authentication --- ****/ @FieldContext( category = CATEGORY_AUTHENTICATION, doc = "Enable authentication" ) private boolean authenticationEnabled = false; @FieldContext( category = CATEGORY_AUTHENTICATION, doc = "Autentication provider name list, which is a list of class names" ) private Set<String> authenticationProviders = Sets.newTreeSet(); @FieldContext( category = CATEGORY_AUTHORIZATION, doc = "Enforce authorization" ) private boolean authorizationEnabled = false; @FieldContext( category = CATEGORY_AUTHORIZATION, doc = "Authorization provider fully qualified class-name" ) private String authorizationProvider = PulsarAuthorizationProvider.class.getName(); @FieldContext( category = CATEGORY_AUTHORIZATION, dynamic = true, doc = "Role names that are treated as `super-user`, meaning they will be able to" + " do all admin operations and publish/consume from all topics" ) private Set<String> superUserRoles = Sets.newTreeSet(); @FieldContext( category = CATEGORY_AUTHORIZATION, doc = "Role names that are treated as `proxy roles`. \n\nIf the broker sees" + " a request with role as proxyRoles - it will demand to see the original" + " client role or certificate.") private Set<String> proxyRoles = Sets.newTreeSet(); @FieldContext( category = CATEGORY_AUTHORIZATION, doc = "If this flag is set then the broker authenticates the original Auth data" + " else it just accepts the originalPrincipal and authorizes it (if required)") private boolean authenticateOriginalAuthData = false; @FieldContext( category = CATEGORY_AUTHORIZATION, doc = "Allow wildcard matching in authorization\n\n" + "(wildcard matching only applicable if wildcard-char: * presents at first" + " or last position eg: *.pulsar.service, pulsar.service.*)") private boolean authorizationAllowWildcardsMatching = false; @FieldContext( category = CATEGORY_AUTHENTICATION, doc = "Authentication settings of the broker itself. \n\nUsed when the broker connects" + " to other brokers, either in same or other clusters. Default uses plugin which disables authentication" ) private String brokerClientAuthenticationPlugin = "org.apache.pulsar.client.impl.auth.AuthenticationDisabled"; @FieldContext( category = CATEGORY_AUTHENTICATION, doc = "Authentication parameters of the authentication plugin the broker is using to connect to other brokers" ) private String brokerClientAuthenticationParameters = ""; @FieldContext( category = CATEGORY_AUTHENTICATION, doc = "Path for the trusted TLS certificate file for outgoing connection to a server (broker)") private String brokerClientTrustCertsFilePath = ""; @FieldContext( category = CATEGORY_AUTHORIZATION, doc = "When this parameter is not empty, unauthenticated users perform as anonymousUserRole" ) private String anonymousUserRole = null; @FieldContext( category = CATEGORY_SASL_AUTH, doc = "This is a regexp, which limits the range of possible ids which can connect to the Broker using SASL.\n" + " Default value is: \".*pulsar.*\", so only clients whose id contains 'pulsar' are allowed to connect." ) private String saslJaasClientAllowedIds = SaslConstants.JAAS_CLIENT_ALLOWED_IDS_DEFAULT; @FieldContext( category = CATEGORY_SASL_AUTH, doc = "Service Principal, for login context name. Default value is \"Broker\"." ) private String saslJaasServerSectionName = SaslConstants.JAAS_DEFAULT_BROKER_SECTION_NAME; @FieldContext( category = CATEGORY_SASL_AUTH, doc = "kerberos kinit command." ) private String kinitCommand = "/usr/bin/kinit"; /**** --- BookKeeper Client --- ****/ @FieldContext( category = CATEGORY_STORAGE_BK, doc = "Authentication plugin to use when connecting to bookies" ) private String bookkeeperClientAuthenticationPlugin; @FieldContext( category = CATEGORY_STORAGE_BK, doc = "BookKeeper auth plugin implementatation specifics parameters name and values" ) private String bookkeeperClientAuthenticationParametersName; @FieldContext( category = CATEGORY_STORAGE_BK, doc = "Parameters for bookkeeper auth plugin" ) private String bookkeeperClientAuthenticationParameters; @FieldContext( category = CATEGORY_STORAGE_BK, doc = "Timeout for BK add / read operations" ) private long bookkeeperClientTimeoutInSeconds = 30; @FieldContext( category = CATEGORY_STORAGE_BK, doc = "Speculative reads are initiated if a read request doesn't complete within" + " a certain time Using a value of 0, is disabling the speculative reads") private int bookkeeperClientSpeculativeReadTimeoutInMillis = 0; @FieldContext( category = CATEGORY_STORAGE_BK, doc = "Use older Bookkeeper wire protocol with bookie" ) private boolean bookkeeperUseV2WireProtocol = true; @FieldContext( category = CATEGORY_STORAGE_BK, doc = "Enable bookies health check. \n\n Bookies that have more than the configured" + " number of failure within the interval will be quarantined for some time." + " During this period, new ledgers won't be created on these bookies") private boolean bookkeeperClientHealthCheckEnabled = true; @FieldContext( category = CATEGORY_STORAGE_BK, doc = "Bookies health check interval in seconds" ) private long bookkeeperClientHealthCheckIntervalSeconds = 60; @FieldContext( category = CATEGORY_STORAGE_BK, doc = "Bookies health check error threshold per check interval" ) private long bookkeeperClientHealthCheckErrorThresholdPerInterval = 5; @FieldContext( category = CATEGORY_STORAGE_BK, doc = "Bookie health check quarantined time in seconds" ) private long bookkeeperClientHealthCheckQuarantineTimeInSeconds = 1800; @FieldContext( category = CATEGORY_STORAGE_BK, doc = "Enable rack-aware bookie selection policy. \n\nBK will chose bookies from" + " different racks when forming a new bookie ensemble") private boolean bookkeeperClientRackawarePolicyEnabled = true; @FieldContext( category = CATEGORY_STORAGE_BK, doc = "Enable region-aware bookie selection policy. \n\nBK will chose bookies from" + " different regions and racks when forming a new bookie ensemble") private boolean bookkeeperClientRegionawarePolicyEnabled = false; @FieldContext( category = CATEGORY_STORAGE_BK, doc = "Enable/disable reordering read sequence on reading entries") private boolean bookkeeperClientReorderReadSequenceEnabled = false; @FieldContext( category = CATEGORY_STORAGE_BK, required = false, doc = "Enable bookie isolation by specifying a list of bookie groups to choose from. \n\n" + "Any bookie outside the specified groups will not be used by the broker") private String bookkeeperClientIsolationGroups; @FieldContext( category = CATEGORY_STORAGE_BK, required = false, doc = "Enable bookie secondary-isolation group if bookkeeperClientIsolationGroups doesn't have enough bookie available." ) private String bookkeeperClientSecondaryIsolationGroups; @FieldContext(category = CATEGORY_STORAGE_BK, doc = "Enable/disable having read operations for a ledger to be sticky to " + "a single bookie.\n" + "If this flag is enabled, the client will use one single bookie (by " + "preference) to read all entries for a ledger.") private boolean bookkeeperEnableStickyReads = true; /**** --- Managed Ledger --- ****/ @FieldContext( minValue = 1, category = CATEGORY_STORAGE_ML, doc = "Number of bookies to use when creating a ledger" ) private int managedLedgerDefaultEnsembleSize = 1; @FieldContext( minValue = 1, category = CATEGORY_STORAGE_ML, doc = "Number of copies to store for each message" ) private int managedLedgerDefaultWriteQuorum = 1; @FieldContext( minValue = 1, category = CATEGORY_STORAGE_ML, doc = "Number of guaranteed copies (acks to wait before write is complete)" ) private int managedLedgerDefaultAckQuorum = 1; // // @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Default type of checksum to use when writing to BookKeeper. \n\nDefault is `CRC32C`." + " Other possible options are `CRC32`, `MAC` or `DUMMY` (no checksum)." ) private DigestType managedLedgerDigestType = DigestType.CRC32C; @FieldContext( minValue = 1, category = CATEGORY_STORAGE_ML, doc = "Max number of bookies to use when creating a ledger" ) private int managedLedgerMaxEnsembleSize = 5; @FieldContext( minValue = 1, category = CATEGORY_STORAGE_ML, doc = "Max number of copies to store for each message" ) private int managedLedgerMaxWriteQuorum = 5; @FieldContext( minValue = 1, category = CATEGORY_STORAGE_ML, doc = "Max number of guaranteed copies (acks to wait before write is complete)" ) private int managedLedgerMaxAckQuorum = 5; @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Amount of memory to use for caching data payload in managed ledger. \n\nThis" + " memory is allocated from JVM direct memory and it's shared across all the topics" + " running in the same broker. By default, uses 1/5th of available direct memory") private int managedLedgerCacheSizeMB = Math.max(64, (int) (PlatformDependent.maxDirectMemory() / 5 / (1024 * 1024))); @FieldContext(category = CATEGORY_STORAGE_ML, doc = "Whether we should make a copy of the entry payloads when inserting in cache") private boolean managedLedgerCacheCopyEntries = false; @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Threshold to which bring down the cache level when eviction is triggered" ) private double managedLedgerCacheEvictionWatermark = 0.9f; @FieldContext(category = CATEGORY_STORAGE_ML, doc = "Configure the cache eviction frequency for the managed ledger cache. Default is 100/s") private double managedLedgerCacheEvictionFrequency = 100.0; @FieldContext(category = CATEGORY_STORAGE_ML, doc = "All entries that have stayed in cache for more than the configured time, will be evicted") private long managedLedgerCacheEvictionTimeThresholdMillis = 1000; @FieldContext(category = CATEGORY_STORAGE_ML, doc = "Configure the threshold (in number of entries) from where a cursor should be considered 'backlogged'" + " and thus should be set as inactive.") private long managedLedgerCursorBackloggedThreshold = 1000; @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Rate limit the amount of writes per second generated by consumer acking the messages" ) private double managedLedgerDefaultMarkDeleteRateLimit = 1.0; @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Allow automated creation of non-partition topics if set to true (default value)." ) private boolean allowAutoTopicCreation = true; @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Number of threads to be used for managed ledger tasks dispatching" ) private int managedLedgerNumWorkerThreads = Runtime.getRuntime().availableProcessors(); @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Number of threads to be used for managed ledger scheduled tasks" ) private int managedLedgerNumSchedulerThreads = Runtime.getRuntime().availableProcessors(); @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Max number of entries to append to a ledger before triggering a rollover.\n\n" + "A ledger rollover is triggered on these conditions Either the max" + " rollover time has been reached or max entries have been written to the" + " ledged and at least min-time has passed") private int managedLedgerMaxEntriesPerLedger = 50000; @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Minimum time between ledger rollover for a topic" ) private int managedLedgerMinLedgerRolloverTimeMinutes = 10; @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Maximum time before forcing a ledger rollover for a topic" ) private int managedLedgerMaxLedgerRolloverTimeMinutes = 240; @FieldContext( category = CATEGORY_STORAGE_OFFLOADING, doc = "Delay between a ledger being successfully offloaded to long term storage," + " and the ledger being deleted from bookkeeper" ) private long managedLedgerOffloadDeletionLagMs = TimeUnit.HOURS.toMillis(4); @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Max number of entries to append to a cursor ledger" ) private int managedLedgerCursorMaxEntriesPerLedger = 50000; @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Max time before triggering a rollover on a cursor ledger" ) private int managedLedgerCursorRolloverTimeInSeconds = 14400; @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Max number of `acknowledgment holes` that are going to be persistently stored.\n\n" + "When acknowledging out of order, a consumer will leave holes that are supposed" + " to be quickly filled by acking all the messages. The information of which" + " messages are acknowledged is persisted by compressing in `ranges` of messages" + " that were acknowledged. After the max number of ranges is reached, the information" + " will only be tracked in memory and messages will be redelivered in case of" + " crashes.") private int managedLedgerMaxUnackedRangesToPersist = 10000; @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Max number of `acknowledgment holes` that can be stored in Zookeeper.\n\n" + "If number of unack message range is higher than this limit then broker will persist" + " unacked ranges into bookkeeper to avoid additional data overhead into zookeeper.") private int managedLedgerMaxUnackedRangesToPersistInZooKeeper = 1000; @FieldContext( category = CATEGORY_STORAGE_OFFLOADING, doc = "Use Open Range-Set to cache unacked messages (it is memory efficient but it can take more cpu)" ) private boolean managedLedgerUnackedRangesOpenCacheSetEnabled = true; @FieldContext( dynamic = true, category = CATEGORY_STORAGE_ML, doc = "Skip reading non-recoverable/unreadable data-ledger under managed-ledger's list.\n\n" + " It helps when data-ledgers gets corrupted at bookkeeper and managed-cursor is stuck at that ledger." ) private boolean autoSkipNonRecoverableData = false; @FieldContext( category = CATEGORY_STORAGE_ML, doc = "operation timeout while updating managed-ledger metadata." ) private long managedLedgerMetadataOperationsTimeoutSeconds = 60; @FieldContext( category = CATEGORY_STORAGE_ML, doc = "Read entries timeout when broker tries to read messages from bookkeeper " + "(0 to disable it)" ) private long managedLedgerReadEntryTimeoutSeconds = 0; @FieldContext(category = CATEGORY_STORAGE_ML, doc = "Add entry timeout when broker tries to publish message to bookkeeper.(0 to disable it)") private long managedLedgerAddEntryTimeoutSeconds = 0; /*** --- Load balancer --- ****/ @FieldContext( category = CATEGORY_LOAD_BALANCER, doc = "Enable load balancer" ) private boolean loadBalancerEnabled = true; @Deprecated @FieldContext( category = CATEGORY_LOAD_BALANCER, deprecated = true, doc = "load placement strategy[weightedRandomSelection/leastLoadedServer] (only used by SimpleLoadManagerImpl)" ) private String loadBalancerPlacementStrategy = "leastLoadedServer"; // weighted random selection @FieldContext( dynamic = true, category = CATEGORY_LOAD_BALANCER, doc = "Percentage of change to trigger load report update" ) private int loadBalancerReportUpdateThresholdPercentage = 10; @FieldContext( dynamic = true, category = CATEGORY_LOAD_BALANCER, doc = "maximum interval to update load report" ) private int loadBalancerReportUpdateMaxIntervalMinutes = 15; @FieldContext( category = CATEGORY_LOAD_BALANCER, doc = "Frequency of report to collect, in minutes" ) private int loadBalancerHostUsageCheckIntervalMinutes = 1; @FieldContext( dynamic = true, category = CATEGORY_LOAD_BALANCER, doc = "Enable/disable automatic bundle unloading for load-shedding" ) private boolean loadBalancerSheddingEnabled = true; @FieldContext( category = CATEGORY_LOAD_BALANCER, doc = "Load shedding interval. \n\nBroker periodically checks whether some traffic" + " should be offload from some over-loaded broker to other under-loaded brokers" ) private int loadBalancerSheddingIntervalMinutes = 1; @FieldContext( category = CATEGORY_LOAD_BALANCER, doc = "Prevent the same topics to be shed and moved to other broker more that" + " once within this timeframe" ) private long loadBalancerSheddingGracePeriodMinutes = 30; @FieldContext( category = CATEGORY_LOAD_BALANCER, deprecated = true, doc = "Usage threshold to determine a broker as under-loaded (only used by SimpleLoadManagerImpl)" ) @Deprecated private int loadBalancerBrokerUnderloadedThresholdPercentage = 50; @FieldContext( dynamic = true, category = CATEGORY_LOAD_BALANCER, doc = "Usage threshold to allocate max number of topics to broker" ) private int loadBalancerBrokerMaxTopics = 50000; @FieldContext( dynamic = true, category = CATEGORY_LOAD_BALANCER, doc = "Usage threshold to determine a broker as over-loaded" ) private int loadBalancerBrokerOverloadedThresholdPercentage = 85; @FieldContext( category = CATEGORY_LOAD_BALANCER, doc = "Interval to flush dynamic resource quota to ZooKeeper" ) private int loadBalancerResourceQuotaUpdateIntervalMinutes = 15; @Deprecated @FieldContext( category = CATEGORY_LOAD_BALANCER, deprecated = true, doc = "Usage threshold to determine a broker is having just right level of load" + " (only used by SimpleLoadManagerImpl)" ) private int loadBalancerBrokerComfortLoadLevelPercentage = 65; @FieldContext( dynamic = true, category = CATEGORY_LOAD_BALANCER, doc = "enable/disable automatic namespace bundle split" ) private boolean loadBalancerAutoBundleSplitEnabled = true; @FieldContext( dynamic = true, category = CATEGORY_LOAD_BALANCER, doc = "enable/disable automatic unloading of split bundles" ) private boolean loadBalancerAutoUnloadSplitBundlesEnabled = true; @FieldContext( category = CATEGORY_LOAD_BALANCER, doc = "maximum topics in a bundle, otherwise bundle split will be triggered" ) private int loadBalancerNamespaceBundleMaxTopics = 1000; @FieldContext( category = CATEGORY_LOAD_BALANCER, doc = "maximum sessions (producers + consumers) in a bundle, otherwise bundle split will be triggered" ) private int loadBalancerNamespaceBundleMaxSessions = 1000; @FieldContext( category = CATEGORY_LOAD_BALANCER, doc = "maximum msgRate (in + out) in a bundle, otherwise bundle split will be triggered" ) private int loadBalancerNamespaceBundleMaxMsgRate = 30000; @FieldContext( category = CATEGORY_LOAD_BALANCER, doc = "maximum bandwidth (in + out) in a bundle, otherwise bundle split will be triggered" ) private int loadBalancerNamespaceBundleMaxBandwidthMbytes = 100; @FieldContext( category = CATEGORY_LOAD_BALANCER, doc = "maximum number of bundles in a namespace" ) private int loadBalancerNamespaceMaximumBundles = 128; @FieldContext( dynamic = true, category = CATEGORY_LOAD_BALANCER, doc = "Name of load manager to use" ) private String loadManagerClassName = "org.apache.pulsar.broker.loadbalance.impl.ModularLoadManagerImpl"; @FieldContext( category = CATEGORY_LOAD_BALANCER, doc = "Option to override the auto-detected network interfaces max speed" ) private Double loadBalancerOverrideBrokerNicSpeedGbps; /**** --- Replication --- ****/ @FieldContext( category = CATEGORY_REPLICATION, doc = "Enable replication metrics" ) private boolean replicationMetricsEnabled = false; @FieldContext( category = CATEGORY_REPLICATION, doc = "Max number of connections to open for each broker in a remote cluster.\n\n" + "More connections host-to-host lead to better throughput over high-latency links" ) private int replicationConnectionsPerBroker = 16; @FieldContext( required = false, category = CATEGORY_REPLICATION, doc = "replicator prefix used for replicator producer name and cursor name" ) private String replicatorPrefix = "pulsar.repl"; @FieldContext( category = CATEGORY_REPLICATION, doc = "Replicator producer queue size" ) private int replicationProducerQueueSize = 1000; @Deprecated @FieldContext( category = CATEGORY_REPLICATION, deprecated = true, doc = "@deprecated - Use brokerClientTlsEnabled instead." ) private boolean replicationTlsEnabled = false; @FieldContext( category = CATEGORY_REPLICATION, doc = "Enable TLS when talking with other brokers in the same cluster (admin operation)" + " or different clusters (replication)" ) private boolean brokerClientTlsEnabled = false; @FieldContext( category = CATEGORY_POLICIES, doc = "Default message retention time" ) private int defaultRetentionTimeInMinutes = 0; @FieldContext( category = CATEGORY_POLICIES, doc = "Default retention size" ) private int defaultRetentionSizeInMB = 0; @FieldContext( category = CATEGORY_SERVER, doc = "How often to check pulsar connection is still alive" ) private int keepAliveIntervalSeconds = 30; @FieldContext( category = CATEGORY_POLICIES, doc = "How often broker checks for inactive topics to be deleted (topics with no subscriptions and no one connected)" ) private int brokerServicePurgeInactiveFrequencyInSeconds = 60; @FieldContext( category = CATEGORY_SERVER, doc = "A comma-separated list of namespaces to bootstrap" ) private List<String> bootstrapNamespaces = new ArrayList<String>(); private Properties properties = new Properties(); @FieldContext( dynamic = true, category = CATEGORY_SERVER, doc = "If true, (and ModularLoadManagerImpl is being used), the load manager will attempt to " + "use only brokers running the latest software version (to minimize impact to bundles)" ) private boolean preferLaterVersions = false; @FieldContext( category = CATEGORY_SERVER, doc = "Interval between checks to see if topics with compaction policies need to be compacted" ) private int brokerServiceCompactionMonitorIntervalInSeconds = 60; @FieldContext( category = CATEGORY_SCHEMA, doc = "Enforce schema validation on following cases:\n\n" + " - if a producer without a schema attempts to produce to a topic with schema, the producer will be\n" + " failed to connect. PLEASE be carefully on using this, since non-java clients don't support schema.\n" + " if you enable this setting, it will cause non-java clients failed to produce." ) private boolean isSchemaValidationEnforced = false; @FieldContext( category = CATEGORY_SCHEMA, doc = "The schema storage implementation used by this broker" ) private String schemaRegistryStorageClassName = "org.apache.pulsar.broker.service.schema.BookkeeperSchemaStorageFactory"; @FieldContext( category = CATEGORY_SCHEMA, doc = "The list compatibility checkers to be used in schema registry" ) private Set<String> schemaRegistryCompatibilityCheckers = Sets.newHashSet( "org.apache.pulsar.broker.service.schema.JsonSchemaCompatibilityCheck", "org.apache.pulsar.broker.service.schema.AvroSchemaCompatibilityCheck" ); /**** --- WebSocket --- ****/ @FieldContext( category = CATEGORY_WEBSOCKET, doc = "Number of IO threads in Pulsar Client used in WebSocket proxy" ) private int webSocketNumIoThreads = Runtime.getRuntime().availableProcessors(); @FieldContext( category = CATEGORY_WEBSOCKET, doc = "Number of connections per Broker in Pulsar Client used in WebSocket proxy" ) private int webSocketConnectionsPerBroker = Runtime.getRuntime().availableProcessors(); @FieldContext( category = CATEGORY_WEBSOCKET, doc = "Time in milliseconds that idle WebSocket session times out" ) private int webSocketSessionIdleTimeoutMillis = 300000; /**** --- Metrics --- ****/ @FieldContext( category = CATEGORY_METRICS, doc = "If true, export topic level metrics otherwise namespace level" ) private boolean exposeTopicLevelMetricsInPrometheus = true; @FieldContext( category = CATEGORY_METRICS, doc = "If true, export consumer level metrics otherwise namespace level" ) private boolean exposeConsumerLevelMetricsInPrometheus = false; @FieldContext( category = CATEGORY_METRICS, doc = "Classname of Pluggable JVM GC metrics logger that can log GC specific metrics") private String jvmGCMetricsLoggerClassName; /**** --- Functions --- ****/ @FieldContext( category = CATEGORY_FUNCTIONS, doc = "Flag indicates enabling or disabling function worker on brokers" ) private boolean functionsWorkerEnabled = false; /**** --- Broker Web Stats --- ****/ @FieldContext( category = CATEGORY_METRICS, doc = "If true, export publisher stats when returning topics stats from the admin rest api" ) private boolean exposePublisherStats = true; @FieldContext( category = CATEGORY_METRICS, doc = "Stats update frequency in seconds" ) private int statsUpdateFrequencyInSecs = 60; @FieldContext( category = CATEGORY_METRICS, doc = "Stats update initial delay in seconds" ) private int statsUpdateInitialDelayInSecs = 60; /**** --- Ledger Offloading --- ****/ /**** * NOTES: all implementation related settings should be put in implementation package. * only common settings like driver name, io threads can be added here. ****/ @FieldContext( category = CATEGORY_STORAGE_OFFLOADING, doc = "The directory to locate offloaders" ) private String offloadersDirectory = "./offloaders"; @FieldContext( category = CATEGORY_STORAGE_OFFLOADING, doc = "Driver to use to offload old data to long term storage" ) private String managedLedgerOffloadDriver = null; @FieldContext( category = CATEGORY_STORAGE_OFFLOADING, doc = "Maximum number of thread pool threads for ledger offloading" ) private int managedLedgerOffloadMaxThreads = 2; /** * @deprecated See {@link #getConfigurationStoreServers} */ @Deprecated public String getGlobalZookeeperServers() { if (this.globalZookeeperServers == null || this.globalZookeeperServers.isEmpty()) { // If the configuration is not set, assuming that the globalZK is not enabled and all data is in the same // ZooKeeper cluster return this.getZookeeperServers(); } return globalZookeeperServers; } /** * @deprecated See {@link #setConfigurationStoreServers(String)} */ @Deprecated public void setGlobalZookeeperServers(String globalZookeeperServers) { this.globalZookeeperServers = globalZookeeperServers; } public String getConfigurationStoreServers() { if (this.configurationStoreServers == null || this.configurationStoreServers.isEmpty()) { // If the configuration is not set, assuming that all data is in the same as globalZK cluster return this.getGlobalZookeeperServers(); } return configurationStoreServers; } public void setConfigurationStoreServers(String configurationStoreServers) { this.configurationStoreServers = configurationStoreServers; } public Object getProperty(String key) { return properties.get(key); } @Override public Properties getProperties() { return properties; } @Override public void setProperties(Properties properties) { this.properties = properties; } public Optional<Double> getLoadBalancerOverrideBrokerNicSpeedGbps() { return Optional.ofNullable(loadBalancerOverrideBrokerNicSpeedGbps); } public int getBookkeeperHealthCheckIntervalSec() { return (int) bookkeeperClientHealthCheckIntervalSeconds; } public Optional<Integer> getBrokerServicePort() { return brokerServicePort; } public Optional<Integer> getBrokerServicePortTls() { return brokerServicePortTls; } public Optional<Integer> getWebServicePort() { return webServicePort; } public Optional<Integer> getWebServicePortTls() { return webServicePortTls; } }
[pulsar-broker] make replication mtls configuration dynamic (#4609)
pulsar-broker-common/src/main/java/org/apache/pulsar/broker/ServiceConfiguration.java
[pulsar-broker] make replication mtls configuration dynamic (#4609)
<ide><path>ulsar-broker-common/src/main/java/org/apache/pulsar/broker/ServiceConfiguration.java <ide> <ide> @FieldContext( <ide> category = CATEGORY_AUTHENTICATION, <add> dynamic = true, <ide> doc = "Authentication settings of the broker itself. \n\nUsed when the broker connects" <ide> + " to other brokers, either in same or other clusters. Default uses plugin which disables authentication" <ide> ) <ide> private String brokerClientAuthenticationPlugin = "org.apache.pulsar.client.impl.auth.AuthenticationDisabled"; <ide> @FieldContext( <ide> category = CATEGORY_AUTHENTICATION, <add> dynamic = true, <ide> doc = "Authentication parameters of the authentication plugin the broker is using to connect to other brokers" <ide> ) <ide> private String brokerClientAuthenticationParameters = ""; <ide> private boolean replicationTlsEnabled = false; <ide> @FieldContext( <ide> category = CATEGORY_REPLICATION, <add> dynamic = true, <ide> doc = "Enable TLS when talking with other brokers in the same cluster (admin operation)" <ide> + " or different clusters (replication)" <ide> )
Java
mit
fe945d91983c854e2c6e79e225761f48ffd04059
0
wuwen5/lombok,riccardobl/lombok,mg6maciej/hrisey,Tradunsky/lombok,Arvoreen/lombok,dmissoh/lombok,riccardobl/lombok,fpeter8/lombok,yangpeiyong/hrisey,redundent/lombok,MaTriXy/lombok,martenbohlin/lombok,arielnetworks/lombok,timtreibmann/lombokDataReceived,dcendents/lombok,openlegacy/lombok,openlegacy/lombok,vampiregod1996/lombok,nickbarban/lombok,jdiasamaro/lombok,dcendents/lombok,timtreibmann/lombokDataReceived,openlegacy/lombok,dcendents/lombok,derektom14/lombok,arielnetworks/lombok,mg6maciej/hrisey,Arvoreen/lombok,martenbohlin/lombok,Lekanich/lombok,nickbarban/lombok,Arvoreen/lombok,jdiasamaro/lombok,Shedings/hrisey,Beabel2/lombok,rzwitserloot/lombok,Tradunsky/lombok,Shedings/hrisey,Beabel2/lombok,luanpotter/lombok,vampiregod1996/lombok,yangpeiyong/hrisey,Lekanich/lombok,develhack/develhacked-lombok,martenbohlin/lombok,jdiasamaro/lombok,dmissoh/lombok,fpeter8/lombok,riccardobl/lombok,domix/lombok,mg6maciej/hrisey,yangpeiyong/hrisey,Shedings/hrisey,fpeter8/lombok,domix/lombok,rzwitserloot/lombok,Arvoreen/lombok,fpeter8/lombok,MaTriXy/lombok,wuwen5/lombok,openlegacy/lombok,luanpotter/lombok,Tradunsky/lombok,luanpotter/lombok,rzwitserloot/lombok,consulo/lombokOld,redundent/lombok,rzwitserloot/lombok,dmissoh/lombok,vampiregod1996/lombok,rzwitserloot/lombok,luanpotter/lombok,domix/lombok,redundent/lombok,wuwen5/lombok,jdiasamaro/lombok,derektom14/lombok,dcendents/lombok,derektom14/lombok,develhack/develhacked-lombok,mg6maciej/hrisey,dmissoh/lombok,fpeter8/lombok,timtreibmann/lombokDataReceived,Shedings/hrisey,timtreibmann/lombokDataReceived,riccardobl/lombok,develhack/develhacked-lombok,derektom14/lombok,Beabel2/lombok,wuwen5/lombok,fpeter8/lombok,Lekanich/lombok,vampiregod1996/lombok,arielnetworks/lombok,MaTriXy/lombok,Tradunsky/lombok,martenbohlin/lombok,nickbarban/lombok,nickbarban/lombok,Beabel2/lombok,yangpeiyong/hrisey,develhack/develhacked-lombok,MaTriXy/lombok,Lekanich/lombok
/* * Copyright © 2009 Reinier Zwitserloot and Roel Spilker. * * 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 lombok.javac.apt; import java.util.ArrayList; import java.util.IdentityHashMap; import java.util.List; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.annotation.processing.SupportedSourceVersion; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic.Kind; import lombok.javac.HandlerLibrary; import lombok.javac.JavacAST; import lombok.javac.JavacASTAdapter; import lombok.javac.JavacAST.Node; import com.sun.source.util.TreePath; import com.sun.source.util.Trees; import com.sun.tools.javac.processing.JavacProcessingEnvironment; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; /** * This Annotation Processor is the standard injection mechanism for lombok-enabling the javac compiler. * * Due to lots of changes in the core javac code, as well as lombok's heavy usage of non-public API, this * code only works for the javac v1.6 compiler; it definitely won't work for javac v1.5, and it probably * won't work for javac v1.7 without modifications. * * To actually enable lombok in a javac compilation run, this class should be in the classpath when * running javac; that's the only requirement. */ @SupportedAnnotationTypes("*") @SupportedSourceVersion(SourceVersion.RELEASE_6) public class Processor extends AbstractProcessor { private JavacProcessingEnvironment processingEnv; private HandlerLibrary handlers; private Trees trees; /** {@inheritDoc} */ @Override public void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); if ( !(processingEnv instanceof JavacProcessingEnvironment) ) { processingEnv.getMessager().printMessage(Kind.WARNING, "You aren't using a compiler based around javac v1.6, so lombok will not work properly."); this.processingEnv = null; } else { this.processingEnv = (JavacProcessingEnvironment) processingEnv; handlers = HandlerLibrary.load(processingEnv.getMessager()); trees = Trees.instance(processingEnv); } } /** {@inheritDoc} */ @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if ( processingEnv == null ) return false; IdentityHashMap<JCCompilationUnit, Void> units = new IdentityHashMap<JCCompilationUnit, Void>(); for ( Element element : roundEnv.getRootElements() ) { JCCompilationUnit unit = toUnit(element); if ( unit != null ) units.put(unit, null); } List<JavacAST> asts = new ArrayList<JavacAST>(); for ( JCCompilationUnit unit : units.keySet() ) asts.add(new JavacAST(trees, processingEnv, unit)); handlers.skipPrintAST(); for ( JavacAST ast : asts ) { ast.traverse(new AnnotationVisitor()); handlers.callASTVisitors(ast); } handlers.skipAllButPrintAST(); for ( JavacAST ast : asts ) { ast.traverse(new AnnotationVisitor()); } return false; } private class AnnotationVisitor extends JavacASTAdapter { @Override public void visitAnnotationOnType(JCClassDecl type, Node annotationNode, JCAnnotation annotation) { if ( annotationNode.isHandled() ) return; JCCompilationUnit top = (JCCompilationUnit) annotationNode.top().get(); boolean handled = handlers.handleAnnotation(top, annotationNode, annotation); if ( handled ) annotationNode.setHandled(); } @Override public void visitAnnotationOnField(JCVariableDecl field, Node annotationNode, JCAnnotation annotation) { if ( annotationNode.isHandled() ) return; JCCompilationUnit top = (JCCompilationUnit) annotationNode.top().get(); boolean handled = handlers.handleAnnotation(top, annotationNode, annotation); if ( handled ) annotationNode.setHandled(); } @Override public void visitAnnotationOnMethod(JCMethodDecl method, Node annotationNode, JCAnnotation annotation) { if ( annotationNode.isHandled() ) return; JCCompilationUnit top = (JCCompilationUnit) annotationNode.top().get(); boolean handled = handlers.handleAnnotation(top, annotationNode, annotation); if ( handled ) annotationNode.setHandled(); } @Override public void visitAnnotationOnMethodArgument(JCVariableDecl argument, JCMethodDecl method, Node annotationNode, JCAnnotation annotation) { if ( annotationNode.isHandled() ) return; JCCompilationUnit top = (JCCompilationUnit) annotationNode.top().get(); boolean handled = handlers.handleAnnotation(top, annotationNode, annotation); if ( handled ) annotationNode.setHandled(); } @Override public void visitAnnotationOnLocal(JCVariableDecl local, Node annotationNode, JCAnnotation annotation) { if ( annotationNode.isHandled() ) return; JCCompilationUnit top = (JCCompilationUnit) annotationNode.top().get(); boolean handled = handlers.handleAnnotation(top, annotationNode, annotation); if ( handled ) annotationNode.setHandled(); } } private JCCompilationUnit toUnit(Element element) { TreePath path = trees.getPath(element); if ( path != null ) return (JCCompilationUnit) path.getCompilationUnit(); else { if ( element == null ) { processingEnv.getMessager().printMessage(Kind.WARNING, "LOMBOK DIAGNOSTIC: no TreePath returned for element, " + "probably because element is null!"); } processingEnv.getMessager().printMessage(Kind.WARNING, "LOMBOK DIAGNOSTIC: no TreePath returned for element of type: " + element.getClass() + "with toString: " + element); return null; } } }
src/lombok/javac/apt/Processor.java
/* * Copyright © 2009 Reinier Zwitserloot and Roel Spilker. * * 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 lombok.javac.apt; import java.util.ArrayList; import java.util.IdentityHashMap; import java.util.List; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.annotation.processing.SupportedSourceVersion; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic.Kind; import lombok.javac.HandlerLibrary; import lombok.javac.JavacAST; import lombok.javac.JavacASTAdapter; import lombok.javac.JavacAST.Node; import com.sun.source.util.Trees; import com.sun.tools.javac.processing.JavacProcessingEnvironment; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; /** * This Annotation Processor is the standard injection mechanism for lombok-enabling the javac compiler. * * Due to lots of changes in the core javac code, as well as lombok's heavy usage of non-public API, this * code only works for the javac v1.6 compiler; it definitely won't work for javac v1.5, and it probably * won't work for javac v1.7 without modifications. * * To actually enable lombok in a javac compilation run, this class should be in the classpath when * running javac; that's the only requirement. */ @SupportedAnnotationTypes("*") @SupportedSourceVersion(SourceVersion.RELEASE_6) public class Processor extends AbstractProcessor { private JavacProcessingEnvironment processingEnv; private HandlerLibrary handlers; private Trees trees; /** {@inheritDoc} */ @Override public void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); if ( !(processingEnv instanceof JavacProcessingEnvironment) ) { processingEnv.getMessager().printMessage(Kind.WARNING, "You aren't using a compiler based around javac v1.6, so lombok will not work properly."); this.processingEnv = null; } else { this.processingEnv = (JavacProcessingEnvironment) processingEnv; handlers = HandlerLibrary.load(processingEnv.getMessager()); trees = Trees.instance(processingEnv); } } /** {@inheritDoc} */ @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if ( processingEnv == null ) return false; IdentityHashMap<JCCompilationUnit, Void> units = new IdentityHashMap<JCCompilationUnit, Void>(); for ( Element element : roundEnv.getRootElements() ) units.put(toUnit(element), null); List<JavacAST> asts = new ArrayList<JavacAST>(); for ( JCCompilationUnit unit : units.keySet() ) asts.add(new JavacAST(trees, processingEnv, unit)); handlers.skipPrintAST(); for ( JavacAST ast : asts ) { ast.traverse(new AnnotationVisitor()); handlers.callASTVisitors(ast); } handlers.skipAllButPrintAST(); for ( JavacAST ast : asts ) { ast.traverse(new AnnotationVisitor()); } return false; } private class AnnotationVisitor extends JavacASTAdapter { @Override public void visitAnnotationOnType(JCClassDecl type, Node annotationNode, JCAnnotation annotation) { if ( annotationNode.isHandled() ) return; JCCompilationUnit top = (JCCompilationUnit) annotationNode.top().get(); boolean handled = handlers.handleAnnotation(top, annotationNode, annotation); if ( handled ) annotationNode.setHandled(); } @Override public void visitAnnotationOnField(JCVariableDecl field, Node annotationNode, JCAnnotation annotation) { if ( annotationNode.isHandled() ) return; JCCompilationUnit top = (JCCompilationUnit) annotationNode.top().get(); boolean handled = handlers.handleAnnotation(top, annotationNode, annotation); if ( handled ) annotationNode.setHandled(); } @Override public void visitAnnotationOnMethod(JCMethodDecl method, Node annotationNode, JCAnnotation annotation) { if ( annotationNode.isHandled() ) return; JCCompilationUnit top = (JCCompilationUnit) annotationNode.top().get(); boolean handled = handlers.handleAnnotation(top, annotationNode, annotation); if ( handled ) annotationNode.setHandled(); } @Override public void visitAnnotationOnMethodArgument(JCVariableDecl argument, JCMethodDecl method, Node annotationNode, JCAnnotation annotation) { if ( annotationNode.isHandled() ) return; JCCompilationUnit top = (JCCompilationUnit) annotationNode.top().get(); boolean handled = handlers.handleAnnotation(top, annotationNode, annotation); if ( handled ) annotationNode.setHandled(); } @Override public void visitAnnotationOnLocal(JCVariableDecl local, Node annotationNode, JCAnnotation annotation) { if ( annotationNode.isHandled() ) return; JCCompilationUnit top = (JCCompilationUnit) annotationNode.top().get(); boolean handled = handlers.handleAnnotation(top, annotationNode, annotation); if ( handled ) annotationNode.setHandled(); } } private JCCompilationUnit toUnit(Element element) { return (JCCompilationUnit) trees.getPath(element).getCompilationUnit(); } }
More attempts to fix NullPointerExceptions reported on the forums. http://groups.google.com/group/project-lombok/browse_thread/thread/a8d59daaf7c1ae09
src/lombok/javac/apt/Processor.java
More attempts to fix NullPointerExceptions reported on the forums.
<ide><path>rc/lombok/javac/apt/Processor.java <ide> import lombok.javac.JavacASTAdapter; <ide> import lombok.javac.JavacAST.Node; <ide> <add>import com.sun.source.util.TreePath; <ide> import com.sun.source.util.Trees; <ide> import com.sun.tools.javac.processing.JavacProcessingEnvironment; <ide> import com.sun.tools.javac.tree.JCTree.JCAnnotation; <ide> <ide> <ide> IdentityHashMap<JCCompilationUnit, Void> units = new IdentityHashMap<JCCompilationUnit, Void>(); <del> for ( Element element : roundEnv.getRootElements() ) units.put(toUnit(element), null); <add> for ( Element element : roundEnv.getRootElements() ) { <add> JCCompilationUnit unit = toUnit(element); <add> if ( unit != null ) units.put(unit, null); <add> } <ide> <ide> List<JavacAST> asts = new ArrayList<JavacAST>(); <ide> <ide> } <ide> <ide> private JCCompilationUnit toUnit(Element element) { <del> return (JCCompilationUnit) trees.getPath(element).getCompilationUnit(); <add> TreePath path = trees.getPath(element); <add> if ( path != null ) return (JCCompilationUnit) path.getCompilationUnit(); <add> else { <add> if ( element == null ) { <add> processingEnv.getMessager().printMessage(Kind.WARNING, "LOMBOK DIAGNOSTIC: no TreePath returned for element, " + <add> "probably because element is null!"); <add> } <add> processingEnv.getMessager().printMessage(Kind.WARNING, "LOMBOK DIAGNOSTIC: no TreePath returned for element of type: " + <add> element.getClass() + "with toString: " + element); <add> return null; <add> } <ide> } <ide> }
JavaScript
mit
7c8d44c5dedaeb655e69cd3b06f99fc7553054e5
0
dstreet/inline-svg
/*! * Inline SVG Polyfill v.1.0.1 * ---------------------------------------------------------------------------- * Find inline SVG elements and replace them with a fallback image set via * the `data-fallback` attribute. * * @author David Street * @license MIT */ (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['exports'], factory); } else if (typeof exports === 'object') { // CommonJS factory(exports); } else { // Browser globals var exports = {}; factory(exports); root.InlineSVG = exports.InlineSVG; } }(this, function (exports) { exports.InlineSVG = function() { var svgList = null , removeEl = []; /** * Create a replacement element with the fallback image */ function _replaceSVG() { svgList = document.getElementsByTagName('svg'); for (var i = 0, len = svgList.length; i < len; i += 1) { var fallback = svgList[i].getAttribute('data-fallback') , parent = null , useEl = null , ref = null , replacement = null , viewBox; // Go to next element if no fallback was given if (!fallback) continue; useEl = svgList[i].querySelector('use'); // Go to next element if the svg does not have a `use` child if (!useEl) continue; ref = document.getElementById(useEl.getAttribute('xlink:href').replace('#', '')); // Go to next element if the svg doc we are referencing doesn't exist if (!ref) continue; viewBox = _getViewBox(ref); parent = svgList[i].parentElement; replacement = _createReplacement(viewBox, fallback, svgList[i]); // Add new replacement element to the parent parent.insertBefore(replacement, svgList[i]); removeEl.push(svgList[i]); } _hideSVG(); } /** * Create a viewBox object for an element * * @param Object The element * * @return Object The viewBox */ function _getViewBox(el) { var attArray = [] , viewBox = {}; attArray = el.getAttribute('viewBox').split(' '); viewBox.x = attArray[0]; viewBox.y = attArray[1]; viewBox.width = attArray[2]; viewBox.height = attArray[3]; return viewBox; } /** * Create new element with fallback background * * @param Object The viewBox object * @param String The path to the fallback image * @param Object The reference element * * @return Object The replacement element */ function _createReplacement(viewBox, fallback, ref) { var replacement; replacement = document.createElement('div'); replacement.setAttribute('class', ref.getAttribute('class')); replacement.style.width = viewBox.width + 'px'; replacement.style.height = viewBox.height + 'px'; replacement.style.background = 'transparent url(' + fallback + ') no-repeat -' + viewBox.x + 'px -' + viewBox.y + 'px'; return replacement } /** * Hide all elements that have been replaced */ function _hideSVG() { for (var i = 0, len = removeEl.length; i < len; i += 1) { removeEl[i].style.display = 'none'; } } /** * Check support for inline SVGs. * * Courtesy of Modernizr: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/svg/inline.js * * @return Boolean */ function _checkSupport() { var div = createElement('div'); div.innerHTML = '<svg/>'; return (div.firstChild && div.firstChild.namespaceURI) == 'http://www.w3.org/2000/svg'; } return { init: function() { // Exit if inline svg is supported by the browser if (_checkSupport()) { return false } else { _replaceSVG(); } } } }; }));
src/main.js
/*! * Inline SVG Polyfill v.1.0.1 * ---------------------------------------------------------------------------- * Find inline SVG elements and replace them with a fallback image set via * the `data-fallback` attribute. * * @author David Street * @license MIT */ (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['exports'], factory); } else if (typeof exports === 'object') { // CommonJS factory(exports); } else { // Browser globals var exports = {}; factory(exports); root.InlineSVG = exports.InlineSVG; } }(this, function (exports) { exports.InlineSVG = function() { var svgList = null , removeEl = []; /** * Create a replacement element with the fallback image */ function _replaceSVG() { svgList = document.getElementsByTagName('svg'); for (var i = 0, len = svgList.length; i < len; i += 1) { var fallback = svgList[i].getAttribute('data-fallback') , parent = null , useEl = null , ref = null , replacement = null , viewBox; // Go to next element if no fallback was given if (!fallback) continue; useEl = svgList[i].querySelector('use'); // Go to next element if the svg does not have a `use` child if (!useEl) continue; ref = document.getElementById(useEl.getAttribute('xlink:href').replace('#', '')); // Go to next element if the svg doc we are referencing doesn't exist if (!ref) continue; viewBox = _getViewBox(ref); parent = svgList[i].parentElement; replacement = _createReplacement(viewBox, fallback, svgList[i]); // Add new replacement element to the parent parent.insertBefore(replacement, svgList[i]); removeEl.push(svgList[i]); } _hideSVG(); } /** * Create a viewBox object for an element * * @param Object The element * * @return Object The viewBox */ function _getViewBox(el) { var attArray = [] , viewBox = {}; attArray = el.getAttribute('viewBox').split(' '); viewBox.x = attArray[0]; viewBox.y = attArray[1]; viewBox.width = attArray[2]; viewBox.height = attArray[3]; return viewBox; } /** * Create new element with fallback background * * @param Object The viewBox object * @param String The path to the fallback image * @param Object The reference element * * @return Object The replacement element */ function _createReplacement(viewBox, fallback, ref) { var replacement; replacement = document.createElement('div'); replacement.setAttribute('class', ref.getAttribute('class')); replacement.style.width = viewBox.width + 'px'; replacement.style.height = viewBox.height + 'px'; replacement.style.background = 'transparent url(' + fallback + ') no-repeat -' + viewBox.x + 'px -' + viewBox.y + 'px'; return replacement } /** * Hide all elements that have been replaced */ function _hideSVG() { for (var i = 0, len = removeEl.length; i < len; i += 1) { removeEl[i].style.display = 'none'; } } /** * Check support for inline SVGs. * * Courtesy of Modernizr: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/svg/inline.js * * @return Boolean */ function _checkSupport() { var div = createElement('div'); div.innerHTML = '<svg/>'; return (div.firstChild && div.firstChild.namespaceURI) == 'http://www.w3.org/2000/svg'; } return { init: function() { // Exit if inline svg is supported by the browser if (_checkSupport()) { return false } else { _replaceSVG(); } } } }; }));
Use tabs over spaces
src/main.js
Use tabs over spaces
<ide><path>rc/main.js <ide> <ide> <ide> (function (root, factory) { <del> if (typeof define === 'function' && define.amd) { <del> // AMD. Register as an anonymous module. <del> define(['exports'], factory); <del> } else if (typeof exports === 'object') { <del> // CommonJS <del> factory(exports); <del> } else { <del> // Browser globals <del> var exports = {}; <add> if (typeof define === 'function' && define.amd) { <add> // AMD. Register as an anonymous module. <add> define(['exports'], factory); <add> } else if (typeof exports === 'object') { <add> // CommonJS <add> factory(exports); <add> } else { <add> // Browser globals <add> var exports = {}; <ide> factory(exports); <ide> root.InlineSVG = exports.InlineSVG; <del> } <add> } <ide> }(this, function (exports) { <ide> <ide> <ide> */ <ide> function _checkSupport() { <ide> var div = createElement('div'); <del> div.innerHTML = '<svg/>'; <del> return (div.firstChild && div.firstChild.namespaceURI) == 'http://www.w3.org/2000/svg'; <add> div.innerHTML = '<svg/>'; <add> return (div.firstChild && div.firstChild.namespaceURI) == 'http://www.w3.org/2000/svg'; <ide> } <ide> <ide> return {
Java
mit
a001862e834a281fc3f82e6bc966bb718c019ec0
0
SMUnlimited/sonar-stash,AmadeusITGroup/sonar-stash,acopet/sonar-stash,SMUnlimited/sonar-stash,acopet/sonar-stash,AmadeusITGroup/sonar-stash
package org.sonar.plugins.stash; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class PluginUtils { // Hiding implicit public constructor with an explicit private one (squid:S1118) private PluginUtils() { } private static final Logger LOGGER = LoggerFactory.getLogger(PluginUtils.class); private static final String ERROR_DETAILS = "Exception detected: {}"; private static final String ERROR_STACK = "Exception stack trace"; public static PluginInfo infoForPluginClass(Class klass) { try { Enumeration<URL> resources = klass.getClassLoader().getResources("META-INF/MANIFEST.MF"); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); Manifest man; try (InputStream ms = resource.openStream()) { man = new Manifest(ms); } Attributes attrs = man.getMainAttributes(); if (attrs == null) { continue; } String pluginClass = attrs.getValue("Plugin-Class"); if (pluginClass == null || ! classesMatching(pluginClass, klass)) { continue; } String pluginVersion = attrs.getValue("Plugin-Version"); String pluginName = attrs.getValue("Plugin-Name"); return new PluginInfo(pluginName, pluginVersion); } } catch (IOException e) { LOGGER.warn(ERROR_DETAILS, e.getMessage()); LOGGER.debug(ERROR_STACK, e); return null; } return null; } private static boolean classesMatching(String className, Class right) { boolean doesMatch = false; // Let's compare the plugin's class with another one (without '==', see SQUID:S1872) try { Class<?> left = Class.forName(className); Object leftObj = left.getClass().newInstance(); Object rightObj = right.getClass().newInstance(); if ( left.isInstance(rightObj) || right.isInstance(leftObj) ) { doesMatch = true; } } catch (ClassNotFoundException|InstantiationException|IllegalAccessException e) { LOGGER.warn(ERROR_DETAILS, e.getMessage()); LOGGER.debug(ERROR_STACK, e); } return doesMatch; } }
src/main/java/org/sonar/plugins/stash/PluginUtils.java
package org.sonar.plugins.stash; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class PluginUtils { // Hiding implicit public constructor with an explicit private one (squid:S1118) private PluginUtils() { } private static final Logger LOGGER = LoggerFactory.getLogger(PluginUtils.class); private static final String ERROR_DETAILS = "Exception detected: {}"; private static final String ERROR_STACK = "Exception stack trace"; public static PluginInfo infoForPluginClass(Class klass) { try { Enumeration<URL> resources = klass.getClassLoader().getResources("META-INF/MANIFEST.MF"); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); Manifest man; try (InputStream ms = resource.openStream()) { man = new Manifest(ms); } Attributes attrs = man.getMainAttributes(); if (attrs == null) { continue; } String pluginClass = attrs.getValue("Plugin-Class"); if (pluginClass == null || ! classesMatching(pluginClass, klass)) { continue; } String pluginVersion = attrs.getValue("Plugin-Version"); String pluginName = attrs.getValue("Plugin-Name"); return new PluginInfo(pluginName, pluginVersion); } } catch (IOException e) { LOGGER.warn(ERROR_DETAILS, e.getMessage()); LOGGER.debug(ERROR_STACK, e); return null; } return null; } private static boolean classesMatching(String className, Class right) { boolean doesMatch = false; // Let's compare the plugin's class with another one (without '==', see SQUID:S1872) try { Class<?> left = Class.forName(className); Object leftObj = left.getClass().newInstance(); Object rightObj = right.getClass().newInstance(); if ( left.isInstance(rightObj) || right.isInstance(leftObj) ) { doesMatch = true; } } catch (ClassNotFoundException e) { LOGGER.warn(ERROR_DETAILS, e.getMessage()); LOGGER.debug(ERROR_STACK, e); } catch (InstantiationException e) { LOGGER.warn(ERROR_DETAILS, e.getMessage()); LOGGER.debug(ERROR_STACK, e); } catch (IllegalAccessException e) { LOGGER.warn(ERROR_DETAILS, e.getMessage()); LOGGER.debug(ERROR_STACK, e); } return doesMatch; } }
CQ: fixing SQUID:S2147
src/main/java/org/sonar/plugins/stash/PluginUtils.java
CQ: fixing SQUID:S2147
<ide><path>rc/main/java/org/sonar/plugins/stash/PluginUtils.java <ide> doesMatch = true; <ide> } <ide> <del> } catch (ClassNotFoundException e) { <add> } catch (ClassNotFoundException|InstantiationException|IllegalAccessException e) { <ide> LOGGER.warn(ERROR_DETAILS, e.getMessage()); <ide> LOGGER.debug(ERROR_STACK, e); <del> <del> } catch (InstantiationException e) { <del> LOGGER.warn(ERROR_DETAILS, e.getMessage()); <del> LOGGER.debug(ERROR_STACK, e); <del> <del> } catch (IllegalAccessException e) { <del> LOGGER.warn(ERROR_DETAILS, e.getMessage()); <del> LOGGER.debug(ERROR_STACK, e); <del> <ide> } <ide> return doesMatch; <ide> }
JavaScript
mit
dcfaeb9fe41edfebccfa4a7686d3b0ae1546c167
0
thealscott/sassquatch,thealscott/sassquatch
exports.init = function(grunt) { var sassquatch = { 'setup' : function() { grunt.log.write('Running full SASSquatch setup, from config JSON'); var config = grunt.config.get('sassquatch'); // Ok, let's get this party started by creating all the config files that are always there grunt.file.write(config.sass_path +'/config/_imports_pages.scss', ''); grunt.file.write(config.sass_path +'/config/_imports_modules.scss', ''); // now we add the extra stuff from the config config.extra_configs.forEach(function(value, index) { grunt.file.write(config.sass_path +'/config/_'+ value +'.scss', ''); }); // Now compile the master imports file var replacements = { 'config_imports' : '', 'helpers_imports' : '' }; config.extra_configs.forEach(function(value, index) { replacements.config_imports += '@import "config/'+ value +'";\r\n'; }); config.helpers.forEach(function(value, index) { replacements.helpers_imports += '@import "helpers/'+ value +'";\r\n'; }); var template = grunt.file.read(__dirname + '/../templates/config_imports.scss'); var write_path = config.sass_path + '/config/_imports.scss'; sassquatch.write_to_template(template, write_path, replacements); var template = grunt.file.read(__dirname + '/../templates/constructor.scss'); var write_path = config.sass_path + '/helpers/_constructor.scss'; sassquatch.write_to_template(template, write_path, replacements); var template = grunt.file.read(__dirname + '/../templates/base.scss'); var write_path = config.sass_path + '/base.scss'; sassquatch.write_to_template(template, write_path, replacements); // Add the default page type sassquatch.add_page('default'); // All the standard bits done, now lets look at the configured pages, modules and breakpoints. config.pages.forEach(function(page, index){ sassquatch.add_page(page); }); config.modules.forEach(function(module, index){ sassquatch.add_module(module); }); config.breakpoints.forEach(function(breakpoint, index){ var output = '@media only screen and (min-width: '+ breakpoint +'px) {\r\n'+ ' @import "config/imports";\r\n'+ ' \r\n'+ ' @include construct() {\r\n'+ ' @include default_page_'+ breakpoint +';\r\n'+ ' };\r\n'+ '}'; grunt.file.write(config.sass_path +'/'+ breakpoint +'.scss', output); grunt.log.write('Added breakpoint stylesheet: "'+ breakpoint + '"').ok(); }); }, 'add_page' : function(page_name) { grunt.log.write('New page: "'+ page_name + '"'); var config = grunt.config.get('sassquatch'), breakpoints = config.breakpoints, content = '@import "base";\r\n'; breakpoints.forEach(function(value, index){ content += '@import "'+ value +'";\r\n'; var local_content = ''+ '@mixin '+ page_name +'_page_'+ value +'() {\r\n' + '}'; grunt.file.write(config.sass_path +'/pages/'+ page_name +'/_'+ value +'.scss', local_content); grunt.log.write('Added breakpoint: "'+ value + '"').ok(); }); grunt.file.write(config.sass_path +'/pages/'+ page_name +'/_base.scss', '@mixin '+ page_name +'_page_base() {\r\n}'); grunt.log.write('Added breakpoint: "base"').ok(); grunt.file.write(config.sass_path +'/pages/'+ page_name +'/_'+ page_name+ '.scss', content); grunt.log.write('Added page: "'+ page_name + '"').ok(); // brittle var imports_config = grunt.file.read('sass/config/_imports_pages.scss'); imports_config += '\r\n@import "pages/'+ page_name +'/'+ page_name +'";'; grunt.file.write('sass/config/_imports_pages.scss', imports_config); grunt.log.write('Added line to config/_imports_pages for "'+ page_name + '"').ok(); }, 'add_module' : function(module_name) { grunt.log.write('New module: "'+ module_name + '"'); var config = grunt.config.get('sassquatch'), content = ''+ '@mixin '+ module_name +'() {\r\n' + ' %'+ module_name +'_example {\r\n'+ ' }\r\n'+ '}'; grunt.file.write(config.sass_path +'/modules/_'+ module_name +'.scss', content); grunt.log.write('Added module: "'+ module_name + '"').ok(); var imports_config = grunt.file.read('sass/config/_imports_modules.scss'); imports_config += '\r\n@import "modules/'+ module_name +'";'; grunt.file.write('sass/config/_imports_modules.scss', imports_config); grunt.log.write('Added line to config/_imports_modules for "'+ module_name + '"').ok(); }, 'write_to_template' : function(template, write_path, replacements) { for (var key in replacements) { template = template.replace('[['+ key +']]', replacements[key]); } grunt.file.write(write_path, template); } } return sassquatch; }
tasks/lib/sassquatch.js
exports.init = function(grunt) { var sassquatch = { 'setup' : function() { grunt.log.write('Running full SASSquatch setup, from config JSON'); var config = grunt.config.get('sassquatch'); // Ok, let's get this party started by creating all the config files that are always there grunt.file.write(config.sass_path +'/config/_imports_pages.scss', ''); grunt.file.write(config.sass_path +'/config/_imports_modules.scss', ''); // now we add the extra stuff from the config config.extra_configs.forEach(function(value, index) { grunt.file.write(config.sass_path +'/config/_'+ value +'.scss', ''); }); // Now compile the master imports file var replacements = { 'config_imports' : '', 'helpers_imports' : '' }; config.extra_configs.forEach(function(value, index) { replacements.config_imports += '@import "config/'+ value +'";\r\n'; }); config.helpers.forEach(function(value, index) { replacements.helpers_imports += '@import "helpers/'+ value +'";\r\n'; }); var template = grunt.file.read(__dirname + '/../templates/config_imports.scss'); var write_path = config.sass_path + '/config/_imports.scss'; sassquatch.write_to_template(template, write_path, replacements); var template = grunt.file.read(__dirname + '/../templates/constructor.scss'); var write_path = config.sass_path + '/helpers/_constructor.scss'; sassquatch.write_to_template(template, write_path, replacements); var template = grunt.file.read(__dirname + '/../templates/base.scss'); var write_path = config.sass_path + '/base.scss'; sassquatch.write_to_template(template, write_path, replacements); // All the standard bits done, now lets look at the configured pages, modules and breakpoints. config.pages.forEach(function(page, index){ sassquatch.add_page(page); }); config.modules.forEach(function(module, index){ sassquatch.add_module(module); }); config.breakpoints.forEach(function(breakpoint, index){ var output = '@media only screen and (min-width: '+ breakpoint +'px) {\r\n'+ ' @import "config/imports";\r\n'+ ' \r\n'+ ' @include construct() {\r\n'+ ' @include default_page_'+ breakpoint +';\r\n'+ ' };\r\n'+ '}'; grunt.file.write(config.sass_path +'/'+ breakpoint +'.scss', output); grunt.log.write('Added breakpoint stylesheet: "'+ breakpoint + '"').ok(); }); }, 'add_page' : function(page_name) { grunt.log.write('New page: "'+ page_name + '"'); var config = grunt.config.get('sassquatch'), breakpoints = config.breakpoints, content = '@import "base";\r\n'; breakpoints.forEach(function(value, index){ content += '@import "'+ value +'";\r\n'; var local_content = ''+ '@mixin '+ page_name +'_'+ value +'() {\r\n' + '}'; grunt.file.write(config.sass_path +'/pages/'+ page_name +'/_'+ value +'.scss', local_content); grunt.log.write('Added breakpoint: "'+ value + '"').ok(); }); grunt.file.write(config.sass_path +'/pages/'+ page_name +'/_base.scss', '@mixin '+ page_name +'_base() {\r\n}'); grunt.log.write('Added breakpoint: "base"').ok(); grunt.file.write(config.sass_path +'/pages/'+ page_name +'/_'+ page_name+ '.scss', content); grunt.log.write('Added page: "'+ page_name + '"').ok(); // brittle var imports_config = grunt.file.read('sass/config/_imports_pages.scss'); imports_config += '\r\n@import "pages/'+ page_name +'/'+ page_name +'";'; grunt.file.write('sass/config/_imports_pages.scss', imports_config); grunt.log.write('Added line to config/_imports_pages for "'+ page_name + '"').ok(); }, 'add_module' : function(module_name) { grunt.log.write('New module: "'+ module_name + '"'); var config = grunt.config.get('sassquatch'), content = ''+ '@mixin '+ module_name +'() {\r\n' + ' %'+ module_name +'_example {\r\n'+ ' }\r\n'+ '}'; grunt.file.write(config.sass_path +'/modules/_'+ module_name +'.scss', content); grunt.log.write('Added module: "'+ module_name + '"').ok(); var imports_config = grunt.file.read('sass/config/_imports_modules.scss'); imports_config += '\r\n@import "modules/'+ module_name +'";'; grunt.file.write('sass/config/_imports_modules.scss', imports_config); grunt.log.write('Added line to config/_imports_modules for "'+ module_name + '"').ok(); }, 'write_to_template' : function(template, write_path, replacements) { for (var key in replacements) { template = template.replace('[['+ key +']]', replacements[key]); } grunt.file.write(write_path, template); } } return sassquatch; }
added default page construction to setup method, and fixed some typos in page includes
tasks/lib/sassquatch.js
added default page construction to setup method, and fixed some typos in page includes
<ide><path>asks/lib/sassquatch.js <ide> <ide> sassquatch.write_to_template(template, write_path, replacements); <ide> <add> // Add the default page type <add> sassquatch.add_page('default'); <ide> <ide> // All the standard bits done, now lets look at the configured pages, modules and breakpoints. <ide> config.pages.forEach(function(page, index){ <ide> content += '@import "'+ value +'";\r\n'; <ide> <ide> var local_content = ''+ <del> '@mixin '+ page_name +'_'+ value +'() {\r\n' + <add> '@mixin '+ page_name +'_page_'+ value +'() {\r\n' + <ide> '}'; <ide> <ide> <ide> grunt.log.write('Added breakpoint: "'+ value + '"').ok(); <ide> }); <ide> <del> grunt.file.write(config.sass_path +'/pages/'+ page_name +'/_base.scss', '@mixin '+ page_name +'_base() {\r\n}'); <add> grunt.file.write(config.sass_path +'/pages/'+ page_name +'/_base.scss', '@mixin '+ page_name +'_page_base() {\r\n}'); <ide> grunt.log.write('Added breakpoint: "base"').ok(); <ide> <ide> grunt.file.write(config.sass_path +'/pages/'+ page_name +'/_'+ page_name+ '.scss', content);
Java
apache-2.0
95850e9daf0cbe966e7499f1698b8b3fd1fff107
0
jexp/idea2,gnuhub/intellij-community,kdwink/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,jexp/idea2,pwoodworth/intellij-community,FHannes/intellij-community,joewalnes/idea-community,lucafavatella/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,joewalnes/idea-community,nicolargo/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,joewalnes/idea-community,adedayo/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,da1z/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,caot/intellij-community,fnouama/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,signed/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,ahb0327/intellij-community,slisson/intellij-community,diorcety/intellij-community,clumsy/intellij-community,samthor/intellij-community,kool79/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,jagguli/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,ryano144/intellij-community,consulo/consulo,jexp/idea2,jagguli/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,izonder/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,da1z/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,retomerz/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,da1z/intellij-community,gnuhub/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,slisson/intellij-community,holmes/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,gnuhub/intellij-community,slisson/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,consulo/consulo,petteyg/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,da1z/intellij-community,jagguli/intellij-community,xfournet/intellij-community,fitermay/intellij-community,allotria/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,izonder/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,signed/intellij-community,ibinti/intellij-community,diorcety/intellij-community,diorcety/intellij-community,holmes/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,signed/intellij-community,petteyg/intellij-community,clumsy/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,jagguli/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,ernestp/consulo,fitermay/intellij-community,jexp/idea2,vvv1559/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,semonte/intellij-community,robovm/robovm-studio,jagguli/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,petteyg/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,slisson/intellij-community,semonte/intellij-community,ahb0327/intellij-community,consulo/consulo,akosyakov/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,ernestp/consulo,diorcety/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,kool79/intellij-community,signed/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,samthor/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,allotria/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,signed/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,supersven/intellij-community,joewalnes/idea-community,blademainer/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,jexp/idea2,apixandru/intellij-community,wreckJ/intellij-community,semonte/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,caot/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,FHannes/intellij-community,hurricup/intellij-community,izonder/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,caot/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,ernestp/consulo,robovm/robovm-studio,robovm/robovm-studio,apixandru/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,amith01994/intellij-community,fnouama/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,joewalnes/idea-community,vvv1559/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,signed/intellij-community,holmes/intellij-community,caot/intellij-community,ibinti/intellij-community,robovm/robovm-studio,allotria/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,ernestp/consulo,FHannes/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,consulo/consulo,consulo/consulo,SerCeMan/intellij-community,vladmm/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,da1z/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,fnouama/intellij-community,wreckJ/intellij-community,signed/intellij-community,caot/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,jagguli/intellij-community,consulo/consulo,caot/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,tmpgit/intellij-community,caot/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,caot/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,semonte/intellij-community,ryano144/intellij-community,dslomov/intellij-community,slisson/intellij-community,jexp/idea2,xfournet/intellij-community,adedayo/intellij-community,diorcety/intellij-community,blademainer/intellij-community,blademainer/intellij-community,slisson/intellij-community,akosyakov/intellij-community,joewalnes/idea-community,signed/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,da1z/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,clumsy/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,samthor/intellij-community,dslomov/intellij-community,holmes/intellij-community,adedayo/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,izonder/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,dslomov/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,samthor/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,adedayo/intellij-community,kool79/intellij-community,izonder/intellij-community,FHannes/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,asedunov/intellij-community,fnouama/intellij-community,fnouama/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,caot/intellij-community,allotria/intellij-community,robovm/robovm-studio,petteyg/intellij-community,blademainer/intellij-community,ibinti/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,joewalnes/idea-community,supersven/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,retomerz/intellij-community,caot/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,dslomov/intellij-community,holmes/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,signed/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,kool79/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,da1z/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,slisson/intellij-community,izonder/intellij-community,semonte/intellij-community,amith01994/intellij-community,robovm/robovm-studio,adedayo/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,joewalnes/idea-community,salguarnieri/intellij-community,samthor/intellij-community,jagguli/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,supersven/intellij-community,joewalnes/idea-community,blademainer/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,dslomov/intellij-community,FHannes/intellij-community,slisson/intellij-community,holmes/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,allotria/intellij-community,caot/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,holmes/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,ernestp/consulo,hurricup/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,dslomov/intellij-community,slisson/intellij-community,da1z/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,hurricup/intellij-community,allotria/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,caot/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,jexp/idea2,nicolargo/intellij-community,dslomov/intellij-community,supersven/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,ernestp/consulo,fengbaicanhe/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,supersven/intellij-community,ibinti/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,dslomov/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,semonte/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,jexp/idea2,orekyuu/intellij-community,supersven/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,allotria/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,kool79/intellij-community,ryano144/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,ibinti/intellij-community,supersven/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,xfournet/intellij-community,diorcety/intellij-community,xfournet/intellij-community,ryano144/intellij-community,holmes/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,semonte/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,petteyg/intellij-community,hurricup/intellij-community,adedayo/intellij-community
/* * Copyright (c) 2005 Your Corporation. All Rights Reserved. */ package com.intellij.util.xml.impl; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtil; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Factory; import com.intellij.openapi.util.Pair; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiLock; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.xml.*; import com.intellij.util.ArrayUtil; import com.intellij.util.Function; import com.intellij.util.IncorrectOperationException; import com.intellij.util.xml.*; import com.intellij.util.xml.events.CollectionElementAddedEvent; import com.intellij.util.xml.events.ElementDefinedEvent; import com.intellij.util.xml.events.ElementUndefinedEvent; import com.intellij.util.xml.reflect.DomAttributeChildDescription; import com.intellij.util.xml.reflect.DomChildrenDescription; import com.intellij.util.xml.reflect.DomFixedChildDescription; import net.sf.cglib.proxy.InvocationHandler; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.*; /** * @author peter */ public abstract class DomInvocationHandler implements InvocationHandler, DomElement { private static final Logger LOG = Logger.getInstance("#com.intellij.util.xml.impl.DomInvocationHandler"); private static final String ATTRIBUTES = "@"; public static Method ACCEPT_METHOD = null; public static Method ACCEPT_CHILDREN_METHOD = null; static { try { ACCEPT_METHOD = DomElement.class.getMethod("accept", DomElementVisitor.class); ACCEPT_CHILDREN_METHOD = DomElement.class.getMethod("acceptChildren", DomElementVisitor.class); } catch (NoSuchMethodException e) { Logger.getInstance("#com.intellij.util.xml.ui.DomUIFactory").error(e); } } private final Type myAbstractType; private final Type myType; private final DomInvocationHandler myParent; private final DomManagerImpl myManager; private final String myTagName; private final Converter myGenericConverter; private XmlTag myXmlTag; private XmlFile myFile; private final DomElement myProxy; private final Set<String> myInitializedChildren = new com.intellij.util.containers.HashSet<String>(); private final Map<Pair<String, Integer>, IndexedElementInvocationHandler> myFixedChildren = new HashMap<Pair<String, Integer>, IndexedElementInvocationHandler>(); private final Map<String, AttributeChildInvocationHandler> myAttributeChildren = new HashMap<String, AttributeChildInvocationHandler>(); final private GenericInfoImpl myGenericInfo; private final Map<String, Class> myFixedChildrenClasses = new HashMap<String, Class>(); private boolean myInvalidated; private InvocationCache myInvocationCache; private final Factory<Converter> myGenericConverterFactory = new Factory<Converter>() { public Converter create() { return myGenericConverter; } }; protected DomInvocationHandler(final Type type, final XmlTag tag, final DomInvocationHandler parent, final String tagName, final DomManagerImpl manager) { myManager = manager; myParent = parent; myTagName = tagName; myAbstractType = type; final Type concreteInterface = TypeChooserManager.getClassChooser(type).chooseType(tag); final Converter converter = getConverter(new Function<Class<? extends Annotation>, Annotation>() { @Nullable public Annotation fun(final Class<? extends Annotation> s) { return getAnnotation(s); } }, DomUtil.getGenericValueParameter(concreteInterface), Factory.NULL_FACTORY); myGenericInfo = manager.getGenericInfo(concreteInterface); myType = concreteInterface; myGenericConverter = converter; myInvocationCache = manager.getInvocationCache(new Pair<Type, Type>(concreteInterface, converter == null ? null : converter.getClass())); final Class<?> rawType = DomReflectionUtil.getRawType(concreteInterface); Class<? extends DomElement> implementation = manager.getImplementation(rawType); if (implementation == null && !rawType.isInterface()) { implementation = (Class<? extends DomElement>)rawType; } myProxy = rawType.isInterface() ? AdvancedProxy.createProxy(this, implementation, rawType) : AdvancedProxy.createProxy(this, implementation, ArrayUtil.EMPTY_CLASS_ARRAY); attach(tag); } @Nullable public <T extends DomElement> DomFileElementImpl<T> getRoot() { return isValid() ? (DomFileElementImpl<T>)myParent.getRoot() : null; } @Nullable public DomElement getParent() { return isValid() ? myParent.getProxy() : null; } final DomInvocationHandler getParentHandler() { return myParent; } public final Type getDomElementType() { return myType; } final Type getAbstractType() { return myAbstractType; } public final void copyFrom(DomElement other) { if (other == getProxy()) return; assert other.getDomElementType().equals(myType); final XmlTag fromTag = other.getXmlTag(); if (fromTag == null) { if (getXmlTag() != null) { undefine(); } return; } final XmlTag tag = ensureTagExists(); detach(false); synchronized (PsiLock.LOCK) { myManager.runChange(new Runnable() { public void run() { try { copyTags(fromTag, tag); } catch (IncorrectOperationException e) { LOG.error(e); } } }); } attach(tag); } private void copyTags(final XmlTag fromTag, final XmlTag toTag) throws IncorrectOperationException { for (PsiElement child : toTag.getChildren()) { if (child instanceof XmlAttribute || child instanceof XmlTag) { child.delete(); } } PsiElement child = fromTag.getFirstChild(); boolean hasChildren = false; while (child != null) { if (child instanceof XmlTag) { final XmlTag xmlTag = (XmlTag)child; copyTags(xmlTag, (XmlTag)toTag.add(createEmptyTag(xmlTag.getName()))); hasChildren = true; } else if (child instanceof XmlAttribute) { toTag.add(child); } child = child.getNextSibling(); } if (!hasChildren) { toTag.getValue().setText(fromTag.getValue().getText()); } } public final <T extends DomElement> T createMockCopy(final boolean physical) { final T copy = myManager.createMockElement((Class<? extends T>)DomReflectionUtil.getRawType(myType), getModule(), physical); copy.copyFrom(getProxy()); return copy; } public final Module getModule() { final Module module = ModuleUtil.findModuleForPsiElement(getFile()); return module != null ? module : getRoot().getUserData(DomManagerImpl.MODULE); } public XmlTag ensureTagExists() { if (myXmlTag != null) return myXmlTag; try { attach(setXmlTag(createEmptyTag())); } catch (IncorrectOperationException e) { LOG.error(e); } myManager.fireEvent(new ElementDefinedEvent(getProxy())); addRequiredChildren(); return myXmlTag; } public XmlElement getXmlElement() { return getXmlTag(); } public XmlElement ensureXmlElementExists() { return ensureTagExists(); } protected final XmlTag createEmptyTag() throws IncorrectOperationException { return createEmptyTag(myTagName); } protected final XmlTag createEmptyTag(final String tagName) throws IncorrectOperationException { return getFile().getManager().getElementFactory().createTagFromText("<" + tagName + "/>"); } public boolean isValid() { if (!myInvalidated && (myXmlTag != null && !myXmlTag.isValid() || myParent != null && !myParent.isValid())) { myInvalidated = true; return false; } return !myInvalidated; } @NotNull public final GenericInfoImpl getGenericInfo() { myGenericInfo.buildMethodMaps(); return myGenericInfo; } protected abstract void undefineInternal(); public final void undefine() { undefineInternal(); } protected final void detachChildren() { for (final AttributeChildInvocationHandler handler : myAttributeChildren.values()) { handler.detach(false); } for (final IndexedElementInvocationHandler handler : myFixedChildren.values()) { handler.detach(false); } } protected final void deleteTag(final XmlTag tag) { final boolean changing = myManager.setChanging(true); try { tag.delete(); } catch (IncorrectOperationException e) { LOG.error(e); } finally { myManager.setChanging(changing); } setXmlTagToNull(); } protected final void setXmlTagToNull() { myXmlTag = null; } protected final void fireUndefinedEvent() { myManager.fireEvent(new ElementUndefinedEvent(getProxy())); } protected abstract XmlTag setXmlTag(final XmlTag tag) throws IncorrectOperationException; protected final void addRequiredChildren() { for (final DomChildrenDescription description : myGenericInfo.getChildrenDescriptions()) { if (description instanceof DomAttributeChildDescription) { final Required required = description.getAnnotation(Required.class); if (required != null && required.value()) { description.getValues(getProxy()).get(0).ensureXmlElementExists(); } } else if (description instanceof DomFixedChildDescription) { final DomFixedChildDescription childDescription = (DomFixedChildDescription)description; List<? extends DomElement> values = null; final int count = childDescription.getCount(); for (int i = 0; i < count; i++) { final Required required = childDescription.getAnnotation(i, Required.class); if (required != null && required.value()) { if (values == null) { values = description.getValues(getProxy()); } values.get(i).ensureTagExists(); } } } } } @NotNull public final String getXmlElementName() { return myTagName; } protected final DomElement findCallerProxy(Method method) { final Object o = InvocationStack.INSTANCE.findDeepestInvocation(method, new Condition<Object>() { public boolean value(final Object object) { return ModelMergerUtil.getImplementation(object, DomElement.class) == null; } }); final DomElement element = ModelMergerUtil.getImplementation(o, DomElement.class); return element == null ? getProxy() : element; } public void accept(final DomElementVisitor visitor) { myManager.getVisitorDescription(visitor.getClass()).acceptElement(visitor, findCallerProxy(ACCEPT_METHOD)); } public void acceptChildren(DomElementVisitor visitor) { final DomElement element = ModelMergerUtil.getImplementation(findCallerProxy(ACCEPT_CHILDREN_METHOD), DomElement.class); for (final DomChildrenDescription description : getGenericInfo().getChildrenDescriptions()) { for (final DomElement value : description.getValues(element)) { value.accept(visitor); } } } public final void initializeAllChildren() { myGenericInfo.buildMethodMaps(); for (final String s : myGenericInfo.getFixedChildrenNames()) { checkInitialized(s); } for (final String s : myGenericInfo.getCollectionChildrenNames()) { checkInitialized(s); } for (final String s : myGenericInfo.getAttributeChildrenNames()) { checkInitialized(s); } } final List<CollectionElementInvocationHandler> getCollectionChildren() { final List<CollectionElementInvocationHandler> collectionChildren = new ArrayList<CollectionElementInvocationHandler>(); final XmlTag tag = getXmlTag(); if (tag != null) { for (XmlTag xmlTag : tag.getSubTags()) { final DomInvocationHandler cachedElement = DomManagerImpl.getCachedElement(xmlTag); if (cachedElement instanceof CollectionElementInvocationHandler) { collectionChildren.add((CollectionElementInvocationHandler)cachedElement); } } } return collectionChildren; } @NotNull protected final Converter getScalarConverter(final Type type, final Method method) { final Class parameter = DomReflectionUtil.substituteGenericType(type, myType); assert parameter != null : type + " " + myType; final Converter converter = getConverter(new Function<Class<? extends Annotation>, Annotation>() { public Annotation fun(final Class<? extends Annotation> s) { return DomReflectionUtil.findAnnotationDFS(method, s); } }, parameter, type instanceof TypeVariable ? myGenericConverterFactory : Factory.NULL_FACTORY); assert converter != null : "No converter specified: String<->" + parameter.getName(); return converter; } @Nullable private Converter getConverter(final Function<Class<? extends Annotation>, Annotation> annotationProvider, Class parameter, final Factory<Converter> continuation) { final Resolve resolveAnnotation = (Resolve)annotationProvider.fun(Resolve.class); if (resolveAnnotation != null) { return DomResolveConverter.createConverter(resolveAnnotation.value()); } final Convert convertAnnotation = (Convert)annotationProvider.fun(Convert.class); final ConverterManager converterManager = myManager.getConverterManager(); if (convertAnnotation != null) { return converterManager.getConverterInstance(convertAnnotation.value()); } final Converter converter = continuation.create(); if (converter != null) { return converter; } return parameter == null ? null : converterManager.getConverterByClass(parameter); } public final DomElement getProxy() { return myProxy; } @NotNull protected final XmlFile getFile() { assert isValid(); if (myFile == null) { myFile = getRoot().getFile(); } return myFile; } public final DomNameStrategy getNameStrategy() { final Class<?> rawType = DomReflectionUtil.getRawType(myType); final DomNameStrategy strategy = DomImplUtil.getDomNameStrategy(rawType, isAttribute()); if (strategy != null) { return strategy; } final DomInvocationHandler parent = getParentHandler(); return parent != null ? parent.getNameStrategy() : DomNameStrategy.HYPHEN_STRATEGY; } protected boolean isAttribute() { return false; } @NotNull public ElementPresentation getPresentation() { return new ElementPresentation() { public String getElementName() { return ElementPresentationManager.getElementName(getProxy()); } public String getTypeName() { return ElementPresentationManager.getTypeNameForObject(getProxy()); } public Icon getIcon() { return ElementPresentationManager.getIcon(getProxy()); } }; } public final GlobalSearchScope getResolveScope() { return getRoot().getResolveScope(); } private static <T extends DomElement> T _getParentOfType(Class<T> requiredClass, DomElement element) { while (element != null && !(requiredClass.isInstance(element))) { element = element.getParent(); } return (T)element; } public final <T extends DomElement> T getParentOfType(Class<T> requiredClass, boolean strict) { return _getParentOfType(requiredClass, strict ? getParent() : getProxy()); } protected final Invocation createInvocation(final Method method) throws IllegalAccessException, InstantiationException { if (DomImplUtil.isTagValueGetter(method)) { return createGetValueInvocation(getScalarConverter(method.getGenericReturnType(), method), method); } if (DomImplUtil.isTagValueSetter(method)) { return createSetValueInvocation(getScalarConverter(method.getGenericParameterTypes()[0], method), method); } return myGenericInfo.createInvocation(method); } protected Invocation createSetValueInvocation(final Converter converter, final Method method) { return new SetValueInvocation(converter, method); } protected Invocation createGetValueInvocation(final Converter converter, final Method method) { return new GetValueInvocation(converter, method); } @NotNull final IndexedElementInvocationHandler getFixedChild(final Pair<String, Integer> info) { return myFixedChildren.get(info); } final Collection<IndexedElementInvocationHandler> getFixedChildren() { return myFixedChildren.values(); } @NotNull final AttributeChildInvocationHandler getAttributeChild(final JavaMethodSignature method) { myGenericInfo.buildMethodMaps(); final String attributeName = myGenericInfo.getAttributeName(method); assert attributeName != null : method.toString(); return getAttributeChild(attributeName); } @NotNull final AttributeChildInvocationHandler getAttributeChild(final String attributeName) { checkInitialized(ATTRIBUTES); final AttributeChildInvocationHandler domElement = myAttributeChildren.get(attributeName); assert domElement != null : attributeName; return domElement; } public final Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { InvocationStack.INSTANCE.push(method, null); return doInvoke(JavaMethodSignature.getSignature(method), args); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } finally { InvocationStack.INSTANCE.pop(); } } public final Object doInvoke(final JavaMethodSignature signature, final Object... args) throws Throwable { Invocation invocation = myInvocationCache.getInvocation(signature); if (invocation == null) { invocation = createInvocation(signature.findMethod(DomReflectionUtil.getRawType(myType))); myInvocationCache.putInvocation(signature, invocation); } return invocation.invoke(this, args); } static void setTagValue(final XmlTag tag, final String value) { tag.getValue().setText(value); } static String getTagValue(final XmlTag tag) { return tag.getValue().getTrimmedText(); /* final XmlText[] textElements = tag.getValue().getTextElements(); return textElements.length != 0 ? textElements[0].getValue().trim() : "";*/ } public final String toString() { return myType.toString() + " @" + hashCode(); } final void checkInitialized(final String qname) { assert isValid(); checkParentInitialized(); synchronized (PsiLock.LOCK) { if (myInitializedChildren.contains(qname)) { return; } try { myGenericInfo.buildMethodMaps(); if (ATTRIBUTES.equals(qname)) { for (Map.Entry<JavaMethodSignature, String> entry : myGenericInfo.getAttributeChildrenEntries()) { getOrCreateAttributeChild(entry.getKey().findMethod(DomReflectionUtil.getRawType(myType)), entry.getValue()); } } final XmlTag tag = getXmlTag(); if (myGenericInfo.isFixedChild(qname)) { final int count = myGenericInfo.getFixedChildrenCount(qname); for (int i = 0; i < count; i++) { getOrCreateIndexedChild(findSubTag(tag, qname, i), new Pair<String, Integer>(qname, i)); } } else if (tag != null && myGenericInfo.isCollectionChild(qname)) { for (XmlTag subTag : tag.findSubTags(qname)) { new CollectionElementInvocationHandler(myGenericInfo.getCollectionChildrenType(qname), subTag, this); } } } finally { myInitializedChildren.add(qname); } } } private void checkParentInitialized() { if (myXmlTag == null && myParent != null && myInitializedChildren.isEmpty() && myParent.isValid()) { myParent.checkInitialized(myTagName); } } private void getOrCreateAttributeChild(final Method method, final String attributeName) { final AttributeChildInvocationHandler handler = new AttributeChildInvocationHandler(method.getGenericReturnType(), getXmlTag(), this, attributeName, myManager); myAttributeChildren.put(handler.getXmlElementName(), handler); } private IndexedElementInvocationHandler getOrCreateIndexedChild(final XmlTag subTag, final Pair<String, Integer> pair) { IndexedElementInvocationHandler handler = myFixedChildren.get(pair); if (handler == null) { handler = createIndexedChild(subTag, pair); myFixedChildren.put(pair, handler); } else { handler.attach(subTag); } return handler; } private IndexedElementInvocationHandler createIndexedChild(final XmlTag subTag, final Pair<String, Integer> pair) { final JavaMethodSignature signature = myGenericInfo.getFixedChildGetter(pair); final String qname = pair.getFirst(); final Class<?> rawType = DomReflectionUtil.getRawType(myType); final Method method = signature.findMethod(rawType); Type type = method.getGenericReturnType(); if (myFixedChildrenClasses.containsKey(qname)) { type = getFixedChildrenClass(qname); } final SubTag annotationDFS = signature.findAnnotation(SubTag.class, rawType); final boolean indicator = annotationDFS != null && annotationDFS.indicator(); return new IndexedElementInvocationHandler(type, subTag, this, qname, pair.getSecond(), indicator); } protected final Class getFixedChildrenClass(final String tagName) { return myFixedChildrenClasses.get(tagName); } @Nullable protected static XmlTag findSubTag(final XmlTag tag, final String qname, final int index) { if (tag == null) { return null; } final XmlTag[] subTags = tag.findSubTags(qname); return subTags.length <= index ? null : subTags[index]; } @Nullable public XmlTag getXmlTag() { checkParentInitialized(); return myXmlTag; } protected final void detach(boolean invalidate) { synchronized (PsiLock.LOCK) { myInvalidated = invalidate; if (!myInitializedChildren.isEmpty()) { for (DomInvocationHandler handler : myFixedChildren.values()) { handler.detach(invalidate); } if (myXmlTag != null && myXmlTag.isValid()) { for (CollectionElementInvocationHandler handler : getCollectionChildren()) { handler.detach(true); } } } myInitializedChildren.clear(); removeFromCache(); setXmlTagToNull(); } } protected void removeFromCache() { DomManagerImpl.setCachedElement(myXmlTag, null); } protected final void attach(final XmlTag tag) { synchronized (PsiLock.LOCK) { myXmlTag = tag; cacheInTag(tag); } } protected void cacheInTag(final XmlTag tag) { DomManagerImpl.setCachedElement(tag, this); } public final DomManagerImpl getManager() { return myManager; } boolean isIndicator() { return false; } public final DomElement addChild(final String tagName, final Type type, int index) throws IncorrectOperationException { checkInitialized(tagName); final XmlTag tag = addEmptyTag(tagName, index); final CollectionElementInvocationHandler handler = new CollectionElementInvocationHandler(type, tag, this); final DomElement element = handler.getProxy(); myManager.fireEvent(new CollectionElementAddedEvent(element, tag.getName())); handler.addRequiredChildren(); return element; } protected final void createFixedChildrenTags(String tagName, int count) throws IncorrectOperationException { checkInitialized(tagName); final XmlTag tag = ensureTagExists(); final XmlTag[] subTags = tag.findSubTags(tagName); if (subTags.length < count) { getFixedChild(new Pair<String, Integer>(tagName, count - 1)).ensureTagExists(); } } private XmlTag addEmptyTag(final String tagName, int index) throws IncorrectOperationException { final XmlTag tag = ensureTagExists(); final XmlTag[] subTags = tag.findSubTags(tagName); if (subTags.length < index) { index = subTags.length; } final boolean changing = myManager.setChanging(true); try { XmlTag newTag = createEmptyTag(tagName); if (index == 0) { if (subTags.length == 0) { return (XmlTag)tag.add(newTag); } return (XmlTag)tag.addBefore(newTag, subTags[0]); } return (XmlTag)tag.addAfter(newTag, subTags[index - 1]); } finally { myManager.setChanging(changing); } } public final boolean isInitialized(final String qname) { synchronized (PsiLock.LOCK) { return myInitializedChildren.contains(qname); } } public final boolean isAnythingInitialized() { synchronized (PsiLock.LOCK) { return !myInitializedChildren.isEmpty(); } } public final boolean areAttributesInitialized() { return isInitialized(ATTRIBUTES); } public void setFixedChildClass(final String tagName, final Class<? extends DomElement> aClass) { synchronized (PsiLock.LOCK) { assert!myInitializedChildren.contains(tagName); myFixedChildrenClasses.put(tagName, aClass); } } }
dom/impl/src/com/intellij/util/xml/impl/DomInvocationHandler.java
/* * Copyright (c) 2005 Your Corporation. All Rights Reserved. */ package com.intellij.util.xml.impl; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtil; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Factory; import com.intellij.openapi.util.Pair; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiLock; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.xml.*; import com.intellij.util.ArrayUtil; import com.intellij.util.Function; import com.intellij.util.IncorrectOperationException; import com.intellij.util.xml.*; import com.intellij.util.xml.events.CollectionElementAddedEvent; import com.intellij.util.xml.events.ElementDefinedEvent; import com.intellij.util.xml.events.ElementUndefinedEvent; import com.intellij.util.xml.reflect.DomAttributeChildDescription; import com.intellij.util.xml.reflect.DomChildrenDescription; import com.intellij.util.xml.reflect.DomFixedChildDescription; import net.sf.cglib.proxy.InvocationHandler; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.*; /** * @author peter */ public abstract class DomInvocationHandler implements InvocationHandler, DomElement { private static final Logger LOG = Logger.getInstance("#com.intellij.util.xml.impl.DomInvocationHandler"); private static final String ATTRIBUTES = "@"; public static Method ACCEPT_METHOD = null; public static Method ACCEPT_CHILDREN_METHOD = null; static { try { ACCEPT_METHOD = DomElement.class.getMethod("accept", DomElementVisitor.class); ACCEPT_CHILDREN_METHOD = DomElement.class.getMethod("acceptChildren", DomElementVisitor.class); } catch (NoSuchMethodException e) { Logger.getInstance("#com.intellij.util.xml.ui.DomUIFactory").error(e); } } private final Type myAbstractType; private final Type myType; private final DomInvocationHandler myParent; private final DomManagerImpl myManager; private final String myTagName; private final Converter myGenericConverter; private XmlTag myXmlTag; private XmlFile myFile; private final DomElement myProxy; private final Set<String> myInitializedChildren = new com.intellij.util.containers.HashSet<String>(); private final Map<Pair<String, Integer>, IndexedElementInvocationHandler> myFixedChildren = new HashMap<Pair<String, Integer>, IndexedElementInvocationHandler>(); private final Map<String, AttributeChildInvocationHandler> myAttributeChildren = new HashMap<String, AttributeChildInvocationHandler>(); final private GenericInfoImpl myGenericInfo; private final Map<String, Class> myFixedChildrenClasses = new HashMap<String, Class>(); private boolean myInvalidated; private InvocationCache myInvocationCache; private final Factory<Converter> myGenericConverterFactory = new Factory<Converter>() { public Converter create() { return myGenericConverter; } }; protected DomInvocationHandler(final Type type, final XmlTag tag, final DomInvocationHandler parent, final String tagName, final DomManagerImpl manager) { myManager = manager; myParent = parent; myTagName = tagName; myAbstractType = type; final Type concreteInterface = TypeChooserManager.getClassChooser(type).chooseType(tag); final Converter converter = getConverter(new Function<Class<? extends Annotation>, Annotation>() { @Nullable public Annotation fun(final Class<? extends Annotation> s) { return getAnnotation(s); } }, DomUtil.getGenericValueParameter(concreteInterface), Factory.NULL_FACTORY); myGenericInfo = manager.getGenericInfo(concreteInterface); myType = concreteInterface; myGenericConverter = converter; myInvocationCache = manager.getInvocationCache(new Pair<Type, Type>(concreteInterface, converter == null ? null : converter.getClass())); final Class<?> rawType = DomReflectionUtil.getRawType(concreteInterface); Class<? extends DomElement> implementation = manager.getImplementation(rawType); if (implementation == null && !rawType.isInterface()) { implementation = (Class<? extends DomElement>)rawType; } myProxy = rawType.isInterface() ? AdvancedProxy.createProxy(this, implementation, rawType) : AdvancedProxy.createProxy(this, implementation, ArrayUtil.EMPTY_CLASS_ARRAY); attach(tag); } @Nullable public <T extends DomElement> DomFileElementImpl<T> getRoot() { return isValid() ? (DomFileElementImpl<T>)myParent.getRoot() : null; } @Nullable public DomElement getParent() { return isValid() ? myParent.getProxy() : null; } final DomInvocationHandler getParentHandler() { return myParent; } public final Type getDomElementType() { return myType; } final Type getAbstractType() { return myAbstractType; } public final void copyFrom(DomElement other) { if (other == getProxy()) return; assert other.getDomElementType().equals(myType); final XmlTag fromTag = other.getXmlTag(); if (fromTag == null) { if (getXmlTag() != null) { undefine(); } return; } final XmlTag tag = ensureTagExists(); detach(false); synchronized (PsiLock.LOCK) { myManager.runChange(new Runnable() { public void run() { try { copyTags(fromTag, tag); } catch (IncorrectOperationException e) { LOG.error(e); } } }); } attach(tag); } private void copyTags(final XmlTag fromTag, final XmlTag toTag) throws IncorrectOperationException { for (PsiElement child : toTag.getChildren()) { if (child instanceof XmlAttribute || child instanceof XmlTag) { child.delete(); } } PsiElement child = fromTag.getFirstChild(); boolean hasChildren = false; while (child != null) { if (child instanceof XmlTag) { final XmlTag xmlTag = (XmlTag)child; copyTags(xmlTag, (XmlTag)toTag.add(createEmptyTag(xmlTag.getName()))); hasChildren = true; } else if (child instanceof XmlAttribute) { toTag.add(child); } child = child.getNextSibling(); } if (!hasChildren) { toTag.getValue().setText(fromTag.getValue().getText()); } } public final <T extends DomElement> T createMockCopy(final boolean physical) { final T copy = myManager.createMockElement((Class<? extends T>)DomReflectionUtil.getRawType(myType), getModule(), physical); copy.copyFrom(getProxy()); return copy; } public final Module getModule() { final Module module = ModuleUtil.findModuleForPsiElement(getFile()); return module != null ? module : getRoot().getUserData(DomManagerImpl.MODULE); } public XmlTag ensureTagExists() { if (myXmlTag != null) return myXmlTag; try { attach(setXmlTag(createEmptyTag())); } catch (IncorrectOperationException e) { LOG.error(e); } myManager.fireEvent(new ElementDefinedEvent(getProxy())); addRequiredChildren(); return myXmlTag; } public XmlElement getXmlElement() { return getXmlTag(); } public XmlElement ensureXmlElementExists() { return ensureTagExists(); } protected final XmlTag createEmptyTag() throws IncorrectOperationException { return createEmptyTag(myTagName); } protected final XmlTag createEmptyTag(final String tagName) throws IncorrectOperationException { return getFile().getManager().getElementFactory().createTagFromText("<" + tagName + "/>"); } public boolean isValid() { if (!myInvalidated && (myXmlTag != null && !myXmlTag.isValid() || myParent != null && !myParent.isValid())) { myInvalidated = true; return false; } return !myInvalidated; } @NotNull public final GenericInfoImpl getGenericInfo() { myGenericInfo.buildMethodMaps(); return myGenericInfo; } protected abstract void undefineInternal(); public final void undefine() { undefineInternal(); } protected final void detachChildren() { for (final AttributeChildInvocationHandler handler : myAttributeChildren.values()) { handler.detach(false); } for (final IndexedElementInvocationHandler handler : myFixedChildren.values()) { handler.detach(false); } } protected final void deleteTag(final XmlTag tag) { final boolean changing = myManager.setChanging(true); try { tag.delete(); } catch (IncorrectOperationException e) { LOG.error(e); } finally { myManager.setChanging(changing); } setXmlTagToNull(); } protected final void setXmlTagToNull() { myXmlTag = null; } protected final void fireUndefinedEvent() { myManager.fireEvent(new ElementUndefinedEvent(getProxy())); } protected abstract XmlTag setXmlTag(final XmlTag tag) throws IncorrectOperationException; protected final void addRequiredChildren() { for (final DomChildrenDescription description : myGenericInfo.getChildrenDescriptions()) { if (description instanceof DomAttributeChildDescription) { final Required required = description.getAnnotation(Required.class); if (required != null && required.value()) { description.getValues(getProxy()).get(0).ensureXmlElementExists(); } } else if (description instanceof DomFixedChildDescription) { final DomFixedChildDescription childDescription = (DomFixedChildDescription)description; List<? extends DomElement> values = null; final int count = childDescription.getCount(); for (int i = 0; i < count; i++) { final Required required = childDescription.getAnnotation(i, Required.class); if (required != null && required.value()) { if (values == null) { values = description.getValues(getProxy()); } values.get(i).ensureTagExists(); } } } } } @NotNull public final String getXmlElementName() { return myTagName; } protected final DomElement findCallerProxy(Method method) { final Object o = InvocationStack.INSTANCE.findDeepestInvocation(method, new Condition<Object>() { public boolean value(final Object object) { return ModelMergerUtil.getImplementation(object, DomElement.class) == null; } }); final DomElement element = ModelMergerUtil.getImplementation(o, DomElement.class); return element == null ? getProxy() : element; } public void accept(final DomElementVisitor visitor) { myManager.getVisitorDescription(visitor.getClass()).acceptElement(visitor, findCallerProxy(ACCEPT_METHOD)); } public void acceptChildren(DomElementVisitor visitor) { final DomElement element = ModelMergerUtil.getImplementation(findCallerProxy(ACCEPT_CHILDREN_METHOD), DomElement.class); for (final DomChildrenDescription description : getGenericInfo().getChildrenDescriptions()) { for (final DomElement value : description.getValues(element)) { value.accept(visitor); } } } public final void initializeAllChildren() { myGenericInfo.buildMethodMaps(); for (final String s : myGenericInfo.getFixedChildrenNames()) { checkInitialized(s); } for (final String s : myGenericInfo.getCollectionChildrenNames()) { checkInitialized(s); } for (final String s : myGenericInfo.getAttributeChildrenNames()) { checkInitialized(s); } } final List<CollectionElementInvocationHandler> getCollectionChildren() { final List<CollectionElementInvocationHandler> collectionChildren = new ArrayList<CollectionElementInvocationHandler>(); final XmlTag tag = getXmlTag(); if (tag != null) { for (XmlTag xmlTag : tag.getSubTags()) { final DomInvocationHandler cachedElement = DomManagerImpl.getCachedElement(xmlTag); if (cachedElement instanceof CollectionElementInvocationHandler) { collectionChildren.add((CollectionElementInvocationHandler)cachedElement); } } } return collectionChildren; } @NotNull protected final Converter getScalarConverter(final Type type, final Method method) { final Class parameter = DomReflectionUtil.substituteGenericType(type, myType); assert parameter != null : type + " " + myType; final Converter converter = getConverter(new Function<Class<? extends Annotation>, Annotation>() { public Annotation fun(final Class<? extends Annotation> s) { return DomReflectionUtil.findAnnotationDFS(method, s); } }, parameter, type instanceof TypeVariable ? myGenericConverterFactory : Factory.NULL_FACTORY); assert converter != null : "No converter specified: String<->" + parameter.getName(); return converter; } @Nullable private Converter getConverter(final Function<Class<? extends Annotation>, Annotation> annotationProvider, Class parameter, final Factory<Converter> continuation) { final Resolve resolveAnnotation = (Resolve)annotationProvider.fun(Resolve.class); if (resolveAnnotation != null) { return DomResolveConverter.createConverter(resolveAnnotation.value()); } final Convert convertAnnotation = (Convert)annotationProvider.fun(Convert.class); final ConverterManager converterManager = myManager.getConverterManager(); if (convertAnnotation != null) { return converterManager.getConverterInstance(convertAnnotation.value()); } final Converter converter = continuation.create(); if (converter != null) { return converter; } return parameter == null ? null : converterManager.getConverterByClass(parameter); } public final DomElement getProxy() { return myProxy; } @NotNull protected final XmlFile getFile() { assert isValid(); if (myFile == null) { myFile = getRoot().getFile(); } return myFile; } public final DomNameStrategy getNameStrategy() { final Class<?> rawType = DomReflectionUtil.getRawType(myType); final DomNameStrategy strategy = DomImplUtil.getDomNameStrategy(rawType, isAttribute()); if (strategy != null) { return strategy; } final DomInvocationHandler parent = getParentHandler(); return parent != null ? parent.getNameStrategy() : DomNameStrategy.HYPHEN_STRATEGY; } protected boolean isAttribute() { return false; } @NotNull public ElementPresentation getPresentation() { return new ElementPresentation() { public String getElementName() { return ElementPresentationManager.getElementName(getProxy()); } public String getTypeName() { return ElementPresentationManager.getTypeNameForObject(getProxy()); } public Icon getIcon() { return ElementPresentationManager.getIcon(getProxy()); } }; } public final GlobalSearchScope getResolveScope() { return getRoot().getResolveScope(); } private static <T extends DomElement> T _getParentOfType(Class<T> requiredClass, DomElement element) { while (element != null && !(requiredClass.isInstance(element))) { element = element.getParent(); } return (T)element; } public final <T extends DomElement> T getParentOfType(Class<T> requiredClass, boolean strict) { return _getParentOfType(requiredClass, strict ? getParent() : getProxy()); } protected final Invocation createInvocation(final Method method) throws IllegalAccessException, InstantiationException { if (DomImplUtil.isTagValueGetter(method)) { return createGetValueInvocation(getScalarConverter(method.getGenericReturnType(), method), method); } if (DomImplUtil.isTagValueSetter(method)) { return createSetValueInvocation(getScalarConverter(method.getGenericParameterTypes()[0], method), method); } return myGenericInfo.createInvocation(method); } protected Invocation createSetValueInvocation(final Converter converter, final Method method) { return new SetValueInvocation(converter, method); } protected Invocation createGetValueInvocation(final Converter converter, final Method method) { return new GetValueInvocation(converter, method); } @NotNull final IndexedElementInvocationHandler getFixedChild(final Pair<String, Integer> info) { return myFixedChildren.get(info); } final Collection<IndexedElementInvocationHandler> getFixedChildren() { return myFixedChildren.values(); } @NotNull final AttributeChildInvocationHandler getAttributeChild(final JavaMethodSignature method) { myGenericInfo.buildMethodMaps(); final String attributeName = myGenericInfo.getAttributeName(method); assert attributeName != null : method.toString(); return getAttributeChild(attributeName); } @NotNull final AttributeChildInvocationHandler getAttributeChild(final String attributeName) { checkInitialized(ATTRIBUTES); final AttributeChildInvocationHandler domElement = myAttributeChildren.get(attributeName); assert domElement != null : attributeName; return domElement; } public final Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { InvocationStack.INSTANCE.push(method, null); return doInvoke(JavaMethodSignature.getSignature(method), args); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } finally { InvocationStack.INSTANCE.pop(); } } public final Object doInvoke(final JavaMethodSignature signature, final Object... args) throws Throwable { Invocation invocation = myInvocationCache.getInvocation(signature); if (invocation == null) { invocation = createInvocation(signature.findMethod(DomReflectionUtil.getRawType(myType))); myInvocationCache.putInvocation(signature, invocation); } return invocation.invoke(this, args); } static void setTagValue(final XmlTag tag, final String value) { tag.getValue().setText(value); } static String getTagValue(final XmlTag tag) { final XmlText[] textElements = tag.getValue().getTextElements(); return textElements.length != 0 ? textElements[0].getValue().trim() : ""; } public final String toString() { return myType.toString() + " @" + hashCode(); } final void checkInitialized(final String qname) { assert isValid(); checkParentInitialized(); synchronized (PsiLock.LOCK) { if (myInitializedChildren.contains(qname)) { return; } try { myGenericInfo.buildMethodMaps(); if (ATTRIBUTES.equals(qname)) { for (Map.Entry<JavaMethodSignature, String> entry : myGenericInfo.getAttributeChildrenEntries()) { getOrCreateAttributeChild(entry.getKey().findMethod(DomReflectionUtil.getRawType(myType)), entry.getValue()); } } final XmlTag tag = getXmlTag(); if (myGenericInfo.isFixedChild(qname)) { final int count = myGenericInfo.getFixedChildrenCount(qname); for (int i = 0; i < count; i++) { getOrCreateIndexedChild(findSubTag(tag, qname, i), new Pair<String, Integer>(qname, i)); } } else if (tag != null && myGenericInfo.isCollectionChild(qname)) { for (XmlTag subTag : tag.findSubTags(qname)) { new CollectionElementInvocationHandler(myGenericInfo.getCollectionChildrenType(qname), subTag, this); } } } finally { myInitializedChildren.add(qname); } } } private void checkParentInitialized() { if (myXmlTag == null && myParent != null && myInitializedChildren.isEmpty() && myParent.isValid()) { myParent.checkInitialized(myTagName); } } private void getOrCreateAttributeChild(final Method method, final String attributeName) { final AttributeChildInvocationHandler handler = new AttributeChildInvocationHandler(method.getGenericReturnType(), getXmlTag(), this, attributeName, myManager); myAttributeChildren.put(handler.getXmlElementName(), handler); } private IndexedElementInvocationHandler getOrCreateIndexedChild(final XmlTag subTag, final Pair<String, Integer> pair) { IndexedElementInvocationHandler handler = myFixedChildren.get(pair); if (handler == null) { handler = createIndexedChild(subTag, pair); myFixedChildren.put(pair, handler); } else { handler.attach(subTag); } return handler; } private IndexedElementInvocationHandler createIndexedChild(final XmlTag subTag, final Pair<String, Integer> pair) { final JavaMethodSignature signature = myGenericInfo.getFixedChildGetter(pair); final String qname = pair.getFirst(); final Class<?> rawType = DomReflectionUtil.getRawType(myType); final Method method = signature.findMethod(rawType); Type type = method.getGenericReturnType(); if (myFixedChildrenClasses.containsKey(qname)) { type = getFixedChildrenClass(qname); } final SubTag annotationDFS = signature.findAnnotation(SubTag.class, rawType); final boolean indicator = annotationDFS != null && annotationDFS.indicator(); return new IndexedElementInvocationHandler(type, subTag, this, qname, pair.getSecond(), indicator); } protected final Class getFixedChildrenClass(final String tagName) { return myFixedChildrenClasses.get(tagName); } @Nullable protected static XmlTag findSubTag(final XmlTag tag, final String qname, final int index) { if (tag == null) { return null; } final XmlTag[] subTags = tag.findSubTags(qname); return subTags.length <= index ? null : subTags[index]; } @Nullable public XmlTag getXmlTag() { checkParentInitialized(); return myXmlTag; } protected final void detach(boolean invalidate) { synchronized (PsiLock.LOCK) { myInvalidated = invalidate; if (!myInitializedChildren.isEmpty()) { for (DomInvocationHandler handler : myFixedChildren.values()) { handler.detach(invalidate); } if (myXmlTag != null && myXmlTag.isValid()) { for (CollectionElementInvocationHandler handler : getCollectionChildren()) { handler.detach(true); } } } myInitializedChildren.clear(); removeFromCache(); setXmlTagToNull(); } } protected void removeFromCache() { DomManagerImpl.setCachedElement(myXmlTag, null); } protected final void attach(final XmlTag tag) { synchronized (PsiLock.LOCK) { myXmlTag = tag; cacheInTag(tag); } } protected void cacheInTag(final XmlTag tag) { DomManagerImpl.setCachedElement(tag, this); } public final DomManagerImpl getManager() { return myManager; } boolean isIndicator() { return false; } public final DomElement addChild(final String tagName, final Type type, int index) throws IncorrectOperationException { checkInitialized(tagName); final XmlTag tag = addEmptyTag(tagName, index); final CollectionElementInvocationHandler handler = new CollectionElementInvocationHandler(type, tag, this); final DomElement element = handler.getProxy(); myManager.fireEvent(new CollectionElementAddedEvent(element, tag.getName())); handler.addRequiredChildren(); return element; } protected final void createFixedChildrenTags(String tagName, int count) throws IncorrectOperationException { checkInitialized(tagName); final XmlTag tag = ensureTagExists(); final XmlTag[] subTags = tag.findSubTags(tagName); if (subTags.length < count) { getFixedChild(new Pair<String, Integer>(tagName, count - 1)).ensureTagExists(); } } private XmlTag addEmptyTag(final String tagName, int index) throws IncorrectOperationException { final XmlTag tag = ensureTagExists(); final XmlTag[] subTags = tag.findSubTags(tagName); if (subTags.length < index) { index = subTags.length; } final boolean changing = myManager.setChanging(true); try { XmlTag newTag = createEmptyTag(tagName); if (index == 0) { if (subTags.length == 0) { return (XmlTag)tag.add(newTag); } return (XmlTag)tag.addBefore(newTag, subTags[0]); } return (XmlTag)tag.addAfter(newTag, subTags[index - 1]); } finally { myManager.setChanging(changing); } } public final boolean isInitialized(final String qname) { synchronized (PsiLock.LOCK) { return myInitializedChildren.contains(qname); } } public final boolean isAnythingInitialized() { synchronized (PsiLock.LOCK) { return !myInitializedChildren.isEmpty(); } } public final boolean areAttributesInitialized() { return isInitialized(ATTRIBUTES); } public void setFixedChildClass(final String tagName, final Class<? extends DomElement> aClass) { synchronized (PsiLock.LOCK) { assert!myInitializedChildren.contains(tagName); myFixedChildrenClasses.put(tagName, aClass); } } }
IDEADEV-7254 EJB-QL editing problem in ejbjar.xml
dom/impl/src/com/intellij/util/xml/impl/DomInvocationHandler.java
IDEADEV-7254 EJB-QL editing problem in ejbjar.xml
<ide><path>om/impl/src/com/intellij/util/xml/impl/DomInvocationHandler.java <ide> } <ide> <ide> static String getTagValue(final XmlTag tag) { <add> return tag.getValue().getTrimmedText(); <add>/* <ide> final XmlText[] textElements = tag.getValue().getTextElements(); <del> return textElements.length != 0 ? textElements[0].getValue().trim() : ""; <add> return textElements.length != 0 ? textElements[0].getValue().trim() : "";*/ <ide> } <ide> <ide> public final String toString() {
Java
mit
0f587d5b4755c1f5b570c732da7226bb3618b675
0
amwenger/igv,godotgildor/igv,godotgildor/igv,amwenger/igv,amwenger/igv,godotgildor/igv,godotgildor/igv,igvteam/igv,itenente/igv,igvteam/igv,itenente/igv,igvteam/igv,itenente/igv,igvteam/igv,itenente/igv,igvteam/igv,amwenger/igv,amwenger/igv,itenente/igv,godotgildor/igv
/* * Copyright (c) 2007-2012 The Broad Institute, Inc. * SOFTWARE COPYRIGHT NOTICE * This software and its documentation are the copyright of the Broad Institute, Inc. All rights are reserved. * * This software is supplied without any warranty or guaranteed support whatsoever. The Broad Institute is not responsible for its use, misuse, or functionality. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), * Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php. */ package org.broad.igv.sam; import net.sf.samtools.util.CloseableIterator; import org.apache.log4j.Logger; import org.broad.igv.Globals; import org.broad.igv.PreferenceManager; import org.broad.igv.feature.SpliceJunctionFeature; import org.broad.igv.sam.reader.AlignmentReader; import org.broad.igv.sam.reader.ReadGroupFilter; import org.broad.igv.ui.IGV; import org.broad.igv.ui.util.MessageUtils; import org.broad.igv.ui.util.ProgressMonitor; import org.broad.igv.util.ObjectCache; import org.broad.igv.util.RuntimeUtils; import org.broad.igv.util.collections.LRUCache; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.*; /** * A wrapper for an AlignmentQueryReader that caches query results * * @author jrobinso */ public class AlignmentTileLoader { private static Logger log = Logger.getLogger(AlignmentTileLoader.class); private static Set<WeakReference<AlignmentTileLoader>> activeLoaders = Collections.synchronizedSet(new HashSet()); /** * Flag to mark a corrupt index. Without this attempted reads will continue in an infinite loop */ private boolean corruptIndex = false; private AlignmentReader reader; private boolean cancel = false; private boolean pairedEnd = false; static void cancelReaders() { for (WeakReference<AlignmentTileLoader> readerRef : activeLoaders) { AlignmentTileLoader reader = readerRef.get(); if (reader != null) { reader.cancel = true; } } log.debug("Readers canceled"); activeLoaders.clear(); } public AlignmentTileLoader(AlignmentReader reader) { this.reader = reader; activeLoaders.add(new WeakReference<AlignmentTileLoader>(this)); } public void close() throws IOException { reader.close(); } public List<String> getSequenceNames() { return reader.getSequenceNames(); } public CloseableIterator<Alignment> iterator() { return reader.iterator(); } public boolean hasIndex() { return reader.hasIndex(); } AlignmentTile loadTile(String chr, int start, int end, SpliceJunctionHelper spliceJunctionHelper, AlignmentDataManager.DownsampleOptions downsampleOptions, Map<String, PEStats> peStats, AlignmentTrack.BisulfiteContext bisulfiteContext, ProgressMonitor monitor) { AlignmentTile t = new AlignmentTile(start, end, spliceJunctionHelper, downsampleOptions, bisulfiteContext); //assert (tiles.size() > 0); if (corruptIndex) { return t; } final PreferenceManager prefMgr = PreferenceManager.getInstance(); boolean filterFailedReads = prefMgr.getAsBoolean(PreferenceManager.SAM_FILTER_FAILED_READS); boolean filterSecondaryAlignments = prefMgr.getAsBoolean(PreferenceManager.SAM_FILTER_SECONDARY_ALIGNMENTS); ReadGroupFilter filter = ReadGroupFilter.getFilter(); boolean showDuplicates = prefMgr.getAsBoolean(PreferenceManager.SAM_SHOW_DUPLICATES); int qualityThreshold = prefMgr.getAsInt(PreferenceManager.SAM_QUALITY_THRESHOLD); CloseableIterator<Alignment> iter = null; //log.debug("Loading : " + start + " - " + end); int alignmentCount = 0; WeakReference<AlignmentTileLoader> ref = new WeakReference(this); try { ObjectCache<String, Alignment> mappedMates = new ObjectCache<String, Alignment>(1000); ObjectCache<String, Alignment> unmappedMates = new ObjectCache<String, Alignment>(1000); activeLoaders.add(ref); iter = reader.query(chr, start, end, false); while (iter != null && iter.hasNext()) { if (cancel) { return t; } Alignment record = iter.next(); // Set mate sequence of unmapped mates // Put a limit on the total size of this collection. String readName = record.getReadName(); if (record.isPaired()) { pairedEnd = true; if (record.isMapped()) { if (!record.getMate().isMapped()) { // record is mapped, mate is not Alignment mate = unmappedMates.get(readName); if (mate == null) { mappedMates.put(readName, record); } else { record.setMateSequence(mate.getReadSequence()); unmappedMates.remove(readName); mappedMates.remove(readName); } } } else if (record.getMate().isMapped()) { // record not mapped, mate is Alignment mappedMate = mappedMates.get(readName); if (mappedMate == null) { unmappedMates.put(readName, record); } else { mappedMate.setMateSequence(record.getReadSequence()); unmappedMates.remove(readName); mappedMates.remove(readName); } } } if (!record.isMapped() || (!showDuplicates && record.isDuplicate()) || (filterFailedReads && record.isVendorFailedRead()) || (filterSecondaryAlignments && !record.isPrimary()) || record.getMappingQuality() < qualityThreshold || (filter != null && filter.filterAlignment(record))) { continue; } t.addRecord(record); alignmentCount++; int interval = Globals.isTesting() ? 100000 : 1000; if (alignmentCount % interval == 0) { if (cancel) return null; String msg = "Reads loaded: " + alignmentCount; MessageUtils.setStatusBarMessage(msg); if(monitor != null){ monitor.updateStatus(msg); } if (memoryTooLow()) { if(monitor != null) monitor.fireProgressChange(100); cancelReaders(); t.finish(); return t; // <= TODO need to cancel all readers } } // Update pe stats if (peStats != null && record.isPaired() && record.isProperPair()) { String lb = record.getLibrary(); if (lb == null) lb = "null"; PEStats stats = peStats.get(lb); if (stats == null) { stats = new PEStats(lb); peStats.put(lb, stats); } stats.update(record); } } // End iteration over alignments // Compute peStats if (peStats != null) { // TODO -- something smarter re the percentiles. For small samples these will revert to min and max double minPercentile = prefMgr.getAsFloat(PreferenceManager.SAM_MIN_INSERT_SIZE_PERCENTILE); double maxPercentile = prefMgr.getAsFloat(PreferenceManager.SAM_MAX_INSERT_SIZE_PERCENTILE); for (PEStats stats : peStats.values()) { stats.compute(minPercentile, maxPercentile); } } // Clean up any remaining unmapped mate sequences for (String mappedMateName : mappedMates.getKeys()) { Alignment mappedMate = mappedMates.get(mappedMateName); Alignment mate = unmappedMates.get(mappedMate.getReadName()); if (mate != null) { mappedMate.setMateSequence(mate.getReadSequence()); } } t.finish(); return t; } catch (java.nio.BufferUnderflowException e) { // This almost always indicates a corrupt BAM index, or less frequently a corrupt bam file corruptIndex = true; MessageUtils.showMessage("<html>Error encountered querying alignments: " + e.toString() + "<br>This is often caused by a corrupt index file."); return null; } catch (Exception e) { log.error("Error loading alignment data", e); MessageUtils.showMessage("<html>Error encountered querying alignments: " + e.toString()); return null; } finally { // reset cancel flag. It doesn't matter how we got here, the read is complete and this flag is reset // for the next time cancel = false; activeLoaders.remove(ref); if(monitor != null){ monitor.fireProgressChange(100); } if (iter != null) { iter.close(); } if (!Globals.isHeadless()) { IGV.getInstance().resetStatusMessage(); } } } private static synchronized boolean memoryTooLow() { if (RuntimeUtils.getAvailableMemoryFraction() < 0.2) { LRUCache.clearCaches(); System.gc(); if (RuntimeUtils.getAvailableMemoryFraction() < 0.2) { String msg = "Memory is low, reading terminating."; MessageUtils.showMessage(msg); return true; } } return false; } /** * Does this file contain paired end data? Assume not until proven otherwise. */ public boolean isPairedEnd() { return pairedEnd; } public Set<String> getPlatforms() { return reader.getPlatforms(); } /** * Caches alignments, coverage, splice junctions, and downsampled intervals */ public static class AlignmentTile { private boolean loaded = false; private int end; private int start; private AlignmentCounts counts; private List<Alignment> alignments; private List<DownsampledInterval> downsampledIntervals; private SpliceJunctionHelper spliceJunctionHelper; private boolean isPairedEnd; private static final Random RAND = new Random(); private boolean downsample; private int samplingWindowSize; private int samplingDepth; private int currentSamplingWindowStart = -1; private int curEffSamplingWindowDepth = 0; //Although not strictly necessary, we keep track of the currentDownsampledInterval //for easy incrementing private DownsampledInterval currentDownsampledInterval; /** * We keep a data structure of alignments which can efficiently * look up by string (read name) or index (for random replacement) */ IndexableMap<String, Alignment> imAlignments; private int downsampledCount = 0; private int offset = 0; AlignmentTile(int start, int end, SpliceJunctionHelper spliceJunctionHelper, AlignmentDataManager.DownsampleOptions downsampleOptions, AlignmentTrack.BisulfiteContext bisulfiteContext) { this.start = start; this.end = end; this.downsampledIntervals = new ArrayList<DownsampledInterval>(); long seed = System.currentTimeMillis(); //System.out.println("seed: " + seed); RAND.setSeed(seed); // Use a sparse array for large regions (> 10 mb) if ((end - start) > 10000000) { this.counts = new SparseAlignmentCounts(start, end, bisulfiteContext); } else { this.counts = new DenseAlignmentCounts(start, end, bisulfiteContext); } // Set the max depth, and the max depth of the sampling bucket. if (downsampleOptions == null) { // Use default settings (from preferences) downsampleOptions = new AlignmentDataManager.DownsampleOptions(); } this.downsample = downsampleOptions.isDownsample(); this.samplingWindowSize = downsampleOptions.getSampleWindowSize(); this.samplingDepth = Math.max(1, downsampleOptions.getMaxReadCount()); this.spliceJunctionHelper = spliceJunctionHelper; if(this.downsample){ imAlignments = new IndexableMap<String, Alignment>(8000); }else{ alignments = new ArrayList<Alignment>(16000); } } public int getStart() { return start; } public void setStart(int start) { this.start = start; } int ignoredCount = 0; // <= just for debugging /** * Add an alignment record to this tile. This record is not necessarily retained after down-sampling. * * @param alignment */ public void addRecord(Alignment alignment) { counts.incCounts(alignment); isPairedEnd |= alignment.isPaired(); if (spliceJunctionHelper != null) { spliceJunctionHelper.addAlignment(alignment); } if (downsample) { final int alignmentStart = alignment.getAlignmentStart(); int currentSamplingBucketEnd = currentSamplingWindowStart + samplingWindowSize; if (currentSamplingWindowStart < 0 || alignmentStart >= currentSamplingBucketEnd) { setCurrentSamplingBucket(alignmentStart); } attemptAddRecordDownsampled(alignment); } else { alignments.add(alignment); } alignment.finish(); } /** * Attempt to add this alignment. The alignment is definitely added iff it's mate was added. * If we haven't seen the mate, the record is added with some probability according to * reservoir sampling * @param alignment */ private void attemptAddRecordDownsampled(Alignment alignment) { String readName = alignment.getReadName(); //A simple way to turn off the mate-checking is to replace the read name with a random string //so that there are no repeats //readName = String.format("%s%d", readName, RAND.nextInt()); //There are 3 possibilities: mate-kept, mate-rejected, mate-unknown (haven't seen, or non-paired reads) //If we kept or rejected the mate, we do the same for this one boolean hasRead = imAlignments.containsKey(readName); if(hasRead){ List<Alignment> mateAlignments = imAlignments.get(readName); boolean haveMate = false; if(mateAlignments != null){ for(Alignment al: mateAlignments){ ReadMate mate = al.getMate(); haveMate |= mate.getChr().equals(alignment.getChr()) && mate.getStart() == alignment.getStart(); } } if(haveMate){ //We keep the alignment if it's mate is kept imAlignments.append(readName, alignment); }else{ currentDownsampledInterval.incCount(); } }else{ if (curEffSamplingWindowDepth < samplingDepth) { imAlignments.append(readName, alignment); curEffSamplingWindowDepth++; } else { double samplingProb = ((double) samplingDepth) / (samplingDepth + downsampledCount + 1); if (RAND.nextDouble() < samplingProb) { int rndInt = (int) (RAND.nextDouble() * (samplingDepth - 1)); int idx = offset + rndInt; // Replace random record with this one List<Alignment> removedValues = imAlignments.replace(idx, readName, alignment); incrementDownsampledIntervals(removedValues); }else{ //Mark that record was not kept imAlignments.markNull(readName); currentDownsampledInterval.incCount(); } downsampledCount++; } } } private void setCurrentSamplingBucket(int alignmentStart) { curEffSamplingWindowDepth = 0; downsampledCount = 0; currentSamplingWindowStart = alignmentStart; offset = imAlignments.size(); int currentSamplingBucketEnd = currentSamplingWindowStart + samplingWindowSize; currentDownsampledInterval = new DownsampledInterval(alignmentStart, currentSamplingBucketEnd, 0); downsampledIntervals.add(currentDownsampledInterval); } private void incrementDownsampledIntervals(List<Alignment> removedValues) { if(removedValues == null) return; for(Alignment al: removedValues){ DownsampledInterval interval = findDownsampledInterval(al, downsampledIntervals.size() / 2); if(interval != null) interval.incCount(); } } private DownsampledInterval findDownsampledInterval(Alignment al, int startInd) { //Attempt to find by binary search DownsampledInterval curInterval = downsampledIntervals.get(startInd); if (al.getStart() >= curInterval.getStart() && al.getStart() < curInterval.getEnd()) { //Found return curInterval; } int sz = downsampledIntervals.size(); int newStart = -1; if(al.getStart() >= curInterval.getEnd()){ // startInd + (sz - startInd)/2 = (sz + startInd)/2 newStart = (sz + startInd)/2; }else{ // startInd - (startInd)/2 = startInd/2 newStart = startInd/2; } //This would be infinite regress, we give up if(newStart == startInd) return null; return findDownsampledInterval(al, newStart); } /** * Sort the alignments by start position, and filter {@code downsampledIntervals}. * This will have the same results as if no downsampling occurred, although will incur * extra computational cost * */ private void sortFilterDownsampled() { if((this.alignments == null || this.alignments.size() == 0) && this.downsample){ this.alignments = imAlignments.getAllValues(); imAlignments.clear(); } Comparator<Alignment> alignmentSorter = new Comparator<Alignment>() { public int compare(Alignment alignment, Alignment alignment1) { return alignment.getStart() - alignment1.getStart(); } }; Collections.sort(this.alignments, alignmentSorter); //Only keep the intervals for which count > 0 List<DownsampledInterval> tmp = new ArrayList<DownsampledInterval>(this.downsampledIntervals.size()); for(DownsampledInterval interval: this.downsampledIntervals){ if(interval.getCount() > 0){ tmp.add(interval); } } this.downsampledIntervals = tmp; } public List<Alignment> getAlignments() { return alignments; } public List<DownsampledInterval> getDownsampledIntervals() { return downsampledIntervals; } public void finish() { //If we downsampled, we need to sort if (downsample) { sortFilterDownsampled(); } finalizeSpliceJunctions(); counts.finish(); } public AlignmentCounts getCounts() { return counts; } private void finalizeSpliceJunctions() { if (spliceJunctionHelper != null) { spliceJunctionHelper.finish(); } } public List<SpliceJunctionFeature> getSpliceJunctionFeatures() { if(spliceJunctionHelper == null) return null; return spliceJunctionHelper.getFilteredJunctions(); } public SpliceJunctionHelper getSpliceJunctionHelper() { return spliceJunctionHelper; } /** * Map-like structure designed to be accessible both by key, and by numeric index * Multiple values are stored for each key, and a list is returned * If the key for a value is set as null, nothing can be added * * Intended to support downsampling, where if a read name is added and then removed * we don't want to add the read pair * @param <K> * @param <V> */ private class IndexableMap<K, V>{ private HashMap<K, List<V>> map; private List<K> list; IndexableMap(int size){ this.map = new HashMap<K, List<V>>(size); this.list = new ArrayList<K>(size); } public List<V> get(K key){ return map.get(key); } /** * Append a value for the specified key, unless * the current value is null. If the current value is * null, it's a no-op. * @param key * @param value * @return Whether the element was added */ public boolean append(K key, V value){ if(!map.containsKey(key)){ addNewValueToMap(key, value); return list.add(key); }else{ List<V> curList = map.get(key); if(curList == null) return false; return curList.add(value); } } public List<V> markNull(K key){ return map.put(key, null); } private void addNewValueToMap(K key, V value){ List<V> curList = new ArrayList<V>(1); curList.add(value); map.put(key, curList); } /** * Place the specified {@code key} and {@code value} in the map, * at index {@code index}. * * In the unlikely event that {@code key} is already * at {@code index}, {@code value} will be appended * @param index * @param key * @param value * @return Whether the replacement actually happened */ public List<V> replace(int index, K key, V value){ checkSize(index); K oldKey = list.get(index); if(!oldKey.equals(key)){ //Remove the old key from map, and make sure nothing else gets put there List<V> oldValue = markNull(oldKey); addNewValueToMap(key, value); list.set(index, key); return oldValue; }else{ append(key, value); return null; } } public int size(){ return list.size(); } private void checkSize(int index){ if(index >= size()){ throw new IllegalArgumentException("index " + index + " greater than current size" + size()); } } public List<V> getAllValues() { List<V> allValues = new ArrayList<V>(2*size()); for(K k: list){ allValues.addAll(map.get(k)); } return allValues; } public boolean containsKey(K key) { return map.containsKey(key); } public void clear() { map.clear(); list.clear(); } } } }
src/org/broad/igv/sam/AlignmentTileLoader.java
/* * Copyright (c) 2007-2012 The Broad Institute, Inc. * SOFTWARE COPYRIGHT NOTICE * This software and its documentation are the copyright of the Broad Institute, Inc. All rights are reserved. * * This software is supplied without any warranty or guaranteed support whatsoever. The Broad Institute is not responsible for its use, misuse, or functionality. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), * Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php. */ package org.broad.igv.sam; import net.sf.samtools.util.CloseableIterator; import org.apache.log4j.Logger; import org.broad.igv.Globals; import org.broad.igv.PreferenceManager; import org.broad.igv.feature.SpliceJunctionFeature; import org.broad.igv.sam.reader.AlignmentReader; import org.broad.igv.sam.reader.ReadGroupFilter; import org.broad.igv.ui.IGV; import org.broad.igv.ui.util.MessageUtils; import org.broad.igv.ui.util.ProgressMonitor; import org.broad.igv.util.ObjectCache; import org.broad.igv.util.RuntimeUtils; import org.broad.igv.util.collections.LRUCache; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.*; /** * A wrapper for an AlignmentQueryReader that caches query results * * @author jrobinso */ public class AlignmentTileLoader { private static Logger log = Logger.getLogger(AlignmentTileLoader.class); private static Set<WeakReference<AlignmentTileLoader>> activeLoaders = Collections.synchronizedSet(new HashSet()); /** * Flag to mark a corrupt index. Without this attempted reads will continue in an infinite loop */ private boolean corruptIndex = false; private AlignmentReader reader; private boolean cancel = false; private boolean pairedEnd = false; static void cancelReaders() { for (WeakReference<AlignmentTileLoader> readerRef : activeLoaders) { AlignmentTileLoader reader = readerRef.get(); if (reader != null) { reader.cancel = true; } } log.debug("Readers canceled"); activeLoaders.clear(); } public AlignmentTileLoader(AlignmentReader reader) { this.reader = reader; activeLoaders.add(new WeakReference<AlignmentTileLoader>(this)); } public void close() throws IOException { reader.close(); } public List<String> getSequenceNames() { return reader.getSequenceNames(); } public CloseableIterator<Alignment> iterator() { return reader.iterator(); } public boolean hasIndex() { return reader.hasIndex(); } AlignmentTile loadTile(String chr, int start, int end, SpliceJunctionHelper spliceJunctionHelper, AlignmentDataManager.DownsampleOptions downsampleOptions, Map<String, PEStats> peStats, AlignmentTrack.BisulfiteContext bisulfiteContext, ProgressMonitor monitor) { AlignmentTile t = new AlignmentTile(start, end, spliceJunctionHelper, downsampleOptions, bisulfiteContext); //assert (tiles.size() > 0); if (corruptIndex) { return t; } final PreferenceManager prefMgr = PreferenceManager.getInstance(); boolean filterFailedReads = prefMgr.getAsBoolean(PreferenceManager.SAM_FILTER_FAILED_READS); boolean filterSecondaryAlignments = prefMgr.getAsBoolean(PreferenceManager.SAM_FILTER_SECONDARY_ALIGNMENTS); ReadGroupFilter filter = ReadGroupFilter.getFilter(); boolean showDuplicates = prefMgr.getAsBoolean(PreferenceManager.SAM_SHOW_DUPLICATES); int qualityThreshold = prefMgr.getAsInt(PreferenceManager.SAM_QUALITY_THRESHOLD); CloseableIterator<Alignment> iter = null; //log.debug("Loading : " + start + " - " + end); int alignmentCount = 0; WeakReference<AlignmentTileLoader> ref = new WeakReference(this); try { ObjectCache<String, Alignment> mappedMates = new ObjectCache<String, Alignment>(1000); ObjectCache<String, Alignment> unmappedMates = new ObjectCache<String, Alignment>(1000); activeLoaders.add(ref); iter = reader.query(chr, start, end, false); while (iter != null && iter.hasNext()) { if (cancel) { return t; } Alignment record = iter.next(); // Set mate sequence of unmapped mates // Put a limit on the total size of this collection. String readName = record.getReadName(); if (record.isPaired()) { pairedEnd = true; if (record.isMapped()) { if (!record.getMate().isMapped()) { // record is mapped, mate is not Alignment mate = unmappedMates.get(readName); if (mate == null) { mappedMates.put(readName, record); } else { record.setMateSequence(mate.getReadSequence()); unmappedMates.remove(readName); mappedMates.remove(readName); } } } else if (record.getMate().isMapped()) { // record not mapped, mate is Alignment mappedMate = mappedMates.get(readName); if (mappedMate == null) { unmappedMates.put(readName, record); } else { mappedMate.setMateSequence(record.getReadSequence()); unmappedMates.remove(readName); mappedMates.remove(readName); } } } if (!record.isMapped() || (!showDuplicates && record.isDuplicate()) || (filterFailedReads && record.isVendorFailedRead()) || (filterSecondaryAlignments && !record.isPrimary()) || record.getMappingQuality() < qualityThreshold || (filter != null && filter.filterAlignment(record))) { continue; } t.addRecord(record); alignmentCount++; int interval = Globals.isTesting() ? 100000 : 1000; if (alignmentCount % interval == 0) { if (cancel) return null; String msg = "Reads loaded: " + alignmentCount; MessageUtils.setStatusBarMessage(msg); if(monitor != null){ monitor.updateStatus(msg); } if (memoryTooLow()) { if(monitor != null) monitor.fireProgressChange(100); cancelReaders(); return t; // <= TODO need to cancel all readers } } // Update pe stats if (peStats != null && record.isPaired() && record.isProperPair()) { String lb = record.getLibrary(); if (lb == null) lb = "null"; PEStats stats = peStats.get(lb); if (stats == null) { stats = new PEStats(lb); peStats.put(lb, stats); } stats.update(record); } } // End iteration over alignments // Compute peStats if (peStats != null) { // TODO -- something smarter re the percentiles. For small samples these will revert to min and max double minPercentile = prefMgr.getAsFloat(PreferenceManager.SAM_MIN_INSERT_SIZE_PERCENTILE); double maxPercentile = prefMgr.getAsFloat(PreferenceManager.SAM_MAX_INSERT_SIZE_PERCENTILE); for (PEStats stats : peStats.values()) { stats.compute(minPercentile, maxPercentile); } } // Clean up any remaining unmapped mate sequences for (String mappedMateName : mappedMates.getKeys()) { Alignment mappedMate = mappedMates.get(mappedMateName); Alignment mate = unmappedMates.get(mappedMate.getReadName()); if (mate != null) { mappedMate.setMateSequence(mate.getReadSequence()); } } t.setLoaded(true); return t; } catch (java.nio.BufferUnderflowException e) { // This almost always indicates a corrupt BAM index, or less frequently a corrupt bam file corruptIndex = true; MessageUtils.showMessage("<html>Error encountered querying alignments: " + e.toString() + "<br>This is often caused by a corrupt index file."); return null; } catch (Exception e) { log.error("Error loading alignment data", e); MessageUtils.showMessage("<html>Error encountered querying alignments: " + e.toString()); return null; } finally { // reset cancel flag. It doesn't matter how we got here, the read is complete and this flag is reset // for the next time cancel = false; activeLoaders.remove(ref); if(monitor != null){ monitor.fireProgressChange(100); } if (iter != null) { iter.close(); } if (!Globals.isHeadless()) { IGV.getInstance().resetStatusMessage(); } } } private static synchronized boolean memoryTooLow() { if (RuntimeUtils.getAvailableMemoryFraction() < 0.2) { LRUCache.clearCaches(); System.gc(); if (RuntimeUtils.getAvailableMemoryFraction() < 0.2) { String msg = "Memory is low, reading terminating."; MessageUtils.showMessage(msg); return true; } } return false; } /** * Does this file contain paired end data? Assume not until proven otherwise. */ public boolean isPairedEnd() { return pairedEnd; } public Set<String> getPlatforms() { return reader.getPlatforms(); } /** * Caches alignments, coverage, splice junctions, and downsampled intervals */ public static class AlignmentTile { private boolean loaded = false; private int end; private int start; private AlignmentCounts counts; private List<Alignment> alignments; private List<DownsampledInterval> downsampledIntervals; private SpliceJunctionHelper spliceJunctionHelper; private boolean isPairedEnd; private static final Random RAND = new Random(); private boolean downsample; private int samplingWindowSize; private int samplingDepth; private int currentSamplingWindowStart = -1; private int curEffSamplingWindowDepth = 0; //Although not strictly necessary, we keep track of the currentDownsampledInterval //for easy incrementing private DownsampledInterval currentDownsampledInterval; /** * We keep a data structure of alignments which can efficiently * look up by string (read name) or index (for random replacement) */ IndexableMap<String, Alignment> imAlignments; private int downsampledCount = 0; private int offset = 0; AlignmentTile(int start, int end, SpliceJunctionHelper spliceJunctionHelper, AlignmentDataManager.DownsampleOptions downsampleOptions, AlignmentTrack.BisulfiteContext bisulfiteContext) { this.start = start; this.end = end; this.downsampledIntervals = new ArrayList<DownsampledInterval>(); long seed = System.currentTimeMillis(); //System.out.println("seed: " + seed); RAND.setSeed(seed); // Use a sparse array for large regions (> 10 mb) if ((end - start) > 10000000) { this.counts = new SparseAlignmentCounts(start, end, bisulfiteContext); } else { this.counts = new DenseAlignmentCounts(start, end, bisulfiteContext); } // Set the max depth, and the max depth of the sampling bucket. if (downsampleOptions == null) { // Use default settings (from preferences) downsampleOptions = new AlignmentDataManager.DownsampleOptions(); } this.downsample = downsampleOptions.isDownsample(); this.samplingWindowSize = downsampleOptions.getSampleWindowSize(); this.samplingDepth = Math.max(1, downsampleOptions.getMaxReadCount()); this.spliceJunctionHelper = spliceJunctionHelper; if(this.downsample){ imAlignments = new IndexableMap<String, Alignment>(8000); }else{ alignments = new ArrayList<Alignment>(16000); } } public int getStart() { return start; } public void setStart(int start) { this.start = start; } int ignoredCount = 0; // <= just for debugging /** * Add an alignment record to this tile. This record is not necessarily retained after down-sampling. * * @param alignment */ public void addRecord(Alignment alignment) { counts.incCounts(alignment); isPairedEnd |= alignment.isPaired(); if (spliceJunctionHelper != null) { spliceJunctionHelper.addAlignment(alignment); } if (downsample) { final int alignmentStart = alignment.getAlignmentStart(); int currentSamplingBucketEnd = currentSamplingWindowStart + samplingWindowSize; if (currentSamplingWindowStart < 0 || alignmentStart >= currentSamplingBucketEnd) { setCurrentSamplingBucket(alignmentStart); } attemptAddRecordDownsampled(alignment); } else { alignments.add(alignment); } alignment.finish(); } /** * Attempt to add this alignment. The alignment is definitely added iff it's mate was added. * If we haven't seen the mate, the record is added with some probability according to * reservoir sampling * @param alignment */ private void attemptAddRecordDownsampled(Alignment alignment) { String readName = alignment.getReadName(); //A simple way to turn off the mate-checking is to replace the read name with a random string //so that there are no repeats //readName = String.format("%s%d", readName, RAND.nextInt()); //There are 3 possibilities: mate-kept, mate-rejected, mate-unknown (haven't seen, or non-paired reads) //If we kept or rejected the mate, we do the same for this one boolean hasRead = imAlignments.containsKey(readName); if(hasRead){ List<Alignment> mateAlignments = imAlignments.get(readName); boolean haveMate = false; if(mateAlignments != null){ for(Alignment al: mateAlignments){ ReadMate mate = al.getMate(); haveMate |= mate.getChr().equals(alignment.getChr()) && mate.getStart() == alignment.getStart(); } } if(haveMate){ //We keep the alignment if it's mate is kept imAlignments.append(readName, alignment); }else{ currentDownsampledInterval.incCount(); } }else{ if (curEffSamplingWindowDepth < samplingDepth) { imAlignments.append(readName, alignment); curEffSamplingWindowDepth++; } else { double samplingProb = ((double) samplingDepth) / (samplingDepth + downsampledCount + 1); if (RAND.nextDouble() < samplingProb) { int rndInt = (int) (RAND.nextDouble() * (samplingDepth - 1)); int idx = offset + rndInt; // Replace random record with this one List<Alignment> removedValues = imAlignments.replace(idx, readName, alignment); incrementDownsampledIntervals(removedValues); }else{ //Mark that record was not kept imAlignments.markNull(readName); currentDownsampledInterval.incCount(); } downsampledCount++; } } } private void setCurrentSamplingBucket(int alignmentStart) { curEffSamplingWindowDepth = 0; downsampledCount = 0; currentSamplingWindowStart = alignmentStart; offset = imAlignments.size(); int currentSamplingBucketEnd = currentSamplingWindowStart + samplingWindowSize; currentDownsampledInterval = new DownsampledInterval(alignmentStart, currentSamplingBucketEnd, 0); downsampledIntervals.add(currentDownsampledInterval); } private void incrementDownsampledIntervals(List<Alignment> removedValues) { if(removedValues == null) return; for(Alignment al: removedValues){ DownsampledInterval interval = findDownsampledInterval(al, downsampledIntervals.size() / 2); if(interval != null) interval.incCount(); } } private DownsampledInterval findDownsampledInterval(Alignment al, int startInd) { //Attempt to find by binary search DownsampledInterval curInterval = downsampledIntervals.get(startInd); if (al.getStart() >= curInterval.getStart() && al.getStart() < curInterval.getEnd()) { //Found return curInterval; } int sz = downsampledIntervals.size(); int newStart = -1; if(al.getStart() >= curInterval.getEnd()){ // startInd + (sz - startInd)/2 = (sz + startInd)/2 newStart = (sz + startInd)/2; }else{ // startInd - (startInd)/2 = startInd/2 newStart = startInd/2; } //This would be infinite regress, we give up if(newStart == startInd) return null; return findDownsampledInterval(al, newStart); } /** * Sort the alignments by start position, and filter {@code downsampledIntervals}. * This will have the same results as if no downsampling occurred, although will incur * extra computational cost * */ private void sortFilterDownsampled() { if((this.alignments == null || this.alignments.size() == 0) && this.downsample){ this.alignments = imAlignments.getAllValues(); } Comparator<Alignment> alignmentSorter = new Comparator<Alignment>() { public int compare(Alignment alignment, Alignment alignment1) { return alignment.getStart() - alignment1.getStart(); } }; Collections.sort(this.alignments, alignmentSorter); //Only keep the intervals for which count > 0 List<DownsampledInterval> tmp = new ArrayList<DownsampledInterval>(this.downsampledIntervals.size()); for(DownsampledInterval interval: this.downsampledIntervals){ if(interval.getCount() > 0){ tmp.add(interval); } } this.downsampledIntervals = tmp; } public List<Alignment> getAlignments() { return alignments; } public List<DownsampledInterval> getDownsampledIntervals() { return downsampledIntervals; } public boolean isLoaded() { return loaded; } public void setLoaded(boolean loaded) { this.loaded = loaded; if (loaded) { //If we downsampled, we need to sort if(downsample){ sortFilterDownsampled(); } finalizeSpliceJunctions(); counts.finish(); } } public AlignmentCounts getCounts() { return counts; } private void finalizeSpliceJunctions() { if (spliceJunctionHelper != null) { spliceJunctionHelper.finish(); } } public List<SpliceJunctionFeature> getSpliceJunctionFeatures() { if(spliceJunctionHelper == null) return null; return spliceJunctionHelper.getFilteredJunctions(); } public SpliceJunctionHelper getSpliceJunctionHelper() { return spliceJunctionHelper; } /** * Map-like structure designed to be accessible both by key, and by numeric index * Multiple values are stored for each key, and a list is returned * If the key for a value is set as null, nothing can be added * * Intended to support downsampling, where if a read name is added and then removed * we don't want to add the read pair * @param <K> * @param <V> */ private class IndexableMap<K, V>{ private HashMap<K, List<V>> map; private List<K> list; IndexableMap(int size){ this.map = new HashMap<K, List<V>>(size); this.list = new ArrayList<K>(size); } public List<V> get(K key){ return map.get(key); } /** * Append a value for the specified key, unless * the current value is null. If the current value is * null, it's a no-op. * @param key * @param value * @return Whether the element was added */ public boolean append(K key, V value){ if(!map.containsKey(key)){ addNewValueToMap(key, value); return list.add(key); }else{ List<V> curList = map.get(key); if(curList == null) return false; return curList.add(value); } } public List<V> markNull(K key){ return map.put(key, null); } private void addNewValueToMap(K key, V value){ List<V> curList = new ArrayList<V>(1); curList.add(value); map.put(key, curList); } /** * Place the specified {@code key} and {@code value} in the map, * at index {@code index}. * * In the unlikely event that {@code key} is already * at {@code index}, {@code value} will be appended * @param index * @param key * @param value * @return Whether the replacement actually happened */ public List<V> replace(int index, K key, V value){ checkSize(index); K oldKey = list.get(index); if(!oldKey.equals(key)){ //Remove the old key from map, and make sure nothing else gets put there List<V> oldValue = markNull(oldKey); addNewValueToMap(key, value); list.set(index, key); return oldValue; }else{ append(key, value); return null; } } public int size(){ return list.size(); } private void checkSize(int index){ if(index >= size()){ throw new IllegalArgumentException("index " + index + " greater than current size" + size()); } } public List<V> getAllValues() { List<V> allValues = new ArrayList<V>(2*size()); for(K k: list){ allValues.addAll(map.get(k)); } return allValues; } public boolean containsKey(K key) { return map.containsKey(key); } } } }
Finish AlignmentTile on cancel clear indexingmap used for downsampling on finish IGV-2065
src/org/broad/igv/sam/AlignmentTileLoader.java
Finish AlignmentTile on cancel
<ide><path>rc/org/broad/igv/sam/AlignmentTileLoader.java <ide> if (memoryTooLow()) { <ide> if(monitor != null) monitor.fireProgressChange(100); <ide> cancelReaders(); <add> t.finish(); <ide> return t; // <= TODO need to cancel all readers <ide> } <ide> } <ide> mappedMate.setMateSequence(mate.getReadSequence()); <ide> } <ide> } <del> t.setLoaded(true); <add> t.finish(); <ide> <ide> return t; <ide> <ide> private void sortFilterDownsampled() { <ide> if((this.alignments == null || this.alignments.size() == 0) && this.downsample){ <ide> this.alignments = imAlignments.getAllValues(); <add> imAlignments.clear(); <ide> } <ide> <ide> Comparator<Alignment> alignmentSorter = new Comparator<Alignment>() { <ide> return downsampledIntervals; <ide> } <ide> <del> public boolean isLoaded() { <del> return loaded; <del> } <del> <del> public void setLoaded(boolean loaded) { <del> this.loaded = loaded; <del> <del> if (loaded) { <del> //If we downsampled, we need to sort <del> if(downsample){ <del> sortFilterDownsampled(); <del> } <del> finalizeSpliceJunctions(); <del> counts.finish(); <del> } <add> public void finish() { <add> //If we downsampled, we need to sort <add> if (downsample) { <add> sortFilterDownsampled(); <add> } <add> finalizeSpliceJunctions(); <add> counts.finish(); <ide> } <ide> <ide> public AlignmentCounts getCounts() { <ide> return map.containsKey(key); <ide> } <ide> <add> public void clear() { <add> map.clear(); <add> list.clear(); <add> } <ide> } <ide> <ide> }
Java
bsd-3-clause
d64c194aa69d7fbf22a1f8d2177fa96a1ca6f295
0
EuropeanSpallationSource/openxal,EuropeanSpallationSource/openxal,EuropeanSpallationSource/openxal,EuropeanSpallationSource/openxal,EuropeanSpallationSource/openxal
/* * Main.java * * Created on March 19, 2003, 1:28 PM */ package xal.app.acceleratordemo; import java.util.logging.*; import xal.extension.application.*; import xal.extension.application.smf.*; /** * Demo is a demo concrete subclass of ApplicationAdaptor. This demo application * is a simple accelerator viewer that demonstrates how to build a simple * accelerator based application using the accelerator application framework. * * @author t6p */ public class Demo extends ApplicationAdaptor { // --------- Document management ------------------------------------------- /** * Returns the text file suffixes of files this application can open. * @return Suffixes of readable files */ public String[] readableDocumentTypes() { return new String[] {"txt", "text"}; } /** * Returns the text file suffixes of files this application can write. * @return Suffixes of writable files */ public String[] writableDocumentTypes() { return new String[] {"txt", "text"}; } /** * Implement this method to return an instance of my custom document. * @return An instance of my custom document. */ public XalDocument newEmptyDocument() { return new DemoDocument(); } /** * Implement this method to return an instance of my custom document * corresponding to the specified URL. * @param url The URL of the file to open. * @return An instance of my custom document. */ public XalDocument newDocument(java.net.URL url) { return new DemoDocument(url); } // --------- Global application management --------------------------------- /** * Specifies the name of my application. * @return Name of my application. */ public String applicationName() { return "DemoAcceleratorApplicaton"; } /** * Specifies whether I want to send standard output and error to the console. * I don't need to override the superclass adaptor to return true (the default), but * it is sometimes convenient to disable the console while debugging. * @return Name of my application. */ public boolean usesConsole() { String usesConsoleProperty = System.getProperty("usesConsole"); if ( usesConsoleProperty != null ) { return Boolean.valueOf(usesConsoleProperty).booleanValue(); } else { return true; } } // --------- Application events -------------------------------------------- /** Capture the application launched event and print it */ public void applicationFinishedLaunching() { System.out.println("Application finished launching..."); Logger.getLogger("global").log( Level.INFO, "Application finished launching." ); } /** The main method of the application. */ static public void main(String[] args) { try { System.out.println("Launching application..."); Logger.getLogger("global").log( Level.INFO, "Launching the application..." ); AcceleratorApplication.launch( new Demo() ); } catch(Exception exception) { System.err.println( exception.getMessage() ); Logger.getLogger("global").log( Level.SEVERE, "Error launching the application." , exception ); exception.printStackTrace(); Application.displayApplicationError("Launch Exception", "Launch Exception", exception); } } }
apps/acceleratordemo/src/xal/app/acceleratordemo/Demo.java
/* * Main.java * * Created on March 19, 2003, 1:28 PM */ package xal.app.acceleratordemo; import javax.swing.*; import java.util.logging.*; import xal.extension.application.*; import xal.extension.application.smf.*; /** * Demo is a demo concrete subclass of ApplicationAdaptor. This demo application * is a simple accelerator viewer that demonstrates how to build a simple * accelerator based application using the accelerator application framework. * * @author t6p */ public class Demo extends ApplicationAdaptor { // --------- Document management ------------------------------------------- /** * Returns the text file suffixes of files this application can open. * @return Suffixes of readable files */ public String[] readableDocumentTypes() { return new String[] {"txt", "text"}; } /** * Returns the text file suffixes of files this application can write. * @return Suffixes of writable files */ public String[] writableDocumentTypes() { return new String[] {"txt", "text"}; } /** * Implement this method to return an instance of my custom document. * @return An instance of my custom document. */ public XalDocument newEmptyDocument() { return new DemoDocument(); } /** * Implement this method to return an instance of my custom document * corresponding to the specified URL. * @param url The URL of the file to open. * @return An instance of my custom document. */ public XalDocument newDocument(java.net.URL url) { return new DemoDocument(url); } // --------- Global application management --------------------------------- /** * Specifies the name of my application. * @return Name of my application. */ public String applicationName() { return "DemoAcceleratorApplicaton"; } /** * Specifies whether I want to send standard output and error to the console. * I don't need to override the superclass adaptor to return true (the default), but * it is sometimes convenient to disable the console while debugging. * @return Name of my application. */ public boolean usesConsole() { String usesConsoleProperty = System.getProperty("usesConsole"); if ( usesConsoleProperty != null ) { return Boolean.valueOf(usesConsoleProperty).booleanValue(); } else { return true; } } // --------- Application events -------------------------------------------- /** Capture the application launched event and print it */ public void applicationFinishedLaunching() { System.out.println("Application finished launching..."); Logger.getLogger("global").log( Level.INFO, "Application finished launching." ); } /** The main method of the application. */ static public void main(String[] args) { try { System.out.println("Launching application..."); Logger.getLogger("global").log( Level.INFO, "Launching the application..." ); AcceleratorApplication.launch( new Demo() ); } catch(Exception exception) { System.err.println( exception.getMessage() ); Logger.getLogger("global").log( Level.SEVERE, "Error launching the application." , exception ); exception.printStackTrace(); JOptionPane.showMessageDialog(null, exception.getMessage(), exception.getClass().getName(), JOptionPane.WARNING_MESSAGE); } } }
using Application.displayApplicationError instead of JOptionPane.showMessageDialog
apps/acceleratordemo/src/xal/app/acceleratordemo/Demo.java
using Application.displayApplicationError instead of JOptionPane.showMessageDialog
<ide><path>pps/acceleratordemo/src/xal/app/acceleratordemo/Demo.java <ide> <ide> package xal.app.acceleratordemo; <ide> <del>import javax.swing.*; <ide> import java.util.logging.*; <ide> <ide> import xal.extension.application.*; <ide> System.err.println( exception.getMessage() ); <ide> Logger.getLogger("global").log( Level.SEVERE, "Error launching the application." , exception ); <ide> exception.printStackTrace(); <del> JOptionPane.showMessageDialog(null, exception.getMessage(), exception.getClass().getName(), JOptionPane.WARNING_MESSAGE); <add> Application.displayApplicationError("Launch Exception", "Launch Exception", exception); <ide> } <ide> } <ide> }
Java
bsd-3-clause
1f9dd15c92df01b0799e427019757f16e12dabb3
0
krishagni/openspecimen,NCIP/catissue-core,asamgir/openspecimen,krishagni/openspecimen,NCIP/catissue-core,krishagni/openspecimen,asamgir/openspecimen,asamgir/openspecimen,NCIP/catissue-core
/** * <p>Title: AdvanceSearchForm Class> * <p>Description: This Class is used to encapsulate all the request parameters passed * from ParticipantSearch.jsp/CollectionProtocolRegistrationSearch.jsp/ * SpecimenCollectionGroupSearch.jsp & SpecimenSearch.jsp pages. </p> * Copyright: Copyright (c) year * Company: Washington University, School of Medicine, St. Louis. * @author Aniruddha Phadnis * @version 1.00 * Created on Jul 15, 2005 */ package edu.wustl.catissuecore.actionForm; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; import edu.wustl.catissuecore.util.global.ApplicationProperties; import edu.wustl.catissuecore.util.global.Validator; import edu.wustl.common.beans.NameValueBean; import edu.wustl.common.util.SearchUtil; /** * This Class is used to encapsulate all the request parameters passed from Search Pages. * @author aniruddha_phadnis */ public class AdvanceSearchForm extends ActionForm { /** * @return Returns the columnNames. */ public String[] getColumnNames() { return columnNames; } /** * @param columnNames The columnNames to set. */ public void setColumnNames(String[] columnNames) { this.columnNames = columnNames; } /** * @return Returns the selectedColumnNames. */ public String[] getSelectedColumnNames() { return selectedColumnNames; } /** * @param selectedColumnNames The selectedColumnNames to set. */ public void setSelectedColumnNames(String[] selectedColumnNames) { this.selectedColumnNames = selectedColumnNames; } /** * @return Returns the tableName. */ public String getTableName() { return tableName; } /** * @param tableName The tableName to set. */ public void setTableName(String tableName) { this.tableName = tableName; } /** * A map that handles all the values of Advanced Search pages */ private Map values = new HashMap(); /** * A map that handles event parameters' data */ private Map eventMap = new HashMap(); /** * Objectname of the advancedConditionNode Object */ private String objectName=new String(); /** * Selected node from the query tree */ private String selectedNode = new String(); /** * A counter that holds the number of event parameter rows */ private int eventCounter = 1; String itemNodeId = ""; //Variables neccessary for Configuration of Advance Search Results private String tableName; private String []selectedColumnNames; private String []columnNames; /** * Returns the selected node from a query tree. * @return The selected node from a query tree. * @see #setSelectedNode(String) */ public String getSelectedNode() { return selectedNode; } /** * Sets the selected node of a query tree. * @param selectedNode the selected node of a query tree. * @see #getSelectedNode() */ public void setSelectedNode(String selectedNode) { this.selectedNode = selectedNode; } /** * No argument constructor for StorageTypeForm class */ public AdvanceSearchForm() { reset(); } /** * Associates the specified object with the specified key in the map. * @param key the key to which the object is mapped. * @param value the object which is mapped. */ public void setValue(String key, Object value) { values.put(key, value); } /** * Returns the object to which this map maps the specified key. * @param key the required key. * @return the object to which this map maps the specified key. */ public Object getValue(String key) { return values.get(key); } //Bug 700: changed the method name for setting the map values as it was same in both AdvanceSearchForm and SimpleQueryInterfaceForm /** * Associates the specified object with the specified key in the map. * @param key the key to which the object is mapped. * @param value the object which is mapped. */ public void setValue1(String key, Object value) { values.put(key, value); } /** * Returns the object to which this map maps the specified key. * @param key the required key. * @return the object to which this map maps the specified key. */ public Object getValue1(String key) { return values.get(key); } /** * Returns all the values of the map. * @return the values of the map. */ public Collection getAllValues() { return values.values(); } /** * Sets the map. * @param values the map. * @see #getValues() */ public void setValues(Map values) { this.values = values; } /** * Returns the map. * @return the map. * @see #setValues(Map) */ public Map getValues() { return this.values; } /** * Associates the specified array object with the specified key in the map. * @param key the key to which the object is mapped. * @param value the object which is mapped. */ public void setValueList(String key, Object [] value) { values.put(key, value); } /** * Returns the object array to which the specified key is been mapped. * @param key the required key. * @return the object to which this map maps the specified key. */ public Object[] getValueList(String key) { return (Object [])values.get(key); } /** * Resets the values of all the fields. * Is called by the overridden reset method defined in ActionForm. */ protected void reset() { } /** * Overrides the validate method of ActionForm. */ public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors(); Validator validator = new Validator(); String opConstant = "Operator:"; Iterator it = values.keySet().iterator(); if(objectName != null && !objectName.equals("")) { Map resourceBundleMap = SearchUtil.getResourceBundleMap(objectName); System.out.println("******** " + resourceBundleMap); Iterator iterator = resourceBundleMap.keySet().iterator(); while(iterator.hasNext()) { String valKey = (String)iterator.next(); //Value Key - ALIAS_NAME:COLUMN_NAME String opKey = opConstant + valKey; //Operator Key - OPERATOR:ALIAS_NAME:COLUMN_NAME String opValue = (String)values.get(opKey); //Operator Value if(validator.isOperator(opValue)) //IF the operator is a valid operator { String value = (String)values.get(valKey); NameValueBean bean = (NameValueBean)resourceBundleMap.get(valKey); String labelName = bean.getName(); //A key in ApplicationResources.properties if(!validator.isValue(value)) //IF the value is a valid value { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.missing",ApplicationProperties.getValue(labelName))); } else { if(!SearchUtil.STRING.equals(bean.getValue())) //IF the datatype is not STRING { if(SearchUtil.DATE.equals(bean.getValue())) //IF the datatype is DATE { if(!validator.checkDate(value)) //IF the start date is improper { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.format",ApplicationProperties.getValue(labelName))); } else { valKey = valKey + ":HLIMIT"; //Key for second field value = (String)values.get(valKey); if(!validator.isValue(value)) //IF the value is a valid value { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.missing",ApplicationProperties.getValue(labelName))); } else { if(value!= null && !validator.checkDate(value)) //IF the end date is improper { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.format",ApplicationProperties.getValue(labelName))); } } } } else if(SearchUtil.NUMERIC.equals(bean.getValue())) //IF the datatype is NUMERIC { if(!validator.isDouble(value)) //IF the numeric value is improper { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.format",ApplicationProperties.getValue(labelName))); } else { valKey = valKey + ":HLIMIT"; //Key for second field value = (String)values.get(valKey); if(!validator.isValue(value)) //IF the value is a valid value { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.missing",ApplicationProperties.getValue(labelName))); } else { if(value!= null && !validator.isDouble(value)) //IF the end value is improper { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.format",ApplicationProperties.getValue(labelName))); } } } } } } } } } return errors; } /** * Returns the object name. * @return the object name. * @see #setObjectName(String) */ public String getObjectName() { return objectName; } /** * Sets the object name. * @param objectName The object name to be set. * @see #getObjectName() */ public void setObjectName(String objectName) { this.objectName = objectName; } /** * Associates the specified object with the specified key in the map. * @param key the key to which the object is mapped. * @param value the object which is mapped. */ public void setEventMap(String key, Object value) { eventMap.put(key, value); } /** * Returns the object to which this map maps the specified key. * @param key the required key. * @return the object to which this map maps the specified key. */ public Object getEventMap(String key) { return eventMap.get(key); } /** * Returns the map of event parameters' values. * @return the map of event parameters' values. */ public Map getEventValues() { return this.eventMap; } /** * Returns the no. of rows of event parameters. * @return The no. of rows of event parameters. * @see #setEventCounter(int) */ public int getEventCounter() { return eventCounter; } /** * Sets the no. of rows of event parameters. * @param eventCounter The no. of rows of event parameters. * @see #getEventCounter() */ public void setEventCounter(int eventCounter) { this.eventCounter = eventCounter; } public String getItemNodeId() { return itemNodeId; } public void setItemNodeId(String itemId) { this.itemNodeId = itemId; } }
WEB-INF/src/edu/wustl/catissuecore/actionForm/AdvanceSearchForm.java
/** * <p>Title: AdvanceSearchForm Class> * <p>Description: This Class is used to encapsulate all the request parameters passed * from ParticipantSearch.jsp/CollectionProtocolRegistrationSearch.jsp/ * SpecimenCollectionGroupSearch.jsp & SpecimenSearch.jsp pages. </p> * Copyright: Copyright (c) year * Company: Washington University, School of Medicine, St. Louis. * @author Aniruddha Phadnis * @version 1.00 * Created on Jul 15, 2005 */ package edu.wustl.catissuecore.actionForm; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; import edu.wustl.catissuecore.util.global.ApplicationProperties; import edu.wustl.catissuecore.util.global.Validator; import edu.wustl.common.beans.NameValueBean; import edu.wustl.common.util.SearchUtil; /** * This Class is used to encapsulate all the request parameters passed from Search Pages. * @author aniruddha_phadnis */ public class AdvanceSearchForm extends ActionForm { /** * A map that handles all the values of Advanced Search pages */ private Map values = new HashMap(); /** * A map that handles event parameters' data */ private Map eventMap = new HashMap(); /** * Objectname of the advancedConditionNode Object */ private String objectName=new String(); /** * Selected node from the query tree */ private String selectedNode = new String(); /** * A counter that holds the number of event parameter rows */ private int eventCounter = 1; String itemNodeId = ""; /** * Returns the selected node from a query tree. * @return The selected node from a query tree. * @see #setSelectedNode(String) */ public String getSelectedNode() { return selectedNode; } /** * Sets the selected node of a query tree. * @param selectedNode the selected node of a query tree. * @see #getSelectedNode() */ public void setSelectedNode(String selectedNode) { this.selectedNode = selectedNode; } /** * No argument constructor for StorageTypeForm class */ public AdvanceSearchForm() { reset(); } /** * Associates the specified object with the specified key in the map. * @param key the key to which the object is mapped. * @param value the object which is mapped. */ public void setValue(String key, Object value) { values.put(key, value); } /** * Returns the object to which this map maps the specified key. * @param key the required key. * @return the object to which this map maps the specified key. */ public Object getValue(String key) { return values.get(key); } //Bug 700: changed the method name for setting the map values as it was same in both AdvanceSearchForm and SimpleQueryInterfaceForm /** * Associates the specified object with the specified key in the map. * @param key the key to which the object is mapped. * @param value the object which is mapped. */ public void setValue1(String key, Object value) { values.put(key, value); } /** * Returns the object to which this map maps the specified key. * @param key the required key. * @return the object to which this map maps the specified key. */ public Object getValue1(String key) { return values.get(key); } /** * Returns all the values of the map. * @return the values of the map. */ public Collection getAllValues() { return values.values(); } /** * Sets the map. * @param values the map. * @see #getValues() */ public void setValues(Map values) { this.values = values; } /** * Returns the map. * @return the map. * @see #setValues(Map) */ public Map getValues() { return this.values; } /** * Associates the specified array object with the specified key in the map. * @param key the key to which the object is mapped. * @param value the object which is mapped. */ public void setValueList(String key, Object [] value) { values.put(key, value); } /** * Returns the object array to which the specified key is been mapped. * @param key the required key. * @return the object to which this map maps the specified key. */ public Object[] getValueList(String key) { return (Object [])values.get(key); } /** * Resets the values of all the fields. * Is called by the overridden reset method defined in ActionForm. */ protected void reset() { } /** * Overrides the validate method of ActionForm. */ public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors(); Validator validator = new Validator(); String opConstant = "Operator:"; Iterator it = values.keySet().iterator(); if(objectName != null && !objectName.equals("")) { Map resourceBundleMap = SearchUtil.getResourceBundleMap(objectName); System.out.println("******** " + resourceBundleMap); Iterator iterator = resourceBundleMap.keySet().iterator(); while(iterator.hasNext()) { String valKey = (String)iterator.next(); //Value Key - ALIAS_NAME:COLUMN_NAME String opKey = opConstant + valKey; //Operator Key - OPERATOR:ALIAS_NAME:COLUMN_NAME String opValue = (String)values.get(opKey); //Operator Value if(validator.isOperator(opValue)) //IF the operator is a valid operator { String value = (String)values.get(valKey); NameValueBean bean = (NameValueBean)resourceBundleMap.get(valKey); String labelName = bean.getName(); //A key in ApplicationResources.properties if(!validator.isValue(value)) //IF the value is a valid value { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.missing",ApplicationProperties.getValue(labelName))); } else { if(!SearchUtil.STRING.equals(bean.getValue())) //IF the datatype is not STRING { if(SearchUtil.DATE.equals(bean.getValue())) //IF the datatype is DATE { if(!validator.checkDate(value)) //IF the start date is improper { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.format",ApplicationProperties.getValue(labelName))); } else { valKey = valKey + ":HLIMIT"; //Key for second field value = (String)values.get(valKey); if(!validator.isValue(value)) //IF the value is a valid value { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.missing",ApplicationProperties.getValue(labelName))); } else { if(value!= null && !validator.checkDate(value)) //IF the end date is improper { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.format",ApplicationProperties.getValue(labelName))); } } } } else if(SearchUtil.NUMERIC.equals(bean.getValue())) //IF the datatype is NUMERIC { if(!validator.isDouble(value)) //IF the numeric value is improper { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.format",ApplicationProperties.getValue(labelName))); } else { valKey = valKey + ":HLIMIT"; //Key for second field value = (String)values.get(valKey); if(!validator.isValue(value)) //IF the value is a valid value { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.missing",ApplicationProperties.getValue(labelName))); } else { if(value!= null && !validator.isDouble(value)) //IF the end value is improper { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.format",ApplicationProperties.getValue(labelName))); } } } } } } } } } return errors; } /** * Returns the object name. * @return the object name. * @see #setObjectName(String) */ public String getObjectName() { return objectName; } /** * Sets the object name. * @param objectName The object name to be set. * @see #getObjectName() */ public void setObjectName(String objectName) { this.objectName = objectName; } /** * Associates the specified object with the specified key in the map. * @param key the key to which the object is mapped. * @param value the object which is mapped. */ public void setEventMap(String key, Object value) { eventMap.put(key, value); } /** * Returns the object to which this map maps the specified key. * @param key the required key. * @return the object to which this map maps the specified key. */ public Object getEventMap(String key) { return eventMap.get(key); } /** * Returns the map of event parameters' values. * @return the map of event parameters' values. */ public Map getEventValues() { return this.eventMap; } /** * Returns the no. of rows of event parameters. * @return The no. of rows of event parameters. * @see #setEventCounter(int) */ public int getEventCounter() { return eventCounter; } /** * Sets the no. of rows of event parameters. * @param eventCounter The no. of rows of event parameters. * @see #getEventCounter() */ public void setEventCounter(int eventCounter) { this.eventCounter = eventCounter; } public String getItemNodeId() { return itemNodeId; } public void setItemNodeId(String itemId) { this.itemNodeId = itemId; } }
Fields added for configuration SVN-Revision: 2266
WEB-INF/src/edu/wustl/catissuecore/actionForm/AdvanceSearchForm.java
Fields added for configuration
<ide><path>EB-INF/src/edu/wustl/catissuecore/actionForm/AdvanceSearchForm.java <ide> public class AdvanceSearchForm extends ActionForm <ide> { <ide> /** <add> * @return Returns the columnNames. <add> */ <add> public String[] getColumnNames() { <add> return columnNames; <add> } <add> /** <add> * @param columnNames The columnNames to set. <add> */ <add> public void setColumnNames(String[] columnNames) { <add> this.columnNames = columnNames; <add> } <add> /** <add> * @return Returns the selectedColumnNames. <add> */ <add> public String[] getSelectedColumnNames() { <add> return selectedColumnNames; <add> } <add> /** <add> * @param selectedColumnNames The selectedColumnNames to set. <add> */ <add> public void setSelectedColumnNames(String[] selectedColumnNames) { <add> this.selectedColumnNames = selectedColumnNames; <add> } <add> /** <add> * @return Returns the tableName. <add> */ <add> public String getTableName() { <add> return tableName; <add> } <add> /** <add> * @param tableName The tableName to set. <add> */ <add> public void setTableName(String tableName) { <add> this.tableName = tableName; <add> } <add> /** <ide> * A map that handles all the values of Advanced Search pages <ide> */ <ide> private Map values = new HashMap(); <ide> <ide> <ide> String itemNodeId = ""; <add> <add> //Variables neccessary for Configuration of Advance Search Results <add> <add> private String tableName; <add> private String []selectedColumnNames; <add> private String []columnNames; <ide> <ide> /** <ide> * Returns the selected node from a query tree.
Java
bsd-3-clause
dd2ac7bb3913553adb9c0c552560e75695aa0ed7
0
Clashsoft/Dyvil,Clashsoft/Dyvil
package dyvil.tools.compiler.ast.expression; import dyvil.tools.compiler.ast.annotation.IAnnotation; import dyvil.tools.compiler.ast.classes.IClass; import dyvil.tools.compiler.ast.constant.IConstantValue; import dyvil.tools.compiler.ast.context.IContext; import dyvil.tools.compiler.ast.generic.ITypeContext; import dyvil.tools.compiler.ast.header.IClassCompilableList; import dyvil.tools.compiler.ast.header.ICompilableList; import dyvil.tools.compiler.ast.structure.Package; import dyvil.tools.compiler.ast.type.IType; import dyvil.tools.compiler.ast.type.IType.TypePosition; import dyvil.tools.compiler.ast.type.builtin.Types; import dyvil.tools.compiler.ast.type.generic.ClassGenericType; import dyvil.tools.compiler.ast.type.raw.ClassType; import dyvil.tools.compiler.backend.MethodWriter; import dyvil.tools.compiler.backend.exception.BytecodeException; import dyvil.tools.compiler.util.Markers; import dyvil.tools.parsing.Name; import dyvil.tools.parsing.marker.MarkerList; import dyvil.tools.parsing.position.ICodePosition; public final class ClassOperator extends AbstractValue implements IConstantValue { public static final class LazyFields { public static final IClass CLASS_CLASS = Package.javaLang.resolveClass("Class"); public static final ClassType CLASS = new ClassType(CLASS_CLASS); public static final IClass CLASS_CONVERTIBLE = Types.LITERALCONVERTIBLE_CLASS .resolveClass(Name.fromRaw("FromClass")); private LazyFields() { // no instances } } protected IType type; // Metadata private IType genericType; public ClassOperator(ICodePosition position) { this.position = position; } public ClassOperator(IType type) { this.setType(type); } @Override public int valueTag() { return CLASS_OPERATOR; } @Override public Object toObject() { return null; } @Override public IType getType() { if (this.genericType == null) { ClassGenericType generic = new ClassGenericType(LazyFields.CLASS_CLASS); generic.addType(this.type); return this.genericType = generic; } return this.genericType; } @Override public void setType(IType type) { this.type = type; } @Override public IValue withType(IType type, ITypeContext typeContext, MarkerList markers, IContext context) { final IAnnotation annotation = type.getAnnotation(LazyFields.CLASS_CONVERTIBLE); if (annotation != null) { return new LiteralConversion(this, annotation).withType(type, typeContext, markers, context); } return Types.isSuperType(type, this.getType()) ? this : null; } @Override public boolean isType(IType type) { return Types.isSuperType(type, this.getType()) || type.getAnnotation(LazyFields.CLASS_CONVERTIBLE) != null; } @Override public int getTypeMatch(IType type) { final int i = super.getTypeMatch(type); if (i != MISMATCH) { return i; } if (type.getAnnotation(LazyFields.CLASS_CONVERTIBLE) != null) { return CONVERSION_MATCH; } return MISMATCH; } @Override public void resolveTypes(MarkerList markers, IContext context) { if (this.type == null) { this.type = dyvil.tools.compiler.ast.type.builtin.Types.UNKNOWN; markers.add(Markers.semantic(this.position, "classoperator.invalid")); return; } this.type = this.type.resolveType(markers, context); ClassGenericType generic = new ClassGenericType(LazyFields.CLASS_CLASS); generic.addType(this.type); this.genericType = generic; } @Override public IValue resolve(MarkerList markers, IContext context) { this.type.resolve(markers, context); return this; } @Override public void checkTypes(MarkerList markers, IContext context) { this.type.checkType(markers, context, TypePosition.CLASS); } @Override public void check(MarkerList markers, IContext context) { this.type.check(markers, context); } @Override public IValue foldConstants() { this.type.foldConstants(); return this; } @Override public IValue cleanup(ICompilableList compilableList, IClassCompilableList classCompilableList) { this.type.cleanup(compilableList, classCompilableList); return this; } @Override public int stringSize() { if (this.type.isPrimitive()) { return this.type.getName().qualified.length(); } IClass iClass = this.type.getTheClass(); if (iClass == null) { return 20; } if (iClass.isInterface()) { return "interface ".length() + iClass.getInternalName().length(); } return "class ".length() + iClass.getInternalName().length(); } @Override public boolean toStringBuilder(StringBuilder builder) { if (this.type.isPrimitive()) { builder.append(this.type.getName().qualified); return true; } IClass iClass = this.type.getTheClass(); if (iClass == null) { return false; } if (iClass.isInterface()) { builder.append("interface "); } else { builder.append("class "); } builder.append(iClass.getFullName()); return true; } @Override public void writeExpression(MethodWriter writer, IType type) throws BytecodeException { this.type.writeClassExpression(writer, false); if (type != null) { this.genericType.writeCast(writer, type, this.getLineNumber()); } } @Override public String toString() { return "class(" + this.type + ")"; } @Override public void toString(String prefix, StringBuilder buffer) { buffer.append("class("); this.type.toString(prefix, buffer); buffer.append(')'); } }
src/compiler/dyvil/tools/compiler/ast/expression/ClassOperator.java
package dyvil.tools.compiler.ast.expression; import dyvil.tools.compiler.ast.annotation.IAnnotation; import dyvil.tools.compiler.ast.classes.IClass; import dyvil.tools.compiler.ast.constant.IConstantValue; import dyvil.tools.compiler.ast.context.IContext; import dyvil.tools.compiler.ast.generic.ITypeContext; import dyvil.tools.compiler.ast.header.IClassCompilableList; import dyvil.tools.compiler.ast.header.ICompilableList; import dyvil.tools.compiler.ast.structure.Package; import dyvil.tools.compiler.ast.type.IType; import dyvil.tools.compiler.ast.type.IType.TypePosition; import dyvil.tools.compiler.ast.type.builtin.Types; import dyvil.tools.compiler.ast.type.generic.ClassGenericType; import dyvil.tools.compiler.ast.type.raw.ClassType; import dyvil.tools.compiler.backend.MethodWriter; import dyvil.tools.compiler.backend.exception.BytecodeException; import dyvil.tools.compiler.util.Markers; import dyvil.tools.parsing.Name; import dyvil.tools.parsing.marker.MarkerList; import dyvil.tools.parsing.position.ICodePosition; public final class ClassOperator extends AbstractValue implements IConstantValue { public static final class LazyFields { public static final IClass CLASS_CLASS = Package.javaLang.resolveClass("Class"); public static final ClassType CLASS = new ClassType(CLASS_CLASS); public static final IClass CLASS_CONVERTIBLE = Types.LITERALCONVERTIBLE_CLASS .resolveClass(Name.fromRaw("FromClass")); private LazyFields() { // no instances } } protected IType type; // Metadata private IType genericType; public ClassOperator(ICodePosition position) { this.position = position; } public ClassOperator(IType type) { this.setType(type); } @Override public int valueTag() { return CLASS_OPERATOR; } @Override public Object toObject() { return dyvil.tools.asm.Type.getType(this.type.getExtendedName()); } @Override public IType getType() { if (this.genericType == null) { ClassGenericType generic = new ClassGenericType(LazyFields.CLASS_CLASS); generic.addType(this.type); return this.genericType = generic; } return this.genericType; } @Override public void setType(IType type) { this.type = type; } @Override public IValue withType(IType type, ITypeContext typeContext, MarkerList markers, IContext context) { final IAnnotation annotation = type.getAnnotation(LazyFields.CLASS_CONVERTIBLE); if (annotation != null) { return new LiteralConversion(this, annotation).withType(type, typeContext, markers, context); } return Types.isSuperType(type, this.getType()) ? this : null; } @Override public boolean isType(IType type) { return Types.isSuperType(type, this.getType()) || type.getAnnotation(LazyFields.CLASS_CONVERTIBLE) != null; } @Override public int getTypeMatch(IType type) { final int i = super.getTypeMatch(type); if (i != MISMATCH) { return i; } if (type.getAnnotation(LazyFields.CLASS_CONVERTIBLE) != null) { return CONVERSION_MATCH; } return MISMATCH; } @Override public void resolveTypes(MarkerList markers, IContext context) { if (this.type == null) { this.type = dyvil.tools.compiler.ast.type.builtin.Types.UNKNOWN; markers.add(Markers.semantic(this.position, "classoperator.invalid")); return; } this.type = this.type.resolveType(markers, context); ClassGenericType generic = new ClassGenericType(LazyFields.CLASS_CLASS); generic.addType(this.type); this.genericType = generic; } @Override public IValue resolve(MarkerList markers, IContext context) { this.type.resolve(markers, context); return this; } @Override public void checkTypes(MarkerList markers, IContext context) { this.type.checkType(markers, context, TypePosition.CLASS); } @Override public void check(MarkerList markers, IContext context) { this.type.check(markers, context); } @Override public IValue foldConstants() { this.type.foldConstants(); return this; } @Override public IValue cleanup(ICompilableList compilableList, IClassCompilableList classCompilableList) { this.type.cleanup(compilableList, classCompilableList); return this; } @Override public int stringSize() { if (this.type.isPrimitive()) { return this.type.getName().qualified.length(); } IClass iClass = this.type.getTheClass(); if (iClass == null) { return 20; } if (iClass.isInterface()) { return "interface ".length() + iClass.getInternalName().length(); } return "class ".length() + iClass.getInternalName().length(); } @Override public boolean toStringBuilder(StringBuilder builder) { if (this.type.isPrimitive()) { builder.append(this.type.getName().qualified); return true; } IClass iClass = this.type.getTheClass(); if (iClass == null) { return false; } if (iClass.isInterface()) { builder.append("interface "); } else { builder.append("class "); } builder.append(iClass.getFullName()); return true; } @Override public void writeExpression(MethodWriter writer, IType type) throws BytecodeException { this.type.writeClassExpression(writer, false); if (type != null) { this.genericType.writeCast(writer, type, this.getLineNumber()); } } @Override public String toString() { return "class(" + this.type + ")"; } @Override public void toString(String prefix, StringBuilder buffer) { buffer.append("class("); this.type.toString(prefix, buffer); buffer.append(')'); } }
Fix Class Operators comp: Fixed an issue that would produce invalid bytecode when class operators were used as constant field values.
src/compiler/dyvil/tools/compiler/ast/expression/ClassOperator.java
Fix Class Operators
<ide><path>rc/compiler/dyvil/tools/compiler/ast/expression/ClassOperator.java <ide> @Override <ide> public Object toObject() <ide> { <del> return dyvil.tools.asm.Type.getType(this.type.getExtendedName()); <add> return null; <ide> } <ide> <ide> @Override
JavaScript
mit
d8116468c96a200c441226a8fc4307d99d3360d0
0
omniscale/anol,omniscale/anol
angular.module('anol.savemanager') .provider('SaveManagerService', [function() { // handles layer source change events and store listener keys for removing // listeners nicely var LayerListener = function(layer, saveManager) { this.layer = layer; this.saveManager = saveManager; this.source = layer.olLayer.getSource(); this.addListenerKey = undefined; this.changeListenerKey = undefined; this.removeListenerKey = undefined; }; LayerListener.prototype.register = function(addHandler, changeHandler, removeHandler) { var self = this; var _register = function(type, handler, key) { if(handler === undefined) { return; } if(key !== undefined) { self.source.unByKey(key); } return self.source.on( type, function(evt) { handler.apply(self.saveManager, [evt, self.layer]); } ); }; self.addListenerKey = _register( ol.source.VectorEventType.ADDFEATURE, addHandler, self.addListenerKey ); self.changeListenerKey = _register( ol.source.VectorEventType.CHANGEFEATURE, changeHandler, self.changeListenerKey ); self.removeListenerKey = _register( ol.source.VectorEventType.REMOVEFEATURE, removeHandler, self.removeListenerKey ); }; LayerListener.prototype.unregister = function() { var self = this; if(self.addListenerKey !== undefined) { self.source.unByKey(self.addListenerKey); self.addListenerKey = undefined; } if(self.changeListenerKey !== undefined) { self.source.unByKey(self.changeListenerKey); self.changeListenerKey = undefined; } if(self.removeListenerKey !== undefined) { self.source.unByKey(self.removeListenerKey); self.removeListenerKey = undefined; } }; // stores features depending on their edit state // and converts stored features to geojson objects var FeatureStore = function(format) { this.format = format || new ol.format.GeoJSON(); this.added = []; this.changed = []; this.removed = []; }; FeatureStore.prototype.add = function(feature, action) { var addIdx = -1; var changeIdx = -1; switch(action) { case this.CHANGED: if(this.added.indexOf(feature) !== -1) { return; } break; case this.REMOVED: changeIdx = this.changed.indexOf(feature); addIdx = this.added.indexOf(feature); break; } if(addIdx !== -1) { this.added.splice(addIdx, 1); return; } if(changeIdx !== -1) { this.changed.splice(changeIdx, 1); } var list; switch(action) { case this.ADDED: list = this.added; break; case this.CHANGED: list = this.changed; break; case this.REMOVED: list = this.removed; break; } if(list.indexOf(feature) === -1) { list.push(feature); } }; FeatureStore.prototype.append = function(featureStore) { this.added = this.added.concat(featureStore.added); this.changed = this.changed.concat(featureStore.changed); this.removed = this.removed.concat(featureStore.removed); }; FeatureStore.prototype.hasAddedFeatures = function() { return this.added.length > 0; }; FeatureStore.prototype.hasChangedFeatures = function() { return this.changed.length > 0; }; FeatureStore.prototype.hasRemovedFeatures = function() { return this.removed.length > 0; }; FeatureStore.prototype.addedFeatures = function() { return this.format.writeFeaturesObject(this.added); }; FeatureStore.prototype.changedFeatures = function() { return this.format.writeFeaturesObject(this.changed); }; FeatureStore.prototype.removedFeatures = function() { var ids = []; angular.forEach(this.removed, function(feature) { ids.push(feature.get('_id')); }); return ids; }; FeatureStore.prototype.ADDED = 1; FeatureStore.prototype.CHANGED = 2; FeatureStore.prototype.REMOVED = 3; var _saveUrl; this.setSaveUrl = function(saveUrl) { _saveUrl = saveUrl; }; this.$get = ['$rootScope', '$q', '$http', '$timeout', function($rootScope, $q, $http, $timeout) { var SaveManager = function(saveUrl) { this.saveUrl = saveUrl; this.changedLayers = {}; this.changedFeatures = {}; }; SaveManager.prototype.addLayer = function(layer) { var self = this; var layerListener = new LayerListener(layer, self); $rootScope.$watch(function() { return layer.loaded; }, function(loaded) { if(loaded === true) { layerListener.register( self.featureAddedHandler, self.featureChangedHandler, self.featureRemovedHandler ); } else { layerListener.unregister(); } }); }; SaveManager.prototype.featureAddedHandler = function(evt, layer) { var self = this; var feature = evt.feature; var featureStore = self.featureStoreByLayer(layer); featureStore.add(feature, featureStore.ADDED); self.addChangedLayer(layer); }; SaveManager.prototype.featureChangedHandler = function(evt, layer) { var self = this; var feature = evt.feature; var featureStore = self.featureStoreByLayer(layer); featureStore.add(feature, featureStore.CHANGED); self.addChangedLayer(layer); }; SaveManager.prototype.featureRemovedHandler = function(evt, layer) { var self = this; var feature = evt.feature; var featureStore = self.featureStoreByLayer(layer); featureStore.add(feature, featureStore.REMOVED); self.addChangedLayer(layer); }; SaveManager.prototype.featureStoreByLayer = function(layer) { var self = this; if(self.changedFeatures[layer.name] === undefined) { self.changedFeatures[layer.name] = new FeatureStore(); } return self.changedFeatures[layer.name]; }; SaveManager.prototype.addChangedLayer = function(layer) { var self = this; if(!(layer.name in self.changedLayers)) { // TODO find out why $apply already in progress $timeout(function() { $rootScope.$apply(function() { self.changedLayers[layer.name] = layer; }); }); } }; SaveManager.prototype.commitFeatures = function(featureStore, layerName, targetUrl) { var promises = []; if(featureStore.hasAddedFeatures()) { var data = featureStore.addedFeatures(); data.layername = layerName; promises.push($http.put(targetUrl, data)); } if(featureStore.hasChangedFeatures()) { promises.push($http.post(targetUrl, featureStore.changedFeatures())); } if(featureStore.hasRemovedFeatures()) { promises.push($http.delete(targetUrl, {params: {'ids': featureStore.removedFeatures()}})); } return $q.all(promises); }; SaveManager.prototype.commit = function(layer) { var self = this; var deferred = $q.defer(); if(layer.name in self.changedLayers) { var featureStore = self.featureStoreByLayer(layer); var promise = self.commitFeatures(featureStore, layer.name, layer.saveUrl || self.saveUrl); promise.then(function() { deferred.resolve(); }, function(reason) { deferred.reject(reason); }); } else { deferred.reject('No changes for layer ' + layer.name + ' present'); } return deferred.promise; }; return new SaveManager(_saveUrl); }]; }]);
src/modules/savemanager/savemanager-service.js
angular.module('anol.savemanager') .provider('SaveManagerService', [function() { // handles layer source change events and store listener keys for removing // listeners nicely var LayerListener = function(layer, saveManager) { this.layer = layer; this.saveManager = saveManager; this.source = layer.olLayer.getSource(); this.addListenerKey = undefined; this.changeListenerKey = undefined; this.removeListenerKey = undefined; }; LayerListener.prototype.register = function(addHandler, changeHandler, removeHandler) { var self = this; var _register = function(type, handler, key) { if(handler === undefined) { return; } if(key !== undefined) { self.source.unByKey(key); } return self.source.on( type, function(evt) { handler.apply(self.saveManager, [evt, self.layer]); } ); }; self.addListenerKey = _register( ol.source.VectorEventType.ADDFEATURE, addHandler, self.addListenerKey ); self.changeListenerKey = _register( ol.source.VectorEventType.CHANGEFEATURE, changeHandler, self.changeListenerKey ); self.removeListenerKey = _register( ol.source.VectorEventType.REMOVEFEATURE, removeHandler, self.removeListenerKey ); }; LayerListener.prototype.unregister = function() { var self = this; if(self.addListenerKey !== undefined) { self.source.unByKey(self.addListenerKey); self.addListenerKey = undefined; } if(self.changeListenerKey !== undefined) { self.source.unByKey(self.changeListenerKey); self.changeListenerKey = undefined; } if(self.removeListenerKey !== undefined) { self.source.unByKey(self.removeListenerKey); self.removeListenerKey = undefined; } }; // stores features depending on their edit state // and converts stored features to geojson objects var FeatureStore = function(format) { this.format = format || new ol.format.GeoJSON(); this.added = []; this.changed = []; this.removed = []; }; FeatureStore.prototype.add = function(feature, action) { var list; switch(action) { case this.ADDED: list = this.added; break; case this.CHANGED: list = this.changed; break; case this.REMOVED: list = this.removed; break; } if(list.indexOf(feature) === -1) { list.push(feature); } var addIdx = -1; var changeIdx = -1; switch(action) { case this.REMOVED: changeIdx = this.changed.indexOf(feature); addIdx = this.added.indexOf(feature); break; case this.CHANGED: addIdx = this.added.indexOf(feature); break; } if(addIdx !== -1) { this.added.splice(addIdx, 1); } if(changeIdx !== -1) { this.changed.splice(changeIdx, 1); } }; FeatureStore.prototype.append = function(featureStore) { this.added = this.added.concat(featureStore.added); this.changed = this.changed.concat(featureStore.changed); this.removed = this.removed.concat(featureStore.removed); }; FeatureStore.prototype.hasAddedFeatures = function() { return this.added.length > 0; }; FeatureStore.prototype.hasChangedFeatures = function() { return this.changed.length > 0; }; FeatureStore.prototype.hasRemovedFeatures = function() { return this.removed.length > 0; }; FeatureStore.prototype.addedFeatures = function() { return this.format.writeFeaturesObject(this.added); }; FeatureStore.prototype.changedFeatures = function() { return this.format.writeFeaturesObject(this.changed); }; FeatureStore.prototype.removedFeatures = function() { var ids = []; angular.forEach(this.removed, function(feature) { ids.push(feature.get('_id')); }); return ids; }; FeatureStore.prototype.ADDED = 1; FeatureStore.prototype.CHANGED = 2; FeatureStore.prototype.REMOVED = 3; var _saveUrl; this.setSaveUrl = function(saveUrl) { _saveUrl = saveUrl; }; this.$get = ['$rootScope', '$q', '$http', '$timeout', function($rootScope, $q, $http, $timeout) { var SaveManager = function(saveUrl) { this.saveUrl = saveUrl; this.changedLayers = {}; this.changedFeatures = {}; }; SaveManager.prototype.addLayer = function(layer) { var self = this; var layerListener = new LayerListener(layer, self); $rootScope.$watch(function() { return layer.loaded; }, function(loaded) { if(loaded === true) { layerListener.register( self.featureAddedHandler, self.featureChangedHandler, self.featureRemovedHandler ); } else { layerListener.unregister(); } }); }; SaveManager.prototype.featureAddedHandler = function(evt, layer) { var self = this; var feature = evt.feature; var featureStore = self.featureStoreByLayer(layer); featureStore.add(feature, featureStore.ADDED); self.addChangedLayer(layer); }; SaveManager.prototype.featureChangedHandler = function(evt, layer) { var self = this; var feature = evt.feature; var featureStore = self.featureStoreByLayer(layer); featureStore.add(feature, featureStore.CHANGED); self.addChangedLayer(layer); }; SaveManager.prototype.featureRemovedHandler = function(evt, layer) { var self = this; var feature = evt.feature; var featureStore = self.featureStoreByLayer(layer); featureStore.add(feature, featureStore.REMOVED); self.addChangedLayer(layer); }; SaveManager.prototype.featureStoreByLayer = function(layer) { var self = this; if(self.changedFeatures[layer.name] === undefined) { self.changedFeatures[layer.name] = new FeatureStore(); } return self.changedFeatures[layer.name]; }; SaveManager.prototype.addChangedLayer = function(layer) { var self = this; if(!(layer.name in self.changedLayers)) { // TODO find out why $apply already in progress $timeout(function() { $rootScope.$apply(function() { self.changedLayers[layer.name] = layer; }); }); } }; SaveManager.prototype.commitFeatures = function(featureStore, layerName, targetUrl) { var promises = []; if(featureStore.hasAddedFeatures()) { var data = featureStore.addedFeatures(); data.layername = layerName; promises.push($http.put(targetUrl, data)); } if(featureStore.hasChangedFeatures()) { promises.push($http.post(targetUrl, featureStore.changedFeatures())); } if(featureStore.hasRemovedFeatures()) { promises.push($http.delete(targetUrl, {params: {'ids': featureStore.removedFeatures()}})); } return $q.all(promises); }; SaveManager.prototype.commit = function(layer) { var self = this; var deferred = $q.defer(); if(layer.name in self.changedLayers) { var featureStore = self.featureStoreByLayer(layer); var promise = self.commitFeatures(featureStore, layer.name, layer.saveUrl || self.saveUrl); promise.then(function() { deferred.resolve(); }, function(reason) { deferred.reject(reason); }); } else { deferred.reject('No changes for layer ' + layer.name + ' present'); } return deferred.promise; }; return new SaveManager(_saveUrl); }]; }]);
Improved add feature to featureStore
src/modules/savemanager/savemanager-service.js
Improved add feature to featureStore
<ide><path>rc/modules/savemanager/savemanager-service.js <ide> this.removed = []; <ide> }; <ide> FeatureStore.prototype.add = function(feature, action) { <add> var addIdx = -1; <add> var changeIdx = -1; <add> switch(action) { <add> case this.CHANGED: <add> if(this.added.indexOf(feature) !== -1) { <add> return; <add> } <add> break; <add> case this.REMOVED: <add> changeIdx = this.changed.indexOf(feature); <add> addIdx = this.added.indexOf(feature); <add> break; <add> } <add> if(addIdx !== -1) { <add> this.added.splice(addIdx, 1); <add> return; <add> } <add> if(changeIdx !== -1) { <add> this.changed.splice(changeIdx, 1); <add> } <add> <ide> var list; <ide> switch(action) { <ide> case this.ADDED: <ide> } <ide> if(list.indexOf(feature) === -1) { <ide> list.push(feature); <del> } <del> <del> <del> var addIdx = -1; <del> var changeIdx = -1; <del> switch(action) { <del> case this.REMOVED: <del> changeIdx = this.changed.indexOf(feature); <del> addIdx = this.added.indexOf(feature); <del> break; <del> case this.CHANGED: <del> addIdx = this.added.indexOf(feature); <del> break; <del> } <del> if(addIdx !== -1) { <del> this.added.splice(addIdx, 1); <del> } <del> if(changeIdx !== -1) { <del> this.changed.splice(changeIdx, 1); <ide> } <ide> }; <ide> FeatureStore.prototype.append = function(featureStore) {
Java
apache-2.0
50a5ba656ae2eff05c917edc3de020a7f4281974
0
scify/Memor-i,scify/Memor-i
package org.scify.memori.helper; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.logging.Level; /** * Created by pisaris on 21/12/2016. */ public class MemoriConfiguration { /** * Get a variable from project.properties file (given an input stream) * @param propertyName the name of the property * @return the value of the given property */ public String getPropertyByName(InputStream propertyFileStream, String propertyName) { Properties props = new Properties(); try { props.load(propertyFileStream); return props.getProperty(String.valueOf(propertyName)); } catch (IOException e) { e.printStackTrace(); } return null; } /** * Given a property key, gets a value from resources/project.properties file * @param propertyKey the property key * @return the property value */ public String getProjectProperty(String propertyKey) { return this.getDataPackProperty(propertyKey, "/project_additional.properties"); } public String getDataPackProperty(String propertyKey, String propertyFileName) { System.out.println("getting property file: " + propertyFileName); //When loading a resource, the "/" means root of the main/resources directory InputStream inputStream = getClass().getResourceAsStream(propertyFileName); //if project_additional.properties file is not found, we load the default one if(inputStream == null) { inputStream = getClass().getResourceAsStream("/project.properties"); MemoriLogger.LOGGER.log(Level.SEVERE, "Property file: " + propertyFileName + " not found"); } String propertyValue = this.getPropertyByName(inputStream, propertyKey); if(propertyValue == null) { inputStream = getClass().getResourceAsStream("/project.properties"); propertyValue = this.getPropertyByName(inputStream, propertyKey); } return propertyValue; } /** * Gets the default user directory for the current architecture */ public String getUserDir() { String userDir; if ((System.getProperty("os.name")).toUpperCase().contains("WINDOWS")) { userDir = System.getenv("AppData"); } else { userDir = System.getProperty("user.dir"); } return userDir + File.separator; } }
src/main/java/org/scify/memori/helper/MemoriConfiguration.java
package org.scify.memori.helper; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * Created by pisaris on 21/12/2016. */ public class MemoriConfiguration { /** * Get a variable from project.properties file (given an input stream) * @param propertyName the name of the property * @return the value of the given property */ public String getPropertyByName(InputStream propertyFileStream, String propertyName) { Properties props = new Properties(); try { props.load(propertyFileStream); return props.getProperty(String.valueOf(propertyName)); } catch (IOException e) { e.printStackTrace(); } return null; } /** * Given a property key, gets a value from resources/project.properties file * @param propertyKey the property key * @return the property value */ public String getProjectProperty(String propertyKey) { //When loading a resource, the "/" means root of the main/resources directory InputStream inputStream = getClass().getResourceAsStream("/project_additional.properties"); //if project_additional.properties file is not found, we load the default one if(inputStream == null) inputStream = getClass().getResourceAsStream("/project.properties"); String propertyValue = this.getPropertyByName(inputStream, propertyKey); if(propertyValue == null) { inputStream = getClass().getResourceAsStream("/project.properties"); propertyValue = this.getPropertyByName(inputStream, propertyKey); } return propertyValue; } /** * Gets the default user directory for the current architecture */ public String getUserDir() { String userDir; if ((System.getProperty("os.name")).toUpperCase().contains("WINDOWS")) { userDir = System.getenv("AppData"); } else { userDir = System.getProperty("user.dir"); } return userDir + File.separator; } }
Refactored Class to read data from the additional pack
src/main/java/org/scify/memori/helper/MemoriConfiguration.java
Refactored Class to read data from the additional pack
<ide><path>rc/main/java/org/scify/memori/helper/MemoriConfiguration.java <ide> import java.io.IOException; <ide> import java.io.InputStream; <ide> import java.util.Properties; <add>import java.util.logging.Level; <ide> <ide> /** <ide> * Created by pisaris on 21/12/2016. <ide> * @return the property value <ide> */ <ide> public String getProjectProperty(String propertyKey) { <add> return this.getDataPackProperty(propertyKey, "/project_additional.properties"); <add> } <add> <add> public String getDataPackProperty(String propertyKey, String propertyFileName) { <add> System.out.println("getting property file: " + propertyFileName); <ide> //When loading a resource, the "/" means root of the main/resources directory <del> InputStream inputStream = getClass().getResourceAsStream("/project_additional.properties"); <add> InputStream inputStream = getClass().getResourceAsStream(propertyFileName); <ide> //if project_additional.properties file is not found, we load the default one <del> if(inputStream == null) <add> if(inputStream == null) { <ide> inputStream = getClass().getResourceAsStream("/project.properties"); <add> MemoriLogger.LOGGER.log(Level.SEVERE, "Property file: " + propertyFileName + " not found"); <add> } <ide> String propertyValue = this.getPropertyByName(inputStream, propertyKey); <ide> if(propertyValue == null) { <ide> inputStream = getClass().getResourceAsStream("/project.properties");
JavaScript
mit
4a81fdb5ed1b04ca2001fae2b41d742e56713333
0
pdelanauze/harvester,pdelanauze/couchstrap,pdelanauze/harvester,pdelanauze/couchstrap
/** * Created with IntelliJ IDEA. * User: pat * Date: 12-05-10 * Time: 2:15 PM * To change this template use File | Settings | File Templates. */ define(['underscore', 'backbone', '../lib/utility', '../lib/backbone-utility', '../lib/backbone-couch-schema-model', '../lib/backbone.couchdb'], function (_, Backbone, Utility, BackboneUtility, BackboneCouchSchemaModel, Backbone) { var TodoApp = { Models:{}, Collections:{}, Routers:{}, App: { router: false } }; TodoApp.Models.Todo = BackboneCouchSchemaModel.extend({ // TODO Introduce a app-config dependency that contains all the configuration options of the application, such as the url of the couchdb server defaults: { type: 'todo' }, schema:{ description:'Todo item', type:'todo', properties:{ name:{ title:'Name', type:'string', required:true, 'default':'What needs to be done?' }, description:{ title:'Description', required: false, type:'string' }, createdAt:{ title:'Creation date', type:'string', format: 'date-time' }, completedAt:{ title:'Completion date', type:'string', format: 'date-time' } } } }); TodoApp.Collections.TodoCollection = Backbone.couch.Collection.extend({ model:TodoApp.Models.Todo, change_feed: true, couch: function() { return { view: Backbone.couch.options.design + '/by_type', key: 'todo', include_docs: true } }, initialize: function(){ this._db = Backbone.couch.db(Backbone.couch.options.database); } // _db:Backbone.couch.db(Backbone.couch.options.database) // Set a runtime... }); TodoApp.Routers.TodoRouter = BackboneUtility.Routers.ScaffoldViewBasedRouter.extend({ modelName:'todo', pluralModelName:'todos', modelClass:TodoApp.Models.Todo, parentContainer: $("#apps-container").append('<div class="todo-app-container"></div>'), initialize: function(opts){ BackboneUtility.Routers.ScaffoldViewBasedRouter.prototype.initialize.apply(this, arguments); this.collection = new TodoApp.Collections.TodoCollection(); } }); return TodoApp; });
js/application/todo-app.js
/** * Created with IntelliJ IDEA. * User: pat * Date: 12-05-10 * Time: 2:15 PM * To change this template use File | Settings | File Templates. */ define(['underscore', 'backbone', '../lib/utility', '../lib/backbone-utility', '../lib/backbone-couch-schema-model', '../lib/backbone.couchdb'], function (_, Backbone, Utility, BackboneUtility, BackboneCouchSchemaModel, Backbone) { var TodoApp = { Models:{}, Collections:{}, Routers:{}, App: { router: false } }; TodoApp.Models.Todo = BackboneCouchSchemaModel.extend({ // TODO Introduce a app-config dependency that contains all the configuration options of the application, such as the url of the couchdb server defaults: { type: 'todo', name: '' }, schema:{ description:'Todo item', type:'todo', properties:{ name:{ title:'Name', type:'string', required:true, 'default':'What needs to be done?' }, description:{ title:'Description', type:'string' }, createdAt:{ title:'Creation date', type:'string', format: 'date-time' }, completedAt:{ title:'Completion date', type:'string', format: 'date-time' } } } }); TodoApp.Collections.TodoCollection = Backbone.couch.Collection.extend({ model:TodoApp.Models.Todo, change_feed: true, couch: function() { return { view: Backbone.couch.options.design + '/by_type', key: 'todo', include_docs: true } }, initialize: function(){ this._db = Backbone.couch.db(Backbone.couch.options.database); } // _db:Backbone.couch.db(Backbone.couch.options.database) // Set a runtime... }); TodoApp.Routers.TodoRouter = BackboneUtility.Routers.ScaffoldViewBasedRouter.extend({ modelName:'todo', pluralModelName:'todos', modelClass:TodoApp.Models.Todo, parentContainer: $("#apps-container").append('<div class="todo-app-container"></div>'), initialize: function(opts){ BackboneUtility.Routers.ScaffoldViewBasedRouter.prototype.initialize.apply(this, arguments); this.collection = new TodoApp.Collections.TodoCollection(); } }); return TodoApp; });
Removing defaults 'name' field, it already puts the backbone model in an invalid state.. which is no good
js/application/todo-app.js
Removing defaults 'name' field, it already puts the backbone model in an invalid state.. which is no good
<ide><path>s/application/todo-app.js <ide> TodoApp.Models.Todo = BackboneCouchSchemaModel.extend({ <ide> // TODO Introduce a app-config dependency that contains all the configuration options of the application, such as the url of the couchdb server <ide> defaults: { <del> type: 'todo', <del> name: '' <add> type: 'todo' <ide> }, <ide> schema:{ <ide> description:'Todo item', <ide> }, <ide> description:{ <ide> title:'Description', <add> required: false, <ide> type:'string' <ide> }, <ide> createdAt:{
Java
apache-2.0
7467cc3d587d7fe680db2b403d1b34e638a2cb19
0
Hurence/log-island,MiniPlayer/log-island,Hurence/log-island,MiniPlayer/log-island,MiniPlayer/log-island,MiniPlayer/log-island,MiniPlayer/log-island
/** * Copyright (C) 2016 Hurence ([email protected]) * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.hurence.logisland.util.time; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import static org.junit.Assert.*; /** * @author tom */ public class DateUtilTest { private static final TimeZone tz = TimeZone.getTimeZone("Europe/Paris"); private static Logger logger = LoggerFactory.getLogger(DateUtilTest.class); // TODO fix test here on unix /** * org.junit.ComparisonFailure: expected:<2012-10-19T[18]:12:49.000 CEST> but was:<2012-10-19T[20]:12:49.000 CEST> * at org.junit.Assert.assertEquals(Assert.java:115) * at org.junit.Assert.assertEquals(Assert.java:144) * at com.hurence.logisland.utils.time.DateUtilsTest.testDateToString(DateUtilsTest.java:33) * * @throws ParseException */ //@Test public void testDateToString() throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss", new Locale("fr", "FR")); Date date = sdf.parse("19/Oct/2012:18:12:49"); String result = DateUtil.toString(date); String expectedResult = "2012-10-19T18:12:49.000 CEST"; assertEquals(expectedResult, result); } @Test public void testStringToDate() throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss", new Locale("en", "US")); sdf.setTimeZone(tz); Date expectedResult = sdf.parse("19/Oct/2012:18:12:49"); String dateString = "2012-10-19T18:12:49.000 CEST"; Date result = DateUtil.fromIsoStringToDate(dateString); assertEquals(expectedResult, result); Date now = new Date(); assertEquals(now, DateUtil.fromIsoStringToDate(DateUtil.toString(now))); } @Test public void testIsWeekEnd() throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("dd/MMM/yyyy:hh:mm:ss", new Locale("en", "US")); Date date = sdf.parse("27/Jul/2013:18:12:49"); assertTrue(DateUtil.isWeekend(date)); date = sdf.parse("28/Jul/2013:18:12:49"); assertTrue(DateUtil.isWeekend(date)); date = sdf.parse("29/Jul/2013:00:00:01"); assertFalse(DateUtil.isWeekend(date)); date = sdf.parse("26/Jul/2013:23:59:59"); assertFalse(DateUtil.isWeekend(date)); } @Test public void testIsWithinRange() throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("dd/MMM/yyyy:hh:mm:ss", new Locale("en", "US")); Date date = sdf.parse("27/Jul/2013:18:12:49"); assertTrue(DateUtil.isWithinHourRange(date, 9, 19)); assertFalse(DateUtil.isWithinHourRange(date, 19, 20)); } @Test public void testTimeout() throws InterruptedException { Date date = new Date(); // go in the past from 5" date.setTime(date.getTime() - 2000); assertFalse(DateUtil.isTimeoutExpired(date, 3000)); Thread.sleep(2000); assertTrue(DateUtil.isTimeoutExpired(date, 3000)); } @Test public void testLegacyFormat() throws ParseException { String strDate = "Thu Jan 02 08:43:49 CET 2014"; SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy", new Locale("en", "US")); Date date = sdf.parse(strDate); assertTrue(1388648629000L == date.getTime()); date = DateUtil.fromLegacyStringToDate(strDate); assertTrue(1388648629000L == date.getTime()); } @Test public void testGetLatestDaysFromNow() throws ParseException { String result = DateUtil.getLatestDaysFromNow(3); // String expectedResult = "2012-10-19T18:12:49.000 CEST"; // assertEquals(expectedResult, result); } @Test public void testParsing() throws ParseException { // Date expectedDate = new Date(1388648629000L); DateTime today = new DateTime(DateTimeZone.UTC); String currentYear = today.year().getAsString(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(DateTimeZone.UTC); DateTime expectedDate = f.parseDateTime(currentYear + "-01-02 07:43:49"); String currentDay = expectedDate.dayOfWeek().getAsShortText(Locale.ENGLISH); String[] strDates = { currentDay + " Jan 02 08:43:49 CET " + currentYear, currentDay + ", 02 Jan " + currentYear + " 08:43:49 CET", currentYear + "-01-02T08:43:49CET", currentYear + "-01-02T08:43:49.000CET", currentYear + "-01-02T08:43:49.0000+01:00", currentYear + "-01-02 07:43:49", currentYear + "-01-02 07:43:49,000", currentYear + "-01-02 07:43:49.000", "02/JAN/" + currentYear + ":09:43:49 +0200", "Jan 02 07:43:49", "02/01/" + currentYear + "-07:43:49:000", "02-Jan-" + currentYear + " 07:43:49:000", "02-Jan-" + currentYear + " 07:43:49.000", "02/Jan/" + currentYear + ":03:43:49 -0400", currentYear + " Jan 02 07:43:49", currentYear + " Jan 2 7:43:49", }; for (String strDate : strDates) { logger.info("parsing " + strDate); Date date = DateUtil.parse(strDate); assertTrue(date + " should be equal to " + expectedDate.toDate(), expectedDate.getMillis() == date.getTime()); } } @Test public void testParsing2() throws ParseException { DateTime today = new DateTime(DateTimeZone.UTC); String currentYear = today.year().getAsString(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy").withZone(DateTimeZone.UTC); DateTime expectedDate = f.parseDateTime(currentYear); Date date = DateUtil.parse(currentYear); assertTrue(date + " should be equal to " + expectedDate.toDate(), expectedDate.getMillis() == date.getTime()); } @Test public void testParsingWithTimeZone() throws ParseException { /** * WARNING ! Oracle is playing with timeZones object between minor version changes... * For exemple that caused this test to fail with "America/Cancun" timeZone if the jvm * version was inferior to 8u45... So I replaced it by "Canada/Atlantic" that should be more stable * and put it as a variable so we can easily change it */ TimeZone testTimeZone = TimeZone.getTimeZone("Canada/Atlantic"); // Date expectedDate = new Date(1388648629000L); DateTime today = new DateTime(DateTimeZone.UTC); String currentYear = today.year().getAsString(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(DateTimeZone.forTimeZone(tz)); DateTime expectedEuropeDate = f.parseDateTime(currentYear + "-01-02 07:43:49"); Date dateAsEuropeanDate = DateUtil.parse(currentYear + "-01-02 07:43:49", "yyyy-MM-dd HH:mm:ss", tz); assertTrue(dateAsEuropeanDate + " should be equal to " + expectedEuropeDate.toDate(), dateAsEuropeanDate.getTime() == expectedEuropeDate.getMillis()); Date dateAsUtcDate = DateUtil.parse(currentYear + "-01-02 07:43:49", "yyyy-MM-dd HH:mm:ss"); assertTrue(dateAsUtcDate + " should be equal to " + expectedEuropeDate.toDate() + " plus 1 hour", dateAsUtcDate.getTime() == expectedEuropeDate.getMillis() + 1000 * 60 * 60); Date dateAsTest = DateUtil.parse(currentYear + "-01-02 07:43:49", "yyyy-MM-dd HH:mm:ss", testTimeZone); assertTrue(dateAsTest + " should be equal to " + expectedEuropeDate.toDate() + " plus 6 hour", dateAsTest.getTime() == expectedEuropeDate.getMillis() + 1000 * 60 * 60 * 5 ); /** * should not use set timezone when timezone on pattern */ f = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ").withZone(DateTimeZone.forTimeZone(tz)); DateTime expectedDate = f.parseDateTime("2001-07-04T12:08:56.235-0700"); dateAsEuropeanDate = DateUtil.parse("2001-07-04T12:08:56.235-0700", "yyyy-MM-dd'T'HH:mm:ss.SSSZ", tz); assertTrue(dateAsEuropeanDate + " should be equal to " + expectedDate.toDate(), dateAsEuropeanDate.getTime() == expectedDate.getMillis()); dateAsUtcDate = DateUtil.parse("2001-07-04T12:08:56.235-0700", "yyyy-MM-dd'T'HH:mm:ss.SSSZ"); assertTrue(dateAsUtcDate + " should be equal to " + expectedDate.toDate(), dateAsUtcDate.getTime() == expectedDate.getMillis()); dateAsTest = DateUtil.parse("2001-07-04T12:08:56.235-0700", "yyyy-MM-dd'T'HH:mm:ss.SSSZ", testTimeZone); assertTrue(dateAsTest + " should be equal to " + expectedDate.toDate(), dateAsTest.getTime() == expectedDate.getMillis()); } @Test public void testParsingWithoutTimeZone() throws ParseException { // Date expectedDate = new Date(1388648629000L); DateTime today = new DateTime(DateTimeZone.UTC); String currentYear = today.year().getAsString(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(DateTimeZone.UTC); DateTime expectedUtcDate = f.parseDateTime(currentYear + "-01-02 07:43:49"); Date dateAsUtcDate = DateUtil.parse(currentYear + "-01-02 07:43:49", "yyyy-MM-dd HH:mm:ss"); assertTrue(dateAsUtcDate + " should be equal to " + expectedUtcDate.toDate(), expectedUtcDate.getMillis() == dateAsUtcDate.getTime()); } }
logisland-framework/logisland-utils/src/test/java/com/hurence/logisland/util/time/DateUtilTest.java
/** * Copyright (C) 2016 Hurence ([email protected]) * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.hurence.logisland.util.time; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import static org.junit.Assert.*; /** * @author tom */ public class DateUtilTest { private static final TimeZone tz = TimeZone.getTimeZone("Europe/Paris"); private static Logger logger = LoggerFactory.getLogger(DateUtilTest.class); // TODO fix test here on unix /** * org.junit.ComparisonFailure: expected:<2012-10-19T[18]:12:49.000 CEST> but was:<2012-10-19T[20]:12:49.000 CEST> * at org.junit.Assert.assertEquals(Assert.java:115) * at org.junit.Assert.assertEquals(Assert.java:144) * at com.hurence.logisland.utils.time.DateUtilsTest.testDateToString(DateUtilsTest.java:33) * * @throws ParseException */ //@Test public void testDateToString() throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss", new Locale("fr", "FR")); Date date = sdf.parse("19/Oct/2012:18:12:49"); String result = DateUtil.toString(date); String expectedResult = "2012-10-19T18:12:49.000 CEST"; assertEquals(expectedResult, result); } @Test public void testStringToDate() throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss", new Locale("en", "US")); sdf.setTimeZone(tz); Date expectedResult = sdf.parse("19/Oct/2012:18:12:49"); String dateString = "2012-10-19T18:12:49.000 CEST"; Date result = DateUtil.fromIsoStringToDate(dateString); assertEquals(expectedResult, result); Date now = new Date(); assertEquals(now, DateUtil.fromIsoStringToDate(DateUtil.toString(now))); } @Test public void testIsWeekEnd() throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("dd/MMM/yyyy:hh:mm:ss", new Locale("en", "US")); Date date = sdf.parse("27/Jul/2013:18:12:49"); assertTrue(DateUtil.isWeekend(date)); date = sdf.parse("28/Jul/2013:18:12:49"); assertTrue(DateUtil.isWeekend(date)); date = sdf.parse("29/Jul/2013:00:00:01"); assertFalse(DateUtil.isWeekend(date)); date = sdf.parse("26/Jul/2013:23:59:59"); assertFalse(DateUtil.isWeekend(date)); } @Test public void testIsWithinRange() throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("dd/MMM/yyyy:hh:mm:ss", new Locale("en", "US")); Date date = sdf.parse("27/Jul/2013:18:12:49"); assertTrue(DateUtil.isWithinHourRange(date, 9, 19)); assertFalse(DateUtil.isWithinHourRange(date, 19, 20)); } @Test public void testTimeout() throws InterruptedException { Date date = new Date(); // go in the past from 5" date.setTime(date.getTime() - 2000); assertFalse(DateUtil.isTimeoutExpired(date, 3000)); Thread.sleep(2000); assertTrue(DateUtil.isTimeoutExpired(date, 3000)); } @Test public void testLegacyFormat() throws ParseException { String strDate = "Thu Jan 02 08:43:49 CET 2014"; SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy", new Locale("en", "US")); Date date = sdf.parse(strDate); assertTrue(1388648629000L == date.getTime()); date = DateUtil.fromLegacyStringToDate(strDate); assertTrue(1388648629000L == date.getTime()); } @Test public void testGetLatestDaysFromNow() throws ParseException { String result = DateUtil.getLatestDaysFromNow(3); // String expectedResult = "2012-10-19T18:12:49.000 CEST"; // assertEquals(expectedResult, result); } @Test public void testParsing() throws ParseException { // Date expectedDate = new Date(1388648629000L); DateTime today = new DateTime(DateTimeZone.UTC); String currentYear = today.year().getAsString(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(DateTimeZone.UTC); DateTime expectedDate = f.parseDateTime(currentYear + "-01-02 07:43:49"); String currentDay = expectedDate.dayOfWeek().getAsShortText(Locale.ENGLISH); String[] strDates = { currentDay + " Jan 02 08:43:49 CET " + currentYear, currentDay + ", 02 Jan " + currentYear + " 08:43:49 CET", currentYear + "-01-02T08:43:49CET", currentYear + "-01-02T08:43:49.000CET", currentYear + "-01-02T08:43:49.0000+01:00", currentYear + "-01-02 07:43:49", currentYear + "-01-02 07:43:49,000", currentYear + "-01-02 07:43:49.000", "02/JAN/" + currentYear + ":09:43:49 +0200", "Jan 02 07:43:49", "02/01/" + currentYear + "-07:43:49:000", "02-Jan-" + currentYear + " 07:43:49:000", "02-Jan-" + currentYear + " 07:43:49.000", "02/Jan/" + currentYear + ":03:43:49 -0400", currentYear + " Jan 02 07:43:49", currentYear + " Jan 2 7:43:49", }; for (String strDate : strDates) { logger.info("parsing " + strDate); Date date = DateUtil.parse(strDate); assertTrue(date + " should be equal to " + expectedDate.toDate(), expectedDate.getMillis() == date.getTime()); } } @Test public void testParsing2() throws ParseException { DateTime today = new DateTime(DateTimeZone.UTC); String currentYear = today.year().getAsString(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy").withZone(DateTimeZone.UTC); DateTime expectedDate = f.parseDateTime(currentYear); Date date = DateUtil.parse(currentYear); assertTrue(date + " should be equal to " + expectedDate.toDate(), expectedDate.getMillis() == date.getTime()); } @Test public void testParsingWithTimeZone() throws ParseException { // Date expectedDate = new Date(1388648629000L); DateTime today = new DateTime(DateTimeZone.UTC); String currentYear = today.year().getAsString(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(DateTimeZone.forTimeZone(tz)); DateTime expectedEuropeDate = f.parseDateTime(currentYear + "-01-02 07:43:49"); Date dateAsEuropeanDate = DateUtil.parse(currentYear + "-01-02 07:43:49", "yyyy-MM-dd HH:mm:ss", tz); assertTrue(dateAsEuropeanDate + " should be equal to " + expectedEuropeDate.toDate(), dateAsEuropeanDate.getTime() == expectedEuropeDate.getMillis()); Date dateAsUtcDate = DateUtil.parse(currentYear + "-01-02 07:43:49", "yyyy-MM-dd HH:mm:ss"); assertTrue(dateAsUtcDate + " should be equal to " + expectedEuropeDate.toDate() + " plus 1 hour", dateAsUtcDate.getTime() == expectedEuropeDate.getMillis() + 1000 * 60 * 60); Date dateAsCancun = DateUtil.parse(currentYear + "-01-02 07:43:49", "yyyy-MM-dd HH:mm:ss", TimeZone.getTimeZone("America/Cancun")); assertTrue(dateAsCancun + " should be equal to " + expectedEuropeDate.toDate() + " plus 6 hour", dateAsCancun.getTime() == expectedEuropeDate.getMillis() + 1000 * 60 * 60 * 6 ); /** * should not use set timezone when timezone on pattern */ f = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ").withZone(DateTimeZone.forTimeZone(tz)); DateTime expectedDate = f.parseDateTime("2001-07-04T12:08:56.235-0700"); dateAsEuropeanDate = DateUtil.parse("2001-07-04T12:08:56.235-0700", "yyyy-MM-dd'T'HH:mm:ss.SSSZ", tz); assertTrue(dateAsEuropeanDate + " should be equal to " + expectedDate.toDate(), dateAsEuropeanDate.getTime() == expectedDate.getMillis()); dateAsUtcDate = DateUtil.parse("2001-07-04T12:08:56.235-0700", "yyyy-MM-dd'T'HH:mm:ss.SSSZ"); assertTrue(dateAsUtcDate + " should be equal to " + expectedDate.toDate(), dateAsUtcDate.getTime() == expectedDate.getMillis()); dateAsCancun = DateUtil.parse("2001-07-04T12:08:56.235-0700", "yyyy-MM-dd'T'HH:mm:ss.SSSZ", TimeZone.getTimeZone("America/Cancun")); assertTrue(dateAsCancun + " should be equal to " + expectedDate.toDate(), dateAsCancun.getTime() == expectedDate.getMillis()); } @Test public void testParsingWithoutTimeZone() throws ParseException { // Date expectedDate = new Date(1388648629000L); DateTime today = new DateTime(DateTimeZone.UTC); String currentYear = today.year().getAsString(); DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(DateTimeZone.UTC); DateTime expectedUtcDate = f.parseDateTime(currentYear + "-01-02 07:43:49"); Date dateAsUtcDate = DateUtil.parse(currentYear + "-01-02 07:43:49", "yyyy-MM-dd HH:mm:ss"); assertTrue(dateAsUtcDate + " should be equal to " + expectedUtcDate.toDate(), expectedUtcDate.getMillis() == dateAsUtcDate.getTime()); } }
fixed a date bug between different version of jdk...
logisland-framework/logisland-utils/src/test/java/com/hurence/logisland/util/time/DateUtilTest.java
fixed a date bug between different version of jdk...
<ide><path>ogisland-framework/logisland-utils/src/test/java/com/hurence/logisland/util/time/DateUtilTest.java <ide> @Test <ide> public void testParsingWithTimeZone() throws ParseException { <ide> <add> /** <add> * WARNING ! Oracle is playing with timeZones object between minor version changes... <add> * For exemple that caused this test to fail with "America/Cancun" timeZone if the jvm <add> * version was inferior to 8u45... So I replaced it by "Canada/Atlantic" that should be more stable <add> * and put it as a variable so we can easily change it <add> */ <add> TimeZone testTimeZone = TimeZone.getTimeZone("Canada/Atlantic"); <ide> // Date expectedDate = new Date(1388648629000L); <ide> DateTime today = new DateTime(DateTimeZone.UTC); <ide> String currentYear = today.year().getAsString(); <ide> assertTrue(dateAsUtcDate + " should be equal to " + expectedEuropeDate.toDate() + " plus 1 hour", <ide> dateAsUtcDate.getTime() == expectedEuropeDate.getMillis() + 1000 * 60 * 60); <ide> <del> Date dateAsCancun = DateUtil.parse(currentYear + "-01-02 07:43:49", "yyyy-MM-dd HH:mm:ss", TimeZone.getTimeZone("America/Cancun")); <del> <del> assertTrue(dateAsCancun + " should be equal to " + expectedEuropeDate.toDate() + " plus 6 hour", <del> dateAsCancun.getTime() == expectedEuropeDate.getMillis() + 1000 * 60 * 60 * 6 ); <add> Date dateAsTest = DateUtil.parse(currentYear + "-01-02 07:43:49", "yyyy-MM-dd HH:mm:ss", testTimeZone); <add> <add> assertTrue(dateAsTest + " should be equal to " + expectedEuropeDate.toDate() + " plus 6 hour", <add> dateAsTest.getTime() == expectedEuropeDate.getMillis() + 1000 * 60 * 60 * 5 ); <ide> <ide> /** <ide> * should not use set timezone when timezone on pattern <ide> assertTrue(dateAsUtcDate + " should be equal to " + expectedDate.toDate(), <ide> dateAsUtcDate.getTime() == expectedDate.getMillis()); <ide> <del> dateAsCancun = DateUtil.parse("2001-07-04T12:08:56.235-0700", "yyyy-MM-dd'T'HH:mm:ss.SSSZ", TimeZone.getTimeZone("America/Cancun")); <del> <del> assertTrue(dateAsCancun + " should be equal to " + expectedDate.toDate(), <del> dateAsCancun.getTime() == expectedDate.getMillis()); <add> dateAsTest = DateUtil.parse("2001-07-04T12:08:56.235-0700", "yyyy-MM-dd'T'HH:mm:ss.SSSZ", testTimeZone); <add> <add> assertTrue(dateAsTest + " should be equal to " + expectedDate.toDate(), <add> dateAsTest.getTime() == expectedDate.getMillis()); <ide> <ide> } <ide> @Test
Java
apache-2.0
77b8f6dc5251f0852c2f08cb5f87a0070ca52812
0
SafetyCulture/elasticsearch-river-couchdb,SafetyCulture/elasticsearch-river-couchdb,elastic/elasticsearch-river-couchdb,gesellix/elasticsearch-river-couchdb,Bouhnosaure/elasticsearch-river-couchdb,elastic/elasticsearch-river-couchdb,gesellix/elasticsearch-river-couchdb,Bouhnosaure/elasticsearch-river-couchdb
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.river.couchdb; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.Strings; import org.elasticsearch.common.base.Predicate; import org.elasticsearch.common.collect.ImmutableList; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.indices.IndexAlreadyExistsException; import org.elasticsearch.indices.IndexMissingException; import org.elasticsearch.plugins.PluginsService; import org.elasticsearch.river.couchdb.helper.CouchDBClient; import org.elasticsearch.script.groovy.GroovyScriptEngineService; import org.elasticsearch.search.SearchHit; import org.elasticsearch.test.ElasticsearchIntegrationTest; import org.junit.Test; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.river.couchdb.helper.CouchDBClient.putDocument; import static org.elasticsearch.river.couchdb.helper.CouchDBClient.putDocumentWithAttachments; import static org.hamcrest.Matchers.*; /** * Integration tests for CouchDb river<br> * You may have a couchdb instance running on localhost:5984 with a mytest database. */ @ElasticsearchIntegrationTest.ClusterScope( scope = ElasticsearchIntegrationTest.Scope.SUITE, numDataNodes = 0, numClientNodes = 0, transportClientRatio = 0.0) @AbstractCouchdbTest.CouchdbTest public class CouchdbRiverIntegrationTest extends ElasticsearchIntegrationTest { @Override protected Settings nodeSettings(int nodeOrdinal) { return ImmutableSettings.builder() .put(super.nodeSettings(nodeOrdinal)) .put("plugins." + PluginsService.LOAD_PLUGIN_FROM_CLASSPATH, true) .put(GroovyScriptEngineService.GROOVY_SCRIPT_SANDBOX_ENABLED, false) .build(); } private interface InjectorHook { public void inject(); } private static final String testDbPrefix = "elasticsearch_couch_test_"; private String getDbName() { return testDbPrefix.concat(Strings.toUnderscoreCase(getTestName())); } private void launchTest(XContentBuilder river, final Integer numDocs, InjectorHook injectorHook) throws IOException, InterruptedException { logger.info(" -> Checking couchdb running"); CouchDBClient.checkCouchDbRunning(); logger.info(" -> Creating test database [{}]", getDbName()); CouchDBClient.dropAndCreateTestDatabase(getDbName()); logger.info(" -> Put [{}] documents", numDocs); for (int i = 0; i < numDocs; i++) { CouchDBClient.putDocument(getDbName(), "" + i, "foo", "bar", "content", "" + i); } logger.info(" -> Put [{}] documents done", numDocs); if (injectorHook != null) { logger.info(" -> Injecting extra data"); injectorHook.inject(); } logger.info(" -> Create river"); try { createIndex(getDbName()); } catch (IndexAlreadyExistsException e) { // No worries. We already created the index before } index("_river", getDbName(), "_meta", river); logger.info(" -> Wait for some docs"); assertThat(awaitBusy(new Predicate<Object>() { public boolean apply(Object obj) { try { refresh(); SearchResponse response = client().prepareSearch(getDbName()).get(); logger.info(" -> got {} docs in {} index", response.getHits().totalHits(), getDbName()); return response.getHits().totalHits() == numDocs; } catch (IndexMissingException e) { return false; } } }, 1, TimeUnit.MINUTES), equalTo(true)); } /** * This is a simple test case for testing attachments removing. */ @Test public void testAttachmentEnabled() throws IOException, InterruptedException { runAttachmentTest(false); } /** * This is a simple test case for testing attachments removing. */ @Test public void testAttachmentDisabled() throws IOException, InterruptedException { runAttachmentTest(true); } private void runAttachmentTest(boolean disabled) throws IOException, InterruptedException { // Create the river launchTest(jsonBuilder() .startObject() .field("type", "couchdb") .startObject("couchdb") .field("host", CouchDBClient.host) .field("port", CouchDBClient.port) .field("db", getDbName()) .field("ignore_attachments", disabled) .endObject() .endObject(), 0, new InjectorHook() { @Override public void inject() { try { putDocumentWithAttachments(getDbName(), "1", new ImmutableList.Builder<String>().add("foo", "bar").build(), "text-in-english.txt", "God save the queen!", "text-in-french.txt", "Allons enfants !"); } catch (IOException e) { logger.error("Error while injecting attachments"); } } }); // Check that docs are indexed by the river assertThat(awaitBusy(new Predicate<Object>() { public boolean apply(Object obj) { try { refresh(); SearchResponse response = client().prepareSearch(getDbName()).get(); logger.info(" -> got {} docs in {} index", response.getHits().totalHits(), getDbName()); return response.getHits().totalHits() == 1; } catch (IndexMissingException e) { return false; } } }, 1, TimeUnit.MINUTES), equalTo(true)); SearchResponse response = client().prepareSearch(getDbName()) .addField("_attachments.text-in-english.txt.content_type") .addField("_attachments.text-in-french.txt.content_type") .get(); assertThat(response.getHits().getAt(0).field("_attachments.text-in-english.txt.content_type"), disabled ? nullValue() : notNullValue()); assertThat(response.getHits().getAt(0).field("_attachments.text-in-french.txt.content_type"), disabled ? nullValue() : notNullValue()); if (!disabled) { assertThat(response.getHits().getAt(0).field("_attachments.text-in-english.txt.content_type").getValue().toString(), is("text/plain")); assertThat(response.getHits().getAt(0).field("_attachments.text-in-french.txt.content_type").getValue().toString(), is("text/plain")); } } @Test public void testParameters() throws IOException, InterruptedException { launchTest(jsonBuilder() .startObject() .field("type", "couchdb") .startObject("couchdb") .field("heartbeat", "5s") .field("read_timeout", "15s") .endObject() .endObject(), randomIntBetween(5, 1000), null); } @Test public void testSimple() throws IOException, InterruptedException { launchTest(jsonBuilder() .startObject() .field("type", "couchdb") .endObject(), randomIntBetween(5, 1000), null); } @Test public void testScriptingDefaultEngine() throws IOException, InterruptedException { launchTest(jsonBuilder() .startObject() .field("type", "couchdb") .startObject("couchdb") .field("script", "ctx.doc.newfield = ctx.doc.foo") .endObject() .endObject(), randomIntBetween(5, 1000), null); SearchResponse response = client().prepareSearch(getDbName()) .addField("newfield") .get(); assertThat(response.getHits().getAt(0).field("newfield"), notNullValue()); assertThat(response.getHits().getAt(0).field("newfield").getValue().toString(), is("bar")); } /** * Test case for #44: https://github.com/elasticsearch/elasticsearch-river-couchdb/issues/44 */ @Test public void testScriptingQuote_44() throws IOException, InterruptedException { launchTest(jsonBuilder() .startObject() .field("type", "couchdb") .startObject("couchdb") .field("script", "ctx.doc.newfield = 'value1'") .endObject() .endObject(), randomIntBetween(5, 1000), null); SearchResponse response = client().prepareSearch(getDbName()) .addField("newfield") .get(); assertThat(response.getHits().getAt(0).field("newfield"), notNullValue()); assertThat(response.getHits().getAt(0).field("newfield").getValue().toString(), is("value1")); } /** * Test case for #51: https://github.com/elasticsearch/elasticsearch-river-couchdb/issues/51 */ @Test public void testScriptingParentChild_51() throws IOException, InterruptedException, ExecutionException { prepareCreate(getDbName()) .addMapping("region", jsonBuilder() .startObject() .startObject("region") .endObject() .endObject().string()) .addMapping("campus", jsonBuilder() .startObject() .startObject("campus") .startObject("_parent") .field("type", "region") .endObject() .endObject() .endObject().string()) .get(); launchTest(jsonBuilder() .startObject() .field("type", "couchdb") .startObject("couchdb") .field("script", "ctx._type = ctx.doc.type; if (ctx._type == 'campus') { ctx._parent = ctx.doc.parent_id; }") .endObject() .endObject(), 0, new InjectorHook() { @Override public void inject() { try { putDocument(getDbName(), "1", "type", "region", "name", "bretagne"); putDocument(getDbName(), "2", "type", "campus", "name", "enib", "parent_id", "1"); } catch (IOException e) { logger.error("Error while injecting documents"); } } }); // Check that docs are indexed by the river assertThat(awaitBusy(new Predicate<Object>() { public boolean apply(Object obj) { try { refresh(); SearchResponse response = client().prepareSearch(getDbName()).get(); logger.info(" -> got {} docs in {} index", response.getHits().totalHits(), getDbName()); return response.getHits().totalHits() == 2; } catch (IndexMissingException e) { return false; } } }, 1, TimeUnit.MINUTES), equalTo(true)); SearchResponse response = client().prepareSearch(getDbName()) .setQuery( QueryBuilders.hasChildQuery("campus", QueryBuilders.matchQuery("name", "enib")) ) .get(); assertThat(response.getHits().getTotalHits(), is(1L)); assertThat(response.getHits().getAt(0).getType(), is("region")); assertThat(response.getHits().getAt(0).getId(), is("1")); } /** * Test case for #45: https://github.com/elasticsearch/elasticsearch-river-couchdb/issues/45 */ @Test public void testScriptingTypeOf_45() throws IOException, InterruptedException { launchTest(jsonBuilder() .startObject() .field("type", "couchdb") .startObject("couchdb") .field("script_type", "groovy") // This groovy script removes all "_id" fields and 50% of "content" fields .field("script", " def docId = Integer.parseInt(ctx.doc[\"_id\"]);\n" + " def removals = [\"content\", \"_id\"]; \n" + " for(i in removals) { \n" + "\tif (ctx.doc.containsKey(i)) { \n" + "\t\tif (\"content\".equals(i)) {\n" + "\t\t\tif ((docId % 2) == 0) {\n" + "\t\t\t\tctx.doc.remove(i)\n" + "\t\t\t} \n" + "\t\t} else {\n" + "\t\t\tctx.doc.remove(i)\n" + "\t\t}\n" + "\t} \n" + "}") .endObject() .endObject(), randomIntBetween(5, 1000), null); int nbOfResultsToCheck = 100; SearchResponse response = client().prepareSearch(getDbName()) .addField("foo") .addField("content") .addField("_id") .setSize(nbOfResultsToCheck) .get(); for (int i=0; i < Math.min(response.getHits().getTotalHits(), nbOfResultsToCheck); i++) { SearchHit hit = response.getHits().getAt(i); int docId = Integer.parseInt(hit.getId()); assertThat(hit.field("foo"), notNullValue()); assertThat(hit.field("foo").getValue().toString(), is("bar")); assertThat(hit.field("_id"), nullValue()); if ((docId % 2) == 0) { assertThat(hit.field("content"), nullValue()); } else { assertThat(hit.field("content").getValue().toString(), is(hit.getId())); } } } /** * Test case for #66: https://github.com/elasticsearch/elasticsearch-river-couchdb/issues/66 */ @Test public void testClosingWhileIndexing_66() throws IOException, InterruptedException { final int nbDocs = 10; logger.info(" -> Checking couchdb running"); CouchDBClient.checkCouchDbRunning(); logger.info(" -> Creating test database [{}]", getDbName()); CouchDBClient.dropAndCreateTestDatabase(getDbName()); logger.info(" -> Inserting [{}] docs in couchdb", nbDocs); for (int i = 0; i < nbDocs; i++) { CouchDBClient.putDocument(getDbName(), "" + i, "foo", "bar", "content", "" + i); } logger.info(" -> Create index"); try { createIndex(getDbName()); } catch (IndexAlreadyExistsException e) { // No worries. We already created the index before } logger.info(" -> Create river"); index("_river", getDbName(), "_meta", jsonBuilder() .startObject() .field("type", "couchdb") .startObject("couchdb") // We use here a script to have a chance to slow down the process and close the river while processing it .field("script", "for (int x = 0; x < 10000000; x++) { x*x*x } ;") .endObject() .startObject("index") .field("flush_interval", "100ms") .endObject() .endObject()); // Check that docs are indexed by the river assertThat(awaitBusy(new Predicate<Object>() { public boolean apply(Object obj) { try { refresh(); SearchResponse response = client().prepareSearch(getDbName()).get(); logger.info(" -> got {} docs in {} index", response.getHits().totalHits(), getDbName()); return response.getHits().totalHits() == nbDocs; } catch (IndexMissingException e) { return false; } } }, 1, TimeUnit.MINUTES), equalTo(true)); logger.info(" -> Inserting [{}] docs in couchdb", nbDocs); for (int i = nbDocs; i < 2*nbDocs; i++) { CouchDBClient.putDocument(getDbName(), "" + i, "foo", "bar", "content", "" + i); } // Check that docs are still processed by the river assertThat(awaitBusy(new Predicate<Object>() { public boolean apply(Object obj) { try { refresh(); SearchResponse response = client().prepareSearch(getDbName()).get(); logger.info(" -> got {} docs in {} index", response.getHits().totalHits(), getDbName()); return response.getHits().totalHits() > nbDocs; } catch (IndexMissingException e) { return false; } } }, 10, TimeUnit.SECONDS), equalTo(true)); logger.info(" -> Remove river while injecting"); client().admin().indices().prepareDeleteMapping("_river").setType(getDbName()).get(); logger.info(" -> Inserting [{}] docs in couchdb", nbDocs); for (int i = 2*nbDocs; i < 3*nbDocs; i++) { CouchDBClient.putDocument(getDbName(), "" + i, "foo", "bar", "content", "" + i); } // Check that docs are indexed by the river boolean foundAllDocs = awaitBusy(new Predicate<Object>() { public boolean apply(Object obj) { try { refresh(); SearchResponse response = client().prepareSearch(getDbName()).get(); logger.info(" -> got {} docs in {} index", response.getHits().totalHits(), getDbName()); return response.getHits().totalHits() == 3 * nbDocs; } catch (IndexMissingException e) { return false; } } }, 10, TimeUnit.SECONDS); // We should not have 20 documents at the end as we removed the river immediately after having // injecting 10 more docs in couchdb assertThat("We should not have 20 documents as the river is supposed to have been stopped!", foundAllDocs, is(false)); // We expect seeing a line in logs like: // [WARN ][org.elasticsearch.river.couchdb] [node_0] [couchdb][elasticsearch_couch_test_test_closing_while_indexing_66] river was closing while trying to index document [elasticsearch_couch_test_test_closing_while_indexing_66/elasticsearch_couch_test_test_closing_while_indexing_66/11]. Operation skipped. } /** * Test case for #17: https://github.com/elasticsearch/elasticsearch-river-couchdb/issues/17 */ @Test public void testCreateCouchdbDatabaseWhileRunning_17() throws IOException, InterruptedException { final int nbDocs = between(50, 300); logger.info(" -> Checking couchdb running"); CouchDBClient.checkCouchDbRunning(); logger.info(" -> Create index"); try { createIndex(getDbName()); } catch (IndexAlreadyExistsException e) { // No worries. We already created the index before } logger.info(" -> Create river"); index("_river", getDbName(), "_meta", jsonBuilder() .startObject() .field("type", "couchdb") .endObject()); // Check that the river is started assertThat(awaitBusy(new Predicate<Object>() { public boolean apply(Object obj) { try { refresh(); GetResponse response = get("_river", getDbName(), "_status"); return response.isExists(); } catch (IndexMissingException e) { return false; } } }, 5, TimeUnit.SECONDS), equalTo(true)); logger.info(" -> Creating test database [{}]", getDbName()); CouchDBClient.dropAndCreateTestDatabase(getDbName()); logger.info(" -> Inserting [{}] docs in couchdb", nbDocs); for (int i = 0; i < nbDocs; i++) { CouchDBClient.putDocument(getDbName(), "" + i, "foo", "bar", "content", "" + i); } // Check that docs are still processed by the river assertThat(awaitBusy(new Predicate<Object>() { public boolean apply(Object obj) { try { refresh(); SearchResponse response = client().prepareSearch(getDbName()).get(); logger.info(" -> got {} docs in {} index", response.getHits().totalHits(), getDbName()); return response.getHits().totalHits() == nbDocs; } catch (IndexMissingException e) { return false; } } }, 1, TimeUnit.MINUTES), equalTo(true)); } /** * Test case for #71: https://github.com/elasticsearch/elasticsearch-river-couchdb/issues/71 */ @Test public void testDropCouchdbDatabaseWhileRunning_71() throws IOException, InterruptedException { final int nbDocs = between(50, 300); launchTest(jsonBuilder() .startObject() .field("type", "couchdb") .endObject(), nbDocs, null); logger.info(" -> Removing test database [{}]", getDbName()); CouchDBClient.dropTestDatabase(getDbName()); // We wait for 10 seconds awaitBusy(new Predicate<Object>() { public boolean apply(Object obj) { return false; } }, 10, TimeUnit.SECONDS); } }
src/test/java/org/elasticsearch/river/couchdb/CouchdbRiverIntegrationTest.java
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.river.couchdb; import org.apache.lucene.util.LuceneTestCase; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.Strings; import org.elasticsearch.common.base.Predicate; import org.elasticsearch.common.collect.ImmutableList; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.indices.IndexAlreadyExistsException; import org.elasticsearch.indices.IndexMissingException; import org.elasticsearch.plugins.PluginsService; import org.elasticsearch.river.couchdb.helper.CouchDBClient; import org.elasticsearch.test.ElasticsearchIntegrationTest; import org.junit.Test; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.river.couchdb.helper.CouchDBClient.putDocument; import static org.elasticsearch.river.couchdb.helper.CouchDBClient.putDocumentWithAttachments; import static org.hamcrest.Matchers.*; /** * Integration tests for CouchDb river<br> * You may have a couchdb instance running on localhost:5984 with a mytest database. */ @ElasticsearchIntegrationTest.ClusterScope( scope = ElasticsearchIntegrationTest.Scope.SUITE, numDataNodes = 0, numClientNodes = 0, transportClientRatio = 0.0) @AbstractCouchdbTest.CouchdbTest public class CouchdbRiverIntegrationTest extends ElasticsearchIntegrationTest { @Override protected Settings nodeSettings(int nodeOrdinal) { return ImmutableSettings.builder() .put(super.nodeSettings(nodeOrdinal)) .put("plugins." + PluginsService.LOAD_PLUGIN_FROM_CLASSPATH, true) .build(); } private interface InjectorHook { public void inject(); } private static final String testDbPrefix = "elasticsearch_couch_test_"; private String getDbName() { return testDbPrefix.concat(Strings.toUnderscoreCase(getTestName())); } private void launchTest(XContentBuilder river, final Integer numDocs, InjectorHook injectorHook) throws IOException, InterruptedException { logger.info(" -> Checking couchdb running"); CouchDBClient.checkCouchDbRunning(); logger.info(" -> Creating test database [{}]", getDbName()); CouchDBClient.dropAndCreateTestDatabase(getDbName()); logger.info(" -> Put [{}] documents", numDocs); for (int i = 0; i < numDocs; i++) { CouchDBClient.putDocument(getDbName(), "" + i, "foo", "bar", "content", "" + i); } if (injectorHook != null) { logger.info(" -> Injecting extra data"); injectorHook.inject(); } logger.info(" -> Create river"); try { createIndex(getDbName()); } catch (IndexAlreadyExistsException e) { // No worries. We already created the index before } index("_river", getDbName(), "_meta", river); logger.info(" -> Wait for some docs"); assertThat(awaitBusy(new Predicate<Object>() { public boolean apply(Object obj) { try { refresh(); SearchResponse response = client().prepareSearch(getDbName()).get(); logger.info(" -> got {} docs in {} index", response.getHits().totalHits(), getDbName()); return response.getHits().totalHits() == numDocs; } catch (IndexMissingException e) { return false; } } }, 1, TimeUnit.MINUTES), equalTo(true)); } /** * This is a simple test case for testing attachments removing. */ @Test public void testAttachmentEnabled() throws IOException, InterruptedException { runAttachmentTest(false); } /** * This is a simple test case for testing attachments removing. */ @Test public void testAttachmentDisabled() throws IOException, InterruptedException { runAttachmentTest(true); } private void runAttachmentTest(boolean disabled) throws IOException, InterruptedException { // Create the river launchTest(jsonBuilder() .startObject() .field("type", "couchdb") .startObject("couchdb") .field("host", CouchDBClient.host) .field("port", CouchDBClient.port) .field("db", getDbName()) .field("ignore_attachments", disabled) .endObject() .endObject(), 0, new InjectorHook() { @Override public void inject() { try { putDocumentWithAttachments(getDbName(), "1", new ImmutableList.Builder<String>().add("foo", "bar").build(), "text-in-english.txt", "God save the queen!", "text-in-french.txt", "Allons enfants !"); } catch (IOException e) { logger.error("Error while injecting attachments"); } } }); // Check that docs are indexed by the river assertThat(awaitBusy(new Predicate<Object>() { public boolean apply(Object obj) { try { refresh(); SearchResponse response = client().prepareSearch(getDbName()).get(); logger.info(" -> got {} docs in {} index", response.getHits().totalHits(), getDbName()); return response.getHits().totalHits() == 1; } catch (IndexMissingException e) { return false; } } }, 1, TimeUnit.MINUTES), equalTo(true)); SearchResponse response = client().prepareSearch(getDbName()) .addField("_attachments.text-in-english.txt.content_type") .addField("_attachments.text-in-french.txt.content_type") .get(); assertThat(response.getHits().getAt(0).field("_attachments.text-in-english.txt.content_type"), disabled ? nullValue() : notNullValue()); assertThat(response.getHits().getAt(0).field("_attachments.text-in-french.txt.content_type"), disabled ? nullValue() : notNullValue()); if (!disabled) { assertThat(response.getHits().getAt(0).field("_attachments.text-in-english.txt.content_type").getValue().toString(), is("text/plain")); assertThat(response.getHits().getAt(0).field("_attachments.text-in-french.txt.content_type").getValue().toString(), is("text/plain")); } } @Test public void testParameters() throws IOException, InterruptedException { launchTest(jsonBuilder() .startObject() .field("type", "couchdb") .startObject("couchdb") .field("heartbeat", "5s") .field("read_timeout", "15s") .endObject() .endObject(), randomIntBetween(5, 1000), null); } @Test public void testSimple() throws IOException, InterruptedException { launchTest(jsonBuilder() .startObject() .field("type", "couchdb") .endObject(), randomIntBetween(5, 1000), null); } @Test public void testScriptingDefaultEngine() throws IOException, InterruptedException { launchTest(jsonBuilder() .startObject() .field("type", "couchdb") .startObject("couchdb") .field("script", "ctx.doc.newfield = ctx.doc.foo") .endObject() .endObject(), randomIntBetween(5, 1000), null); SearchResponse response = client().prepareSearch(getDbName()) .addField("newfield") .get(); assertThat(response.getHits().getAt(0).field("newfield"), notNullValue()); assertThat(response.getHits().getAt(0).field("newfield").getValue().toString(), is("bar")); } /** * Test case for #44: https://github.com/elasticsearch/elasticsearch-river-couchdb/issues/44 */ @Test public void testScriptingQuote_44() throws IOException, InterruptedException { launchTest(jsonBuilder() .startObject() .field("type", "couchdb") .startObject("couchdb") .field("script", "ctx.doc.newfield = 'value1'") .endObject() .endObject(), randomIntBetween(5, 1000), null); SearchResponse response = client().prepareSearch(getDbName()) .addField("newfield") .get(); assertThat(response.getHits().getAt(0).field("newfield"), notNullValue()); assertThat(response.getHits().getAt(0).field("newfield").getValue().toString(), is("value1")); } /** * Test case for #51: https://github.com/elasticsearch/elasticsearch-river-couchdb/issues/51 */ @Test public void testScriptingParentChild_51() throws IOException, InterruptedException, ExecutionException { prepareCreate(getDbName()) .addMapping("region", jsonBuilder() .startObject() .startObject("region") .endObject() .endObject().string()) .addMapping("campus", jsonBuilder() .startObject() .startObject("campus") .startObject("_parent") .field("type", "region") .endObject() .endObject() .endObject().string()) .get(); launchTest(jsonBuilder() .startObject() .field("type", "couchdb") .startObject("couchdb") .field("script", "ctx._type = ctx.doc.type; if (ctx._type == 'campus') { ctx._parent = ctx.doc.parent_id; }") .endObject() .endObject(), 0, new InjectorHook() { @Override public void inject() { try { putDocument(getDbName(), "1", "type", "region", "name", "bretagne"); putDocument(getDbName(), "2", "type", "campus", "name", "enib", "parent_id", "1"); } catch (IOException e) { logger.error("Error while injecting documents"); } } }); // Check that docs are indexed by the river assertThat(awaitBusy(new Predicate<Object>() { public boolean apply(Object obj) { try { refresh(); SearchResponse response = client().prepareSearch(getDbName()).get(); logger.info(" -> got {} docs in {} index", response.getHits().totalHits(), getDbName()); return response.getHits().totalHits() == 2; } catch (IndexMissingException e) { return false; } } }, 1, TimeUnit.MINUTES), equalTo(true)); SearchResponse response = client().prepareSearch(getDbName()) .setQuery( QueryBuilders.hasChildQuery("campus", QueryBuilders.matchQuery("name", "enib")) ) .get(); assertThat(response.getHits().getTotalHits(), is(1L)); assertThat(response.getHits().getAt(0).getType(), is("region")); assertThat(response.getHits().getAt(0).getId(), is("1")); } /** * Test case for #45: https://github.com/elasticsearch/elasticsearch-river-couchdb/issues/45 */ @Test @LuceneTestCase.AwaitsFix(bugUrl = "https://github.com/elasticsearch/elasticsearch-river-couchdb/issues/65") public void testScriptingTypeOf_45() throws IOException, InterruptedException { launchTest(jsonBuilder() .startObject() .field("type", "couchdb") .startObject("couchdb") .field("script_type", "mvel") .field("script", "var oblitertron = function(x) { var things = [\"foo\"]; var toberemoved = new java.util.ArrayList(); foreach (i : x.keySet()) { if(things.indexOf(i) == -1) { toberemoved.add(i); } } foreach (i : toberemoved) { x.remove(i); } return x; }; ctx.doc = oblitertron(ctx.doc);") .endObject() .endObject(), randomIntBetween(5, 1000), null); SearchResponse response = client().prepareSearch(getDbName()) .addField("foo") .addField("_id") .get(); assertThat(response.getHits().getAt(0).field("foo"), notNullValue()); assertThat(response.getHits().getAt(0).field("foo").getValue().toString(), is("bar")); assertThat(response.getHits().getAt(0).field("_id"), nullValue()); } /** * Test case for #66: https://github.com/elasticsearch/elasticsearch-river-couchdb/issues/66 */ @Test public void testClosingWhileIndexing_66() throws IOException, InterruptedException { final int nbDocs = 10; logger.info(" -> Checking couchdb running"); CouchDBClient.checkCouchDbRunning(); logger.info(" -> Creating test database [{}]", getDbName()); CouchDBClient.dropAndCreateTestDatabase(getDbName()); logger.info(" -> Inserting [{}] docs in couchdb", nbDocs); for (int i = 0; i < nbDocs; i++) { CouchDBClient.putDocument(getDbName(), "" + i, "foo", "bar", "content", "" + i); } logger.info(" -> Create index"); try { createIndex(getDbName()); } catch (IndexAlreadyExistsException e) { // No worries. We already created the index before } logger.info(" -> Create river"); index("_river", getDbName(), "_meta", jsonBuilder() .startObject() .field("type", "couchdb") .startObject("couchdb") // We use here a script to have a chance to slow down the process and close the river while processing it .field("script", "for (int x = 0; x < 10000000; x++) { x*x*x } ;") .endObject() .startObject("index") .field("flush_interval", "100ms") .endObject() .endObject()); // Check that docs are indexed by the river assertThat(awaitBusy(new Predicate<Object>() { public boolean apply(Object obj) { try { refresh(); SearchResponse response = client().prepareSearch(getDbName()).get(); logger.info(" -> got {} docs in {} index", response.getHits().totalHits(), getDbName()); return response.getHits().totalHits() == nbDocs; } catch (IndexMissingException e) { return false; } } }, 1, TimeUnit.MINUTES), equalTo(true)); logger.info(" -> Inserting [{}] docs in couchdb", nbDocs); for (int i = nbDocs; i < 2*nbDocs; i++) { CouchDBClient.putDocument(getDbName(), "" + i, "foo", "bar", "content", "" + i); } // Check that docs are still processed by the river assertThat(awaitBusy(new Predicate<Object>() { public boolean apply(Object obj) { try { refresh(); SearchResponse response = client().prepareSearch(getDbName()).get(); logger.info(" -> got {} docs in {} index", response.getHits().totalHits(), getDbName()); return response.getHits().totalHits() > nbDocs; } catch (IndexMissingException e) { return false; } } }, 10, TimeUnit.SECONDS), equalTo(true)); logger.info(" -> Remove river while injecting"); client().admin().indices().prepareDeleteMapping("_river").setType(getDbName()).get(); logger.info(" -> Inserting [{}] docs in couchdb", nbDocs); for (int i = 2*nbDocs; i < 3*nbDocs; i++) { CouchDBClient.putDocument(getDbName(), "" + i, "foo", "bar", "content", "" + i); } // Check that docs are indexed by the river boolean foundAllDocs = awaitBusy(new Predicate<Object>() { public boolean apply(Object obj) { try { refresh(); SearchResponse response = client().prepareSearch(getDbName()).get(); logger.info(" -> got {} docs in {} index", response.getHits().totalHits(), getDbName()); return response.getHits().totalHits() == 3 * nbDocs; } catch (IndexMissingException e) { return false; } } }, 10, TimeUnit.SECONDS); // We should not have 20 documents at the end as we removed the river immediately after having // injecting 10 more docs in couchdb assertThat("We should not have 20 documents as the river is supposed to have been stopped!", foundAllDocs, is(false)); // We expect seeing a line in logs like: // [WARN ][org.elasticsearch.river.couchdb] [node_0] [couchdb][elasticsearch_couch_test_test_closing_while_indexing_66] river was closing while trying to index document [elasticsearch_couch_test_test_closing_while_indexing_66/elasticsearch_couch_test_test_closing_while_indexing_66/11]. Operation skipped. } /** * Test case for #17: https://github.com/elasticsearch/elasticsearch-river-couchdb/issues/17 */ @Test public void testCreateCouchdbDatabaseWhileRunning_17() throws IOException, InterruptedException { final int nbDocs = between(50, 300); logger.info(" -> Checking couchdb running"); CouchDBClient.checkCouchDbRunning(); logger.info(" -> Create index"); try { createIndex(getDbName()); } catch (IndexAlreadyExistsException e) { // No worries. We already created the index before } logger.info(" -> Create river"); index("_river", getDbName(), "_meta", jsonBuilder() .startObject() .field("type", "couchdb") .endObject()); // Check that the river is started assertThat(awaitBusy(new Predicate<Object>() { public boolean apply(Object obj) { try { refresh(); GetResponse response = get("_river", getDbName(), "_status"); return response.isExists(); } catch (IndexMissingException e) { return false; } } }, 5, TimeUnit.SECONDS), equalTo(true)); logger.info(" -> Creating test database [{}]", getDbName()); CouchDBClient.dropAndCreateTestDatabase(getDbName()); logger.info(" -> Inserting [{}] docs in couchdb", nbDocs); for (int i = 0; i < nbDocs; i++) { CouchDBClient.putDocument(getDbName(), "" + i, "foo", "bar", "content", "" + i); } // Check that docs are still processed by the river assertThat(awaitBusy(new Predicate<Object>() { public boolean apply(Object obj) { try { refresh(); SearchResponse response = client().prepareSearch(getDbName()).get(); logger.info(" -> got {} docs in {} index", response.getHits().totalHits(), getDbName()); return response.getHits().totalHits() == nbDocs; } catch (IndexMissingException e) { return false; } } }, 1, TimeUnit.MINUTES), equalTo(true)); } /** * Test case for #71: https://github.com/elasticsearch/elasticsearch-river-couchdb/issues/71 */ @Test public void testDropCouchdbDatabaseWhileRunning_71() throws IOException, InterruptedException { final int nbDocs = between(50, 300); launchTest(jsonBuilder() .startObject() .field("type", "couchdb") .endObject(), nbDocs, null); logger.info(" -> Removing test database [{}]", getDbName()); CouchDBClient.dropTestDatabase(getDbName()); // We wait for 10 seconds awaitBusy(new Predicate<Object>() { public boolean apply(Object obj) { return false; } }, 10, TimeUnit.SECONDS); } }
[TEST] Move tests using mvel to groovy Closes #65
src/test/java/org/elasticsearch/river/couchdb/CouchdbRiverIntegrationTest.java
[TEST] Move tests using mvel to groovy
<ide><path>rc/test/java/org/elasticsearch/river/couchdb/CouchdbRiverIntegrationTest.java <ide> <ide> package org.elasticsearch.river.couchdb; <ide> <del>import org.apache.lucene.util.LuceneTestCase; <ide> import org.elasticsearch.action.get.GetResponse; <ide> import org.elasticsearch.action.search.SearchResponse; <ide> import org.elasticsearch.common.Strings; <ide> import org.elasticsearch.indices.IndexMissingException; <ide> import org.elasticsearch.plugins.PluginsService; <ide> import org.elasticsearch.river.couchdb.helper.CouchDBClient; <add>import org.elasticsearch.script.groovy.GroovyScriptEngineService; <add>import org.elasticsearch.search.SearchHit; <ide> import org.elasticsearch.test.ElasticsearchIntegrationTest; <ide> import org.junit.Test; <ide> <ide> return ImmutableSettings.builder() <ide> .put(super.nodeSettings(nodeOrdinal)) <ide> .put("plugins." + PluginsService.LOAD_PLUGIN_FROM_CLASSPATH, true) <del> .build(); <add> .put(GroovyScriptEngineService.GROOVY_SCRIPT_SANDBOX_ENABLED, false) <add> .build(); <ide> } <ide> <ide> private interface InjectorHook { <ide> for (int i = 0; i < numDocs; i++) { <ide> CouchDBClient.putDocument(getDbName(), "" + i, "foo", "bar", "content", "" + i); <ide> } <add> logger.info(" -> Put [{}] documents done", numDocs); <ide> <ide> if (injectorHook != null) { <ide> logger.info(" -> Injecting extra data"); <ide> /** <ide> * Test case for #45: https://github.com/elasticsearch/elasticsearch-river-couchdb/issues/45 <ide> */ <del> @Test @LuceneTestCase.AwaitsFix(bugUrl = "https://github.com/elasticsearch/elasticsearch-river-couchdb/issues/65") <add> @Test <ide> public void testScriptingTypeOf_45() throws IOException, InterruptedException { <ide> launchTest(jsonBuilder() <ide> .startObject() <ide> .field("type", "couchdb") <ide> .startObject("couchdb") <del> .field("script_type", "mvel") <del> .field("script", "var oblitertron = function(x) { var things = [\"foo\"]; var toberemoved = new java.util.ArrayList(); foreach (i : x.keySet()) { if(things.indexOf(i) == -1) { toberemoved.add(i); } } foreach (i : toberemoved) { x.remove(i); } return x; }; ctx.doc = oblitertron(ctx.doc);") <add> .field("script_type", "groovy") <add> // This groovy script removes all "_id" fields and 50% of "content" fields <add> .field("script", " def docId = Integer.parseInt(ctx.doc[\"_id\"]);\n" + <add> " def removals = [\"content\", \"_id\"]; \n" + <add> " for(i in removals) { \n" + <add> "\tif (ctx.doc.containsKey(i)) { \n" + <add> "\t\tif (\"content\".equals(i)) {\n" + <add> "\t\t\tif ((docId % 2) == 0) {\n" + <add> "\t\t\t\tctx.doc.remove(i)\n" + <add> "\t\t\t} \n" + <add> "\t\t} else {\n" + <add> "\t\t\tctx.doc.remove(i)\n" + <add> "\t\t}\n" + <add> "\t} \n" + <add> "}") <ide> .endObject() <ide> .endObject(), randomIntBetween(5, 1000), null); <ide> <add> int nbOfResultsToCheck = 100; <add> <ide> SearchResponse response = client().prepareSearch(getDbName()) <ide> .addField("foo") <add> .addField("content") <ide> .addField("_id") <add> .setSize(nbOfResultsToCheck) <ide> .get(); <ide> <del> assertThat(response.getHits().getAt(0).field("foo"), notNullValue()); <del> assertThat(response.getHits().getAt(0).field("foo").getValue().toString(), is("bar")); <del> assertThat(response.getHits().getAt(0).field("_id"), nullValue()); <add> for (int i=0; i < Math.min(response.getHits().getTotalHits(), nbOfResultsToCheck); i++) { <add> SearchHit hit = response.getHits().getAt(i); <add> int docId = Integer.parseInt(hit.getId()); <add> <add> assertThat(hit.field("foo"), notNullValue()); <add> assertThat(hit.field("foo").getValue().toString(), is("bar")); <add> assertThat(hit.field("_id"), nullValue()); <add> if ((docId % 2) == 0) { <add> assertThat(hit.field("content"), nullValue()); <add> } else { <add> assertThat(hit.field("content").getValue().toString(), is(hit.getId())); <add> } <add> } <ide> } <ide> <ide> /**
JavaScript
mit
7dd21d76c7ef073b7dfaeded4e90a163694d07f5
0
corysimmons/lost,peterramsing/lost,peterramsing/lost
var newBlock = require('./new-block.js'); /** * lost-masonry-wrap: Creates a wrapping element for working with JS Masonry * libraries like Isotope. Assigns a negative margin on each side of this * wrapping element. * * @param {string} [flex|no-flex] - Determines whether this element should * use Flexbox or not. * * @param {length} [gutter] - How large the gutter involved is, typically * this won't be adjusted and will inherit settings.gutter, but it's made * available if you want your masonry grid to have a special gutter, it * should match your masonry-column's gutter. * * @example * section { * lost-masonry-wrap: no-flex; * } * div { * lost-masonry-column: 1/3; * } */ module.exports = function lostMasonryWrapDecl(css, settings) { css.walkDecls('lost-masonry-wrap', function lostMasonryWrapDeclFunction(decl) { var declArr = []; var lostMasonryWrap; var lostMasonryWrapFlexbox = settings.flexbox; var lostMasonryWrapGutter = settings.gutter; var lostMasonryWrapGutterUnit; function cloneAllBefore(props) { Object.keys(props).forEach(function traverseProps(prop) { decl.cloneBefore({ prop: prop, value: props[prop] }); }); } declArr = decl.value.split(' '); if ((declArr[0] !== undefined && declArr[0] === 'flex') || declArr[0] === 'no-flex') { lostMasonryWrapFlexbox = declArr[0]; } if (declArr.indexOf('flex') !== -1) { lostMasonryWrapFlexbox = 'flex'; } if (declArr.indexOf('no-flex') !== -1) { lostMasonryWrapFlexbox = 'no-flex'; } if (declArr[1] !== undefined && declArr[1].search(/^\d/) !== -1) { lostMasonryWrapGutter = declArr[1]; } decl.parent.nodes.forEach(function lostMasonryWrapFlexboxFunction(declaration) { if (declaration.prop === 'lost-masonry-wrap-flexbox') { if (declaration.value === 'flex') { lostMasonryWrapFlexbox = 'flex'; } declaration.remove(); } }); decl.parent.nodes.forEach(function lostMasonryWrapFunction(declaration) { if (declaration.prop === 'lost-masonry-wrap-gutter') { lostMasonryWrap = declaration.value; declaration.remove(); } }); if (lostMasonryWrapFlexbox !== 'flex') { newBlock( decl, ':after', ['content', 'display', 'clear'], ['\'\'', 'table', 'both'] ); newBlock( decl, ':before', ['content', 'display'], ['\'\'', 'table'] ); } else { decl.cloneBefore({ prop: 'display', value: 'flex' }); decl.cloneBefore({ prop: 'flex-flow', value: 'row wrap' }); } lostMasonryWrapGutterUnit = lostMasonryWrapGutter.match(/\D/g).join(''); cloneAllBefore({ 'margin-left': (parseInt(lostMasonryWrapGutter, 10) / -2) + lostMasonryWrapGutterUnit, 'margin-right': (parseInt(lostMasonryWrapGutter, 10) / -2) + lostMasonryWrapGutterUnit }); decl.remove(); }); };
lib/lost-masonry-wrap.js
var newBlock = require('./new-block.js'); /** * lost-masonry-wrap: Creates a wrapping element for working with JS Masonry * libraries like Isotope. Assigns a negative margin on each side of this * wrapping element. * * @param {string} [flex|no-flex] - Determines whether this element should * use Flexbox or not. * * @param {length} [gutter] - How large the gutter involved is, typically * this won't be adjusted and will inherit settings.gutter, but it's made * available if you want your masonry grid to have a special gutter, it * should match your masonry-column's gutter. * * @example * section { * lost-masonry-wrap: no-flex; * } * div { * lost-masonry-column: 1/3; * } */ module.exports = function lostMasonryWrapDecl(css, settings) { css.walkDecls('lost-masonry-wrap', function(decl) { var declArr = [], lostMasonryWrap, lostMasonryWrapFlexbox = settings.flexbox, lostMasonryWrapGutter = settings.gutter, lostMasonryWrapGutterUnit; function cloneAllBefore(props) { Object.keys(props).forEach(function traverseProps(prop) { decl.cloneBefore({ prop: prop, value: props[prop] }); }); } declArr = decl.value.split(' '); if (declArr[0] !== undefined && declArr[0] == 'flex' || declArr[0] == 'no-flex') { lostMasonryWrapFlexbox = declArr[0]; } if (declArr.indexOf('flex') !== -1) { lostMasonryWrapFlexbox = 'flex'; } if (declArr.indexOf('no-flex') !== -1) { lostMasonryWrapFlexbox = 'no-flex'; } if (declArr[1] !== undefined && declArr[1].search(/^\d/) !== -1) { lostMasonryWrapGutter = declArr[1]; } decl.parent.nodes.forEach(function (decl) { if (decl.prop == 'lost-masonry-wrap-flexbox') { if (decl.value == 'flex') { lostMasonryWrapFlexbox = 'flex'; } decl.remove(); } }); decl.parent.nodes.forEach(function (decl) { if (decl.prop == 'lost-masonry-wrap-gutter') { lostMasonryWrap = decl.value; decl.remove(); } }); if (lostMasonryWrapFlexbox !== 'flex') { newBlock( decl, ':after', ['content', 'display', 'clear'], ['\'\'', 'table', 'both'] ); newBlock( decl, ':before', ['content', 'display'], ['\'\'', 'table'] ); } else { decl.cloneBefore({ prop: 'display', value: 'flex' }); decl.cloneBefore({ prop: 'flex-flow', value: 'row wrap' }); } lostMasonryWrapGutterUnit = lostMasonryWrapGutter.match(/\D/g).join(''); cloneAllBefore({ 'margin-left': (parseInt(lostMasonryWrapGutter) / -2) + lostMasonryWrapGutterUnit, 'margin-right': (parseInt(lostMasonryWrapGutter) / -2) + lostMasonryWrapGutterUnit }); decl.remove(); }); };
Updates lostMasonryWrap for ESLint
lib/lost-masonry-wrap.js
Updates lostMasonryWrap for ESLint
<ide><path>ib/lost-masonry-wrap.js <ide> * } <ide> */ <ide> module.exports = function lostMasonryWrapDecl(css, settings) { <del> css.walkDecls('lost-masonry-wrap', function(decl) { <del> var declArr = [], <del> lostMasonryWrap, <del> lostMasonryWrapFlexbox = settings.flexbox, <del> lostMasonryWrapGutter = settings.gutter, <del> lostMasonryWrapGutterUnit; <add> css.walkDecls('lost-masonry-wrap', function lostMasonryWrapDeclFunction(decl) { <add> var declArr = []; <add> var lostMasonryWrap; <add> var lostMasonryWrapFlexbox = settings.flexbox; <add> var lostMasonryWrapGutter = settings.gutter; <add> var lostMasonryWrapGutterUnit; <ide> <ide> function cloneAllBefore(props) { <ide> Object.keys(props).forEach(function traverseProps(prop) { <ide> <ide> declArr = decl.value.split(' '); <ide> <del> if (declArr[0] !== undefined && declArr[0] == 'flex' || declArr[0] == 'no-flex') { <add> if ((declArr[0] !== undefined && declArr[0] === 'flex') || declArr[0] === 'no-flex') { <ide> lostMasonryWrapFlexbox = declArr[0]; <ide> } <ide> <ide> lostMasonryWrapGutter = declArr[1]; <ide> } <ide> <del> decl.parent.nodes.forEach(function (decl) { <del> if (decl.prop == 'lost-masonry-wrap-flexbox') { <del> if (decl.value == 'flex') { <add> decl.parent.nodes.forEach(function lostMasonryWrapFlexboxFunction(declaration) { <add> if (declaration.prop === 'lost-masonry-wrap-flexbox') { <add> if (declaration.value === 'flex') { <ide> lostMasonryWrapFlexbox = 'flex'; <ide> } <ide> <del> decl.remove(); <add> declaration.remove(); <ide> } <ide> }); <ide> <del> decl.parent.nodes.forEach(function (decl) { <del> if (decl.prop == 'lost-masonry-wrap-gutter') { <del> lostMasonryWrap = decl.value; <add> decl.parent.nodes.forEach(function lostMasonryWrapFunction(declaration) { <add> if (declaration.prop === 'lost-masonry-wrap-gutter') { <add> lostMasonryWrap = declaration.value; <ide> <del> decl.remove(); <add> declaration.remove(); <ide> } <ide> }); <ide> <ide> lostMasonryWrapGutterUnit = lostMasonryWrapGutter.match(/\D/g).join(''); <ide> <ide> cloneAllBefore({ <del> 'margin-left': (parseInt(lostMasonryWrapGutter) / -2) + lostMasonryWrapGutterUnit, <del> 'margin-right': (parseInt(lostMasonryWrapGutter) / -2) + lostMasonryWrapGutterUnit <add> 'margin-left': (parseInt(lostMasonryWrapGutter, 10) / -2) + lostMasonryWrapGutterUnit, <add> 'margin-right': (parseInt(lostMasonryWrapGutter, 10) / -2) + lostMasonryWrapGutterUnit <ide> }); <ide> <ide> decl.remove();
Java
mit
af3ffe6c65e1c927def3ecb237ed55e5930564e7
0
jbosboom/streamjit,jbosboom/streamjit
src/edu/mit/streamjit/impl/common/BlobGraph.java
package edu.mit.streamjit.impl.common; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import edu.mit.streamjit.impl.blob.Blob; /** * BlobGraph builds predecessor successor relationship for set of {@link Blob}s * and verifies for cyclic dependencies among the blobs. Further, it gives * {@link Drainer} that can be get used perform draining over the blob graph. * * @author Sumanan [email protected] * @since Jul 28, 2013 */ public final class BlobGraph { private final Drainer drainer; private final ImmutableSet<Blob> blobSet; public BlobGraph(Set<Blob> blobSet) { this.blobSet = ImmutableSet.copyOf(blobSet); Set<BlobNode> blobNodes = new HashSet<>(blobSet.size()); for (Blob b : blobSet) { blobNodes.add(new BlobNode(b)); } for (BlobNode cur : blobNodes) { for (BlobNode other : blobNodes) { if (cur == other) continue; if (Sets.intersection(cur.getBlob().getOutputs(), other.getBlob().getInputs()).size() != 0) { cur.addSuccessor(other); other.addPredecessor(cur); } } } checkCycles(blobNodes); BlobNode sourceBlob = null; for (BlobNode bn : blobNodes) { if (bn.getDependencyCount() == 0) { assert sourceBlob == null : "Multiple independent blobs found."; sourceBlob = bn; } } drainer = Drainer.getDrainer(blobNodes, sourceBlob); } /** * @return The drainer object of this Blobgraph that can be used for * draining. */ public Drainer getDrainer() { return drainer; } /** * Does a depth first traversal to detect cycles in the graph. * * @param blobNodes */ private void checkCycles(Set<BlobNode> blobNodes) { Map<BlobNode, Color> colorMap = new HashMap<>(); for (BlobNode b : blobNodes) { colorMap.put(b, Color.WHITE); } for (BlobNode b : blobNodes) { if (colorMap.get(b) == Color.WHITE) if (DFS(b, colorMap)) throw new AssertionError("Cycles found among blobs"); } } /** * A cycle exits in a directed graph if a back edge is detected during a DFS * traversal. A back edge exists in a directed graph if the currently * explored vertex has an adjacent vertex that was already colored gray * * @param vertex * @param colorMap * @return <code>true</code> if cycle found, <code>false</code> otherwise. */ private boolean DFS(BlobNode vertex, Map<BlobNode, Color> colorMap) { colorMap.put(vertex, Color.GRAY); for (BlobNode adj : vertex.getSuccessors()) { if (colorMap.get(adj) == Color.GRAY) return true; if (colorMap.get(adj) == Color.WHITE) DFS(adj, colorMap); } colorMap.put(vertex, Color.BLACK); return false; } /** * @return Set of blobs in the blob graph. */ public ImmutableSet<Blob> getBlobSet() { return blobSet; } /** * Drainer triggers the draining operation for a blob graph. Once draining * is started, blobs will be called for draining iff all of their * predecessor blobs have been drained. */ public static class Drainer { /** * All nodes in the blob graph. */ private final Set<BlobNode> blobNodes; /** * The blob that has overall input token. */ private final BlobNode sourceBlob; private static Drainer getDrainer(Set<BlobNode> blobNodes, BlobNode sourceBlob) { return new Drainer(blobNodes, sourceBlob); } private Drainer(Set<BlobNode> blobNodes, BlobNode sourceBlob) { this.sourceBlob = sourceBlob; this.blobNodes = blobNodes; } /** * @param threadMap * Map that contains blobs and corresponding set of blob * threads belong to the blob. */ public void startDraining(Map<Blob, Set<BlobThread>> threadMap) { for (BlobNode bn : blobNodes) { if (!threadMap.containsKey(bn.getBlob())) throw new AssertionError( "threadMap doesn't contain thread information for the blob " + bn.getBlob()); bn.setBlobThreads(threadMap.get(bn.getBlob())); } sourceBlob.drain(); } /** * @return <code>true</code> iff all blobs in the blob graph has * finished the draining. */ public boolean isDrained() { for (BlobNode bn : blobNodes) if (!bn.isDrained()) return false; return true; } } /** * BlobNode represents the vertex in the blob graph ({@link BlobGraph}). It * wraps a {@link Blob} and carry the draining process of that blob. * * @author Sumanan */ private class BlobNode { /** * The blob that wrapped by this blob node. */ private Blob blob; /** * Predecessor blob nodes of this blob node. */ private List<BlobNode> predecessors; /** * Successor blob nodes of this blob node. */ private List<BlobNode> successors; /** * The number of undrained predecessors of this blobs. Everytime, when a * predecessor finished draining, dependencyCount will be decremented * and once it reached to 0 this blob will be called for draining. */ private AtomicInteger dependencyCount; /** * Set of threads those belong to the blob. */ private Set<BlobThread> blobThreads; /** * Set to ture iff this blob has been drained. */ private volatile boolean isDrained; private BlobNode(Blob blob) { this.blob = blob; predecessors = new ArrayList<>(); successors = new ArrayList<>(); dependencyCount = new AtomicInteger(0); isDrained = false; } private ImmutableList<BlobNode> getSuccessors() { return ImmutableList.copyOf(successors); } private void addPredecessor(BlobNode pred) { assert !predecessors.contains(pred) : String.format( "The BlobNode %s has already been set as a predecessors", pred); predecessors.add(pred); dependencyCount.set(dependencyCount.get() + 1); } private void addSuccessor(BlobNode succ) { assert !successors.contains(succ) : String .format("The BlobNode %s has already been set as a successor", succ); successors.add(succ); } private Blob getBlob() { return blob; } private void predecessorDrained(BlobNode pred) { if (!predecessors.contains(pred)) throw new IllegalArgumentException("Illegal Predecessor"); assert dependencyCount.get() > 0 : String .format("Graph mismatch : My predecessors count is %d. But more than %d of BlobNodes claim me as their successor", predecessors.size(), predecessors.size()); if (dependencyCount.decrementAndGet() == 0) { drain(); } } /** * @return The number of undrained predecessors. */ private int getDependencyCount() { return dependencyCount.get(); } /** * Should be called when the draining of the current blob has been * finished. This function stops all threads belong to the blob and * inform its successors as well. */ private void drained() { for (BlobThread bt : blobThreads) bt.requestStop(); for (BlobNode suc : this.successors) { suc.predecessorDrained(this); } isDrained = true; } private void drain() { blob.drain(new DrainCallback(this)); } private void setBlobThreads(Set<BlobThread> blobThreads) { this.blobThreads = blobThreads; } private boolean isDrained() { return isDrained; } } private class DrainCallback implements Runnable { private final BlobNode myNode; private DrainCallback(BlobNode blobNode) { this.myNode = blobNode; } @Override public void run() { myNode.drained(); } } /** * Color enumerator used by DFS algorithm to find cycles in the blob graph. */ private enum Color { WHITE, GRAY, BLACK } }
blob graph deleted. Restructured blob graph will be added
src/edu/mit/streamjit/impl/common/BlobGraph.java
blob graph deleted.
<ide><path>rc/edu/mit/streamjit/impl/common/BlobGraph.java <del>package edu.mit.streamjit.impl.common; <del> <del>import java.util.ArrayList; <del>import java.util.HashMap; <del>import java.util.HashSet; <del>import java.util.List; <del>import java.util.Map; <del>import java.util.Set; <del>import java.util.concurrent.atomic.AtomicInteger; <del> <del>import com.google.common.collect.ImmutableList; <del>import com.google.common.collect.ImmutableSet; <del>import com.google.common.collect.Sets; <del> <del>import edu.mit.streamjit.impl.blob.Blob; <del> <del>/** <del> * BlobGraph builds predecessor successor relationship for set of {@link Blob}s <del> * and verifies for cyclic dependencies among the blobs. Further, it gives <del> * {@link Drainer} that can be get used perform draining over the blob graph. <del> * <del> * @author Sumanan [email protected] <del> * @since Jul 28, 2013 <del> */ <del>public final class BlobGraph { <del> <del> private final Drainer drainer; <del> <del> private final ImmutableSet<Blob> blobSet; <del> <del> public BlobGraph(Set<Blob> blobSet) { <del> this.blobSet = ImmutableSet.copyOf(blobSet); <del> Set<BlobNode> blobNodes = new HashSet<>(blobSet.size()); <del> for (Blob b : blobSet) { <del> blobNodes.add(new BlobNode(b)); <del> } <del> <del> for (BlobNode cur : blobNodes) { <del> for (BlobNode other : blobNodes) { <del> if (cur == other) <del> continue; <del> if (Sets.intersection(cur.getBlob().getOutputs(), <del> other.getBlob().getInputs()).size() != 0) { <del> cur.addSuccessor(other); <del> other.addPredecessor(cur); <del> } <del> } <del> } <del> checkCycles(blobNodes); <del> <del> BlobNode sourceBlob = null; <del> for (BlobNode bn : blobNodes) { <del> if (bn.getDependencyCount() == 0) { <del> assert sourceBlob == null : "Multiple independent blobs found."; <del> sourceBlob = bn; <del> } <del> } <del> <del> drainer = Drainer.getDrainer(blobNodes, sourceBlob); <del> } <del> <del> /** <del> * @return The drainer object of this Blobgraph that can be used for <del> * draining. <del> */ <del> public Drainer getDrainer() { <del> return drainer; <del> } <del> <del> /** <del> * Does a depth first traversal to detect cycles in the graph. <del> * <del> * @param blobNodes <del> */ <del> private void checkCycles(Set<BlobNode> blobNodes) { <del> Map<BlobNode, Color> colorMap = new HashMap<>(); <del> for (BlobNode b : blobNodes) { <del> colorMap.put(b, Color.WHITE); <del> } <del> for (BlobNode b : blobNodes) { <del> if (colorMap.get(b) == Color.WHITE) <del> if (DFS(b, colorMap)) <del> throw new AssertionError("Cycles found among blobs"); <del> } <del> } <del> <del> /** <del> * A cycle exits in a directed graph if a back edge is detected during a DFS <del> * traversal. A back edge exists in a directed graph if the currently <del> * explored vertex has an adjacent vertex that was already colored gray <del> * <del> * @param vertex <del> * @param colorMap <del> * @return <code>true</code> if cycle found, <code>false</code> otherwise. <del> */ <del> private boolean DFS(BlobNode vertex, Map<BlobNode, Color> colorMap) { <del> colorMap.put(vertex, Color.GRAY); <del> for (BlobNode adj : vertex.getSuccessors()) { <del> if (colorMap.get(adj) == Color.GRAY) <del> return true; <del> if (colorMap.get(adj) == Color.WHITE) <del> DFS(adj, colorMap); <del> } <del> colorMap.put(vertex, Color.BLACK); <del> return false; <del> } <del> <del> /** <del> * @return Set of blobs in the blob graph. <del> */ <del> public ImmutableSet<Blob> getBlobSet() { <del> return blobSet; <del> } <del> <del> /** <del> * Drainer triggers the draining operation for a blob graph. Once draining <del> * is started, blobs will be called for draining iff all of their <del> * predecessor blobs have been drained. <del> */ <del> public static class Drainer { <del> <del> /** <del> * All nodes in the blob graph. <del> */ <del> private final Set<BlobNode> blobNodes; <del> <del> /** <del> * The blob that has overall input token. <del> */ <del> private final BlobNode sourceBlob; <del> <del> private static Drainer getDrainer(Set<BlobNode> blobNodes, <del> BlobNode sourceBlob) { <del> return new Drainer(blobNodes, sourceBlob); <del> } <del> <del> private Drainer(Set<BlobNode> blobNodes, BlobNode sourceBlob) { <del> this.sourceBlob = sourceBlob; <del> this.blobNodes = blobNodes; <del> } <del> <del> /** <del> * @param threadMap <del> * Map that contains blobs and corresponding set of blob <del> * threads belong to the blob. <del> */ <del> public void startDraining(Map<Blob, Set<BlobThread>> threadMap) { <del> for (BlobNode bn : blobNodes) { <del> if (!threadMap.containsKey(bn.getBlob())) <del> throw new AssertionError( <del> "threadMap doesn't contain thread information for the blob " <del> + bn.getBlob()); <del> <del> bn.setBlobThreads(threadMap.get(bn.getBlob())); <del> } <del> sourceBlob.drain(); <del> } <del> <del> /** <del> * @return <code>true</code> iff all blobs in the blob graph has <del> * finished the draining. <del> */ <del> public boolean isDrained() { <del> for (BlobNode bn : blobNodes) <del> if (!bn.isDrained()) <del> return false; <del> return true; <del> } <del> } <del> <del> /** <del> * BlobNode represents the vertex in the blob graph ({@link BlobGraph}). It <del> * wraps a {@link Blob} and carry the draining process of that blob. <del> * <del> * @author Sumanan <del> */ <del> private class BlobNode { <del> /** <del> * The blob that wrapped by this blob node. <del> */ <del> private Blob blob; <del> /** <del> * Predecessor blob nodes of this blob node. <del> */ <del> private List<BlobNode> predecessors; <del> /** <del> * Successor blob nodes of this blob node. <del> */ <del> private List<BlobNode> successors; <del> /** <del> * The number of undrained predecessors of this blobs. Everytime, when a <del> * predecessor finished draining, dependencyCount will be decremented <del> * and once it reached to 0 this blob will be called for draining. <del> */ <del> private AtomicInteger dependencyCount; <del> <del> /** <del> * Set of threads those belong to the blob. <del> */ <del> private Set<BlobThread> blobThreads; <del> <del> /** <del> * Set to ture iff this blob has been drained. <del> */ <del> private volatile boolean isDrained; <del> <del> private BlobNode(Blob blob) { <del> this.blob = blob; <del> predecessors = new ArrayList<>(); <del> successors = new ArrayList<>(); <del> dependencyCount = new AtomicInteger(0); <del> isDrained = false; <del> } <del> <del> private ImmutableList<BlobNode> getSuccessors() { <del> return ImmutableList.copyOf(successors); <del> } <del> <del> private void addPredecessor(BlobNode pred) { <del> assert !predecessors.contains(pred) : String.format( <del> "The BlobNode %s has already been set as a predecessors", <del> pred); <del> predecessors.add(pred); <del> dependencyCount.set(dependencyCount.get() + 1); <del> } <del> <del> private void addSuccessor(BlobNode succ) { <del> assert !successors.contains(succ) : String <del> .format("The BlobNode %s has already been set as a successor", <del> succ); <del> successors.add(succ); <del> } <del> <del> private Blob getBlob() { <del> return blob; <del> } <del> <del> private void predecessorDrained(BlobNode pred) { <del> if (!predecessors.contains(pred)) <del> throw new IllegalArgumentException("Illegal Predecessor"); <del> <del> assert dependencyCount.get() > 0 : String <del> .format("Graph mismatch : My predecessors count is %d. But more than %d of BlobNodes claim me as their successor", <del> predecessors.size(), predecessors.size()); <del> <del> if (dependencyCount.decrementAndGet() == 0) { <del> drain(); <del> } <del> } <del> <del> /** <del> * @return The number of undrained predecessors. <del> */ <del> private int getDependencyCount() { <del> return dependencyCount.get(); <del> } <del> <del> /** <del> * Should be called when the draining of the current blob has been <del> * finished. This function stops all threads belong to the blob and <del> * inform its successors as well. <del> */ <del> private void drained() { <del> for (BlobThread bt : blobThreads) <del> bt.requestStop(); <del> <del> for (BlobNode suc : this.successors) { <del> suc.predecessorDrained(this); <del> } <del> <del> isDrained = true; <del> } <del> <del> private void drain() { <del> blob.drain(new DrainCallback(this)); <del> } <del> <del> private void setBlobThreads(Set<BlobThread> blobThreads) { <del> this.blobThreads = blobThreads; <del> } <del> <del> private boolean isDrained() { <del> return isDrained; <del> } <del> } <del> <del> private class DrainCallback implements Runnable { <del> private final BlobNode myNode; <del> <del> private DrainCallback(BlobNode blobNode) { <del> this.myNode = blobNode; <del> } <del> <del> @Override <del> public void run() { <del> myNode.drained(); <del> } <del> } <del> <del> /** <del> * Color enumerator used by DFS algorithm to find cycles in the blob graph. <del> */ <del> private enum Color { <del> WHITE, GRAY, BLACK <del> } <del>}
Java
apache-2.0
54c29407c0e8a0fbea513e1236a334adc768e405
0
164738777/ZhihuDailyPurify
package io.github.izzyleung.zhihudailypurify.ui.fragment; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import io.github.izzyleung.zhihudailypurify.R; import io.github.izzyleung.zhihudailypurify.ZhihuDailyPurifyApplication; import io.github.izzyleung.zhihudailypurify.adapter.NewsAdapter; import io.github.izzyleung.zhihudailypurify.bean.DailyNews; import io.github.izzyleung.zhihudailypurify.observable.DailyNewsFromAccelerateServerObservable; import io.github.izzyleung.zhihudailypurify.observable.DailyNewsFromDatabaseObservable; import io.github.izzyleung.zhihudailypurify.observable.DailyNewsFromZhihuObservable; import io.github.izzyleung.zhihudailypurify.support.Constants; import io.github.izzyleung.zhihudailypurify.task.SaveNewsListTask; import io.github.izzyleung.zhihudailypurify.ui.activity.BaseActivity; import rx.Observable; import rx.Observer; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class NewsListFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, Observer<List<DailyNews>> { private List<DailyNews> newsList = new ArrayList<>(); private String date; private NewsAdapter mAdapter; // Fragment is single in SingleDayNewsActivity private boolean isToday; private boolean isRefreshed = false; private SwipeRefreshLayout mSwipeRefreshLayout; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { Bundle bundle = getArguments(); date = bundle.getString(Constants.BundleKeys.DATE); isToday = bundle.getBoolean(Constants.BundleKeys.IS_FIRST_PAGE); setRetainInstance(true); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_news_list, container, false); assert view != null; RecyclerView mRecyclerView = (RecyclerView) view.findViewById(R.id.news_list); mRecyclerView.setHasFixedSize(!isToday); LinearLayoutManager llm = new LinearLayoutManager(getActivity()); llm.setOrientation(LinearLayoutManager.VERTICAL); mRecyclerView.setLayoutManager(llm); mAdapter = new NewsAdapter(newsList); mRecyclerView.setAdapter(mAdapter); mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout); mSwipeRefreshLayout.setOnRefreshListener(this); mSwipeRefreshLayout.setColorSchemeResources(R.color.color_primary); return view; } @Override public void onResume() { super.onResume(); DailyNewsFromDatabaseObservable.ofDate(date) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(this); } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); refreshIf(shouldRefreshOnVisibilityChange(isVisibleToUser)); } private void refreshIf(boolean prerequisite) { if (prerequisite) { doRefresh(); } } private void doRefresh() { newsList.clear(); Observable<List<DailyNews>> observable; if (shouldSubscribeToZhihu()) { observable = DailyNewsFromZhihuObservable.ofDate(date); } else { observable = DailyNewsFromAccelerateServerObservable.ofDate(date); } observable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(this); if (mSwipeRefreshLayout != null) { mSwipeRefreshLayout.setRefreshing(true); } } private boolean shouldSubscribeToZhihu() { return isToday || !shouldUseAccelerateServer(); } private boolean shouldUseAccelerateServer() { return ZhihuDailyPurifyApplication.getSharedPreferences() .getBoolean(Constants.SharedPreferencesKeys.KEY_SHOULD_USE_ACCELERATE_SERVER, false); } private boolean shouldAutoRefresh() { return ZhihuDailyPurifyApplication.getSharedPreferences() .getBoolean(Constants.SharedPreferencesKeys.KEY_SHOULD_AUTO_REFRESH, true); } private boolean shouldRefreshOnVisibilityChange(boolean isVisibleToUser) { return isVisibleToUser && shouldAutoRefresh() && !isRefreshed; } @Override public void onRefresh() { doRefresh(); } @Override public void onNext(List<DailyNews> newsList) { this.newsList = newsList; } @Override public void onError(Throwable e) { mSwipeRefreshLayout.setRefreshing(false); if (isAdded()) { ((BaseActivity) getActivity()).showSnackbar(R.string.network_error); } } @Override public void onCompleted() { isRefreshed = true; mSwipeRefreshLayout.setRefreshing(false); mAdapter.updateNewsList(newsList); new SaveNewsListTask(date, newsList).execute(); } }
app/src/main/java/io/github/izzyleung/zhihudailypurify/ui/fragment/NewsListFragment.java
package io.github.izzyleung.zhihudailypurify.ui.fragment; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import io.github.izzyleung.zhihudailypurify.R; import io.github.izzyleung.zhihudailypurify.ZhihuDailyPurifyApplication; import io.github.izzyleung.zhihudailypurify.adapter.NewsAdapter; import io.github.izzyleung.zhihudailypurify.bean.DailyNews; import io.github.izzyleung.zhihudailypurify.observable.DailyNewsFromAccelerateServerObservable; import io.github.izzyleung.zhihudailypurify.observable.DailyNewsFromDatabaseObservable; import io.github.izzyleung.zhihudailypurify.observable.DailyNewsFromZhihuObservable; import io.github.izzyleung.zhihudailypurify.support.Constants; import io.github.izzyleung.zhihudailypurify.task.SaveNewsListTask; import io.github.izzyleung.zhihudailypurify.ui.activity.BaseActivity; import rx.Observable; import rx.Observer; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class NewsListFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, Observer<List<DailyNews>> { private List<DailyNews> newsList = new ArrayList<>(); private String date; private NewsAdapter mAdapter; // Fragment is single in SingleDayNewsActivity private boolean isToday; private boolean isRefreshed = false; private SwipeRefreshLayout mSwipeRefreshLayout; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { Bundle bundle = getArguments(); date = bundle.getString(Constants.BundleKeys.DATE); isToday = bundle.getBoolean(Constants.BundleKeys.IS_FIRST_PAGE); setRetainInstance(true); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_news_list, container, false); assert view != null; RecyclerView mRecyclerView = (RecyclerView) view.findViewById(R.id.news_list); mRecyclerView.setHasFixedSize(!isToday); LinearLayoutManager llm = new LinearLayoutManager(getActivity()); llm.setOrientation(LinearLayoutManager.VERTICAL); mRecyclerView.setLayoutManager(llm); mAdapter = new NewsAdapter(newsList); mRecyclerView.setAdapter(mAdapter); mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout); mSwipeRefreshLayout.setOnRefreshListener(this); mSwipeRefreshLayout.setColorSchemeResources(R.color.color_primary); return view; } @Override public void onResume() { super.onResume(); DailyNewsFromDatabaseObservable.ofDate(date) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(this); } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); refreshIf(shouldRefreshOnVisibilityChange(isVisibleToUser)); } private void refreshIf(boolean prerequisite) { if (prerequisite) { doRefresh(); } } private void doRefresh() { newsList.clear(); Observable<List<DailyNews>> observable; if (shouldSubscribeToZhihu()) { observable = DailyNewsFromZhihuObservable.ofDate(date); } else { observable = DailyNewsFromAccelerateServerObservable.ofDate(date); } observable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(this); if (mSwipeRefreshLayout != null) { mSwipeRefreshLayout.setRefreshing(true); } } private boolean shouldSubscribeToZhihu() { return isToday || shouldUseAccelerateServer(); } private boolean shouldUseAccelerateServer() { return ZhihuDailyPurifyApplication.getSharedPreferences() .getBoolean(Constants.SharedPreferencesKeys.KEY_SHOULD_USE_ACCELERATE_SERVER, false); } private boolean shouldAutoRefresh() { return ZhihuDailyPurifyApplication.getSharedPreferences() .getBoolean(Constants.SharedPreferencesKeys.KEY_SHOULD_AUTO_REFRESH, true); } private boolean shouldRefreshOnVisibilityChange(boolean isVisibleToUser) { return isVisibleToUser && shouldAutoRefresh() && !isRefreshed; } @Override public void onRefresh() { doRefresh(); } @Override public void onNext(List<DailyNews> newsList) { this.newsList = newsList; } @Override public void onError(Throwable e) { mSwipeRefreshLayout.setRefreshing(false); if (isAdded()) { ((BaseActivity) getActivity()).showSnackbar(R.string.network_error); } } @Override public void onCompleted() { isRefreshed = true; mSwipeRefreshLayout.setRefreshing(false); mAdapter.updateNewsList(newsList); new SaveNewsListTask(date, newsList).execute(); } }
Fix shouldSubscribeToZhihu logic
app/src/main/java/io/github/izzyleung/zhihudailypurify/ui/fragment/NewsListFragment.java
Fix shouldSubscribeToZhihu logic
<ide><path>pp/src/main/java/io/github/izzyleung/zhihudailypurify/ui/fragment/NewsListFragment.java <ide> } <ide> <ide> private boolean shouldSubscribeToZhihu() { <del> return isToday || shouldUseAccelerateServer(); <add> return isToday || !shouldUseAccelerateServer(); <ide> } <ide> <ide> private boolean shouldUseAccelerateServer() {
Java
apache-2.0
d576c1f5e61dd02dfd030437454f543a9cf13918
0
mikepenz/FastAdapter,mikepenz/FastAdapter,mikepenz/FastAdapter,mikepenz/FastAdapter
package com.mikepenz.fastadapter; import android.os.Bundle; import android.support.v4.util.ArrayMap; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.util.SparseIntArray; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import com.mikepenz.fastadapter.utils.AdapterUtil; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.Set; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; /** * Created by mikepenz on 27.12.15. */ public class FastAdapter<Item extends IItem> extends RecyclerView.Adapter<RecyclerView.ViewHolder> { protected static final String BUNDLE_SELECTIONS = "bundle_selections"; protected static final String BUNDLE_EXPANDED = "bundle_expanded"; // we remember all adapters //priority queue... final private ArrayMap<Integer, IAdapter<Item>> mAdapters = new ArrayMap<>(); // we remember all possible types so we can create a new view efficiently final private ArrayMap<Integer, Item> mTypeInstances = new ArrayMap<>(); // cache the sizes of the different adapters so we can access the items more performant final private NavigableMap<Integer, IAdapter<Item>> mAdapterSizes = new TreeMap<>(); // the total size private int mGlobalSize = 0; // if enabled we will select the item via a notifyItemChanged -> will animate with the Animator // you can also use this if you have any custom logic for selections, and do not depend on the "selected" state of the view // note if enabled it will feel a bit slower because it will animate the selection private boolean mSelectWithItemUpdate = false; // if we want multiSelect enabled private boolean mMultiSelect = false; // if we want the multiSelect only on longClick private boolean mSelectOnLongClick = false; // if a user can deselect a selection via click. required if there is always one selected item! private boolean mAllowDeselection = true; // if items are selectable in general private boolean mSelectable = false; // only one expanded section private boolean mOnlyOneExpandedItem = false; // we need to remember all selections to recreate them after orientation change private SortedSet<Integer> mSelections = new TreeSet<>(); // we need to remember all expanded items to recreate them after orientation change private SparseIntArray mExpanded = new SparseIntArray(); // the listeners which can be hooked on an item private OnClickListener<Item> mOnPreClickListener; private OnClickListener<Item> mOnClickListener; private OnLongClickListener<Item> mOnPreLongClickListener; private OnLongClickListener<Item> mOnLongClickListener; private OnTouchListener<Item> mOnTouchListener; //the listeners for onCreateViewHolder or onBindViewHolder private OnCreateViewHolderListener mOnCreateViewHolderListener = new OnCreateViewHolderListenerImpl(); private OnBindViewHolderListener mOnBindViewHolderListener = new OnBindViewHolderListenerImpl(); /** * default CTOR */ public FastAdapter() { setHasStableIds(true); } /** * Define the OnClickListener which will be used for a single item * * @param onClickListener the OnClickListener which will be used for a single item * @return this */ public FastAdapter<Item> withOnClickListener(OnClickListener<Item> onClickListener) { this.mOnClickListener = onClickListener; return this; } /** * Define the OnPreClickListener which will be used for a single item and is called after all internal methods are done * * @param onPreClickListener the OnPreClickListener which will be called after a single item was clicked and all internal methods are done * @return this */ public FastAdapter<Item> withOnPreClickListener(OnClickListener<Item> onPreClickListener) { this.mOnPreClickListener = onPreClickListener; return this; } /** * Define the OnLongClickListener which will be used for a single item * * @param onLongClickListener the OnLongClickListener which will be used for a single item * @return this */ public FastAdapter<Item> withOnLongClickListener(OnLongClickListener<Item> onLongClickListener) { this.mOnLongClickListener = onLongClickListener; return this; } /** * Define the OnLongClickListener which will be used for a single item and is called after all internal methods are done * * @param onPreLongClickListener the OnLongClickListener which will be called after a single item was clicked and all internal methods are done * @return this */ public FastAdapter<Item> withOnPreLongClickListener(OnLongClickListener<Item> onPreLongClickListener) { this.mOnPreLongClickListener = onPreLongClickListener; return this; } /** * Define the TouchListener which will be used for a single item * * @param onTouchListener the TouchListener which will be used for a single item * @return this */ public FastAdapter<Item> withOnTouchListener(OnTouchListener<Item> onTouchListener) { this.mOnTouchListener = onTouchListener; return this; } /** * allows you to set a custom OnCreateViewHolderListener which will be used before and after the ViewHolder is created * You may check the OnCreateViewHolderListenerImpl for the default behavior * * @param onCreateViewHolderListener the OnCreateViewHolderListener (you may use the OnCreateViewHolderListenerImpl) */ public FastAdapter<Item> withOnCreateViewHolderListener(OnCreateViewHolderListener onCreateViewHolderListener) { this.mOnCreateViewHolderListener = onCreateViewHolderListener; return this; } /** * allows you to set an custom OnBindViewHolderListener which is used to bind the view. This will overwrite the libraries behavior. * You may check the OnBindViewHolderListenerImpl for the default behavior * * @param onBindViewHolderListener the OnBindViewHolderListener */ public FastAdapter<Item> withOnBindViewHolderListener(OnBindViewHolderListener onBindViewHolderListener) { this.mOnBindViewHolderListener = onBindViewHolderListener; return this; } /** * select between the different selection behaviors. * there are now 2 different variants of selection. you can toggle this via `withSelectWithItemUpdate(boolean)` (where false == default - variant 1) * 1.) direct selection via the view "selected" state, we also make sure we do not animate here so no notifyItemChanged is called if we repeatly press the same item * 2.) we select the items via a notifyItemChanged. this will allow custom selected logics within your views (isSelected() - do something...) and it will also animate the change via the provided itemAnimator. because of the animation of the itemAnimator the selection will have a small delay (time of animating) * * @param selectWithItemUpdate true if notifyItemChanged should be called upon select * @return this */ public FastAdapter<Item> withSelectWithItemUpdate(boolean selectWithItemUpdate) { this.mSelectWithItemUpdate = selectWithItemUpdate; return this; } /** * Enable this if you want multiSelection possible in the list * * @param multiSelect true to enable multiSelect * @return this */ public FastAdapter<Item> withMultiSelect(boolean multiSelect) { mMultiSelect = multiSelect; return this; } /** * Disable this if you want the selection on a single tap * * @param selectOnLongClick false to do select via single click * @return this */ public FastAdapter<Item> withSelectOnLongClick(boolean selectOnLongClick) { mSelectOnLongClick = selectOnLongClick; return this; } /** * If false, a user can't deselect an item via click (you can still do this programmatically) * * @param allowDeselection true if a user can deselect an already selected item via click * @return this */ public FastAdapter<Item> withAllowDeselection(boolean allowDeselection) { this.mAllowDeselection = allowDeselection; return this; } /** * set if no item is selectable * * @param selectable true if items are selectable * @return this */ public FastAdapter<Item> withSelectable(boolean selectable) { this.mSelectable = selectable; return this; } /** * @return if items are selectable */ public boolean isSelectable() { return mSelectable; } /** * set if there should only be one opened expandable item * DEFAULT: false * * @param mOnlyOneExpandedItem true if there should be only one expanded, expandable item in the list * @return this */ public FastAdapter<Item> withOnlyOneExpandedItem(boolean mOnlyOneExpandedItem) { this.mOnlyOneExpandedItem = mOnlyOneExpandedItem; return this; } /** * @return if there should be only one expanded, expandable item in the list */ public boolean isOnlyOneExpandedItem() { return mOnlyOneExpandedItem; } /** * re-selects all elements stored in the savedInstanceState * IMPORTANT! Call this method only after all items where added to the adapters again. Otherwise it may select wrong items! * * @param savedInstanceState If the activity is being re-initialized after * previously being shut down then this Bundle contains the data it most * recently supplied in Note: Otherwise it is null. * @return this */ public FastAdapter<Item> withSavedInstanceState(Bundle savedInstanceState) { return withSavedInstanceState(savedInstanceState, ""); } /** * re-selects all elements stored in the savedInstanceState * IMPORTANT! Call this method only after all items where added to the adapters again. Otherwise it may select wrong items! * * @param savedInstanceState If the activity is being re-initialized after * previously being shut down then this Bundle contains the data it most * recently supplied in Note: Otherwise it is null. * @param prefix a prefix added to the savedInstance key so we can store multiple states * @return this */ public FastAdapter<Item> withSavedInstanceState(Bundle savedInstanceState, String prefix) { if (savedInstanceState != null) { //make sure already done selections are removed deselect(); //first restore opened collasable items, as otherwise may not all selections could be restored int[] expandedItems = savedInstanceState.getIntArray(BUNDLE_EXPANDED + prefix); if (expandedItems != null) { for (Integer expandedItem : expandedItems) { expand(expandedItem); } } //restore the selections int[] selections = savedInstanceState.getIntArray(BUNDLE_SELECTIONS + prefix); if (selections != null) { for (Integer selection : selections) { select(selection); } } } return this; } /** * registers an AbstractAdapter which will be hooked into the adapter chain * * @param adapter an adapter which extends the AbstractAdapter */ public <A extends AbstractAdapter<Item>> void registerAdapter(A adapter) { if (!mAdapters.containsKey(adapter.getOrder())) { mAdapters.put(adapter.getOrder(), adapter); cacheSizes(); } } /** * register a new type into the TypeInstances to be able to efficiently create thew ViewHolders * * @param item an IItem which will be shown in the list */ public void registerTypeInstance(Item item) { if (!mTypeInstances.containsKey(item.getType())) { mTypeInstances.put(item.getType(), item); } } /** * gets the TypeInstance remembered within the FastAdapter for an item * * @param type the int type of the item * @return the Item typeInstance */ public Item getTypeInstance(int type) { return mTypeInstances.get(type); } /** * Creates the ViewHolder by the viewType * * @param parent the parent view (the RecyclerView) * @param viewType the current viewType which is bound * @return the ViewHolder with the bound data */ @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { final RecyclerView.ViewHolder holder = mOnCreateViewHolderListener.onPreCreateViewHolder(parent, viewType); //handle click behavior holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int pos = holder.getAdapterPosition(); if (pos != RecyclerView.NO_POSITION) { boolean consumed = false; RelativeInfo<Item> relativeInfo = getRelativeInfo(pos); Item item = relativeInfo.item; if (item != null && item.isEnabled()) { //on the very first we call the click listener from the item itself (if defined) if (item instanceof IClickable && ((IClickable) item).getOnPreItemClickListener() != null) { consumed = ((IClickable<Item>) item).getOnPreItemClickListener().onClick(v, relativeInfo.adapter, item, pos); } //first call the onPreClickListener which would allow to prevent executing of any following code, including selection if (!consumed && mOnPreClickListener != null) { consumed = mOnPreClickListener.onClick(v, relativeInfo.adapter, item, pos); } //if this is a expandable item :D if (!consumed && item instanceof IExpandable) { if (((IExpandable) item).getSubItems() != null) { toggleExpandable(pos); } } //if there should be only one expanded item we want to collapse all the others but the current one if (mOnlyOneExpandedItem) { int[] expandedItems = getExpandedItems(); for (int i = expandedItems.length - 1; i >= 0; i--) { if (expandedItems[i] != pos) { collapse(expandedItems[i], true); } } } //handle the selection if the event was not yet consumed, and we are allowed to select an item (only occurs when we select with long click only) if (!consumed && !mSelectOnLongClick && mSelectable) { handleSelection(v, item, pos); } //before calling the global adapter onClick listener call the item specific onClickListener if (item instanceof IClickable && ((IClickable) item).getOnItemClickListener() != null) { consumed = ((IClickable<Item>) item).getOnItemClickListener().onClick(v, relativeInfo.adapter, item, pos); } //call the normal click listener after selection was handlded if (!consumed && mOnClickListener != null) { mOnClickListener.onClick(v, relativeInfo.adapter, item, pos); } } } } }); //handle long click behavior holder.itemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { int pos = holder.getAdapterPosition(); if (pos != RecyclerView.NO_POSITION) { boolean consumed = false; RelativeInfo<Item> relativeInfo = getRelativeInfo(pos); if (relativeInfo.item != null && relativeInfo.item.isEnabled()) { //first call the OnPreLongClickListener which would allow to prevent executing of any following code, including selection if (mOnPreLongClickListener != null) { consumed = mOnPreLongClickListener.onLongClick(v, relativeInfo.adapter, relativeInfo.item, pos); } //now handle the selection if we are in multiSelect mode and allow selecting on longClick if (!consumed && mSelectOnLongClick && mSelectable) { handleSelection(v, relativeInfo.item, pos); } //call the normal long click listener after selection was handled if (mOnLongClickListener != null) { consumed = mOnLongClickListener.onLongClick(v, relativeInfo.adapter, relativeInfo.item, pos); } } return consumed; } return false; } }); //handle touch behavior holder.itemView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (mOnTouchListener != null) { int pos = holder.getAdapterPosition(); if (pos != RecyclerView.NO_POSITION) { RelativeInfo<Item> relativeInfo = getRelativeInfo(pos); return mOnTouchListener.onTouch(v, event, relativeInfo.adapter, relativeInfo.item, pos); } } return false; } }); return mOnCreateViewHolderListener.onPostCreateViewHolder(holder); } /** * Binds the data to the created ViewHolder and sets the listeners to the holder.itemView * * @param holder the viewHolder we bind the data on * @param position the global position */ @Override public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) { mOnBindViewHolderListener.onBindViewHolder(holder, position); } /** * Searches for the given item and calculates it's global position * * @param item the item which is searched for * @return the global position, or -1 if not found */ public int getPosition(Item item) { if (item.getIdentifier() == -1) { Log.e("FastAdapter", "You have to define an identifier for your item to retrieve the position via this method"); return -1; } int position = 0; int length = mAdapters.size(); for (int i = 0; i < length; i++) { IAdapter<Item> adapter = mAdapters.valueAt(i); if (adapter.getOrder() < 0) { continue; } int relativePosition = adapter.getAdapterPosition(item); if (relativePosition != -1) { return position + relativePosition; } position = adapter.getAdapterItemCount(); } return -1; } /** * gets the IItem by a position, from all registered adapters * * @param position the global position * @return the found IItem or null */ public Item getItem(int position) { //if we are out of range just return null if (position < 0 || position >= mGlobalSize) { return null; } //now get the adapter which is responsible for the given position Map.Entry<Integer, IAdapter<Item>> entry = mAdapterSizes.floorEntry(position); return entry.getValue().getAdapterItem(position - entry.getKey()); } /** * Internal method to get the Item as ItemHolder which comes with the relative position within it's adapter * Finds the responsible adapter for the given position * * @param position the global position * @return the adapter which is responsible for this position */ public RelativeInfo<Item> getRelativeInfo(int position) { if (position < 0) { return new RelativeInfo<>(); } RelativeInfo<Item> relativeInfo = new RelativeInfo<>(); Map.Entry<Integer, IAdapter<Item>> entry = mAdapterSizes.floorEntry(position); if (entry != null) { relativeInfo.item = entry.getValue().getAdapterItem(position - entry.getKey()); relativeInfo.adapter = entry.getValue(); relativeInfo.position = position; } return relativeInfo; } /** * Gets the adapter for the given position * * @param position the global position * @return the adapter responsible for this global position */ public IAdapter<Item> getAdapter(int position) { //if we are out of range just return null if (position < 0 || position >= mGlobalSize) { return null; } //now get the adapter which is responsible for the given position return mAdapterSizes.floorEntry(position).getValue(); } /** * finds the int ItemViewType from the IItem which exists at the given position * * @param position the global position * @return the viewType for this position */ @Override public int getItemViewType(int position) { return getItem(position).getType(); } /** * finds the int ItemId from the IItem which exists at the given position * * @param position the global position * @return the itemId for this position */ @Override public long getItemId(int position) { return getItem(position).getIdentifier(); } /** * calculates the total ItemCount over all registered adapters * * @return the global count */ public int getItemCount() { return mGlobalSize; } /** * calculates the item count up to a given (excluding this) order number * * @param order the number up to which the items are counted * @return the total count of items up to the adapter order */ public int getPreItemCountByOrder(int order) { //if we are empty just return 0 count if (mGlobalSize == 0) { return 0; } int size = 0; //count the number of items before the adapter with the given order for (IAdapter<Item> adapter : mAdapters.values()) { if (adapter.getOrder() == order) { return size; } else { size = size + adapter.getAdapterItemCount(); } } //get the count of items which are before this order return size; } /** * calculates the item count up to a given (excluding this) adapter (defined by the global position of the item) * * @param position the global position of an adapter item * @return the total count of items up to the adapter which holds the given position */ public int getPreItemCount(int position) { //if we are empty just return 0 count if (mGlobalSize == 0) { return 0; } //get the count of items which are before this order return mAdapterSizes.floorKey(position); } /** * calculates the count of expandable items before a given position * * @param from the global start position you should pass here the count of items of the previous adapters (or 0 if you want to start from the beginning) * @param position the global position * @return the count of expandable items before a given position */ public int getExpandedItemsCount(int from, int position) { int totalAddedItems = 0; int length = mExpanded.size(); for (int i = 0; i < length; i++) { //now we count the amount of expanded items within our range we check if (mExpanded.keyAt(i) >= from && mExpanded.keyAt(i) < position) { totalAddedItems = totalAddedItems + mExpanded.get(mExpanded.keyAt(i)); } else if (mExpanded.keyAt(i) >= position) { //we do not care about all expanded items which are outside our range break; } } return totalAddedItems; } /** * add the values to the bundle for saveInstanceState * * @param savedInstanceState If the activity is being re-initialized after * previously being shut down then this Bundle contains the data it most * recently supplied in Note: Otherwise it is null. * @return the passed bundle with the newly added data */ public Bundle saveInstanceState(Bundle savedInstanceState) { return saveInstanceState(savedInstanceState, ""); } /** * add the values to the bundle for saveInstanceState * * @param savedInstanceState If the activity is being re-initialized after * previously being shut down then this Bundle contains the data it most * recently supplied in Note: Otherwise it is null. * @param prefix a prefix added to the savedInstance key so we can store multiple states * @return the passed bundle with the newly added data */ public Bundle saveInstanceState(Bundle savedInstanceState, String prefix) { if (savedInstanceState != null) { //remember the selections int[] selections = new int[mSelections.size()]; int index = 0; for (Integer selection : mSelections) { selections[index] = selection; index++; } savedInstanceState.putIntArray(BUNDLE_SELECTIONS + prefix, selections); //remember the collapsed states savedInstanceState.putIntArray(BUNDLE_EXPANDED + prefix, getExpandedItems()); } return savedInstanceState; } /** * we cache the sizes of our adapters so get accesses are faster */ private void cacheSizes() { mAdapterSizes.clear(); int size = 0; //we also have to add this for the first adapter otherwise the floorKey method will return the wrong value if (mAdapters.size() > 0) { mAdapterSizes.put(0, mAdapters.valueAt(0)); } for (IAdapter<Item> adapter : mAdapters.values()) { if (adapter.getAdapterItemCount() > 0) { mAdapterSizes.put(size, adapter); size = size + adapter.getAdapterItemCount(); } } mGlobalSize = size; } //------------------------- //------------------------- //Selection stuff //------------------------- //------------------------- /** * @return a set with the global positions of all selected items */ public Set<Integer> getSelections() { return mSelections; } /** * @return a set with the items which are currently selected */ public Set<Item> getSelectedItems() { Set<Item> items = new HashSet<>(); for (Integer position : getSelections()) { items.add(getItem(position)); } return items; } /** * toggles the selection of the item at the given position * * @param position the global position */ public void toggleSelection(int position) { if (mSelections.contains(position)) { deselect(position); } else { select(position); } } /** * handles the selection and deselects item if multiSelect is disabled * * @param position the global position */ private void handleSelection(View view, Item item, int position) { //if this item is not selectable don't continue if (!item.isSelectable()) { return; } //if we have disabled deselection via click don't continue if (item.isSelected() && !mAllowDeselection) { return; } boolean selected = mSelections.contains(position); if (mSelectWithItemUpdate || view == null) { if (!mMultiSelect) { deselect(); } if (selected) { deselect(position); } else { select(position); } } else { if (!mMultiSelect) { //we have to separately handle deselection here because if we toggle the current item we do not want to deselect this first! Iterator<Integer> entries = mSelections.iterator(); while (entries.hasNext()) { //deselect all but the current one! this is important! Integer pos = entries.next(); if (pos != position) { deselect(pos, entries); } } } //we toggle the state of the view item.withSetSelected(!selected); view.setSelected(!selected); //now we make sure we remember the selection! if (selected) { if (mSelections.contains(position)) { mSelections.remove(position); } } else { mSelections.add(position); } } } /** * selects all items at the positions in the iteratable * * @param positions the global positions to select */ public void select(Iterable<Integer> positions) { for (Integer position : positions) { select(position); } } /** * selects an item and remembers it's position in the selections list * * @param position the global position */ public void select(int position) { select(position, false); } /** * selects an item and remembers it's position in the selections list * * @param position the global position * @param fireEvent true if the onClick listener should be called */ public void select(int position, boolean fireEvent) { Item item = getItem(position); if (item != null) { item.withSetSelected(true); mSelections.add(position); } notifyItemChanged(position); if (mOnClickListener != null && fireEvent) { mOnClickListener.onClick(null, getAdapter(position), item, position); } } /** * deselects all selections */ public void deselect() { deselect(mSelections); } /** * deselects all items at the positions in the iteratable * * @param positions the global positions to deselect */ public void deselect(Iterable<Integer> positions) { Iterator<Integer> entries = positions.iterator(); while (entries.hasNext()) { deselect(entries.next(), entries); } } /** * deselects an item and removes it's position in the selections list * * @param position the global position */ public void deselect(int position) { deselect(position, null); } /** * deselects an item and removes it's position in the selections list * also takes an iterator to remove items from the map * * @param position the global position * @param entries the iterator which is used to deselect all */ private void deselect(int position, Iterator<Integer> entries) { Item item = getItem(position); if (item != null) { item.withSetSelected(false); } if (entries == null) { if (mSelections.contains(position)) { mSelections.remove(position); } } else { entries.remove(); } notifyItemChanged(position); } /** * deletes all current selected items * * @return a list of the IItem elements which were deleted */ public List<Item> deleteAllSelectedItems() { List<Item> deletedItems = new LinkedList<>(); //we have to re-fetch the selections array again and again as the position will change after one item is deleted Set<Integer> selections = getSelections(); while (selections.size() > 0) { Iterator<Integer> iterator = selections.iterator(); int position = iterator.next(); IAdapter adapter = getAdapter(position); if (adapter != null && adapter instanceof IItemAdapter) { deletedItems.add(getItem(position)); ((IItemAdapter) adapter).remove(position); } else { iterator.remove(); } selections = getSelections(); } return deletedItems; } //------------------------- //------------------------- //Expandable stuff //------------------------- //------------------------- /** * returns the expanded items this contains position and the count of items * which are expanded by this position * * @return the expanded items */ public SparseIntArray getExpanded() { return mExpanded; } /** * @return a set with the global positions of all expanded items */ public int[] getExpandedItems() { int[] expandedItems = new int[mExpanded.size()]; int length = mExpanded.size(); for (int i = 0; i < length; i++) { expandedItems[i] = mExpanded.keyAt(i); } return expandedItems; } /** * toggles the expanded state of the given expandable item at the given position * * @param position the global position */ public void toggleExpandable(int position) { if (mExpanded.indexOfKey(position) >= 0) { collapse(position); } else { expand(position); } } /** * collapses all expanded items */ public void collapse() { collapse(true); } /** * collapses all expanded items * * @param notifyItemChanged true if we need to call notifyItemChanged. DEFAULT: false */ public void collapse(boolean notifyItemChanged) { int[] expandedItems = getExpandedItems(); for (int i = expandedItems.length - 1; i >= 0; i--) { collapse(expandedItems[i], notifyItemChanged); } } /** * collapses (closes) the given collapsible item at the given position * * @param position the global position */ public void collapse(int position) { collapse(position, false); } /** * collapses (closes) the given collapsible item at the given position * * @param position the global position * @param notifyItemChanged true if we need to call notifyItemChanged. DEFAULT: false */ public void collapse(int position, boolean notifyItemChanged) { Item item = getItem(position); if (item != null && item instanceof IExpandable) { IExpandable expandable = (IExpandable) item; //as we now know the item we will collapse we can collapse all subitems //if this item is not already collapsed and has sub items we go on if (expandable.isExpanded() && expandable.getSubItems() != null && expandable.getSubItems().size() > 0) { //first we find out how many items were added in total int totalAddedItems = expandable.getSubItems().size(); int length = mExpanded.size(); for (int i = 0; i < length; i++) { if (mExpanded.keyAt(i) > position && mExpanded.keyAt(i) <= position + totalAddedItems) { totalAddedItems = totalAddedItems + mExpanded.get(mExpanded.keyAt(i)); } } //we will deselect starting with the lowest one Iterator<Integer> selectionsIterator = mSelections.iterator(); while (selectionsIterator.hasNext()) { Integer value = selectionsIterator.next(); if (value > position && value <= position + totalAddedItems) { deselect(value, selectionsIterator); } } //now we start to collapse them for (int i = length - 1; i >= 0; i--) { if (mExpanded.keyAt(i) > position && mExpanded.keyAt(i) <= position + totalAddedItems) { //we collapsed those items now we remove update the added items totalAddedItems = totalAddedItems - mExpanded.get(mExpanded.keyAt(i)); //we collapse the item internalCollapse(mExpanded.keyAt(i), notifyItemChanged); } } //we collapse our root element internalCollapse(expandable, position, notifyItemChanged); } } } private void internalCollapse(int position, boolean notifyItemChanged) { Item item = getItem(position); if (item != null && item instanceof IExpandable) { IExpandable expandable = (IExpandable) item; //if this item is not already collapsed and has sub items we go on if (expandable.isExpanded() && expandable.getSubItems() != null && expandable.getSubItems().size() > 0) { internalCollapse(expandable, position, notifyItemChanged); } } } private void internalCollapse(IExpandable expandable, int position, boolean notifyItemChanged) { IAdapter adapter = getAdapter(position); if (adapter != null && adapter instanceof IItemAdapter) { ((IItemAdapter) adapter).removeRange(position + 1, expandable.getSubItems().size()); } //remember that this item is now collapsed again expandable.withIsExpanded(false); //remove the information that this item was opened int indexOfKey = mExpanded.indexOfKey(position); if (indexOfKey >= 0) { mExpanded.removeAt(indexOfKey); } //we need to notify to get the correct drawable if there is one showing the current state if (notifyItemChanged) { notifyItemChanged(position); } } /** * opens the expandable item at the given position * * @param position the global position */ public void expand(int position) { expand(position, false); } /** * opens the expandable item at the given position * * @param position the global position * @param notifyItemChanged true if we need to call notifyItemChanged. DEFAULT: false */ public void expand(int position, boolean notifyItemChanged) { Item item = getItem(position); if (item != null && item instanceof IExpandable) { IExpandable<?, Item> expandable = (IExpandable<?, Item>) item; //if this item is not already expanded and has sub items we go on if (mExpanded.indexOfKey(position) < 0 && expandable.getSubItems() != null && expandable.getSubItems().size() > 0) { IAdapter<Item> adapter = getAdapter(position); if (adapter != null && adapter instanceof IItemAdapter) { ((IItemAdapter<Item>) adapter).add(position + 1, expandable.getSubItems()); } //remember that this item is now opened (not collapsed) expandable.withIsExpanded(true); //we need to notify to get the correct drawable if there is one showing the current state if (notifyItemChanged) { notifyItemChanged(position); } //store it in the list of opened expandable items mExpanded.put(position, expandable.getSubItems() != null ? expandable.getSubItems().size() : 0); } } } //------------------------- //------------------------- //wrap the notify* methods so we can have our required selection adjustment code //------------------------- //------------------------- /** * wraps notifyDataSetChanged */ public void notifyAdapterDataSetChanged() { mSelections.clear(); mExpanded.clear(); cacheSizes(); notifyDataSetChanged(); //we make sure the new items are displayed properly AdapterUtil.handleStates(this, 0, getItemCount() - 1); } /** * wraps notifyItemInserted * * @param position the global position */ public void notifyAdapterItemInserted(int position) { notifyAdapterItemRangeInserted(position, 1); } /** * wraps notifyItemRangeInserted * * @param position the global position * @param itemCount the count of items inserted */ public void notifyAdapterItemRangeInserted(int position, int itemCount) { //we have to update all current stored selection and expandable states in our map mSelections = AdapterUtil.adjustPosition(mSelections, position, Integer.MAX_VALUE, itemCount); mExpanded = AdapterUtil.adjustPosition(mExpanded, position, Integer.MAX_VALUE, itemCount); cacheSizes(); notifyItemRangeInserted(position, itemCount); //we make sure the new items are displayed properly AdapterUtil.handleStates(this, position, position + itemCount - 1); } /** * wraps notifyItemRemoved * * @param position the global position */ public void notifyAdapterItemRemoved(int position) { notifyAdapterItemRangeRemoved(position, 1); } /** * wraps notifyItemRangeRemoved * * @param position the global position * @param itemCount the count of items removed */ public void notifyAdapterItemRangeRemoved(int position, int itemCount) { //we have to update all current stored selection and expandable states in our map mSelections = AdapterUtil.adjustPosition(mSelections, position, Integer.MAX_VALUE, itemCount * (-1)); mExpanded = AdapterUtil.adjustPosition(mExpanded, position, Integer.MAX_VALUE, itemCount * (-1)); cacheSizes(); notifyItemRangeRemoved(position, itemCount); } /** * wraps notifyItemMoved * * @param fromPosition the global fromPosition * @param toPosition the global toPosition */ public void notifyAdapterItemMoved(int fromPosition, int toPosition) { //collapse items we move. just in case :D collapse(fromPosition); collapse(toPosition); if (!mSelections.contains(fromPosition) && mSelections.contains(toPosition)) { mSelections.remove(toPosition); mSelections.add(fromPosition); } else if (mSelections.contains(fromPosition) && !mSelections.contains(toPosition)) { mSelections.remove(fromPosition); mSelections.add(toPosition); } notifyItemMoved(fromPosition, toPosition); } /** * wraps notifyItemChanged * * @param position the global position */ public void notifyAdapterItemChanged(int position) { notifyAdapterItemChanged(position, null); } /** * wraps notifyItemChanged * * @param position the global position * @param payload additional payload */ public void notifyAdapterItemChanged(int position, Object payload) { notifyAdapterItemRangeChanged(position, 1, payload); } /** * wraps notifyItemRangeChanged * * @param position the global position * @param itemCount the count of items changed */ public void notifyAdapterItemRangeChanged(int position, int itemCount) { notifyAdapterItemRangeChanged(position, itemCount, null); } /** * wraps notifyItemRangeChanged * * @param position the global position * @param itemCount the count of items changed * @param payload an additional payload */ public void notifyAdapterItemRangeChanged(int position, int itemCount, Object payload) { for (int i = position; i < position + itemCount; i++) { if (mExpanded.indexOfKey(i) >= 0) { collapse(i); } } if (payload == null) { notifyItemRangeChanged(position, itemCount); } else { notifyItemRangeChanged(position, itemCount, payload); } //we make sure the new items are displayed properly AdapterUtil.handleStates(this, position, position + itemCount - 1); } /** * notifies the fastAdapter about new / removed items within a sub hierarchy * NOTE this currently only works for sub items with only 1 level * * @param position the global position of the parent item */ public void notifyAdapterSubItemsChanged(int position) { Item item = getItem(position); if (item != null && item instanceof IExpandable) { IExpandable expandable = (IExpandable) item; //TODO ALSO CARE ABOUT SUB SUB ... HIRACHIES //first we find out how many items this parent item contains int itemsCount = expandable.getSubItems().size(); //we only need to do something if this item is expanded if (mExpanded.indexOfKey(position) > -1) { int previousCount = mExpanded.get(position); IAdapter adapter = getAdapter(position); if (adapter != null && adapter instanceof IItemAdapter) { ((IItemAdapter) adapter).removeRange(position + 1, previousCount); ((IItemAdapter) adapter).add(position + 1, expandable.getSubItems()); } mExpanded.put(position, itemsCount); } } } //listeners public interface OnTouchListener<Item extends IItem> { /** * the onTouch event of a specific item inside the RecyclerView * * @param v the view we clicked * @param event the touch event * @param adapter the adapter which is responsible for the given item * @param item the IItem which was clicked * @param position the global position * @return return true if the event was consumed, otherwise false */ boolean onTouch(View v, MotionEvent event, IAdapter<Item> adapter, Item item, int position); } public interface OnClickListener<Item extends IItem> { /** * the onClick event of a specific item inside the RecyclerView * * @param v the view we clicked * @param adapter the adapter which is responsible for the given item * @param item the IItem which was clicked * @param position the global position * @return return true if the event was consumed, otherwise false */ boolean onClick(View v, IAdapter<Item> adapter, Item item, int position); } public interface OnLongClickListener<Item extends IItem> { /** * the onLongClick event of a specific item inside the RecyclerView * * @param v the view we clicked * @param adapter the adapter which is responsible for the given item * @param item the IItem which was clicked * @param position the global position * @return return true if the event was consumed, otherwise false */ boolean onLongClick(View v, IAdapter<Item> adapter, Item item, int position); } public interface OnCreateViewHolderListener { /** * is called inside the onCreateViewHolder method and creates the viewHolder based on the provided viewTyp * * @param parent the parent which will host the View * @param viewType the type of the ViewHolder we want to create * @return the generated ViewHolder based on the given viewType */ RecyclerView.ViewHolder onPreCreateViewHolder(ViewGroup parent, int viewType); /** * is called after the viewHolder was created and the default listeners were added * * @param viewHolder the created viewHolder after all listeners were set * @return the viewHolder given as param */ RecyclerView.ViewHolder onPostCreateViewHolder(RecyclerView.ViewHolder viewHolder); } /** * default implementation of the OnCreateViewHolderListener */ public class OnCreateViewHolderListenerImpl implements OnCreateViewHolderListener { /** * is called inside the onCreateViewHolder method and creates the viewHolder based on the provided viewTyp * * @param parent the parent which will host the View * @param viewType the type of the ViewHolder we want to create * @return the generated ViewHolder based on the given viewType */ @Override public RecyclerView.ViewHolder onPreCreateViewHolder(ViewGroup parent, int viewType) { return getTypeInstance(viewType).getViewHolder(parent); } /** * is called after the viewHolder was created and the default listeners were added * * @param viewHolder the created viewHolder after all listeners were set * @return the viewHolder given as param */ @Override public RecyclerView.ViewHolder onPostCreateViewHolder(RecyclerView.ViewHolder viewHolder) { return viewHolder; } } public interface OnBindViewHolderListener { /** * is called in onBindViewHolder to bind the data on the ViewHolder * * @param viewHolder the viewHolder for the type at this position * @param position the position of thsi viewHolder */ void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position); } public class OnBindViewHolderListenerImpl implements OnBindViewHolderListener { /** * is called in onBindViewHolder to bind the data on the ViewHolder * * @param viewHolder the viewHolder for the type at this position * @param position the position of this viewHolder */ @Override public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { getItem(position).bindView(viewHolder); } } /** * an internal class to return the IItem and relativePosition and it's adapter at once. used to save one iteration inside the getInternalItem method */ public static class RelativeInfo<Item extends IItem> { public IAdapter<Item> adapter = null; public Item item = null; public int position = -1; } }
library/src/main/java/com/mikepenz/fastadapter/FastAdapter.java
package com.mikepenz.fastadapter; import android.os.Bundle; import android.support.v4.util.ArrayMap; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.util.SparseIntArray; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import com.mikepenz.fastadapter.utils.AdapterUtil; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.Set; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; /** * Created by mikepenz on 27.12.15. */ public class FastAdapter<Item extends IItem> extends RecyclerView.Adapter<RecyclerView.ViewHolder> { protected static final String BUNDLE_SELECTIONS = "bundle_selections"; protected static final String BUNDLE_EXPANDED = "bundle_expanded"; // we remember all adapters //priority queue... final private ArrayMap<Integer, IAdapter<Item>> mAdapters = new ArrayMap<>(); // we remember all possible types so we can create a new view efficiently final private ArrayMap<Integer, Item> mTypeInstances = new ArrayMap<>(); // cache the sizes of the different adapters so we can access the items more performant final private NavigableMap<Integer, IAdapter<Item>> mAdapterSizes = new TreeMap<>(); // the total size private int mGlobalSize = 0; // if enabled we will select the item via a notifyItemChanged -> will animate with the Animator // you can also use this if you have any custom logic for selections, and do not depend on the "selected" state of the view // note if enabled it will feel a bit slower because it will animate the selection private boolean mSelectWithItemUpdate = false; // if we want multiSelect enabled private boolean mMultiSelect = false; // if we want the multiSelect only on longClick private boolean mSelectOnLongClick = false; // if a user can deselect a selection via click. required if there is always one selected item! private boolean mAllowDeselection = true; // if items are selectable in general private boolean mSelectable = false; // only one expanded section private boolean mOnlyOneExpandedItem = false; // we need to remember all selections to recreate them after orientation change private SortedSet<Integer> mSelections = new TreeSet<>(); // we need to remember all expanded items to recreate them after orientation change private SparseIntArray mExpanded = new SparseIntArray(); // the listeners which can be hooked on an item private OnClickListener<Item> mOnPreClickListener; private OnClickListener<Item> mOnClickListener; private OnLongClickListener<Item> mOnPreLongClickListener; private OnLongClickListener<Item> mOnLongClickListener; private OnTouchListener<Item> mOnTouchListener; //the listeners for onCreateViewHolder or onBindViewHolder private OnCreateViewHolderListener mOnCreateViewHolderListener = new OnCreateViewHolderListenerImpl(); private OnBindViewHolderListener mOnBindViewHolderListener = new OnBindViewHolderListenerImpl(); /** * default CTOR */ public FastAdapter() { setHasStableIds(true); } /** * Define the OnClickListener which will be used for a single item * * @param onClickListener the OnClickListener which will be used for a single item * @return this */ public FastAdapter<Item> withOnClickListener(OnClickListener<Item> onClickListener) { this.mOnClickListener = onClickListener; return this; } /** * Define the OnPreClickListener which will be used for a single item and is called after all internal methods are done * * @param onPreClickListener the OnPreClickListener which will be called after a single item was clicked and all internal methods are done * @return this */ public FastAdapter<Item> withOnPreClickListener(OnClickListener<Item> onPreClickListener) { this.mOnPreClickListener = onPreClickListener; return this; } /** * Define the OnLongClickListener which will be used for a single item * * @param onLongClickListener the OnLongClickListener which will be used for a single item * @return this */ public FastAdapter<Item> withOnLongClickListener(OnLongClickListener<Item> onLongClickListener) { this.mOnLongClickListener = onLongClickListener; return this; } /** * Define the OnLongClickListener which will be used for a single item and is called after all internal methods are done * * @param onPreLongClickListener the OnLongClickListener which will be called after a single item was clicked and all internal methods are done * @return this */ public FastAdapter<Item> withOnPreLongClickListener(OnLongClickListener<Item> onPreLongClickListener) { this.mOnPreLongClickListener = onPreLongClickListener; return this; } /** * Define the TouchListener which will be used for a single item * * @param onTouchListener the TouchListener which will be used for a single item * @return this */ public FastAdapter<Item> withOnTouchListener(OnTouchListener<Item> onTouchListener) { this.mOnTouchListener = onTouchListener; return this; } /** * allows you to set a custom OnCreateViewHolderListener which will be used before and after the ViewHolder is created * You may check the OnCreateViewHolderListenerImpl for the default behavior * * @param onCreateViewHolderListener the OnCreateViewHolderListener (you may use the OnCreateViewHolderListenerImpl) */ public FastAdapter<Item> withOnCreateViewHolderListener(OnCreateViewHolderListener onCreateViewHolderListener) { this.mOnCreateViewHolderListener = onCreateViewHolderListener; return this; } /** * allows you to set an custom OnBindViewHolderListener which is used to bind the view. This will overwrite the libraries behavior. * You may check the OnBindViewHolderListenerImpl for the default behavior * * @param onBindViewHolderListener the OnBindViewHolderListener */ public FastAdapter<Item> withOnBindViewHolderListener(OnBindViewHolderListener onBindViewHolderListener) { this.mOnBindViewHolderListener = onBindViewHolderListener; return this; } /** * select between the different selection behaviors. * there are now 2 different variants of selection. you can toggle this via `withSelectWithItemUpdate(boolean)` (where false == default - variant 1) * 1.) direct selection via the view "selected" state, we also make sure we do not animate here so no notifyItemChanged is called if we repeatly press the same item * 2.) we select the items via a notifyItemChanged. this will allow custom selected logics within your views (isSelected() - do something...) and it will also animate the change via the provided itemAnimator. because of the animation of the itemAnimator the selection will have a small delay (time of animating) * * @param selectWithItemUpdate true if notifyItemChanged should be called upon select * @return this */ public FastAdapter<Item> withSelectWithItemUpdate(boolean selectWithItemUpdate) { this.mSelectWithItemUpdate = selectWithItemUpdate; return this; } /** * Enable this if you want multiSelection possible in the list * * @param multiSelect true to enable multiSelect * @return this */ public FastAdapter<Item> withMultiSelect(boolean multiSelect) { mMultiSelect = multiSelect; return this; } /** * Disable this if you want the selection on a single tap * * @param selectOnLongClick false to do select via single click * @return this */ public FastAdapter<Item> withSelectOnLongClick(boolean selectOnLongClick) { mSelectOnLongClick = selectOnLongClick; return this; } /** * If false, a user can't deselect an item via click (you can still do this programmatically) * * @param allowDeselection true if a user can deselect an already selected item via click * @return this */ public FastAdapter<Item> withAllowDeselection(boolean allowDeselection) { this.mAllowDeselection = allowDeselection; return this; } /** * set if no item is selectable * * @param selectable true if items are selectable * @return this */ public FastAdapter<Item> withSelectable(boolean selectable) { this.mSelectable = selectable; return this; } /** * @return if items are selectable */ public boolean isSelectable() { return mSelectable; } /** * set if there should only be one opened expandable item * DEFAULT: false * * @param mOnlyOneExpandedItem true if there should be only one expanded, expandable item in the list * @return this */ public FastAdapter<Item> withOnlyOneExpandedItem(boolean mOnlyOneExpandedItem) { this.mOnlyOneExpandedItem = mOnlyOneExpandedItem; return this; } /** * @return if there should be only one expanded, expandable item in the list */ public boolean isOnlyOneExpandedItem() { return mOnlyOneExpandedItem; } /** * re-selects all elements stored in the savedInstanceState * IMPORTANT! Call this method only after all items where added to the adapters again. Otherwise it may select wrong items! * * @param savedInstanceState If the activity is being re-initialized after * previously being shut down then this Bundle contains the data it most * recently supplied in Note: Otherwise it is null. * @return this */ public FastAdapter<Item> withSavedInstanceState(Bundle savedInstanceState) { return withSavedInstanceState(savedInstanceState, ""); } /** * re-selects all elements stored in the savedInstanceState * IMPORTANT! Call this method only after all items where added to the adapters again. Otherwise it may select wrong items! * * @param savedInstanceState If the activity is being re-initialized after * previously being shut down then this Bundle contains the data it most * recently supplied in Note: Otherwise it is null. * @param prefix a prefix added to the savedInstance key so we can store multiple states * @return this */ public FastAdapter<Item> withSavedInstanceState(Bundle savedInstanceState, String prefix) { if (savedInstanceState != null) { //make sure already done selections are removed deselect(); //first restore opened collasable items, as otherwise may not all selections could be restored int[] expandedItems = savedInstanceState.getIntArray(BUNDLE_EXPANDED + prefix); if (expandedItems != null) { for (Integer expandedItem : expandedItems) { expand(expandedItem); } } //restore the selections int[] selections = savedInstanceState.getIntArray(BUNDLE_SELECTIONS + prefix); if (selections != null) { for (Integer selection : selections) { select(selection); } } } return this; } /** * registers an AbstractAdapter which will be hooked into the adapter chain * * @param adapter an adapter which extends the AbstractAdapter */ public <A extends AbstractAdapter<Item>> void registerAdapter(A adapter) { if (!mAdapters.containsKey(adapter.getOrder())) { mAdapters.put(adapter.getOrder(), adapter); cacheSizes(); } } /** * register a new type into the TypeInstances to be able to efficiently create thew ViewHolders * * @param item an IItem which will be shown in the list */ public void registerTypeInstance(Item item) { if (!mTypeInstances.containsKey(item.getType())) { mTypeInstances.put(item.getType(), item); } } /** * gets the TypeInstance remembered within the FastAdapter for an item * * @param type the int type of the item * @return the Item typeInstance */ public Item getTypeInstance(int type) { return mTypeInstances.get(type); } /** * Creates the ViewHolder by the viewType * * @param parent the parent view (the RecyclerView) * @param viewType the current viewType which is bound * @return the ViewHolder with the bound data */ @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { final RecyclerView.ViewHolder holder = mOnCreateViewHolderListener.onPreCreateViewHolder(parent, viewType); //handle click behavior holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int pos = holder.getAdapterPosition(); if (pos != RecyclerView.NO_POSITION) { boolean consumed = false; RelativeInfo<Item> relativeInfo = getRelativeInfo(pos); Item item = relativeInfo.item; if (item != null && item.isEnabled()) { //on the very first we call the click listener from the item itself (if defined) if (item instanceof IClickable && ((IClickable) item).getOnPreItemClickListener() != null) { consumed = ((IClickable<Item>) item).getOnPreItemClickListener().onClick(v, relativeInfo.adapter, item, pos); } //first call the onPreClickListener which would allow to prevent executing of any following code, including selection if (!consumed && mOnPreClickListener != null) { consumed = mOnPreClickListener.onClick(v, relativeInfo.adapter, item, pos); } //if this is a expandable item :D if (!consumed && item instanceof IExpandable) { if (((IExpandable) item).getSubItems() != null) { toggleExpandable(pos); } } //if there should be only one expanded item we want to collapse all the others but the current one if (mOnlyOneExpandedItem) { int[] expandedItems = getExpandedItems(); for (int i = expandedItems.length - 1; i >= 0; i--) { if (expandedItems[i] != pos) { collapse(expandedItems[i], true); } } } //handle the selection if the event was not yet consumed, and we are allowed to select an item (only occurs when we select with long click only) if (!consumed && !mSelectOnLongClick && mSelectable) { handleSelection(v, item, pos); } //before calling the global adapter onClick listener call the item specific onClickListener if (item instanceof IClickable && ((IClickable) item).getOnItemClickListener() != null) { consumed = ((IClickable<Item>) item).getOnItemClickListener().onClick(v, relativeInfo.adapter, item, pos); } //call the normal click listener after selection was handlded if (!consumed && mOnClickListener != null) { mOnClickListener.onClick(v, relativeInfo.adapter, item, pos); } } } } }); //handle long click behavior holder.itemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { int pos = holder.getAdapterPosition(); if (pos != RecyclerView.NO_POSITION) { boolean consumed = false; RelativeInfo<Item> relativeInfo = getRelativeInfo(pos); if (relativeInfo.item != null && relativeInfo.item.isEnabled()) { //first call the OnPreLongClickListener which would allow to prevent executing of any following code, including selection if (mOnPreLongClickListener != null) { consumed = mOnPreLongClickListener.onLongClick(v, relativeInfo.adapter, relativeInfo.item, pos); } //now handle the selection if we are in multiSelect mode and allow selecting on longClick if (!consumed && mSelectOnLongClick && mSelectable) { handleSelection(v, relativeInfo.item, pos); } //call the normal long click listener after selection was handled if (mOnLongClickListener != null) { consumed = mOnLongClickListener.onLongClick(v, relativeInfo.adapter, relativeInfo.item, pos); } } return consumed; } return false; } }); //handle touch behavior holder.itemView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (mOnTouchListener != null) { int pos = holder.getAdapterPosition(); if (pos != RecyclerView.NO_POSITION) { RelativeInfo<Item> relativeInfo = getRelativeInfo(pos); return mOnTouchListener.onTouch(v, event, relativeInfo.adapter, relativeInfo.item, pos); } } return false; } }); return mOnCreateViewHolderListener.onPostCreateViewHolder(holder); } /** * Binds the data to the created ViewHolder and sets the listeners to the holder.itemView * * @param holder the viewHolder we bind the data on * @param position the global position */ @Override public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) { mOnBindViewHolderListener.onBindViewHolder(holder, position); } /** * Searches for the given item and calculates it's global position * * @param item the item which is searched for * @return the global position, or -1 if not found */ public int getPosition(Item item) { if (item.getIdentifier() == -1) { Log.e("FastAdapter", "You have to define an identifier for your item to retrieve the position via this method"); return -1; } int position = 0; int length = mAdapters.size(); for (int i = 0; i < length; i++) { IAdapter<Item> adapter = mAdapters.valueAt(i); if (adapter.getOrder() < 0) { continue; } int relativePosition = adapter.getAdapterPosition(item); if (relativePosition != -1) { return position + relativePosition; } position = adapter.getAdapterItemCount(); } return -1; } /** * gets the IItem by a position, from all registered adapters * * @param position the global position * @return the found IItem or null */ public Item getItem(int position) { //if we are out of range just return null if (position < 0 || position >= mGlobalSize) { return null; } //now get the adapter which is responsible for the given position Map.Entry<Integer, IAdapter<Item>> entry = mAdapterSizes.floorEntry(position); return entry.getValue().getAdapterItem(position - entry.getKey()); } /** * Internal method to get the Item as ItemHolder which comes with the relative position within it's adapter * Finds the responsible adapter for the given position * * @param position the global position * @return the adapter which is responsible for this position */ public RelativeInfo<Item> getRelativeInfo(int position) { if (position < 0) { return new RelativeInfo<>(); } RelativeInfo<Item> relativeInfo = new RelativeInfo<>(); Map.Entry<Integer, IAdapter<Item>> entry = mAdapterSizes.floorEntry(position); if (entry != null) { relativeInfo.item = entry.getValue().getAdapterItem(position - entry.getKey()); relativeInfo.adapter = entry.getValue(); relativeInfo.position = position; } return relativeInfo; } /** * Gets the adapter for the given position * * @param position the global position * @return the adapter responsible for this global position */ public IAdapter<Item> getAdapter(int position) { //if we are out of range just return null if (position < 0 || position >= mGlobalSize) { return null; } //now get the adapter which is responsible for the given position return mAdapterSizes.floorEntry(position).getValue(); } /** * finds the int ItemViewType from the IItem which exists at the given position * * @param position the global position * @return the viewType for this position */ @Override public int getItemViewType(int position) { return getItem(position).getType(); } /** * finds the int ItemId from the IItem which exists at the given position * * @param position the global position * @return the itemId for this position */ @Override public long getItemId(int position) { return getItem(position).getIdentifier(); } /** * calculates the total ItemCount over all registered adapters * * @return the global count */ public int getItemCount() { return mGlobalSize; } /** * calculates the item count up to a given (excluding this) order number * * @param order the number up to which the items are counted * @return the total count of items up to the adapter order */ public int getPreItemCountByOrder(int order) { //if we are empty just return 0 count if (mGlobalSize == 0) { return 0; } int size = 0; //count the number of items before the adapter with the given order for (IAdapter<Item> adapter : mAdapters.values()) { if (adapter.getOrder() == order) { return size; } else { size = size + adapter.getAdapterItemCount(); } } //get the count of items which are before this order return size; } /** * calculates the item count up to a given (excluding this) adapter (defined by the global position of the item) * * @param position the global position of an adapter item * @return the total count of items up to the adapter which holds the given position */ public int getPreItemCount(int position) { //if we are empty just return 0 count if (mGlobalSize == 0) { return 0; } //get the count of items which are before this order return mAdapterSizes.floorKey(position); } /** * calculates the count of expandable items before a given position * * @param from the global start position you should pass here the count of items of the previous adapters (or 0 if you want to start from the beginning) * @param position the global position * @return the count of expandable items before a given position */ public int getExpandedItemsCount(int from, int position) { int totalAddedItems = 0; int length = mExpanded.size(); for (int i = 0; i < length; i++) { //now we count the amount of expanded items within our range we check if (mExpanded.keyAt(i) >= from && mExpanded.keyAt(i) < position) { totalAddedItems = totalAddedItems + mExpanded.get(mExpanded.keyAt(i)); } else if (mExpanded.keyAt(i) >= position) { //we do not care about all expanded items which are outside our range break; } } return totalAddedItems; } /** * add the values to the bundle for saveInstanceState * * @param savedInstanceState If the activity is being re-initialized after * previously being shut down then this Bundle contains the data it most * recently supplied in Note: Otherwise it is null. * @return the passed bundle with the newly added data */ public Bundle saveInstanceState(Bundle savedInstanceState) { return saveInstanceState(savedInstanceState, ""); } /** * add the values to the bundle for saveInstanceState * * @param savedInstanceState If the activity is being re-initialized after * previously being shut down then this Bundle contains the data it most * recently supplied in Note: Otherwise it is null. * @param prefix a prefix added to the savedInstance key so we can store multiple states * @return the passed bundle with the newly added data */ public Bundle saveInstanceState(Bundle savedInstanceState, String prefix) { if (savedInstanceState != null) { //remember the selections int[] selections = new int[mSelections.size()]; int index = 0; for (Integer selection : mSelections) { selections[index] = selection; index++; } savedInstanceState.putIntArray(BUNDLE_SELECTIONS + prefix, selections); //remember the collapsed states savedInstanceState.putIntArray(BUNDLE_EXPANDED + prefix, getExpandedItems()); } return savedInstanceState; } /** * we cache the sizes of our adapters so get accesses are faster */ private void cacheSizes() { mAdapterSizes.clear(); int size = 0; //we also have to add this for the first adapter otherwise the floorKey method will return the wrong value if (mAdapters.size() > 0) { mAdapterSizes.put(0, mAdapters.valueAt(0)); } for (IAdapter<Item> adapter : mAdapters.values()) { if (adapter.getAdapterItemCount() > 0) { mAdapterSizes.put(size, adapter); size = size + adapter.getAdapterItemCount(); } } mGlobalSize = size; } //------------------------- //------------------------- //Selection stuff //------------------------- //------------------------- /** * @return a set with the global positions of all selected items */ public Set<Integer> getSelections() { return mSelections; } /** * @return a set with the items which are currently selected */ public Set<Item> getSelectedItems() { Set<Item> items = new HashSet<>(); for (Integer position : getSelections()) { items.add(getItem(position)); } return items; } /** * toggles the selection of the item at the given position * * @param position the global position */ public void toggleSelection(int position) { if (mSelections.contains(position)) { deselect(position); } else { select(position); } } /** * handles the selection and deselects item if multiSelect is disabled * * @param position the global position */ private void handleSelection(View view, Item item, int position) { //if this item is not selectable don't continue if (!item.isSelectable()) { return; } //if we have disabled deselection via click don't continue if (item.isSelected() && !mAllowDeselection) { return; } boolean selected = mSelections.contains(position); if (mSelectWithItemUpdate || view == null) { if (!mMultiSelect) { deselect(); } if (selected) { deselect(position); } else { select(position); } } else { if (!mMultiSelect) { //we have to separately handle deselection here because if we toggle the current item we do not want to deselect this first! Iterator<Integer> entries = mSelections.iterator(); while (entries.hasNext()) { //deselect all but the current one! this is important! Integer pos = entries.next(); if (pos != position) { deselect(pos, entries); } } } //we toggle the state of the view item.withSetSelected(!selected); view.setSelected(!selected); //now we make sure we remember the selection! if (selected) { if (mSelections.contains(position)) { mSelections.remove(position); } } else { mSelections.add(position); } } } /** * selects all items at the positions in the iteratable * * @param positions the global positions to select */ public void select(Iterable<Integer> positions) { for (Integer position : positions) { select(position); } } /** * selects an item and remembers it's position in the selections list * * @param position the global position */ public void select(int position) { select(position, false); } /** * selects an item and remembers it's position in the selections list * * @param position the global position * @param fireEvent true if the onClick listener should be called */ public void select(int position, boolean fireEvent) { Item item = getItem(position); if (item != null) { item.withSetSelected(true); mSelections.add(position); } notifyItemChanged(position); if (mOnClickListener != null && fireEvent) { mOnClickListener.onClick(null, getAdapter(position), item, position); } } /** * deselects all selections */ public void deselect() { deselect(mSelections); } /** * deselects all items at the positions in the iteratable * * @param positions the global positions to deselect */ public void deselect(Iterable<Integer> positions) { Iterator<Integer> entries = positions.iterator(); while (entries.hasNext()) { deselect(entries.next(), entries); } } /** * deselects an item and removes it's position in the selections list * * @param position the global position */ public void deselect(int position) { deselect(position, null); } /** * deselects an item and removes it's position in the selections list * also takes an iterator to remove items from the map * * @param position the global position * @param entries the iterator which is used to deselect all */ private void deselect(int position, Iterator<Integer> entries) { Item item = getItem(position); if (item != null) { item.withSetSelected(false); } if (entries == null) { if (mSelections.contains(position)) { mSelections.remove(position); } } else { entries.remove(); } notifyItemChanged(position); } /** * deletes all current selected items * * @return a list of the IItem elements which were deleted */ public List<Item> deleteAllSelectedItems() { List<Item> deletedItems = new LinkedList<>(); //we have to re-fetch the selections array again and again as the position will change after one item is deleted Set<Integer> selections = getSelections(); while (selections.size() > 0) { Iterator<Integer> iterator = selections.iterator(); int position = iterator.next(); IAdapter adapter = getAdapter(position); if (adapter != null && adapter instanceof IItemAdapter) { deletedItems.add(getItem(position)); ((IItemAdapter) adapter).remove(position); } else { iterator.remove(); } selections = getSelections(); } return deletedItems; } //------------------------- //------------------------- //Expandable stuff //------------------------- //------------------------- /** * returns the expanded items this contains position and the count of items * which are expanded by this position * * @return the expanded items */ public SparseIntArray getExpanded() { return mExpanded; } /** * @return a set with the global positions of all expanded items */ public int[] getExpandedItems() { int[] expandedItems = new int[mExpanded.size()]; int length = mExpanded.size(); for (int i = 0; i < length; i++) { expandedItems[i] = mExpanded.keyAt(i); } return expandedItems; } /** * toggles the expanded state of the given expandable item at the given position * * @param position the global position */ public void toggleExpandable(int position) { if (mExpanded.indexOfKey(position) >= 0) { collapse(position); } else { expand(position); } } /** * collapses all expanded items */ public void collapse() { collapse(true); } /** * collapses all expanded items * * @param notifyItemChanged true if we need to call notifyItemChanged. DEFAULT: false */ public void collapse(boolean notifyItemChanged) { int[] expandedItems = getExpandedItems(); for (int i = expandedItems.length - 1; i >= 0; i--) { collapse(expandedItems[i], notifyItemChanged); } } /** * collapses (closes) the given collapsible item at the given position * * @param position the global position */ public void collapse(int position) { collapse(position, false); } /** * collapses (closes) the given collapsible item at the given position * * @param position the global position * @param notifyItemChanged true if we need to call notifyItemChanged. DEFAULT: false */ public void collapse(int position, boolean notifyItemChanged) { Item item = getItem(position); if (item != null && item instanceof IExpandable) { IExpandable expandable = (IExpandable) item; //as we now know the item we will collapse we can collapse all subitems //if this item is not already collapsed and has sub items we go on if (expandable.isExpanded() && expandable.getSubItems() != null && expandable.getSubItems().size() > 0) { //first we find out how many items were added in total int totalAddedItems = expandable.getSubItems().size(); int length = mExpanded.size(); for (int i = 0; i < length; i++) { if (mExpanded.keyAt(i) > position && mExpanded.keyAt(i) <= position + totalAddedItems) { totalAddedItems = totalAddedItems + mExpanded.get(mExpanded.keyAt(i)); } } //we will deselect starting with the lowest one for (Integer value : mSelections) { if (value > position && value <= position + totalAddedItems) { deselect(value); } } //now we start to collapse them for (int i = length - 1; i >= 0; i--) { if (mExpanded.keyAt(i) > position && mExpanded.keyAt(i) <= position + totalAddedItems) { //we collapsed those items now we remove update the added items totalAddedItems = totalAddedItems - mExpanded.get(mExpanded.keyAt(i)); //we collapse the item internalCollapse(mExpanded.keyAt(i), notifyItemChanged); } } //we collapse our root element internalCollapse(expandable, position, notifyItemChanged); } } } private void internalCollapse(int position, boolean notifyItemChanged) { Item item = getItem(position); if (item != null && item instanceof IExpandable) { IExpandable expandable = (IExpandable) item; //if this item is not already collapsed and has sub items we go on if (expandable.isExpanded() && expandable.getSubItems() != null && expandable.getSubItems().size() > 0) { internalCollapse(expandable, position, notifyItemChanged); } } } private void internalCollapse(IExpandable expandable, int position, boolean notifyItemChanged) { IAdapter adapter = getAdapter(position); if (adapter != null && adapter instanceof IItemAdapter) { ((IItemAdapter) adapter).removeRange(position + 1, expandable.getSubItems().size()); } //remember that this item is now collapsed again expandable.withIsExpanded(false); //remove the information that this item was opened int indexOfKey = mExpanded.indexOfKey(position); if (indexOfKey >= 0) { mExpanded.removeAt(indexOfKey); } //we need to notify to get the correct drawable if there is one showing the current state if (notifyItemChanged) { notifyItemChanged(position); } } /** * opens the expandable item at the given position * * @param position the global position */ public void expand(int position) { expand(position, false); } /** * opens the expandable item at the given position * * @param position the global position * @param notifyItemChanged true if we need to call notifyItemChanged. DEFAULT: false */ public void expand(int position, boolean notifyItemChanged) { Item item = getItem(position); if (item != null && item instanceof IExpandable) { IExpandable<?, Item> expandable = (IExpandable<?, Item>) item; //if this item is not already expanded and has sub items we go on if (mExpanded.indexOfKey(position) < 0 && expandable.getSubItems() != null && expandable.getSubItems().size() > 0) { IAdapter<Item> adapter = getAdapter(position); if (adapter != null && adapter instanceof IItemAdapter) { ((IItemAdapter<Item>) adapter).add(position + 1, expandable.getSubItems()); } //remember that this item is now opened (not collapsed) expandable.withIsExpanded(true); //we need to notify to get the correct drawable if there is one showing the current state if (notifyItemChanged) { notifyItemChanged(position); } //store it in the list of opened expandable items mExpanded.put(position, expandable.getSubItems() != null ? expandable.getSubItems().size() : 0); } } } //------------------------- //------------------------- //wrap the notify* methods so we can have our required selection adjustment code //------------------------- //------------------------- /** * wraps notifyDataSetChanged */ public void notifyAdapterDataSetChanged() { mSelections.clear(); mExpanded.clear(); cacheSizes(); notifyDataSetChanged(); //we make sure the new items are displayed properly AdapterUtil.handleStates(this, 0, getItemCount() - 1); } /** * wraps notifyItemInserted * * @param position the global position */ public void notifyAdapterItemInserted(int position) { notifyAdapterItemRangeInserted(position, 1); } /** * wraps notifyItemRangeInserted * * @param position the global position * @param itemCount the count of items inserted */ public void notifyAdapterItemRangeInserted(int position, int itemCount) { //we have to update all current stored selection and expandable states in our map mSelections = AdapterUtil.adjustPosition(mSelections, position, Integer.MAX_VALUE, itemCount); mExpanded = AdapterUtil.adjustPosition(mExpanded, position, Integer.MAX_VALUE, itemCount); cacheSizes(); notifyItemRangeInserted(position, itemCount); //we make sure the new items are displayed properly AdapterUtil.handleStates(this, position, position + itemCount - 1); } /** * wraps notifyItemRemoved * * @param position the global position */ public void notifyAdapterItemRemoved(int position) { notifyAdapterItemRangeRemoved(position, 1); } /** * wraps notifyItemRangeRemoved * * @param position the global position * @param itemCount the count of items removed */ public void notifyAdapterItemRangeRemoved(int position, int itemCount) { //we have to update all current stored selection and expandable states in our map mSelections = AdapterUtil.adjustPosition(mSelections, position, Integer.MAX_VALUE, itemCount * (-1)); mExpanded = AdapterUtil.adjustPosition(mExpanded, position, Integer.MAX_VALUE, itemCount * (-1)); cacheSizes(); notifyItemRangeRemoved(position, itemCount); } /** * wraps notifyItemMoved * * @param fromPosition the global fromPosition * @param toPosition the global toPosition */ public void notifyAdapterItemMoved(int fromPosition, int toPosition) { //collapse items we move. just in case :D collapse(fromPosition); collapse(toPosition); if (!mSelections.contains(fromPosition) && mSelections.contains(toPosition)) { mSelections.remove(toPosition); mSelections.add(fromPosition); } else if (mSelections.contains(fromPosition) && !mSelections.contains(toPosition)) { mSelections.remove(fromPosition); mSelections.add(toPosition); } notifyItemMoved(fromPosition, toPosition); } /** * wraps notifyItemChanged * * @param position the global position */ public void notifyAdapterItemChanged(int position) { notifyAdapterItemChanged(position, null); } /** * wraps notifyItemChanged * * @param position the global position * @param payload additional payload */ public void notifyAdapterItemChanged(int position, Object payload) { notifyAdapterItemRangeChanged(position, 1, payload); } /** * wraps notifyItemRangeChanged * * @param position the global position * @param itemCount the count of items changed */ public void notifyAdapterItemRangeChanged(int position, int itemCount) { notifyAdapterItemRangeChanged(position, itemCount, null); } /** * wraps notifyItemRangeChanged * * @param position the global position * @param itemCount the count of items changed * @param payload an additional payload */ public void notifyAdapterItemRangeChanged(int position, int itemCount, Object payload) { for (int i = position; i < position + itemCount; i++) { if (mExpanded.indexOfKey(i) >= 0) { collapse(i); } } if (payload == null) { notifyItemRangeChanged(position, itemCount); } else { notifyItemRangeChanged(position, itemCount, payload); } //we make sure the new items are displayed properly AdapterUtil.handleStates(this, position, position + itemCount - 1); } /** * notifies the fastAdapter about new / removed items within a sub hierarchy * NOTE this currently only works for sub items with only 1 level * * @param position the global position of the parent item */ public void notifyAdapterSubItemsChanged(int position) { Item item = getItem(position); if (item != null && item instanceof IExpandable) { IExpandable expandable = (IExpandable) item; //TODO ALSO CARE ABOUT SUB SUB ... HIRACHIES //first we find out how many items this parent item contains int itemsCount = expandable.getSubItems().size(); //we only need to do something if this item is expanded if (mExpanded.indexOfKey(position) > -1) { int previousCount = mExpanded.get(position); IAdapter adapter = getAdapter(position); if (adapter != null && adapter instanceof IItemAdapter) { ((IItemAdapter) adapter).removeRange(position + 1, previousCount); ((IItemAdapter) adapter).add(position + 1, expandable.getSubItems()); } mExpanded.put(position, itemsCount); } } } //listeners public interface OnTouchListener<Item extends IItem> { /** * the onTouch event of a specific item inside the RecyclerView * * @param v the view we clicked * @param event the touch event * @param adapter the adapter which is responsible for the given item * @param item the IItem which was clicked * @param position the global position * @return return true if the event was consumed, otherwise false */ boolean onTouch(View v, MotionEvent event, IAdapter<Item> adapter, Item item, int position); } public interface OnClickListener<Item extends IItem> { /** * the onClick event of a specific item inside the RecyclerView * * @param v the view we clicked * @param adapter the adapter which is responsible for the given item * @param item the IItem which was clicked * @param position the global position * @return return true if the event was consumed, otherwise false */ boolean onClick(View v, IAdapter<Item> adapter, Item item, int position); } public interface OnLongClickListener<Item extends IItem> { /** * the onLongClick event of a specific item inside the RecyclerView * * @param v the view we clicked * @param adapter the adapter which is responsible for the given item * @param item the IItem which was clicked * @param position the global position * @return return true if the event was consumed, otherwise false */ boolean onLongClick(View v, IAdapter<Item> adapter, Item item, int position); } public interface OnCreateViewHolderListener { /** * is called inside the onCreateViewHolder method and creates the viewHolder based on the provided viewTyp * * @param parent the parent which will host the View * @param viewType the type of the ViewHolder we want to create * @return the generated ViewHolder based on the given viewType */ RecyclerView.ViewHolder onPreCreateViewHolder(ViewGroup parent, int viewType); /** * is called after the viewHolder was created and the default listeners were added * * @param viewHolder the created viewHolder after all listeners were set * @return the viewHolder given as param */ RecyclerView.ViewHolder onPostCreateViewHolder(RecyclerView.ViewHolder viewHolder); } /** * default implementation of the OnCreateViewHolderListener */ public class OnCreateViewHolderListenerImpl implements OnCreateViewHolderListener { /** * is called inside the onCreateViewHolder method and creates the viewHolder based on the provided viewTyp * * @param parent the parent which will host the View * @param viewType the type of the ViewHolder we want to create * @return the generated ViewHolder based on the given viewType */ @Override public RecyclerView.ViewHolder onPreCreateViewHolder(ViewGroup parent, int viewType) { return getTypeInstance(viewType).getViewHolder(parent); } /** * is called after the viewHolder was created and the default listeners were added * * @param viewHolder the created viewHolder after all listeners were set * @return the viewHolder given as param */ @Override public RecyclerView.ViewHolder onPostCreateViewHolder(RecyclerView.ViewHolder viewHolder) { return viewHolder; } } public interface OnBindViewHolderListener { /** * is called in onBindViewHolder to bind the data on the ViewHolder * * @param viewHolder the viewHolder for the type at this position * @param position the position of thsi viewHolder */ void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position); } public class OnBindViewHolderListenerImpl implements OnBindViewHolderListener { /** * is called in onBindViewHolder to bind the data on the ViewHolder * * @param viewHolder the viewHolder for the type at this position * @param position the position of this viewHolder */ @Override public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { getItem(position).bindView(viewHolder); } } /** * an internal class to return the IItem and relativePosition and it's adapter at once. used to save one iteration inside the getInternalItem method */ public static class RelativeInfo<Item extends IItem> { public IAdapter<Item> adapter = null; public Item item = null; public int position = -1; } }
* fix ConcurrentModificationException in the collapse function * FIX #118
library/src/main/java/com/mikepenz/fastadapter/FastAdapter.java
* fix ConcurrentModificationException in the collapse function * FIX #118
<ide><path>ibrary/src/main/java/com/mikepenz/fastadapter/FastAdapter.java <ide> } <ide> <ide> //we will deselect starting with the lowest one <del> for (Integer value : mSelections) { <add> Iterator<Integer> selectionsIterator = mSelections.iterator(); <add> while (selectionsIterator.hasNext()) { <add> Integer value = selectionsIterator.next(); <ide> if (value > position && value <= position + totalAddedItems) { <del> deselect(value); <add> deselect(value, selectionsIterator); <ide> } <ide> } <ide>
Java
apache-2.0
9023631bfd2e7db50c3f62c00b61af403e4f3733
0
LogisticsImpactModel/LIMO,LogisticsImpactModel/LIMO,LogisticsImpactModel/LIMO
/* * 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 nl.fontys.sofa.limo.domain.component; import java.awt.image.BufferedImage; import java.awt.image.DataBufferByte; import java.io.File; import java.io.IOException; import java.util.Arrays; import javax.imageio.ImageIO; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import org.openide.util.Exceptions; /** * * @author Ben */ public class IconTest { Icon icon; String location = "testing_src/ic.png"; public IconTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { icon = new Icon();//icon w/ empty byteArray } @After public void tearDown() { icon = null; } /** * Test of getData method, of class Icon. */ @Test public void testGetData() { System.out.println("getData"); } /** * Test of setData method, of class Icon. */ @Test public void testSetData() { System.out.println("setData"); try { BufferedImage inputImg = ImageIO.read(new File(this.location)); assertTrue("Input img must have height>0 but has not",inputImg.getHeight()>0); byte[] inputImageBytes = ((DataBufferByte) inputImg.getData().getDataBuffer()).getData(); icon.setData(inputImageBytes); BufferedImage outputImg = icon.getImage(); //TODO: matthias: setData and afterwards retrieving img by calling getImage does not work //assertTrue(outputImg.getHeight()>0); //byte[] outputImageBytes = ((DataBufferByte) outputImg.getData().getDataBuffer()).getData();//using Icon class method getImage //Assert.assertArrayEquals("Input and output image byte arrays should match but do not",inputImageBytes,outputImageBytes); } catch (IOException ex) { fail("Could not locate image"); } } /** * Test of getImage method, of class Icon. */ @Test public void testGetImage() { System.out.println("getImage"); testSetImage_String();//set img using other test BufferedImage actualImg = icon.getImage(); byte[] actualImageBytes = ((DataBufferByte) actualImg.getData().getDataBuffer()).getData();//using Icon class method getImage BufferedImage expectedImg; try { expectedImg = ImageIO.read(new File(this.location)); byte[] expectedImageBytes = ((DataBufferByte) expectedImg.getData().getDataBuffer()).getData(); assertTrue("Actual image should have a dimension higher than 0",actualImg.getHeight()>0); System.out.println("Actual img height: "+actualImg); Assert.assertArrayEquals("ByteArrays for actual and expected images should be equal but are not",expectedImageBytes,actualImageBytes); } catch (IOException e) { fail("Could not locate image at "+ this.location); } } /** * Test of setImage method, of class Icon. */ @Test public void testSetImage_BufferedImage() { System.out.println("setImage"); try { BufferedImage inputImg = ImageIO.read(new File(this.location)); byte[] inputImageBytes = ((DataBufferByte) inputImg.getData().getDataBuffer()).getData(); icon.setImage(inputImg); BufferedImage outputImg = icon.getImage(); byte[] outputImageBytes = ((DataBufferByte) outputImg.getData().getDataBuffer()).getData(); Assert.assertArrayEquals("Byte arrays should be equal",inputImageBytes,outputImageBytes); assertTrue("Input img height should be > 0",inputImg.getHeight()>0); assertEquals("Input and output img should have same heights",inputImg.getHeight(),outputImg.getHeight()); } catch (IOException e) { fail("Could not locate image at "+ this.location); } } /** * Test of setImage method, of class Icon. */ @Test public void testSetImage_Image() { System.out.println("setImage"); // TODO review the generated test code and remove the default call to fail. } /** * Test of setImage method, providing String (loc), of class Icon. */ @Test public void testSetImage_String() { System.out.println("setImage w/ string ref to existing img"); icon.setImage(this.location);//set image based on URL byte[] imageBytes = ((DataBufferByte) icon.getImage().getData().getDataBuffer()).getData(); assertNotNull("ByteArray of img should not be null",imageBytes); } /** * Test of setImage method, providing string (loc) WHICH DOES NOT EXIST * Throws exception */ @Test public void testSetImage_String_notExistingPath() { System.out.println("setImage w/ string ref to Non-existing img"); icon.setImage("lkjadfkljasdfkljasdklfj");//non existing path, img can not be found -> exception assertNull("Non existing image should not have a valid height but has",icon.getImage()); } }
LIMO/LIMO-domain/src/test/java/nl/fontys/sofa/limo/domain/component/IconTest.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 nl.fontys.sofa.limo.domain.component; import java.awt.image.BufferedImage; import java.awt.image.DataBufferByte; import java.io.File; import java.io.IOException; import java.util.Arrays; import javax.imageio.ImageIO; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Ben */ public class IconTest { Icon icon; String location = "testing_src/ic.png"; public IconTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { icon = new Icon();//icon w/ empty byteArray } @After public void tearDown() { } /** * Test of getData method, of class Icon. */ @Test public void testGetData() { System.out.println("getData"); } /** * Test of setData method, of class Icon. */ @Test public void testSetData() { System.out.println("setData"); } /** * Test of getImage method, of class Icon. */ @Test public void testGetImage() { System.out.println("getImage"); testSetImage_String();//set img using other test BufferedImage actualImg = icon.getImage(); byte[] actualImageBytes = ((DataBufferByte) actualImg.getData().getDataBuffer()).getData();//using Icon class method getImage BufferedImage expectedImg; try { expectedImg = ImageIO.read(new File(this.location)); byte[] expectedImageBytes = ((DataBufferByte) expectedImg.getData().getDataBuffer()).getData(); assertTrue("Actual image should have a dimension higher than 0",actualImg.getHeight()>0); System.out.println("Actual img height: "+actualImg); Assert.assertArrayEquals("ByteArrays for actual and expected images should be equal but are not",expectedImageBytes,actualImageBytes); } catch (IOException e) { fail("Could not locate image at "+ this.location); } } /** * Test of setImage method, of class Icon. */ @Test public void testSetImage_BufferedImage() { System.out.println("setImage"); // TODO review the generated test code and remove the default call to fail. } /** * Test of setImage method, of class Icon. */ @Test public void testSetImage_Image() { System.out.println("setImage"); // TODO review the generated test code and remove the default call to fail. } /** * Test of setImage method, of class Icon. */ @Test public void testSetImage_String() { System.out.println("setImage"); icon.setImage(this.location);//set image based on URL byte[] imageBytes = ((DataBufferByte) icon.getImage().getData().getDataBuffer()).getData(); assertNotNull("ByteArray of img should not be null",imageBytes); } }
updated iconTest
LIMO/LIMO-domain/src/test/java/nl/fontys/sofa/limo/domain/component/IconTest.java
updated iconTest
<ide><path>IMO/LIMO-domain/src/test/java/nl/fontys/sofa/limo/domain/component/IconTest.java <ide> import org.junit.BeforeClass; <ide> import org.junit.Test; <ide> import static org.junit.Assert.*; <add>import org.openide.util.Exceptions; <ide> <ide> /** <ide> * <ide> <ide> @After <ide> public void tearDown() { <add> icon = null; <ide> <ide> } <ide> <ide> */ <ide> @Test <ide> public void testSetData() { <del> System.out.println("setData"); <add> System.out.println("setData"); <add> try { <add> BufferedImage inputImg = ImageIO.read(new File(this.location)); <add> assertTrue("Input img must have height>0 but has not",inputImg.getHeight()>0); <add> byte[] inputImageBytes = ((DataBufferByte) inputImg.getData().getDataBuffer()).getData(); <add> <add> icon.setData(inputImageBytes); <add> <add> BufferedImage outputImg = icon.getImage(); <add> //TODO: matthias: setData and afterwards retrieving img by calling getImage does not work <add> <add> <add> //assertTrue(outputImg.getHeight()>0); <add> //byte[] outputImageBytes = ((DataBufferByte) outputImg.getData().getDataBuffer()).getData();//using Icon class method getImage <add> //Assert.assertArrayEquals("Input and output image byte arrays should match but do not",inputImageBytes,outputImageBytes); <add> } catch (IOException ex) { <add> fail("Could not locate image"); <add> } <ide> } <ide> <ide> /** <ide> */ <ide> @Test <ide> public void testSetImage_BufferedImage() { <del> System.out.println("setImage"); <del> // TODO review the generated test code and remove the default call to fail. <add> System.out.println("setImage"); <add> try { <add> BufferedImage inputImg = ImageIO.read(new File(this.location)); <add> byte[] inputImageBytes = ((DataBufferByte) inputImg.getData().getDataBuffer()).getData(); <add> <add> icon.setImage(inputImg); <add> <add> BufferedImage outputImg = icon.getImage(); <add> byte[] outputImageBytes = ((DataBufferByte) outputImg.getData().getDataBuffer()).getData(); <add> Assert.assertArrayEquals("Byte arrays should be equal",inputImageBytes,outputImageBytes); <add> assertTrue("Input img height should be > 0",inputImg.getHeight()>0); <add> assertEquals("Input and output img should have same heights",inputImg.getHeight(),outputImg.getHeight()); <add> } catch (IOException e) { <add> fail("Could not locate image at "+ this.location); <add> } <ide> } <ide> <ide> /** <ide> } <ide> <ide> /** <del> * Test of setImage method, of class Icon. <add> * Test of setImage method, providing String (loc), of class Icon. <ide> */ <ide> @Test <ide> public void testSetImage_String() { <del> System.out.println("setImage"); <add> System.out.println("setImage w/ string ref to existing img"); <ide> icon.setImage(this.location);//set image based on URL <ide> <ide> byte[] imageBytes = ((DataBufferByte) icon.getImage().getData().getDataBuffer()).getData(); <ide> assertNotNull("ByteArray of img should not be null",imageBytes); <ide> <ide> } <add> /** <add> * Test of setImage method, providing string (loc) WHICH DOES NOT EXIST <add> * Throws exception <add> */ <add> @Test <add> public void testSetImage_String_notExistingPath() { <add> System.out.println("setImage w/ string ref to Non-existing img"); <add> icon.setImage("lkjadfkljasdfkljasdklfj");//non existing path, img can not be found -> exception <add> assertNull("Non existing image should not have a valid height but has",icon.getImage()); <add> } <ide> <ide> }
JavaScript
mit
9bbbd81326815cc3fab8d945675074e15f9fa8c0
0
Aplyca/patternlab-standard
/****************************************************** * PATTERN LAB NODE * EDITION-NODE-GULP * The gulp wrapper around patternlab-node core, providing tasks to interact with the core library and move supporting frontend assets. ******************************************************/ var gulp = require('gulp'), path = require('path'), del = require('del'), uglify = require('gulp-uglify'), rename = require('gulp-rename'), concat = require('gulp-concat'), cssmin = require('gulp-cssnano'), sassLint = require('gulp-sass-lint'), cssLint = require('gulp-csslint'), sourcemaps = require('gulp-sourcemaps'), sass = require('gulp-sass'), browserSync = require('browser-sync').create(), argv = require('minimist')(process.argv.slice(2)); /****************************************************** * COPY TASKS - stream assets from source to public ******************************************************/ // JS copy gulp.task('pl-copy:js', function(){ return gulp.src('**/*.js', {cwd: path.resolve(paths().source.js)} ) .pipe(gulp.dest(path.resolve(paths().public.js))); }); // Images copy gulp.task('pl-copy:img', function(){ return gulp.src('**/*.{ico,png,gif,jpg,jpeg,svg,tif,bmp,ico}',{cwd: path.resolve(paths().source.images)} ) .pipe(gulp.dest(path.resolve(paths().public.images))); }); // Favicon copy gulp.task('pl-copy:favicon', function(){ return gulp.src('*.{ico,png,gif,jpg,jpeg,svg}', {cwd: path.resolve(paths().source.root)} ) .pipe(gulp.dest(path.resolve(paths().public.root))); }); // Fonts copy gulp.task('pl-copy:font', function(){ return gulp.src('**/*.{svg,eot,ttf,woff,otf,woff2}', {cwd: path.resolve(paths().source.fonts)}) .pipe(gulp.dest(path.resolve(paths().public.fonts))); }); // AJAX Copy gulp.task('pl-copy:ajax', function(){ return gulp.src(path.resolve(paths().source.ajax, '*.json')) .pipe(gulp.dest(path.resolve(paths().public.ajax))); }); // CSS Copy gulp.task('pl-copy:css', function(){ return gulp.src(path.resolve(paths().source.css, '*.css')) .pipe(gulp.dest(path.resolve(paths().public.css))) .pipe(browserSync.stream()); }); // Components Copy gulp.task('pl-copy:components', function(){ return gulp.src('**/*.*',{cwd: path.resolve(paths().source.components)} ) .pipe(gulp.dest(path.resolve(paths().public.components))); }); // Vendors copy gulp.task('pl-copy:vendors', function(){ return gulp.src('**/*.*',{cwd: path.resolve(paths().source.vendors)} ) .pipe(gulp.dest(path.resolve(paths().public.vendors))); }); // Styleguide Copy everything but css gulp.task('pl-copy:styleguide', function(){ return gulp.src(path.resolve(paths().source.styleguide, '**/!(*.css)')) .pipe(gulp.dest(path.resolve(paths().public.root))) .pipe(browserSync.stream()); }); // Styleguide Copy and flatten css gulp.task('pl-copy:styleguide-css', function(){ return gulp.src(path.resolve(paths().source.styleguide, '**/*.css')) .pipe(gulp.dest(function(file){ //flatten anything inside the styleguide into a single output dir per http://stackoverflow.com/a/34317320/1790362 file.path = path.join(file.base, path.basename(file.path)); return path.resolve(path.join(paths().public.styleguide, 'css')); })) .pipe(browserSync.stream()); }); gulp.task('pl-compile:sass', function(){ return gulp.src('*.scss',{cwd: path.resolve(paths().source.css)} ) .pipe(sourcemaps.init()) .pipe(sass({ outputStyle: 'expanded', precision: 8 })) .pipe(sourcemaps.write('.')) .pipe(gulp.dest(path.resolve(paths().public.css))) .pipe(browserSync.stream({match: '**/*.css'})); }) gulp.task('pl-compile:validate-sass', function() { return gulp.src('**/*.scss',{cwd: path.resolve(paths().source.css)} ) .pipe(sassLint()) .pipe(sassLint.format()); }) gulp.task('pl-compile:validate-css', function() { return gulp.src('**/*.css',{cwd: path.resolve(paths().source.css)} ) .pipe(cssLint()) .pipe(cssLint.format()); }) /****************************************************** * CLEAN TASKS - Clean assets ******************************************************/ // Clean gulp.task('pl-clean:publish', function(){ return del([path.resolve(paths().publish.root) + '**/*']); }); gulp.task('pl-clean:public', function(){ return del([path.resolve(paths().public.root) + '**/*']); }); /****************************************************** * PUBLISH TASKS - stream assets from public to dist ******************************************************/ // JS copy gulp.task('pl-dist:js', function(){ return gulp.src('**/*.js', {cwd: path.resolve(paths().public.js)} ) .pipe(gulp.dest(path.resolve(paths().publish.js))) .pipe(uglify()) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest(path.resolve(paths().publish.js))) .pipe(concat(paths().publish.combineName + '.min.js')) .pipe(gulp.dest(path.resolve(paths().publish.js))); }); // Images copy gulp.task('pl-dist:img', function(){ return gulp.src('**/*.{ico,png,gif,jpg,jpeg,svg,tif,bmp,ico}', {cwd: path.resolve(paths().public.images)} ) .pipe(gulp.dest(path.resolve(paths().publish.images))); }); // Favicon copy gulp.task('pl-dist:favicon', function(){ return gulp.src('*.{ico,png,gif,jpg,jpeg,svg}', {cwd: path.resolve(paths().public.root)} ) .pipe(gulp.dest(path.resolve(paths().publish.root))); }); // Fonts copy gulp.task('pl-dist:font', function(){ return gulp.src('**/*.{svg,eot,ttf,woff,otf,woff2}', {cwd: path.resolve(paths().public.fonts)}) .pipe(gulp.dest(path.resolve(paths().publish.fonts))); }); // CSS Copy gulp.task('pl-dist:css', function(){ return gulp.src(path.resolve(paths().public.css, '*.css')) .pipe(gulp.dest(path.resolve(paths().publish.css))) .pipe(cssmin({zindex: false})) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest(path.resolve(paths().publish.css))) .pipe(concat(paths().publish.combineName + '.min.css')) .pipe(gulp.dest(path.resolve(paths().publish.css))); }); // Fonts copy gulp.task('pl-dist:components', function(){ return gulp.src('**/*.*', {cwd: path.resolve(paths().public.components)}) .pipe(gulp.dest(path.resolve(paths().publish.components))); }); /****************************************************** * PATTERN LAB CONFIGURATION - API with core library ******************************************************/ //read all paths from our namespaced config file var config = require('./patternlab-config.json'), patternlab = require('patternlab-node')(config); function paths() { return config.paths; } function getConfiguredCleanOption() { return config.cleanPublic; } function build(done) { patternlab.build(done, getConfiguredCleanOption()); } gulp.task('pl-stylesheets', gulp.series( 'pl-copy:css', 'pl-compile:sass', function(done){ done(); }) ); gulp.task('pl-assets', gulp.series( gulp.parallel( 'pl-copy:js', 'pl-copy:img', 'pl-copy:favicon', 'pl-copy:font', 'pl-stylesheets', 'pl-copy:ajax', 'pl-copy:components', 'pl-copy:vendors', 'pl-copy:styleguide', 'pl-copy:styleguide-css' ), function(done){ done(); }) ); gulp.task('pl-dist', gulp.series( gulp.parallel( 'pl-dist:js', 'pl-dist:img', 'pl-dist:favicon', 'pl-dist:font', 'pl-dist:css', 'pl-dist:components' ), function(done){ done(); }) ); gulp.task('pl-clean', gulp.series( gulp.parallel( 'pl-clean:public', 'pl-clean:publish' ), function(done){ done(); }) ); gulp.task('patternlab:version', function (done) { patternlab.version(); done(); }); gulp.task('patternlab:help', function (done) { patternlab.help(); done(); }); gulp.task('patternlab:patternsonly', function (done) { patternlab.patternsonly(done, getConfiguredCleanOption()); }); gulp.task('patternlab:liststarterkits', function (done) { patternlab.liststarterkits(); done(); }); gulp.task('patternlab:loadstarterkit', function (done) { patternlab.loadstarterkit(argv.kit, argv.clean); done(); }); gulp.task('patternlab:build', gulp.series('pl-assets', build, function(done){ done(); })); /****************************************************** * TESTS TASKS ******************************************************/ //unit test gulp.task('pl-nodeunit', function(){ return gulp.src('./test/**/*_tests.js') .pipe(nodeunit()); }) /****************************************************** * SERVER AND WATCH TASKS ******************************************************/ // watch task utility functions function getSupportedTemplateExtensions() { var engines = require('./node_modules/patternlab-node/core/lib/pattern_engines'); return engines.getSupportedFileExtensions(); } function getTemplateWatches() { return getSupportedTemplateExtensions().map(function (dotExtension) { return path.resolve(paths().source.patterns, '**/*' + dotExtension); }); } function reload() { browserSync.reload(); } function reloadCSS() { browserSync.reload('*.css'); } function watch() { gulp.watch(path.resolve(paths().source.css, '**/*.{css,scss}'), { awaitWriteFinish: false }).on('change', gulp.series('pl-stylesheets')); gulp.watch(path.resolve(paths().source.js, '**/*.js'), { awaitWriteFinish: false }).on('change', gulp.series('pl-copy:js')); gulp.watch(path.resolve(paths().source.styleguide, '**/*.*'), { awaitWriteFinish: true }).on('change', gulp.series('pl-copy:styleguide', 'pl-copy:styleguide-css', reloadCSS)); var patternWatches = [ path.resolve(paths().source.patterns, '**/*.{json,mustache,md}'), path.resolve(paths().source.data, '*.json'), path.resolve(paths().source.ajax, '*.json'), path.resolve(paths().source.fonts + '/*'), path.resolve(paths().source.images + '/*'), path.resolve(paths().source.meta, '*'), path.resolve(paths().source.annotations + '/*') ].concat(getTemplateWatches()); gulp.watch(patternWatches, { awaitWriteFinish: false }).on('change', gulp.series(build, reload)); } gulp.task('patternlab:connect', gulp.series(function(done) { browserSync.init({ server: { baseDir: path.resolve(paths().public.root) }, snippetOptions: { // Ignore all HTML files within the templates folder blacklist: ['/index.html', '/', '/?*'] }, notify: { styles: [ 'display: none', 'padding: 15px', 'font-family: sans-serif', 'position: fixed', 'font-size: 1em', 'z-index: 9999', 'bottom: 0px', 'right: 0px', 'border-top-left-radius: 5px', 'background-color: #1B2032', 'opacity: 0.4', 'margin: 0', 'color: white', 'text-align: center' ] } }, function(){ console.log('PATTERN LAB NODE WATCHING FOR CHANGES'); done(); }); })); /****************************************************** * COMPOUND TASKS ******************************************************/ gulp.task('default', gulp.series('patternlab:build')); gulp.task('patternlab:watch', gulp.series('patternlab:build', watch)); gulp.task('patternlab:serve', gulp.series('patternlab:build', 'patternlab:connect', watch)); gulp.task('patternlab:dist', gulp.series('pl-dist')); gulp.task('patternlab:clean', gulp.series('pl-clean')); gulp.task('serve', gulp.series('patternlab:serve')); gulp.task('clean', gulp.series('patternlab:clean')); gulp.task('publish', gulp.series('patternlab:clean', 'patternlab:build', 'patternlab:dist'));
gulpfile.js
/****************************************************** * PATTERN LAB NODE * EDITION-NODE-GULP * The gulp wrapper around patternlab-node core, providing tasks to interact with the core library and move supporting frontend assets. ******************************************************/ var gulp = require('gulp'), path = require('path'), del = require('del'), uglify = require('gulp-uglify'), rename = require('gulp-rename'), concat = require('gulp-concat'), cssmin = require('gulp-cssnano'), sassLint = require('gulp-sass-lint'), cssLint = require('gulp-csslint'), sourcemaps = require('gulp-sourcemaps'), sass = require('gulp-sass'), browserSync = require('browser-sync').create(), argv = require('minimist')(process.argv.slice(2)); /****************************************************** * COPY TASKS - stream assets from source to public ******************************************************/ // JS copy gulp.task('pl-copy:js', function(){ return gulp.src('**/*.js', {cwd: path.resolve(paths().source.js)} ) .pipe(gulp.dest(path.resolve(paths().public.js))); }); // Images copy gulp.task('pl-copy:img', function(){ return gulp.src('**/*.{ico,png,gif,jpg,jpeg,svg,tif,bmp,ico}',{cwd: path.resolve(paths().source.images)} ) .pipe(gulp.dest(path.resolve(paths().public.images))); }); // Favicon copy gulp.task('pl-copy:favicon', function(){ return gulp.src('*.{ico,png,gif,jpg,jpeg,svg}', {cwd: path.resolve(paths().source.root)} ) .pipe(gulp.dest(path.resolve(paths().public.root))); }); // Fonts copy gulp.task('pl-copy:font', function(){ return gulp.src('**/*.{svg,eot,ttf,woff,otf,woff2}', {cwd: path.resolve(paths().source.fonts)}) .pipe(gulp.dest(path.resolve(paths().public.fonts))); }); // AJAX Copy gulp.task('pl-copy:ajax', function(){ return gulp.src(path.resolve(paths().source.ajax, '*.json')) .pipe(gulp.dest(path.resolve(paths().public.ajax))); }); // CSS Copy gulp.task('pl-copy:css', function(){ return gulp.src(path.resolve(paths().source.css, '*.css')) .pipe(gulp.dest(path.resolve(paths().public.css))) .pipe(browserSync.stream()); }); // Components Copy gulp.task('pl-copy:components', function(){ return gulp.src('**/*.*',{cwd: path.resolve(paths().source.components)} ) .pipe(gulp.dest(path.resolve(paths().public.components))); }); // Vendors copy gulp.task('pl-copy:vendors', function(){ return gulp.src('**/*.*',{cwd: path.resolve(paths().source.vendors)} ) .pipe(gulp.dest(path.resolve(paths().public.vendors))); }); // Styleguide Copy everything but css gulp.task('pl-copy:styleguide', function(){ return gulp.src(path.resolve(paths().source.styleguide, '**/!(*.css)')) .pipe(gulp.dest(path.resolve(paths().public.root))) .pipe(browserSync.stream()); }); // Styleguide Copy and flatten css gulp.task('pl-copy:styleguide-css', function(){ return gulp.src(path.resolve(paths().source.styleguide, '**/*.css')) .pipe(gulp.dest(function(file){ //flatten anything inside the styleguide into a single output dir per http://stackoverflow.com/a/34317320/1790362 file.path = path.join(file.base, path.basename(file.path)); return path.resolve(path.join(paths().public.styleguide, 'css')); })) .pipe(browserSync.stream()); }); gulp.task('pl-compile:sass', function(){ return gulp.src('*.scss',{cwd: path.resolve(paths().source.css)} ) .pipe(sourcemaps.init()) .pipe(sass({ outputStyle: 'expanded', precision: 8 })) .pipe(sourcemaps.write('.')) .pipe(gulp.dest(path.resolve(paths().public.css))) .pipe(browserSync.stream({match: '**/*.css'})); }) gulp.task('pl-compile:validate-sass', function() { return gulp.src('**/*.scss',{cwd: path.resolve(paths().source.css)} ) .pipe(sassLint()) .pipe(sassLint.format()); }) gulp.task('pl-compile:validate-css', function() { return gulp.src('**/*.css',{cwd: path.resolve(paths().source.css)} ) .pipe(cssLint()) .pipe(cssLint.format()); }) /****************************************************** * CLEAN TASKS - Clean assets ******************************************************/ // Clean gulp.task('pl-clean:publish', function(){ return del([path.resolve(paths().publish.root) + '**/*']); }); gulp.task('pl-clean:public', function(){ return del([path.resolve(paths().public.root) + '**/*']); }); /****************************************************** * PUBLISH TASKS - stream assets from public to dist ******************************************************/ // JS copy gulp.task('pl-dist:js', function(){ return gulp.src('**/*.js', {cwd: path.resolve(paths().public.js)} ) .pipe(gulp.dest(path.resolve(paths().publish.js))) .pipe(uglify()) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest(path.resolve(paths().publish.js))) .pipe(concat(paths().publish.combineName + '.min.js')) .pipe(gulp.dest(path.resolve(paths().publish.js))); }); // Images copy gulp.task('pl-dist:img', function(){ return gulp.src('**/*.{ico,png,gif,jpg,jpeg,svg,tif,bmp,ico}', {cwd: path.resolve(paths().public.images)} ) .pipe(gulp.dest(path.resolve(paths().publish.images))); }); // Favicon copy gulp.task('pl-dist:favicon', function(){ return gulp.src('*.{ico,png,gif,jpg,jpeg,svg}', {cwd: path.resolve(paths().public.root)} ) .pipe(gulp.dest(path.resolve(paths().publish.root))); }); // Fonts copy gulp.task('pl-dist:font', function(){ return gulp.src('**/*.{svg,eot,ttf,woff,otf,woff2}', {cwd: path.resolve(paths().public.fonts)}) .pipe(gulp.dest(path.resolve(paths().publish.fonts))); }); // CSS Copy gulp.task('pl-dist:css', function(){ return gulp.src(path.resolve(paths().public.css, '*.css')) .pipe(gulp.dest(path.resolve(paths().publish.css))) .pipe(cssmin({zindex: false})) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest(path.resolve(paths().publish.css))) .pipe(concat(paths().publish.combineName + '.min.css')) .pipe(gulp.dest(path.resolve(paths().publish.css))); }); // Fonts copy gulp.task('pl-dist:components', function(){ return gulp.src('**/*.*', {cwd: path.resolve(paths().public.components)}) .pipe(gulp.dest(path.resolve(paths().publish.components))); }); /****************************************************** * PATTERN LAB CONFIGURATION - API with core library ******************************************************/ //read all paths from our namespaced config file var config = require('./patternlab-config.json'), patternlab = require('patternlab-node')(config); function paths() { return config.paths; } function getConfiguredCleanOption() { return config.cleanPublic; } function build(done) { patternlab.build(done, getConfiguredCleanOption()); } gulp.task('pl-stylesheets', gulp.series( 'pl-copy:css', 'pl-compile:sass', function(done){ done(); }) ); gulp.task('pl-assets', gulp.series( gulp.parallel( 'pl-copy:js', 'pl-copy:img', 'pl-copy:favicon', 'pl-copy:font', 'pl-stylesheets', 'pl-copy:ajax', 'pl-copy:components', 'pl-copy:vendors', 'pl-copy:styleguide', 'pl-copy:styleguide-css' ), function(done){ done(); }) ); gulp.task('pl-dist', gulp.series( gulp.parallel( 'pl-dist:js', 'pl-dist:img', 'pl-dist:favicon', 'pl-dist:font', 'pl-dist:css' ), function(done){ done(); }) ); gulp.task('pl-clean', gulp.series( gulp.parallel( 'pl-clean:public', 'pl-clean:publish' ), function(done){ done(); }) ); gulp.task('patternlab:version', function (done) { patternlab.version(); done(); }); gulp.task('patternlab:help', function (done) { patternlab.help(); done(); }); gulp.task('patternlab:patternsonly', function (done) { patternlab.patternsonly(done, getConfiguredCleanOption()); }); gulp.task('patternlab:liststarterkits', function (done) { patternlab.liststarterkits(); done(); }); gulp.task('patternlab:loadstarterkit', function (done) { patternlab.loadstarterkit(argv.kit, argv.clean); done(); }); gulp.task('patternlab:build', gulp.series('pl-assets', build, function(done){ done(); })); /****************************************************** * TESTS TASKS ******************************************************/ //unit test gulp.task('pl-nodeunit', function(){ return gulp.src('./test/**/*_tests.js') .pipe(nodeunit()); }) /****************************************************** * SERVER AND WATCH TASKS ******************************************************/ // watch task utility functions function getSupportedTemplateExtensions() { var engines = require('./node_modules/patternlab-node/core/lib/pattern_engines'); return engines.getSupportedFileExtensions(); } function getTemplateWatches() { return getSupportedTemplateExtensions().map(function (dotExtension) { return path.resolve(paths().source.patterns, '**/*' + dotExtension); }); } function reload() { browserSync.reload(); } function reloadCSS() { browserSync.reload('*.css'); } function watch() { gulp.watch(path.resolve(paths().source.css, '**/*.{css,scss}'), { awaitWriteFinish: false }).on('change', gulp.series('pl-stylesheets')); gulp.watch(path.resolve(paths().source.js, '**/*.js'), { awaitWriteFinish: false }).on('change', gulp.series('pl-copy:js')); gulp.watch(path.resolve(paths().source.styleguide, '**/*.*'), { awaitWriteFinish: true }).on('change', gulp.series('pl-copy:styleguide', 'pl-copy:styleguide-css', reloadCSS)); var patternWatches = [ path.resolve(paths().source.patterns, '**/*.{json,mustache,md}'), path.resolve(paths().source.data, '*.json'), path.resolve(paths().source.ajax, '*.json'), path.resolve(paths().source.fonts + '/*'), path.resolve(paths().source.images + '/*'), path.resolve(paths().source.meta, '*'), path.resolve(paths().source.annotations + '/*') ].concat(getTemplateWatches()); gulp.watch(patternWatches, { awaitWriteFinish: false }).on('change', gulp.series(build, reload)); } gulp.task('patternlab:connect', gulp.series(function(done) { browserSync.init({ server: { baseDir: path.resolve(paths().public.root) }, snippetOptions: { // Ignore all HTML files within the templates folder blacklist: ['/index.html', '/', '/?*'] }, notify: { styles: [ 'display: none', 'padding: 15px', 'font-family: sans-serif', 'position: fixed', 'font-size: 1em', 'z-index: 9999', 'bottom: 0px', 'right: 0px', 'border-top-left-radius: 5px', 'background-color: #1B2032', 'opacity: 0.4', 'margin: 0', 'color: white', 'text-align: center' ] } }, function(){ console.log('PATTERN LAB NODE WATCHING FOR CHANGES'); done(); }); })); /****************************************************** * COMPOUND TASKS ******************************************************/ gulp.task('default', gulp.series('patternlab:build')); gulp.task('patternlab:watch', gulp.series('patternlab:build', watch)); gulp.task('patternlab:serve', gulp.series('patternlab:build', 'patternlab:connect', watch)); gulp.task('patternlab:dist', gulp.series('pl-dist')); gulp.task('patternlab:clean', gulp.series('pl-clean')); gulp.task('serve', gulp.series('patternlab:serve')); gulp.task('clean', gulp.series('patternlab:clean')); gulp.task('publish', gulp.series('patternlab:clean', 'patternlab:build', 'patternlab:dist'));
Adding components
gulpfile.js
Adding components
<ide><path>ulpfile.js <ide> 'pl-dist:img', <ide> 'pl-dist:favicon', <ide> 'pl-dist:font', <del> 'pl-dist:css' <add> 'pl-dist:css', <add> 'pl-dist:components' <ide> ), <ide> function(done){ <ide> done();
Java
apache-2.0
593dcc3000ae358d1e362ed09b258b3815089ecb
0
google/nomulus,google/nomulus,google/nomulus,google/nomulus,google/nomulus,google/nomulus
// Copyright 2017 The Nomulus 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 google.registry.rde; import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl; import static com.google.common.base.Verify.verify; import static com.google.common.net.MediaType.PLAIN_TEXT_UTF_8; import static com.jcraft.jsch.ChannelSftp.OVERWRITE; import static google.registry.model.common.Cursor.CursorType.RDE_UPLOAD_SFTP; import static google.registry.model.common.Cursor.getCursorTimeOrStartOfTime; import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.rde.RdeMode.FULL; import static google.registry.request.Action.Method.POST; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Arrays.asList; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.tools.cloudstorage.GcsFilename; import com.google.common.annotations.VisibleForTesting; import com.google.common.flogger.FluentLogger; import com.google.common.io.ByteStreams; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import dagger.Lazy; import google.registry.config.RegistryConfig.Config; import google.registry.gcs.GcsUtils; import google.registry.keyring.api.KeyModule.Key; import google.registry.model.common.Cursor; import google.registry.model.common.Cursor.CursorType; import google.registry.model.rde.RdeNamingUtils; import google.registry.model.rde.RdeRevision; import google.registry.model.registry.Registry; import google.registry.rde.EscrowTaskRunner.EscrowTask; import google.registry.rde.JSchSshSession.JSchSshSessionFactory; import google.registry.request.Action; import google.registry.request.HttpException.ServiceUnavailableException; import google.registry.request.Parameter; import google.registry.request.RequestParameters; import google.registry.request.Response; import google.registry.request.auth.Auth; import google.registry.util.Clock; import google.registry.util.Retrier; import google.registry.util.TaskQueueUtils; import google.registry.util.TeeOutputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import javax.inject.Inject; import javax.inject.Named; import org.bouncycastle.openpgp.PGPKeyPair; import org.bouncycastle.openpgp.PGPPrivateKey; import org.bouncycastle.openpgp.PGPPublicKey; import org.joda.time.DateTime; import org.joda.time.Duration; /** * Action that securely uploads an RDE XML file from Cloud Storage to a trusted third party (such as * Iron Mountain) via SFTP. * * <p>This action is invoked by {@link RdeStagingAction} once it's created the files we need. The * date is calculated from {@link CursorType#RDE_UPLOAD}. * * <p>Once this action completes, it rolls the cursor forward a day and triggers * {@link RdeReportAction}. */ @Action( path = RdeUploadAction.PATH, method = POST, auth = Auth.AUTH_INTERNAL_ONLY ) public final class RdeUploadAction implements Runnable, EscrowTask { static final String PATH = "/_dr/task/rdeUpload"; private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Inject Clock clock; @Inject GcsUtils gcsUtils; @Inject Ghostryde ghostryde; @Inject EscrowTaskRunner runner; // Using Lazy<JSch> instead of JSch to prevent fetching of rdeSsh*Keys before we know we're // actually going to use them. See b/37868282 // // This prevents making an unnecessary time-expensive (and potentially failing) API call to the // external KMS system when the RdeUploadAction ends up not being used (if the EscrowTaskRunner // determins this EscrowTask was already completed today). @Inject Lazy<JSch> lazyJsch; @Inject JSchSshSessionFactory jschSshSessionFactory; @Inject Response response; @Inject RydePgpCompressionOutputStreamFactory pgpCompressionFactory; @Inject RydePgpEncryptionOutputStreamFactory pgpEncryptionFactory; @Inject RydePgpFileOutputStreamFactory pgpFileFactory; @Inject RydePgpSigningOutputStreamFactory pgpSigningFactory; @Inject RydeTarOutputStreamFactory tarFactory; @Inject TaskQueueUtils taskQueueUtils; @Inject Retrier retrier; @Inject @Parameter(RequestParameters.PARAM_TLD) String tld; @Inject @Config("rdeBucket") String bucket; @Inject @Config("rdeInterval") Duration interval; @Inject @Config("rdeUploadLockTimeout") Duration timeout; @Inject @Config("rdeUploadSftpCooldown") Duration sftpCooldown; @Inject @Config("rdeUploadUrl") URI uploadUrl; @Inject @Key("rdeReceiverKey") PGPPublicKey receiverKey; @Inject @Key("rdeSigningKey") PGPKeyPair signingKey; @Inject @Key("rdeStagingDecryptionKey") PGPPrivateKey stagingDecryptionKey; @Inject @Named("rde-report") Queue reportQueue; @Inject RdeUploadAction() {} @Override public void run() { logger.atInfo().log("Attempting to acquire RDE upload lock for TLD '%s'.", tld); runner.lockRunAndRollForward(this, Registry.get(tld), timeout, CursorType.RDE_UPLOAD, interval); taskQueueUtils.enqueue( reportQueue, withUrl(RdeReportAction.PATH).param(RequestParameters.PARAM_TLD, tld)); } @Override public void runWithLock(final DateTime watermark) throws Exception { logger.atInfo().log("Verifying readiness to upload the RDE deposit."); DateTime stagingCursorTime = getCursorTimeOrStartOfTime( ofy().load().key(Cursor.createKey(CursorType.RDE_STAGING, Registry.get(tld))).now()); if (!stagingCursorTime.isAfter(watermark)) { logger.atInfo().log( "tld=%s uploadCursor=%s stagingCursor=%s", tld, watermark, stagingCursorTime); throw new ServiceUnavailableException("Waiting for RdeStagingAction to complete"); } DateTime sftpCursorTime = getCursorTimeOrStartOfTime( ofy().load().key(Cursor.createKey(RDE_UPLOAD_SFTP, Registry.get(tld))).now()); if (sftpCursorTime.plus(sftpCooldown).isAfter(clock.nowUtc())) { // Fail the task good and hard so it retries until the cooldown passes. logger.atInfo().log("tld=%s cursor=%s sftpCursor=%s", tld, watermark, sftpCursorTime); throw new ServiceUnavailableException("SFTP cooldown has not yet passed"); } int revision = RdeRevision.getNextRevision(tld, watermark, FULL) - 1; verify(revision >= 0, "RdeRevision was not set on generated deposit"); final String name = RdeNamingUtils.makeRydeFilename(tld, watermark, FULL, 1, revision); final GcsFilename xmlFilename = new GcsFilename(bucket, name + ".xml.ghostryde"); final GcsFilename xmlLengthFilename = new GcsFilename(bucket, name + ".xml.length"); GcsFilename reportFilename = new GcsFilename(bucket, name + "-report.xml.ghostryde"); verifyFileExists(xmlFilename); verifyFileExists(xmlLengthFilename); verifyFileExists(reportFilename); logger.atInfo().log("Commencing RDE upload for TLD '%s' to '%s'.", tld, uploadUrl); final long xmlLength = readXmlLength(xmlLengthFilename); retrier.callWithRetry( () -> { upload(xmlFilename, xmlLength, watermark, name); return null; }, JSchException.class); logger.atInfo().log( "Updating RDE cursor '%s' for TLD '%s' following successful upload.", RDE_UPLOAD_SFTP, tld); ofy() .transact( () -> ofy() .save() .entity( Cursor.create( RDE_UPLOAD_SFTP, ofy().getTransactionTime(), Registry.get(tld))) .now()); response.setContentType(PLAIN_TEXT_UTF_8); response.setPayload(String.format("OK %s %s\n", tld, watermark)); } /** * Performs a blocking upload of a cloud storage XML file to escrow provider, converting * it to the RyDE format along the way by applying tar+compress+encrypt+sign, and saving the * created RyDE file on GCS for future reference. * * <p>This is done by layering a bunch of {@link java.io.FilterOutputStream FilterOutputStreams} * on top of each other in reverse order that turn XML bytes into a RyDE file while * simultaneously uploading it to the SFTP endpoint, and then using {@link ByteStreams#copy} to * blocking-copy bytes from the cloud storage {@code InputStream} to the RyDE/SFTP pipeline. * * <p>In psuedoshell, the whole process looks like the following: * * <pre> {@code * gcs read $xmlFile \ # Get GhostRyDE from cloud storage. * | decrypt | decompress \ # Convert it to XML. * | tar | file | compress | encrypt | sign /tmp/sig \ # Convert it to a RyDE file. * | tee gs://bucket/$rydeFilename.ryde \ # Save a copy of the RyDE file to GCS. * | sftp put $dstUrl/$rydeFilename.ryde \ # Upload to SFTP server. * && sftp put $dstUrl/$rydeFilename.sig </tmp/sig \ # Upload detached signature. * && cat /tmp/sig > gs://bucket/$rydeFilename.sig # Save a copy of signature to GCS. * }</pre> */ @VisibleForTesting protected void upload( GcsFilename xmlFile, long xmlLength, DateTime watermark, String name) throws Exception { logger.atInfo().log("Uploading XML file '%s' to remote path '%s'.", xmlFile, uploadUrl); try (InputStream gcsInput = gcsUtils.openInputStream(xmlFile); Ghostryde.Decryptor decryptor = ghostryde.openDecryptor(gcsInput, stagingDecryptionKey); Ghostryde.Decompressor decompressor = ghostryde.openDecompressor(decryptor); Ghostryde.Input xmlInput = ghostryde.openInput(decompressor)) { try (JSchSshSession session = jschSshSessionFactory.create(lazyJsch.get(), uploadUrl); JSchSftpChannel ftpChan = session.openSftpChannel()) { byte[] signature; String rydeFilename = name + ".ryde"; GcsFilename rydeGcsFilename = new GcsFilename(bucket, rydeFilename); try (OutputStream ftpOutput = ftpChan.get().put(rydeFilename, OVERWRITE); OutputStream gcsOutput = gcsUtils.openOutputStream(rydeGcsFilename); TeeOutputStream teeOutput = new TeeOutputStream(asList(ftpOutput, gcsOutput)); RydePgpSigningOutputStream signer = pgpSigningFactory.create(teeOutput, signingKey)) { try (OutputStream encryptLayer = pgpEncryptionFactory.create(signer, receiverKey); OutputStream kompressor = pgpCompressionFactory.create(encryptLayer); OutputStream fileLayer = pgpFileFactory.create(kompressor, watermark, name + ".tar"); OutputStream tarLayer = tarFactory.create(fileLayer, xmlLength, watermark, name + ".xml")) { ByteStreams.copy(xmlInput, tarLayer); } signature = signer.getSignature(); logger.atInfo().log("uploaded %,d bytes: %s.ryde", signer.getBytesWritten(), name); } String sigFilename = name + ".sig"; gcsUtils.createFromBytes(new GcsFilename(bucket, sigFilename), signature); ftpChan.get().put(new ByteArrayInputStream(signature), sigFilename); logger.atInfo().log("uploaded %,d bytes: %s.sig", signature.length, name); } } } /** Reads the contents of a file from Cloud Storage that contains nothing but an integer. */ private long readXmlLength(GcsFilename xmlLengthFilename) throws IOException { try (InputStream input = gcsUtils.openInputStream(xmlLengthFilename)) { return Long.parseLong(new String(ByteStreams.toByteArray(input), UTF_8).trim()); } } private void verifyFileExists(GcsFilename filename) { verify(gcsUtils.existsAndNotEmpty(filename), "Missing file: %s", filename); } }
java/google/registry/rde/RdeUploadAction.java
// Copyright 2017 The Nomulus 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 google.registry.rde; import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl; import static com.google.common.base.Verify.verify; import static com.google.common.net.MediaType.PLAIN_TEXT_UTF_8; import static com.jcraft.jsch.ChannelSftp.OVERWRITE; import static google.registry.model.common.Cursor.CursorType.RDE_UPLOAD_SFTP; import static google.registry.model.common.Cursor.getCursorTimeOrStartOfTime; import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.rde.RdeMode.FULL; import static google.registry.request.Action.Method.POST; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Arrays.asList; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.tools.cloudstorage.GcsFilename; import com.google.common.annotations.VisibleForTesting; import com.google.common.flogger.FluentLogger; import com.google.common.io.ByteStreams; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import dagger.Lazy; import google.registry.config.RegistryConfig.Config; import google.registry.gcs.GcsUtils; import google.registry.keyring.api.KeyModule.Key; import google.registry.model.common.Cursor; import google.registry.model.common.Cursor.CursorType; import google.registry.model.rde.RdeNamingUtils; import google.registry.model.rde.RdeRevision; import google.registry.model.registry.Registry; import google.registry.rde.EscrowTaskRunner.EscrowTask; import google.registry.rde.JSchSshSession.JSchSshSessionFactory; import google.registry.request.Action; import google.registry.request.HttpException.ServiceUnavailableException; import google.registry.request.Parameter; import google.registry.request.RequestParameters; import google.registry.request.Response; import google.registry.request.auth.Auth; import google.registry.util.Clock; import google.registry.util.Retrier; import google.registry.util.TaskQueueUtils; import google.registry.util.TeeOutputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import javax.inject.Inject; import javax.inject.Named; import org.bouncycastle.openpgp.PGPKeyPair; import org.bouncycastle.openpgp.PGPPrivateKey; import org.bouncycastle.openpgp.PGPPublicKey; import org.joda.time.DateTime; import org.joda.time.Duration; /** * Action that securely uploads an RDE XML file from Cloud Storage to a trusted third party (such as * Iron Mountain) via SFTP. * * <p>This action is invoked by {@link RdeStagingAction} once it's created the files we need. The * date is calculated from {@link CursorType#RDE_UPLOAD}. * * <p>Once this action completes, it rolls the cursor forward a day and triggers * {@link RdeReportAction}. */ @Action( path = RdeUploadAction.PATH, method = POST, auth = Auth.AUTH_INTERNAL_ONLY ) public final class RdeUploadAction implements Runnable, EscrowTask { static final String PATH = "/_dr/task/rdeUpload"; private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Inject Clock clock; @Inject GcsUtils gcsUtils; @Inject Ghostryde ghostryde; @Inject EscrowTaskRunner runner; // Using Lazy<JSch> instead of JSch to prevent fetching of rdeSsh*Keys before we know we're // actually going to use them. See b/37868282 // // This prevents making an unnecessary time-expensive (and potentially failing) API call to the // external KMS system when the RdeUploadAction ends up not being used (if the EscrowTaskRunner // determins this EscrowTask was already completed today). @Inject Lazy<JSch> lazyJsch; @Inject JSchSshSessionFactory jschSshSessionFactory; @Inject Response response; @Inject RydePgpCompressionOutputStreamFactory pgpCompressionFactory; @Inject RydePgpEncryptionOutputStreamFactory pgpEncryptionFactory; @Inject RydePgpFileOutputStreamFactory pgpFileFactory; @Inject RydePgpSigningOutputStreamFactory pgpSigningFactory; @Inject RydeTarOutputStreamFactory tarFactory; @Inject TaskQueueUtils taskQueueUtils; @Inject Retrier retrier; @Inject @Parameter(RequestParameters.PARAM_TLD) String tld; @Inject @Config("rdeBucket") String bucket; @Inject @Config("rdeInterval") Duration interval; @Inject @Config("rdeUploadLockTimeout") Duration timeout; @Inject @Config("rdeUploadSftpCooldown") Duration sftpCooldown; @Inject @Config("rdeUploadUrl") URI uploadUrl; @Inject @Key("rdeReceiverKey") PGPPublicKey receiverKey; @Inject @Key("rdeSigningKey") PGPKeyPair signingKey; @Inject @Key("rdeStagingDecryptionKey") PGPPrivateKey stagingDecryptionKey; @Inject @Named("rde-report") Queue reportQueue; @Inject RdeUploadAction() {} @Override public void run() { runner.lockRunAndRollForward(this, Registry.get(tld), timeout, CursorType.RDE_UPLOAD, interval); taskQueueUtils.enqueue( reportQueue, withUrl(RdeReportAction.PATH).param(RequestParameters.PARAM_TLD, tld)); } @Override public void runWithLock(final DateTime watermark) throws Exception { DateTime stagingCursorTime = getCursorTimeOrStartOfTime( ofy().load().key(Cursor.createKey(CursorType.RDE_STAGING, Registry.get(tld))).now()); if (!stagingCursorTime.isAfter(watermark)) { logger.atInfo().log( "tld=%s uploadCursor=%s stagingCursor=%s", tld, watermark, stagingCursorTime); throw new ServiceUnavailableException("Waiting for RdeStagingAction to complete"); } DateTime sftpCursorTime = getCursorTimeOrStartOfTime( ofy().load().key(Cursor.createKey(RDE_UPLOAD_SFTP, Registry.get(tld))).now()); if (sftpCursorTime.plus(sftpCooldown).isAfter(clock.nowUtc())) { // Fail the task good and hard so it retries until the cooldown passes. logger.atInfo().log("tld=%s cursor=%s sftpCursor=%s", tld, watermark, sftpCursorTime); throw new ServiceUnavailableException("SFTP cooldown has not yet passed"); } int revision = RdeRevision.getNextRevision(tld, watermark, FULL) - 1; verify(revision >= 0, "RdeRevision was not set on generated deposit"); final String name = RdeNamingUtils.makeRydeFilename(tld, watermark, FULL, 1, revision); final GcsFilename xmlFilename = new GcsFilename(bucket, name + ".xml.ghostryde"); final GcsFilename xmlLengthFilename = new GcsFilename(bucket, name + ".xml.length"); GcsFilename reportFilename = new GcsFilename(bucket, name + "-report.xml.ghostryde"); verifyFileExists(xmlFilename); verifyFileExists(xmlLengthFilename); verifyFileExists(reportFilename); final long xmlLength = readXmlLength(xmlLengthFilename); retrier.callWithRetry( () -> { upload(xmlFilename, xmlLength, watermark, name); return null; }, JSchException.class); ofy() .transact( () -> ofy() .save() .entity( Cursor.create( RDE_UPLOAD_SFTP, ofy().getTransactionTime(), Registry.get(tld))) .now()); response.setContentType(PLAIN_TEXT_UTF_8); response.setPayload(String.format("OK %s %s\n", tld, watermark)); } /** * Performs a blocking upload of a cloud storage XML file to escrow provider, converting * it to the RyDE format along the way by applying tar+compress+encrypt+sign, and saving the * created RyDE file on GCS for future reference. * * <p>This is done by layering a bunch of {@link java.io.FilterOutputStream FilterOutputStreams} * on top of each other in reverse order that turn XML bytes into a RyDE file while * simultaneously uploading it to the SFTP endpoint, and then using {@link ByteStreams#copy} to * blocking-copy bytes from the cloud storage {@code InputStream} to the RyDE/SFTP pipeline. * * <p>In psuedoshell, the whole process looks like the following: * * <pre> {@code * gcs read $xmlFile \ # Get GhostRyDE from cloud storage. * | decrypt | decompress \ # Convert it to XML. * | tar | file | compress | encrypt | sign /tmp/sig \ # Convert it to a RyDE file. * | tee gs://bucket/$rydeFilename.ryde \ # Save a copy of the RyDE file to GCS. * | sftp put $dstUrl/$rydeFilename.ryde \ # Upload to SFTP server. * && sftp put $dstUrl/$rydeFilename.sig </tmp/sig \ # Upload detached signature. * && cat /tmp/sig > gs://bucket/$rydeFilename.sig # Save a copy of signature to GCS. * }</pre> */ @VisibleForTesting protected void upload( GcsFilename xmlFile, long xmlLength, DateTime watermark, String name) throws Exception { logger.atInfo().log("Uploading %s to %s", xmlFile, uploadUrl); try (InputStream gcsInput = gcsUtils.openInputStream(xmlFile); Ghostryde.Decryptor decryptor = ghostryde.openDecryptor(gcsInput, stagingDecryptionKey); Ghostryde.Decompressor decompressor = ghostryde.openDecompressor(decryptor); Ghostryde.Input xmlInput = ghostryde.openInput(decompressor)) { try (JSchSshSession session = jschSshSessionFactory.create(lazyJsch.get(), uploadUrl); JSchSftpChannel ftpChan = session.openSftpChannel()) { byte[] signature; String rydeFilename = name + ".ryde"; GcsFilename rydeGcsFilename = new GcsFilename(bucket, rydeFilename); try (OutputStream ftpOutput = ftpChan.get().put(rydeFilename, OVERWRITE); OutputStream gcsOutput = gcsUtils.openOutputStream(rydeGcsFilename); TeeOutputStream teeOutput = new TeeOutputStream(asList(ftpOutput, gcsOutput)); RydePgpSigningOutputStream signer = pgpSigningFactory.create(teeOutput, signingKey)) { try (OutputStream encryptLayer = pgpEncryptionFactory.create(signer, receiverKey); OutputStream kompressor = pgpCompressionFactory.create(encryptLayer); OutputStream fileLayer = pgpFileFactory.create(kompressor, watermark, name + ".tar"); OutputStream tarLayer = tarFactory.create(fileLayer, xmlLength, watermark, name + ".xml")) { ByteStreams.copy(xmlInput, tarLayer); } signature = signer.getSignature(); logger.atInfo().log("uploaded %,d bytes: %s.ryde", signer.getBytesWritten(), name); } String sigFilename = name + ".sig"; gcsUtils.createFromBytes(new GcsFilename(bucket, sigFilename), signature); ftpChan.get().put(new ByteArrayInputStream(signature), sigFilename); logger.atInfo().log("uploaded %,d bytes: %s.sig", signature.length, name); } } } /** Reads the contents of a file from Cloud Storage that contains nothing but an integer. */ private long readXmlLength(GcsFilename xmlLengthFilename) throws IOException { try (InputStream input = gcsUtils.openInputStream(xmlLengthFilename)) { return Long.parseLong(new String(ByteStreams.toByteArray(input), UTF_8).trim()); } } private void verifyFileExists(GcsFilename filename) { verify(gcsUtils.existsAndNotEmpty(filename), "Missing file: %s", filename); } }
Add more RDE upload informational logging ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=198587342
java/google/registry/rde/RdeUploadAction.java
Add more RDE upload informational logging
<ide><path>ava/google/registry/rde/RdeUploadAction.java <ide> <ide> @Override <ide> public void run() { <add> logger.atInfo().log("Attempting to acquire RDE upload lock for TLD '%s'.", tld); <ide> runner.lockRunAndRollForward(this, Registry.get(tld), timeout, CursorType.RDE_UPLOAD, interval); <ide> taskQueueUtils.enqueue( <del> reportQueue, <del> withUrl(RdeReportAction.PATH).param(RequestParameters.PARAM_TLD, tld)); <add> reportQueue, withUrl(RdeReportAction.PATH).param(RequestParameters.PARAM_TLD, tld)); <ide> } <ide> <ide> @Override <ide> public void runWithLock(final DateTime watermark) throws Exception { <add> logger.atInfo().log("Verifying readiness to upload the RDE deposit."); <ide> DateTime stagingCursorTime = getCursorTimeOrStartOfTime( <ide> ofy().load().key(Cursor.createKey(CursorType.RDE_STAGING, Registry.get(tld))).now()); <ide> if (!stagingCursorTime.isAfter(watermark)) { <ide> verifyFileExists(xmlFilename); <ide> verifyFileExists(xmlLengthFilename); <ide> verifyFileExists(reportFilename); <add> logger.atInfo().log("Commencing RDE upload for TLD '%s' to '%s'.", tld, uploadUrl); <ide> final long xmlLength = readXmlLength(xmlLengthFilename); <ide> retrier.callWithRetry( <ide> () -> { <ide> return null; <ide> }, <ide> JSchException.class); <add> logger.atInfo().log( <add> "Updating RDE cursor '%s' for TLD '%s' following successful upload.", RDE_UPLOAD_SFTP, tld); <ide> ofy() <ide> .transact( <ide> () -> <ide> @VisibleForTesting <ide> protected void upload( <ide> GcsFilename xmlFile, long xmlLength, DateTime watermark, String name) throws Exception { <del> logger.atInfo().log("Uploading %s to %s", xmlFile, uploadUrl); <add> logger.atInfo().log("Uploading XML file '%s' to remote path '%s'.", xmlFile, uploadUrl); <ide> try (InputStream gcsInput = gcsUtils.openInputStream(xmlFile); <ide> Ghostryde.Decryptor decryptor = ghostryde.openDecryptor(gcsInput, stagingDecryptionKey); <ide> Ghostryde.Decompressor decompressor = ghostryde.openDecompressor(decryptor);
Java
mit
acd60817f31e4507bfd045671b8eab3701a96b5d
0
CenturyLinkCloud/mdw,CenturyLinkCloud/mdw,CenturyLinkCloud/mdw,CenturyLinkCloud/mdw,CenturyLinkCloud/mdw,CenturyLinkCloud/mdw
/* * Copyright (C) 2017 CenturyLink, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.centurylink.mdw.services.workflow; import com.centurylink.mdw.activity.types.GeneralActivity; import com.centurylink.mdw.app.Templates; import com.centurylink.mdw.cache.CachingException; import com.centurylink.mdw.cache.impl.PackageCache; import com.centurylink.mdw.common.service.Query; import com.centurylink.mdw.common.service.ServiceException; import com.centurylink.mdw.common.translator.impl.JavaObjectTranslator; import com.centurylink.mdw.common.translator.impl.StringDocumentTranslator; import com.centurylink.mdw.common.translator.impl.YamlTranslator; import com.centurylink.mdw.config.PropertyManager; import com.centurylink.mdw.constant.OwnerType; import com.centurylink.mdw.constant.PropertyNames; import com.centurylink.mdw.dataaccess.DataAccess; import com.centurylink.mdw.dataaccess.DataAccessException; import com.centurylink.mdw.dataaccess.DatabaseAccess; import com.centurylink.mdw.dataaccess.RuntimeDataAccess; import com.centurylink.mdw.dataaccess.db.CommonDataAccess; import com.centurylink.mdw.dataaccess.reports.*; import com.centurylink.mdw.model.JsonObject; import com.centurylink.mdw.model.Jsonable; import com.centurylink.mdw.model.StringDocument; import com.centurylink.mdw.model.Value; import com.centurylink.mdw.model.asset.Asset; import com.centurylink.mdw.model.asset.AssetHeader; import com.centurylink.mdw.model.asset.AssetInfo; import com.centurylink.mdw.model.asset.AssetVersionSpec; import com.centurylink.mdw.model.event.Event; import com.centurylink.mdw.model.event.EventInstance; import com.centurylink.mdw.model.listener.Listener; import com.centurylink.mdw.model.report.Hotspot; import com.centurylink.mdw.model.report.Insight; import com.centurylink.mdw.model.report.Timepoint; import com.centurylink.mdw.model.system.SysInfo; import com.centurylink.mdw.model.system.SysInfoCategory; import com.centurylink.mdw.model.task.TaskInstance; import com.centurylink.mdw.model.user.UserAction; import com.centurylink.mdw.model.user.UserAction.Action; import com.centurylink.mdw.model.variable.Document; import com.centurylink.mdw.model.variable.DocumentReference; import com.centurylink.mdw.model.variable.Variable; import com.centurylink.mdw.model.variable.VariableInstance; import com.centurylink.mdw.model.workflow.Package; import com.centurylink.mdw.model.workflow.Process; import com.centurylink.mdw.model.workflow.*; import com.centurylink.mdw.service.data.WorkflowDataAccess; import com.centurylink.mdw.service.data.process.EngineDataAccess; import com.centurylink.mdw.service.data.process.EngineDataAccessDB; import com.centurylink.mdw.service.data.process.ProcessCache; import com.centurylink.mdw.services.*; import com.centurylink.mdw.services.messenger.InternalMessenger; import com.centurylink.mdw.services.messenger.MessengerFactory; import com.centurylink.mdw.services.process.ProcessEngineDriver; import com.centurylink.mdw.services.process.ProcessExecutor; import com.centurylink.mdw.translator.JsonTranslator; import com.centurylink.mdw.translator.TranslationException; import com.centurylink.mdw.translator.VariableTranslator; import com.centurylink.mdw.translator.XmlDocumentTranslator; import com.centurylink.mdw.util.log.LoggerUtil; import com.centurylink.mdw.util.log.StandardLogger; import com.centurylink.mdw.util.timer.CodeTimer; import com.centurylink.mdw.xml.XmlBeanWrapper; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlOptions; import org.json.JSONException; import org.json.JSONObject; import org.yaml.snakeyaml.Yaml; import javax.xml.bind.JAXBElement; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.file.Files; import java.nio.file.Paths; import java.sql.SQLException; import java.text.ParseException; import java.util.*; public class WorkflowServicesImpl implements WorkflowServices { private static StandardLogger logger = LoggerUtil.getStandardLogger(); private WorkflowDataAccess getWorkflowDao() { return new WorkflowDataAccess(); } protected RuntimeDataAccess getRuntimeDataAccess() throws DataAccessException { return DataAccess.getRuntimeDataAccess(new DatabaseAccess(null)); } protected ProcessAggregation getProcessAggregation() { return new ProcessAggregation(); } protected ActivityAggregation getActivityAggregation() { return new ActivityAggregation(); } public Map<String,String> getAttributes(String ownerType, Long ownerId) throws ServiceException { try { return getWorkflowDao().getAttributes(ownerType, ownerId); } catch (SQLException ex) { throw new ServiceException("Failed to load attributes for " + ownerType + "/" + ownerId, ex); } } public void setAttributes(String ownerType, Long ownerId, Map<String,String> attributes) throws ServiceException { try { getWorkflowDao().setAttributes(ownerType, ownerId, attributes); } catch (Exception ex) { throw new ServiceException("Failed to set attributes for " + ownerType + "/" + ownerId, ex); } } /** * Update attributes without deleting all attributes for this ownerId first */ public void updateAttributes(String ownerType, Long ownerId, Map<String,String> attributes) throws ServiceException { try { for (Map.Entry<String, String> attribute : attributes.entrySet()) { String attributeName = attribute.getKey(); String attributeValue = attribute.getValue(); getWorkflowDao().setAttribute(ownerType, ownerId, attributeName, attributeValue); } } catch (SQLException ex) { throw new ServiceException("Failed to update attributes for " + ownerType + "/" + ownerId, ex); } } /** * Replace all existing values */ public void setValues(String ownerType, String ownerId, Map<String,String> values) throws ServiceException { try { CommonDataAccess dao = new CommonDataAccess(); dao.setValues(ownerType, ownerId, values); } catch (SQLException ex) { throw new ServiceException(ex.getMessage(), ex); } } /** * Update certain values */ public void updateValues(String ownerType, String ownerId, Map<String,String> values) throws ServiceException { try { CommonDataAccess dao = new CommonDataAccess(); for (String key : values.keySet()) dao.setValue(ownerType, ownerId, key, values.get(key)); } catch (SQLException ex) { throw new ServiceException(ex.getMessage(), ex); } } public Map<String,String> getValues(String ownerType, String ownerId) throws ServiceException { try { if (OwnerType.SYSTEM.equals(ownerType)) { if ("mdwProperties".equals(ownerId)) { Map<String,String> mdwProps = new HashMap<>(); SysInfoCategory cat = ServiceLocator.getSystemServices().getMdwProperties(); for (SysInfo sysInfo : cat.getSysInfos()) { mdwProps.put(sysInfo.getName(), sysInfo.getValue()); } return mdwProps; } else { throw new ServiceException(ServiceException.BAD_REQUEST, "Unsupported System values: " + ownerId); } } else { CommonDataAccess dao = new CommonDataAccess(); return dao.getValues(ownerType, ownerId); } } catch (SQLException ex) { throw new ServiceException(ex.getMessage(), ex); } } public String getValue(String ownerType, String ownerId, String name) throws ServiceException { try { if (OwnerType.SYSTEM.equals(ownerType)) { if ("mdwProperties".equals(ownerId)) { Map<String,String> mdwProps = new HashMap<>(); SysInfoCategory cat = ServiceLocator.getSystemServices().getMdwProperties(); for (SysInfo sysInfo : cat.getSysInfos()) { mdwProps.put(sysInfo.getName(), sysInfo.getValue()); } return mdwProps.get(name); } else { throw new ServiceException(ServiceException.BAD_REQUEST, "Unsupported System values: " + ownerId); } } else { CommonDataAccess dao = new CommonDataAccess(); return dao.getValue(ownerType, ownerId, name); } } catch (SQLException ex) { throw new ServiceException(ex.getMessage(), ex); } } public List<String> getValueHolderIds(String valueName, String valuePattern) throws ServiceException { return getValueHolderIds(valueName, valuePattern, null); } public List<String> getValueHolderIds(String valueName, String valuePattern, String ownerType) throws ServiceException { try { CommonDataAccess dao = new CommonDataAccess(); if (ownerType == null) return dao.getValueOwnerIds(valueName, valuePattern); else return dao.getValueOwnerIds(ownerType, valueName, valuePattern); } catch (SQLException ex) { throw new ServiceException(ex.getMessage(), ex); } } public void registerTaskWaitEvent(Long taskInstanceId, Event event) throws ServiceException { registerTaskWaitEvent(taskInstanceId, event.getId(), event.getCompletionCode() == null ? "FINISH" : event.getCompletionCode()); } public void registerTaskWaitEvent(Long taskInstanceId, String eventName) throws ServiceException { registerTaskWaitEvent(taskInstanceId, eventName, "FINISH"); } public void registerTaskWaitEvent(Long taskInstanceId, String eventName, String completionCode) throws ServiceException { try { TaskInstance taskInstance = ServiceLocator.getTaskServices().getInstance(taskInstanceId); if (taskInstance != null) { Long activityInstanceId = taskInstance.getActivityInstanceId(); EngineDataAccess edao = new EngineDataAccessDB(); InternalMessenger msgBroker = MessengerFactory.newInternalMessenger(); ProcessExecutor engine = new ProcessExecutor(edao, msgBroker, false); // When registering an event on a Task via this method, the following rules apply: // - Event cannot be a legacy "recurring" event (means there can be multiple waiter for same event) // - Event will not trigger notification if pre-arrived. Notification will occur when event is published after this registration occurs engine.createEventWaitInstance(activityInstanceId, eventName, completionCode, false, false, true); } else throw new ServiceException("Task Instance was not found for ID " + taskInstanceId); } catch (Exception ex) { throw new ServiceException(ex.getMessage(), ex); } } @Override public void actionActivity(Long activityInstanceId, String action, String completionCode, String user) throws ServiceException { EngineDataAccessDB dataAccess = null; try { UserAction userAction = auditLog(action, UserAction.Entity.ActivityInstance, activityInstanceId, user, completionCode); if (Action.Proceed.toString().equalsIgnoreCase(action)) { ServiceLocator.getEventServices().skipActivity(null, activityInstanceId, completionCode); } else if (Action.Retry.toString().equalsIgnoreCase(action) || Action.Fail.toString().equalsIgnoreCase(action)) { ActivityInstance activityVo = ServiceLocator.getEventServices().getActivityInstance(activityInstanceId); if (Action.Retry.toString().equalsIgnoreCase(action)) ServiceLocator.getEventServices().retryActivity(activityVo.getActivityId(), activityInstanceId); else if (activityVo.getEndDate() == null) {// Only fail it if not yet completed dataAccess = new EngineDataAccessDB(); dataAccess.getDatabaseAccess().openConnection(); dataAccess.setActivityInstanceStatus(activityVo, WorkStatus.STATUS_FAILED, "Manually Failed by user " + user); } } else if (Action.Resume.toString().equalsIgnoreCase(action)) { String eventName = "mdw.Resume-" + activityInstanceId; notify(eventName, userAction.getJson().toString(), 0); } else { throw new ServiceException("Unsupported action: '" + action + "' for activity " + activityInstanceId); } } catch (Exception ex) { throw new ServiceException(ex.getMessage(), ex); } finally { if (dataAccess != null) dataAccess.getDatabaseAccess().closeConnection(); } } @Override public ActivityList getActivities(Query query) throws ServiceException { try { CodeTimer timer = new CodeTimer(true); ActivityList list = getRuntimeDataAccess().getActivityInstanceList(query); timer.logTimingAndContinue("getRuntimeDataAccess().getActivityInstanceList()"); list = populateActivities(list, query); timer.stopAndLogTiming("WorkflowServicesImpl.populateActivities()"); return list; } catch (DataAccessException ex) { throw new ServiceException(500, "Error retrieving activity instance for query: " + query, ex); } } public ProcessInstance getProcess(Long instanceId) throws ServiceException { return getProcess(instanceId, false); } public ProcessInstance getProcess(Long instanceId, boolean withSubprocs) throws ServiceException { try { RuntimeDataAccess runtimeDataAccess = getRuntimeDataAccess(); ProcessInstance process = runtimeDataAccess.getProcessInstanceAll(instanceId); if (process == null) throw new ServiceException(ServiceException.NOT_FOUND, "Process instance not found: " + instanceId); if (withSubprocs) { // embedded subprocs Map<String,String> criteria = new HashMap<>(); criteria.put("owner", OwnerType.MAIN_PROCESS_INSTANCE); criteria.put("ownerId", process.getId().toString()); criteria.put("processId", process.getProcessId().toString()); ProcessList subprocList = runtimeDataAccess.getProcessInstanceList(criteria, 0, Query.MAX_ALL, "order by process_instance_id"); if (subprocList != null && subprocList.getItems() != null && subprocList.getItems().size() > 0) { List<ProcessInstance> subprocs = new ArrayList<>(); for (ProcessInstance subproc : subprocList.getItems()) { ProcessInstance fullsub = runtimeDataAccess.getProcessInstance(subproc.getId()); fullsub.setProcessId(Long.parseLong(subproc.getComment())); subprocs.add(fullsub); } process.setSubprocessInstances(subprocs); } } return process; } catch (DataAccessException ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, "Error retrieving process instance: " + instanceId + ": " + ex.getMessage(), ex); } } public ProcessInstance getMasterProcess(String masterRequestId) throws ServiceException { Query query = new Query(); query.setFilter("master", true); query.setFilter("masterRequestId", masterRequestId); query.setSort("process_instance_id"); query.setDescending(true); List<ProcessInstance> instances = getProcesses(query).getProcesses(); if (instances.isEmpty()) return null; else return getProcess(instances.get(0).getId()); } public Map<String,Value> getProcessValues(Long instanceId) throws ServiceException { return getProcessValues(instanceId, false); } public Map<String,Value> getProcessValues(Long instanceId, boolean includeEmpty) throws ServiceException { ProcessRuntimeContext runtimeContext = getContext(instanceId); Map<String,Value> values = new HashMap<>(); Map<String,Variable> varDefs = getVariableDefinitions(runtimeContext.getProcess().getVariables()); Map<String,Object> variables = runtimeContext.getVariables(); if (variables != null) { for (String key : variables.keySet()) { String stringVal = runtimeContext.getValueAsString(key); if (stringVal != null) { Variable varDef = varDefs.get(key); Value value; if (varDef != null) value = varDef.toValue(); else value = new Value(key); value.setValue(stringVal); values.put(key, value); } } } if (includeEmpty) { for (String name : varDefs.keySet()) { if (!values.containsKey(name)) values.put(name, varDefs.get(name).toValue()); } } return values; } protected Map<String,Variable> getVariableDefinitions(List<Variable> varList) { Map<String,Variable> varDefs = new HashMap<>(); if (varList != null) { for (Variable var : varList) varDefs.put(var.getName(), var); } return varDefs; } public Value getProcessValue(Long instanceId, String name) throws ServiceException { ProcessRuntimeContext runtimeContext = getContext(instanceId); Variable var = runtimeContext.getProcess().getVariable(name); if (var == null && !ProcessRuntimeContext.isExpression(name)) throw new ServiceException(ServiceException.NOT_FOUND, "No variable defined: " + name); String stringVal = null; if (var != null && VariableTranslator.isDocumentReferenceVariable(runtimeContext.getPackage(), var.getType())) { VariableInstance varInst = runtimeContext.getProcessInstance().getVariable(name); // ensure consistent formatting for doc values if (varInst != null && varInst.getStringValue() != null && varInst.getStringValue().startsWith("DOCUMENT:")) stringVal = getDocumentStringValue(new DocumentReference(varInst.getStringValue()).getDocumentId()); } else { stringVal = runtimeContext.getValueAsString(name); } if (stringVal == null) throw new ServiceException(ServiceException.NOT_FOUND, "No value '" + name + "' found for instance: " + instanceId); Variable varDef = getVariableDefinitions(runtimeContext.getProcess().getVariables()).get(name); Value value; if (varDef != null) value = varDef.toValue(); else value = new Value(name); value.setValue(stringVal); return value; } public ProcessRuntimeContext getContext(Long instanceId) throws ServiceException { return getContext(instanceId, false); } public ProcessRuntimeContext getContext(Long instanceId, Boolean embeddedVars) throws ServiceException { ProcessInstance instance = getProcess(instanceId); // Edge case where we want to get main process variables when we loaded embedded process instance // Applies to when looking/setting process variables in manual task located in embedded subproc if (instance.isEmbedded() && embeddedVars) instance.setVariables(getProcess(instance.getOwnerId()).getVariables()); Process process = null; if (instance.getProcessInstDefId() > 0L) process = ProcessCache.getProcessInstanceDefiniton(instance.getProcessId(), instance.getProcessInstDefId()); if (process == null) process = ProcessCache.getProcess(instance.getProcessId()); Package pkg = PackageCache.getProcessPackage(instance.getProcessId()); if (process == null) throw new ServiceException(ServiceException.NOT_FOUND, "Process definition not found for id: " + instance.getProcessId()); Map<String,Object> vars = new HashMap<>(); try { if (instance.getVariables() != null) { for (VariableInstance var : instance.getVariables()) { Object value = var.getData(); if (value instanceof DocumentReference) { try { Document docVO = getWorkflowDao().getDocument(((DocumentReference)value).getDocumentId()); value = docVO == null ? null : docVO.getObject(var.getType(), pkg); vars.put(var.getName(), value); } catch (TranslationException ex) { // parse error on one doc should not prevent other vars from populating logger.severeException("Error translating " + var.getName() + " for process instance " + instanceId, ex); } } else { vars.put(var.getName(), value); } } } return new ProcessRuntimeContext(pkg, process, instance, 0, vars); } catch (DataAccessException ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, ex.getMessage(), ex); } } @Override public ProcessList getProcesses(Query query) throws ServiceException { try { String procDefSpec = query.getFilter("definition"); // in form of AssetVersionSpec if (procDefSpec != null) { AssetVersionSpec spec = AssetVersionSpec.parse(procDefSpec); if (spec.getName().endsWith(".proc")) spec = new AssetVersionSpec(spec.getPackageName(), spec.getName().substring(0, spec.getName().length() - 5), spec.getVersion()); if (spec.isRange()) { List<Process> procDefs = ProcessCache.getProcessesSmart(spec); String[] procIds = new String[procDefs.size()]; for (int i = 0; i < procDefs.size(); i++) procIds[i] = procDefs.get(i).getId().toString(); query.setArrayFilter("processIds", procIds); } else { Process procDef = ProcessCache.getProcessSmart(spec); if (procDef == null) throw new ServiceException(ServiceException.NOT_FOUND, "Process definition not found for spec: " + procDefSpec); query.setFilter("processId", procDef.getId()); } } return getWorkflowDao().getProcessInstances(query); } catch (DataAccessException ex) { throw new ServiceException(500, "Error retrieving process instance for query: " + query, ex); } } public ProcessInstance getProcessForTrigger(Long triggerId) throws ServiceException { String ownerContent = getDocumentStringValue(triggerId); try { JSONObject json = new JsonObject(ownerContent); if (!json.has("runtimeContext")) throw new ServiceException(ServiceException.NOT_FOUND, "Trigger document does not have RuntimeContext information: " + triggerId); JSONObject runtimeContext = json.getJSONObject("runtimeContext"); long procInstId; if (runtimeContext.has("activityInstance")) procInstId = runtimeContext.getJSONObject("activityInstance").getLong("processInstanceId"); else if (runtimeContext.has("processInstance")) procInstId = runtimeContext.getJSONObject("processInstance").getLong("id"); else throw new ServiceException(ServiceException.NOT_FOUND, "Trigger document does not have instance information: " + triggerId); return getProcess(procInstId); } catch (JSONException ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, "Error retrieving triggerId: " + triggerId , ex); } } public Document getDocument(Long id) throws ServiceException { try { if (!getWorkflowDao().isDocument(id)) throw new ServiceException(ServiceException.NOT_FOUND, "Document not found: " + id); return getWorkflowDao().getDocument(id); } catch (Exception ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, "Error retrieving document: " + id, ex); } } @Override public ActivityInstance getActivity(Long instanceId) throws ServiceException { try { Query query = new Query(); query.setFilter("instanceId", instanceId); query.setFind(null); ActivityList list = getRuntimeDataAccess().getActivityInstanceList(query); if (list.getCount() > 0) { list = populateActivities(list, query); return list.getActivities().get(0); } else { return null; } } catch (Exception ex) { throw new ServiceException(500, "Error retrieving activity instance: " + instanceId + ": " + ex.getMessage(), ex); } } public List<ProcessAggregate> getTopProcesses(Query query) throws ServiceException { try { CodeTimer timer = new CodeTimer(true); List<ProcessAggregate> list = getProcessAggregation().getTops(query); timer.logTimingAndContinue("WorkflowServicesImpl.getTopProcesses()"); if ("status".equals(query.getFilter("by"))) { list = populateProcessStatuses(list); } else { list = populateProcesses(list); } timer.stopAndLogTiming("WorkflowServicesImpl.getTopProcesses()"); return list; } catch (DataAccessException ex) { throw new ServiceException(500, "Error retrieving top throughput processes: query=" + query, ex); } } public TreeMap<Date,List<ProcessAggregate>> getProcessBreakdown(Query query) throws ServiceException { try { TreeMap<Date,List<ProcessAggregate>> map = getProcessAggregation().getBreakdown(query); if (query.getFilters().get("processIds") != null) { for (Date date : map.keySet()) populateProcesses(map.get(date)); } return map; } catch (DataAccessException ex) { throw new ServiceException(500, "Error retrieving process breakdown: query=" + query, ex); } } public List<Insight> getProcessInsights(Query query) throws ServiceException { try { return new ProcessInsights().getInsights(query); } catch (SQLException | ParseException ex) { throw new ServiceException(500, "Error retrieving process insights: query=" + query, ex); } } public List<Timepoint> getProcessTrend(Query query) throws ServiceException { try { return new ProcessInsights().getTrend(query); } catch (SQLException | ParseException ex) { throw new ServiceException(500, "Error retrieving process trend: query=" + query, ex); } } public List<Hotspot> getProcessHotspots(Query query) throws ServiceException { try { return new ProcessHotspots().getHotspots(query); } catch (SQLException ex) { throw new ServiceException(500, "Error retrieving process hotspots: query=" + query, ex); } } /** * Fills in process header info, consulting latest instance comment if necessary. */ protected List<ProcessAggregate> populateProcesses(List<ProcessAggregate> processAggregates) throws DataAccessException { AggregateDataAccess dataAccess = null; for (ProcessAggregate pc : processAggregates) { Process process = ProcessCache.getProcess(pc.getId()); if (process == null) { logger.severe("Missing definition for process id: " + pc.getId()); pc.setDefinitionMissing(true); // may have been deleted -- infer from comments if (dataAccess == null) dataAccess = getProcessAggregation(); CodeTimer timer = new CodeTimer(true); String comments = getWorkflowDao().getLatestProcessInstanceComments(pc.getId()); timer.stopAndLogTiming("getLatestProcessInstanceComments()"); if (comments != null) { AssetHeader assetHeader = new AssetHeader(comments); pc.setName(assetHeader.getName()); pc.setVersion(assetHeader.getVersion()); pc.setPackageName(assetHeader.getPackageName()); } else { logger.severe("Unable to infer process name for: " + pc.getId()); pc.setName("Unknown (" + pc.getId() + ")"); } } else { pc.setName(process.getName()); pc.setVersion(Asset.formatVersion(process.getVersion())); pc.setPackageName(process.getPackageName()); } } return processAggregates; } protected List<ProcessAggregate> populateProcessStatuses(List<ProcessAggregate> processAggregates) { for (ProcessAggregate processAggregate : processAggregates) { processAggregate.setName(WorkStatuses.getName((int)processAggregate.getId())); } // add any empty statuses for (Integer statusCd : WorkStatuses.getWorkStatuses().keySet()) { if (!statusCd.equals(WorkStatus.STATUS_PENDING_PROCESS) && !statusCd.equals(WorkStatus.STATUS_HOLD)) { boolean found = processAggregates.stream().anyMatch(agg -> agg.getId() == statusCd); if (!found) { ProcessAggregate processAggregate = new ProcessAggregate(0); processAggregate.setId(statusCd); processAggregate.setCount(0); processAggregate.setName(WorkStatuses.getWorkStatuses().get(statusCd)); processAggregates.add(processAggregate); } } } return processAggregates; } /** * Fills in process header info, consulting latest instance comment if necessary. * @param query */ protected ActivityList populateActivities(ActivityList activityList, Query query) throws DataAccessException { AggregateDataAccess dataAccess = null; List<ActivityInstance> aList = activityList.getActivities(); ArrayList<ActivityInstance> matchActivities = new ArrayList<>(); String activityName = query.getFilter("activityName"); String decodedActName = ""; if (activityName != null) { try { decodedActName = java.net.URLDecoder.decode(activityName, "UTF-8"); } catch (UnsupportedEncodingException e) { logger.severe("Unable to decode: " + activityName); } } for (ActivityInstance activityInstance : aList) { Process process = ProcessCache.getProcess(activityInstance.getProcessId()); if (process == null) { logger.severe("Missing definition for process id: " + activityInstance.getProcessId()); activityInstance.setDefinitionMissing(true); // may have been deleted -- infer from comments if (dataAccess == null) dataAccess = getActivityAggregation(); CodeTimer timer = new CodeTimer(true); String comments = getWorkflowDao().getLatestProcessInstanceComments(activityInstance.getProcessId()); timer.stopAndLogTiming("getLatestProcessInstanceComments()"); if (comments != null) { AssetHeader assetHeader = new AssetHeader(comments); activityInstance.setProcessName(assetHeader.getName()); activityInstance.setProcessVersion(assetHeader.getVersion()); activityInstance.setPackageName(assetHeader.getPackageName()); } else { logger.severe("Unable to infer process name for: " + activityInstance.getProcessId()); activityInstance.setProcessName("Unknown (" + activityInstance.getProcessId() + ")"); } activityInstance.setName("Unknown (" + activityInstance.getDefinitionId() + ")"); } else { String logicalId = activityInstance.getDefinitionId(); Activity actdef = process.getActivityById(logicalId); if (actdef != null) { if (!decodedActName.isEmpty() && actdef.getName().startsWith(decodedActName)) matchActivities.add(activityInstance); activityInstance.setName(actdef.getName().replaceAll("\\r", "").replace('\n', ' ')); } else { activityInstance.setName("Unknown (" + activityInstance.getDefinitionId() + ")"); } activityInstance.setProcessName(process.getName()); activityInstance.setProcessVersion(Asset.formatVersion(process.getVersion())); activityInstance.setPackageName(process.getPackageName()); } } if (!decodedActName.isEmpty()) activityList.setActivities(matchActivities); activityList.setCount(activityList.getActivities().size()); if (activityList.getTotal() <= 0L) activityList.setTotal(activityList.getActivities().size()); return activityList; } /** * Fills in process header info, consulting latest instance comment if necessary. */ protected List<ActivityAggregate> populateActivities(List<ActivityAggregate> activityCounts) throws DataAccessException { AggregateDataAccess dataAccess = null; for (ActivityAggregate ac : activityCounts) { Process process = ProcessCache.getProcess(ac.getProcessId()); if (process == null) { logger.severe("Missing definition for process id: " + ac.getProcessId()); ac.setDefinitionMissing(true); // may have been deleted -- infer from comments if (dataAccess == null) dataAccess = getActivityAggregation(); CodeTimer timer = new CodeTimer(true); String comments = getWorkflowDao().getLatestProcessInstanceComments(ac.getProcessId()); timer.stopAndLogTiming("getLatestProcessInstanceComments()"); if (comments != null) { AssetHeader assetHeader = new AssetHeader(comments); ac.setProcessName(assetHeader.getName()); ac.setActivityName(ac.getDefinitionId()); ac.setName(ac.getProcessName() + ": " + ac.getActivityName()); ac.setVersion(assetHeader.getVersion()); ac.setPackageName(assetHeader.getPackageName()); } else { logger.severe("Unable to infer process name for: " + ac.getProcessId()); ac.setProcessName("Unknown (" + ac.getProcessId() + ")"); } } else { ac.setProcessName(process.getName()); ac.setVersion(Asset.formatVersion(process.getVersion())); ac.setPackageName(process.getPackageName()); String logicalId = ac.getDefinitionId(); Activity actdef = process.getActivityById(logicalId); if (actdef != null) { String actName = actdef.getName().replaceAll("\\r", "").replace('\n', ' '); ac.setActivityName(actName); ac.setProcessName(actdef.getProcessName()); // in case subproc ac.setName(ac.getProcessName() + ": " + ac.getActivityName()); } else { ac.setName("Unknown (" + ac.getDefinitionId() + ")"); } } } return activityCounts; } protected List<ActivityAggregate> populateActivityStatuses(List<ActivityAggregate> activityAggregates) { for (ActivityAggregate activityAggregate : activityAggregates) { activityAggregate.setName(WorkStatuses.getName((int)activityAggregate.getId())); } // add any empty statuses int[] statusCds = new int[] {WorkStatus.STATUS_IN_PROGRESS, WorkStatus.STATUS_FAILED, WorkStatus.STATUS_WAITING}; for (int statusCd : statusCds) { boolean found = activityAggregates.stream().anyMatch(agg -> { return agg.getId() == statusCd; }); if (!found) { ActivityAggregate activityAggregate = new ActivityAggregate(0); activityAggregate.setId(statusCd); activityAggregate.setCount(0); activityAggregate.setName(WorkStatuses.getWorkStatuses().get(statusCd)); activityAggregates.add(activityAggregate); } } return activityAggregates; } public List<ActivityAggregate> getTopActivities(Query query) throws ServiceException { try { CodeTimer timer = new CodeTimer(true); List<ActivityAggregate> list = getActivityAggregation().getTops(query); timer.logTimingAndContinue("AggregateDataAccessVcs.getTopThroughputActivityInstances()"); if ("status".equals(query.getFilter("by"))) { list = populateActivityStatuses(list); } else { list = populateActivities(list); } timer.stopAndLogTiming("WorkflowServicesImpl.populate()"); return list; } catch (DataAccessException ex) { throw new ServiceException(500, "Error retrieving top throughput activities: query=" + query, ex); } } public TreeMap<Date,List<ActivityAggregate>> getActivityBreakdown(Query query) throws ServiceException { try { TreeMap<Date,List<ActivityAggregate>> map = getActivityAggregation().getBreakdown(query); if (query.getFilters().get("activityIds") != null) { for (Date date : map.keySet()) populateActivities(map.get(date)); } return map; } catch (DataAccessException ex) { throw new ServiceException(500, "Error retrieving activity instance breakdown: query=" + query, ex); } } public Process getProcessDefinition(String assetPath, Query query) throws ServiceException { int lastSlash = assetPath.lastIndexOf('/'); if (lastSlash <= 0) throw new ServiceException(ServiceException.BAD_REQUEST, "Bad asset path: " + assetPath); String processName = assetPath; //.substring(lastSlash + 1); if (assetPath.endsWith(".proc")) processName = processName.substring(0, processName.length() - ".proc".length()); int version = query == null ? 0 : query.getIntFilter("version"); if (version < 0) version = 0; boolean forUpdate = query == null ? false : query.getBooleanFilter("forUpdate"); Process process = ProcessCache.getProcess(processName, version); if (forUpdate) { // load from file try { byte[] bytes = Files.readAllBytes(Paths.get(process.getRawFile().getAbsolutePath())); process = new Process(new JsonObject(new String(bytes))); process.setName(processName.substring(lastSlash + 1)); process.setPackageName(processName.substring(0, lastSlash)); } catch (Exception ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, "Error reading process: " + process.getRawFile()); } } if (process == null) throw new ServiceException(ServiceException.NOT_FOUND, "Process definition not found: " + assetPath); return process; } public List<Process> getProcessDefinitions(Query query) throws ServiceException { try { String find = query.getFind(); if (find == null) { return ProcessCache.getAllProcesses(); } else { List<Process> found = new ArrayList<>(); for (Process processVO : ProcessCache.getAllProcesses()) { if (processVO.getName() != null && processVO.getName().startsWith(find)) found.add(processVO); else if (find.indexOf(".") > 0 && processVO.getPackageName() != null && processVO.getPackageName().startsWith(find)) found.add(processVO); } return found; } } catch (DataAccessException ex) { throw new ServiceException(500, ex.getMessage(), ex); } } public Process getProcessDefinition(Long id) { return ProcessCache.getProcess(id); } public ActivityList getActivityDefinitions(Query query) throws ServiceException { try { String find = query.getFind(); List<ActivityInstance> activityInstanceList = new ArrayList<>(); ActivityList found = new ActivityList(ActivityList.ACTIVITY_INSTANCES, activityInstanceList); if (find == null) { List<Process> processes = ProcessCache.getAllProcesses(); for (Process process : processes) { process = ProcessCache.getProcess(process.getId()); List<Activity> activities = process.getActivities(); for (Activity activityVO : activities) { if (activityVO.getName() != null && activityVO.getName().startsWith(find)) { ActivityInstance ai = new ActivityInstance(); ai.setId(activityVO.getId()); ai.setName(activityVO.getName()); ai.setDefinitionId(activityVO.getLogicalId()); ai.setProcessId(process.getId()); ai.setProcessName(process.getName()); ai.setProcessVersion(process.getVersionString()); activityInstanceList.add(ai); } } } } else { for (Process process : ProcessCache.getAllProcesses()) { process = ProcessCache.getProcess(process.getId()); List<Activity> activities = process.getActivities(); for (Activity activityVO : activities) { if (activityVO.getName() != null && activityVO.getName().startsWith(find)) { ActivityInstance ai = new ActivityInstance(); ai.setId(activityVO.getId()); ai.setName(activityVO.getName()); ai.setDefinitionId(activityVO.getLogicalId()); ai.setProcessId(process.getId()); ai.setProcessName(process.getName()); ai.setProcessVersion(process.getVersionString()); activityInstanceList.add(ai); } } } } found.setRetrieveDate(DatabaseAccess.getDbDate()); found.setCount(activityInstanceList.size()); found.setTotal(activityInstanceList.size()); return found; } catch (DataAccessException ex) { throw new ServiceException(500, ex.getMessage(), ex); } } private static List<ActivityImplementor> activityImplementors; /** * Does not include pagelet. * TODO: cache should be refreshable */ public List<ActivityImplementor> getImplementors() throws ServiceException { if (activityImplementors == null) { try { activityImplementors = DataAccess.getProcessLoader().getActivityImplementors(); for (ActivityImplementor impl : activityImplementors) { // qualify the icon location String icon = impl.getIcon(); if (icon != null && !icon.startsWith("shape:") && icon.indexOf('/') <= 0) { for (Package pkg : PackageCache.getPackages()) { for (Asset asset : pkg.getAssets()) { if (asset.getName().equals(icon)) { impl.setIcon(pkg.getName() + "/" + icon); break; } } } } impl.setPagelet(null); } AssetServices assetServices = ServiceLocator.getAssetServices(); Map<String,List<AssetInfo>> annotatedAssets = assetServices.getAssetsOfTypes(new String[]{"java", "kt"}); for (String packageName : annotatedAssets.keySet()) { Package pkg = PackageCache.getPackage(packageName); for (AssetInfo assetInfo : annotatedAssets.get(packageName)) { ActivityImplementor impl = getAnnotatedImpl(pkg, assetInfo); if (impl != null) activityImplementors.add(impl); } } } catch (CachingException ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, ex.getMessage(), ex); } catch (DataAccessException ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, ex.getMessage(), ex); } } return activityImplementors; } public ActivityImplementor getImplementor(String className) throws ServiceException { try { for (ActivityImplementor implementor : DataAccess.getProcessLoader().getActivityImplementors()) { String implClassName = implementor.getImplementorClass(); if (className == null) { if (implClassName == null) return implementor; } else if (implClassName.equals(className)) { return implementor; } } Package pkg = PackageCache.getPackage(className.substring(0, className.lastIndexOf('.'))); if (pkg != null) { AssetInfo assetInfo = ServiceLocator.getAssetServices().getImplAsset(className); if (assetInfo != null) return getAnnotatedImpl(pkg, assetInfo); } return null; } catch (DataAccessException ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, ex.getMessage(), ex); } } private ActivityImplementor getAnnotatedImpl(Package pkg, AssetInfo assetInfo) { String implClass = pkg.getName() + "." + assetInfo.getRootName(); try { String contents = new String(Files.readAllBytes(assetInfo.getFile().toPath())); if (contents.contains("@Activity")) { GeneralActivity activity = pkg.getActivityImplementor(implClass); com.centurylink.mdw.annotations.Activity annotation = activity.getClass().getAnnotation(com.centurylink.mdw.annotations.Activity.class); return new ActivityImplementor(implClass, annotation); } } catch (Exception ex) { logger.severeException("Cannot load " + implClass, ex); } return null; } public Long launchProcess(String name, String masterRequestId, String ownerType, Long ownerId, Map<String,Object> parameters) throws ServiceException { try { Process process = ProcessCache.getProcess(name); ProcessEngineDriver driver = new ProcessEngineDriver(); Map<String,String> params = translateParameters(process, parameters); return driver.startProcess(process.getId(), masterRequestId, ownerType, ownerId, params, null); } catch (Exception ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, ex.getMessage(), ex); } } public Long launchProcess(Process process, String masterRequestId, String ownerType, Long ownerId, Map<String,String> params) throws ServiceException { try { ProcessEngineDriver driver = new ProcessEngineDriver(); return driver.startProcess(process.getId(), masterRequestId, ownerType, ownerId, params, null); } catch (Exception ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, ex.getMessage(), ex); } } public Object invokeServiceProcess(String name, Object masterRequest, String masterRequestId, Map<String,Object> parameters, Map<String,String> headers) throws ServiceException { return invokeServiceProcess(name, masterRequest, masterRequestId, parameters, headers, null); } public Object invokeServiceProcess(String processName, Object masterRequest, String masterRequestId, Map<String,Object> parameters, Map<String,String> headers, Map<String,String> responseHeaders) throws ServiceException { try { Long docId = 0L; String request = null; Process processVO = ProcessCache.getProcess(processName, 0); Package pkg = PackageCache.getProcessPackage(processVO.getId()); if (masterRequest != null) { String docType = getDocType(masterRequest); EventServices eventMgr = ServiceLocator.getEventServices(); docId = eventMgr.createDocument(docType, OwnerType.LISTENER_REQUEST, 0L, masterRequest, pkg); request = VariableTranslator.realToString(pkg, docType, masterRequest); if (headers == null) headers = new HashMap<>(); headers.put(Listener.METAINFO_DOCUMENT_ID, docId.toString()); } Map<String,String> stringParams = translateParameters(processVO, parameters); String responseVarName = "response"; // currently not configurable ProcessEngineDriver engineDriver = new ProcessEngineDriver(); String resp = engineDriver.invokeService(processVO.getId(), OwnerType.DOCUMENT, docId, masterRequestId, request, stringParams, responseVarName, headers); Object response = resp; if (resp != null) { Variable var = processVO.getVariable(responseVarName); if (var != null && var.isOutput() && !var.isString()) { response = VariableTranslator.realToObject(pkg, var.getType(), resp); } } Variable responseHeadersVar = processVO.getVariable("responseHeaders"); if (responseHeaders != null && responseHeadersVar != null && responseHeadersVar.getType().equals("java.util.Map<String,String>")) { ProcessInstance processInstance = getMasterProcess(masterRequestId); if (processInstance != null) { VariableInstance respHeadersVar = processInstance.getVariable("responseHeaders"); if (respHeadersVar != null) { Document doc = getDocument(((DocumentReference)respHeadersVar.getData()).getDocumentId()); Map<?,?> respHeaders = (Map<?,?>) doc.getObject("java.util.Map<String,String>", PackageCache.getPackage(processInstance.getPackageName())); for (Object key : respHeaders.keySet()) responseHeaders.put(key.toString(), respHeaders.get(key).toString()); } } } return response; } catch (ServiceException ex) { throw ex; } catch (Exception ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, ex.getMessage(), ex); } } public String invokeServiceProcess(Process process, String masterRequestId, String ownerType, Long ownerId, Map<String,String> params) throws ServiceException { return invokeServiceProcess(process, masterRequestId, ownerType, ownerId, params, null); } public String invokeServiceProcess(Process process, String masterRequestId, String ownerType, Long ownerId, Map<String,String> params, Map<String,String> headers) throws ServiceException { try { ProcessEngineDriver driver = new ProcessEngineDriver(); String masterRequest = params == null ? null : params.get("request"); return driver.invokeService(process.getId(), ownerType, ownerId, masterRequestId, masterRequest, params, null, headers); } catch (Exception ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, ex.getMessage(), ex); } } /** * Saves document as raw StringDocument. */ public Integer notify(String event, String message, int delay) throws ServiceException { try { EventServices eventManager = ServiceLocator.getEventServices(); Long docId = eventManager.createDocument(StringDocument.class.getName(), OwnerType.INTERNAL_EVENT, 0L, message, null); return eventManager.notifyProcess(event, docId, message, delay); } catch (Exception ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, ex.getMessage(), ex); } } public Integer notify(Package runtimePackage, String eventName, Object eventMessage) throws ServiceException { int delay = PropertyManager.getIntegerProperty(PropertyNames.ACTIVITY_RESUME_DELAY, 2); return notify(runtimePackage, eventName, eventMessage, delay); } public Integer notify(Package runtimePackage, String eventName, Object eventMessage, int delay) throws ServiceException { try { Long docId = 0L; String message = null; if (eventMessage != null) { String docType = getDocType(eventMessage); EventServices eventMgr = ServiceLocator.getEventServices(); docId = eventMgr.createDocument(docType, OwnerType.LISTENER_REQUEST, 0L, eventMessage, runtimePackage); message = VariableTranslator.realToString(runtimePackage, docType, eventMessage); } EventServices eventManager = ServiceLocator.getEventServices(); return eventManager.notifyProcess(eventName, docId, message, delay); } catch (ServiceException ex) { throw ex; } catch (Exception ex) { logger.severeException(ex.getMessage(), ex); // TODO why not throw? return EventInstance.RESUME_STATUS_FAILURE; } } public void setVariable(Long processInstanceId, String varName, Object value) throws ServiceException { ProcessRuntimeContext runtimeContext = getContext(processInstanceId); if (runtimeContext == null) throw new ServiceException(ServiceException.NOT_FOUND, "Process instance not found: " + processInstanceId); setVariable(runtimeContext, varName, value); } public void setVariable(ProcessRuntimeContext context, String varName, Object value) throws ServiceException { Integer statusCode = context.getProcessInstance().getStatusCode(); if (WorkStatus.STATUS_COMPLETED.equals(statusCode) || WorkStatus.STATUS_CANCELLED.equals(statusCode) || WorkStatus.STATUS_FAILED.equals(statusCode)) { throw new ServiceException(ServiceException.BAD_REQUEST, "Cannot set value for process in final status: " + statusCode); } Variable var = context.getProcess().getVariable(varName); if (var == null) throw new ServiceException(ServiceException.NOT_FOUND, "Process variable not defined: " + varName); String type = var.getType(); if (VariableTranslator.isDocumentReferenceVariable(context.getPackage(), type)) { setDocumentValue(context, varName, value); } else { try { VariableInstance varInst = context.getProcessInstance().getVariable(varName); WorkflowDataAccess workflowDataAccess = getWorkflowDao(); if (varInst == null) { varInst = new VariableInstance(); varInst.setName(varName); varInst.setVariableId(var.getId()); varInst.setType(type); if (value != null && !value.equals("")) { if (value instanceof String) varInst.setStringValue((String)value); else varInst.setData(value); Long procInstId = context.getProcessInstance().isEmbedded() ? context.getProcessInstance().getOwnerId() : context.getProcessInstanceId(); workflowDataAccess.createVariable(procInstId, varInst); } } else { if (value == null || value.equals("")) { workflowDataAccess.deleteVariable(varInst); } else { if (value instanceof String) varInst.setStringValue((String)value); else varInst.setData(value); workflowDataAccess.updateVariable(varInst); } } } catch (SQLException ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, "Error updating " + varName + " for process: " + context.getProcessInstanceId(), ex); } } } public void setVariables(Long processInstanceId, Map<String,Object> values) throws ServiceException { ProcessRuntimeContext runtimeContext = getContext(processInstanceId); if (runtimeContext == null) throw new ServiceException(ServiceException.NOT_FOUND, "Process instance not found: " + processInstanceId); setVariables(runtimeContext, values); } public void setVariables(ProcessRuntimeContext context, Map<String,Object> values) throws ServiceException { for (String name : values.keySet()) { setVariable(context, name, values.get(name)); } } public void setDocumentValue(ProcessRuntimeContext context, String varName, Object value) throws ServiceException { VariableInstance varInst = context.getProcessInstance().getVariable(varName); if (varInst == null && value != null && !value.equals("")) { createDocument(context, varName, value); } else { if (value == null || value.equals("")) { try { // TODO: delete doc content also getWorkflowDao().deleteVariable(varInst); } catch (SQLException ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, "Error deleting " + varName + " for process: " + context.getProcessInstanceId(), ex); } } else { updateDocument(context, varName, value); } } } /** * TODO: Many places fail to set the ownerId for documents owned by VARIABLE_INSTANCE, * and these need to be updated to use this method. */ public void createDocument(ProcessRuntimeContext context, String varName, Object value) throws ServiceException { String type = context.getProcess().getVariable(varName).getType(); EventServices eventMgr = ServiceLocator.getEventServices(); Long procInstId = context.getProcessInstance().isEmbedded() ? context.getProcessInstance().getOwnerId() : context.getProcessInstanceId(); try { Long docId = eventMgr.createDocument(type, OwnerType.PROCESS_INSTANCE, procInstId, value, context.getPackage()); VariableInstance varInst = eventMgr.setVariableInstance(procInstId, varName, new DocumentReference(docId)); eventMgr.updateDocumentInfo(docId, type, OwnerType.VARIABLE_INSTANCE, varInst.getInstanceId()); } catch (DataAccessException ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, "Error creating document for process: " + procInstId, ex); } } public ProcessRun runProcess(ProcessRun runRequest) throws ServiceException, JSONException { Long definitionId = runRequest.getDefinitionId(); if (definitionId == null) throw new ServiceException(ServiceException.BAD_REQUEST, "Missing definitionId"); Process proc = getProcessDefinition(definitionId); if (proc == null) throw new ServiceException(ServiceException.NOT_FOUND, "Process definition not found for id: " + definitionId); ProcessRun actualRun = new ProcessRun(runRequest.getJson()); // clone Long runId = runRequest.getId(); if (runId == null) { runId = System.nanoTime(); actualRun.setId(runId); } String masterRequestId = runRequest.getMasterRequestId(); if (masterRequestId == null) { masterRequestId = runId.toString(); actualRun.setMasterRequestId(masterRequestId); } String ownerType = runRequest.getOwnerType(); Long ownerId = runRequest.getOwnerId(); if (ownerType == null) { if (ownerId != null) throw new ServiceException(ServiceException.BAD_REQUEST, "ownerId not allowed without ownerType"); EventServices eventMgr = ServiceLocator.getEventServices(); try { ownerType = OwnerType.DOCUMENT; actualRun.setOwnerType(ownerType); ownerId = eventMgr.createDocument(JSONObject.class.getName(), OwnerType.PROCESS_RUN, runId, runRequest.getJson(), PackageCache.getPackage(proc.getPackageName())); actualRun.setOwnerId(ownerId); } catch (DataAccessException ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, "Error creating document for run id: " + runId); } } else if (ownerId == null) throw new ServiceException(ServiceException.BAD_REQUEST, "ownerType not allowed without ownerId"); Map<String,String> params = new HashMap<>(); if (runRequest.getValues() != null) { for (String name : runRequest.getValues().keySet()) { Value value = runRequest.getValues().get(name); if (value.getValue() != null) params.put(name, value.getValue()); } } if (proc.isService()) { Map<String,String> headers = new HashMap<>(); invokeServiceProcess(proc, masterRequestId, ownerType, ownerId, params, headers); String instIdStr = headers.get(Listener.METAINFO_MDW_PROCESS_INSTANCE_ID); if (instIdStr != null) actualRun.setInstanceId(Long.parseLong(instIdStr)); } else { Long instanceId = launchProcess(proc, masterRequestId, ownerType, ownerId, params); actualRun.setInstanceId(instanceId); } return actualRun; } public void updateDocument(ProcessRuntimeContext context, String varName, Object value) throws ServiceException { EventServices eventMgr = ServiceLocator.getEventServices(); VariableInstance varInst = context.getProcessInstance().getVariable(varName); if (varInst == null) throw new ServiceException(ServiceException.NOT_FOUND, varName + " not found for process: " + context.getProcessInstanceId()); try { eventMgr.updateDocumentContent(varInst.getDocumentId(), value, varInst.getType(), context.getPackage()); } catch (DataAccessException ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, "Error updating document: " + varInst.getDocumentId()); } } private Map<String,String> translateParameters(Process process, Map<String,Object> parameters) throws ProcessException { Map<String,String> stringParams = new HashMap<String,String>(); if (parameters != null) { for (String key : parameters.keySet()) { Object val = parameters.get(key); Variable vo = process.getVariable(key); if (vo == null) throw new ProcessException("Variable '" + key + "' not found for process: " + process.getName() + " v" + process.getVersionString() + "(id=" + process.getId() + ")"); String translated; if (val instanceof String) translated = (String)val; else { Package pkg = PackageCache.getProcessPackage(process.getId()); if (VariableTranslator.isDocumentReferenceVariable(pkg, vo.getType())) { translated = VariableTranslator.realToString(pkg, vo.getType(), val); } else { translated = VariableTranslator.toString(PackageCache.getProcessPackage(process.getId()), vo.getType(), val); } } stringParams.put(key, translated); } } return stringParams; } /** * TODO: There's gotta be a better way */ public String getDocType(Object docObj) { if (docObj instanceof String || docObj instanceof StringDocument) return StringDocument.class.getName(); else if (docObj instanceof XmlObject) return XmlObject.class.getName(); else if (docObj instanceof XmlBeanWrapper) return XmlBeanWrapper.class.getName(); else if (docObj instanceof groovy.util.Node) return groovy.util.Node.class.getName(); else if (docObj instanceof JAXBElement) return JAXBElement.class.getName(); else if (docObj instanceof Document) return Document.class.getName(); else if (docObj instanceof JSONObject) return JSONObject.class.getName(); else if (docObj.getClass().getName().equals("org.apache.camel.component.cxf.CxfPayload")) return "org.apache.camel.component.cxf.CxfPayload"; else if (docObj instanceof Jsonable) return Jsonable.class.getName(); else if (docObj instanceof Yaml) return Yaml.class.getName(); else return Object.class.getName(); } @SuppressWarnings("deprecation") public String getDocumentStringValue(Long id) throws ServiceException { try { Document doc = getWorkflowDao().getDocument(id); if (doc.getDocumentType() == null) throw new ServiceException(ServiceException.INTERNAL_ERROR, "Unable to determine document type."); // check raw content for parsability if (doc.getContent() == null || doc.getContent().isEmpty()) return doc.getContent(); Package pkg = getPackage(doc); com.centurylink.mdw.variable.VariableTranslator trans = VariableTranslator.getTranslator(pkg, doc.getDocumentType()); if (trans instanceof JavaObjectTranslator) { Object obj = doc.getObject(Object.class.getName(), pkg); return obj.toString(); } else if (trans instanceof StringDocumentTranslator) { return doc.getContent(); } else if (trans instanceof XmlDocumentTranslator && !(trans instanceof YamlTranslator)) { org.w3c.dom.Document domDoc = ((XmlDocumentTranslator)trans).toDomDocument(doc.getObject(doc.getDocumentType(), pkg)); XmlObject xmlBean = XmlObject.Factory.parse(domDoc); return xmlBean.xmlText(new XmlOptions().setSavePrettyPrint().setSavePrettyPrintIndent(4)); } else if (trans instanceof JsonTranslator && !(trans instanceof YamlTranslator)) { JSONObject jsonObj = ((JsonTranslator)trans).toJson(doc.getObject(doc.getDocumentType(), pkg)); if (jsonObj instanceof JsonObject) return jsonObj.toString(2); else return new JsonObject(jsonObj.toString()).toString(2); // reformat for predictable prop ordering } return doc.getContent(pkg); } catch (ServiceException ex) { throw ex; } catch (Exception ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, "Error retrieving document: " + id, ex); } } private Package getPackage(Document docVO) throws ServiceException { try { EventServices eventMgr = ServiceLocator.getEventServices(); if (docVO.getOwnerId() == 0) // eg: sdwf request headers return null; if (docVO.getOwnerType().equals(OwnerType.VARIABLE_INSTANCE)) { VariableInstance varInstInf = eventMgr.getVariableInstance(docVO.getOwnerId()); Long procInstId = varInstInf.getProcessInstanceId(); ProcessInstance procInstVO = eventMgr.getProcessInstance(procInstId); if (procInstVO != null) return PackageCache.getProcessPackage(procInstVO.getProcessId()); } else if (docVO.getOwnerType().equals(OwnerType.PROCESS_INSTANCE)) { Long procInstId = docVO.getOwnerId(); ProcessInstance procInstVO = eventMgr.getProcessInstance(procInstId); if (procInstVO != null) return PackageCache.getProcessPackage(procInstVO.getProcessId()); } else if (docVO.getOwnerType().equals("Designer")) { // test case, etc return PackageCache.getProcessPackage(docVO.getOwnerId()); } return null; } catch (Exception ex) { throw new ServiceException(ex.getMessage(), ex); } } public void createProcess(String assetPath, Query query) throws ServiceException, IOException { if (!assetPath.endsWith(".proc")) assetPath += ".proc"; String template = query.getFilter("template"); if (template == null) throw new ServiceException(ServiceException.BAD_REQUEST, "Missing param: template"); byte[] content = Templates.getBytes("assets/" + template + ".proc"); if (content == null) throw new ServiceException(ServiceException.NOT_FOUND, "Template not found: " + template); ServiceLocator.getAssetServices().createAsset(assetPath, content); } public Process getInstanceDefinition(String assetPath, Long instanceId) throws ServiceException { EngineDataAccessDB dataAccess = new EngineDataAccessDB(); try { dataAccess.getDatabaseAccess().openConnection(); ProcessInstance procInst = dataAccess.getProcessInstance(instanceId); // We need the processID if (procInst.getProcessInstDefId() > 0L) { Process process = ProcessCache.getProcessInstanceDefiniton(procInst.getProcessId(), procInst.getProcessInstDefId()); if (process.getQualifiedName().equals(assetPath)) // Make sure instanceId is for requested assetPath return process; } return null; } catch (SQLException ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, "Error retrieving instance document " + assetPath + ": " + instanceId); } finally { if (dataAccess.getDatabaseAccess().connectionIsOpen()) dataAccess.getDatabaseAccess().closeConnection(); } } public void saveInstanceDefinition(String assetPath, Long instanceId, Process process) throws ServiceException { EngineDataAccessDB dataAccess = new EngineDataAccessDB(); try { EventServices eventServices = ServiceLocator.getEventServices(); dataAccess.getDatabaseAccess().openConnection(); ProcessInstance procInst = dataAccess.getProcessInstance(instanceId); long docId = procInst.getProcessInstDefId(); if (docId == 0L) { docId = eventServices.createDocument(Jsonable.class.getName(), OwnerType.PROCESS_INSTANCE_DEF, instanceId, process, PackageCache.getPackage(process.getPackageName())); String[] fields = new String[]{"COMMENTS"}; String comment = procInst.getComment() == null ? "" : procInst.getComment(); Object[] args = new Object[]{comment + "|HasInstanceDef|" + docId, null}; dataAccess.updateTableRow("process_instance", "process_instance_id", instanceId, fields, args); } else { eventServices.updateDocumentContent(docId, process, Jsonable.class.getName(), PackageCache.getPackage(process.getPackageName())); } // Update any embedded Sub processes to indicate they have instance definition for (ProcessInstance inst : dataAccess.getProcessInstances(procInst.getProcessId(), OwnerType.MAIN_PROCESS_INSTANCE, procInst.getId())) { String[] fields = new String[]{"COMMENTS"}; String comment = inst.getComment() == null ? "" : inst.getComment(); Object[] args = new Object[]{comment + "|HasInstanceDef|" + docId, null}; dataAccess.updateTableRow("process_instance", "process_instance_id", inst.getId(), fields, args); } } catch (DataAccessException | SQLException ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, "Error creating process instance definition " + assetPath + ": " + instanceId, ex); } finally { if (dataAccess.getDatabaseAccess().connectionIsOpen()) dataAccess.getDatabaseAccess().closeConnection(); } } protected UserAction auditLog(String action, UserAction.Entity entity, Long entityId, String user, String completionCode) throws ServiceException { UserAction userAction = new UserAction(user, UserAction.getAction(action), entity, entityId, null); userAction.setSource("Workflow Services"); userAction.setDestination(completionCode); if (userAction.getAction().equals(UserAction.Action.Other)) { userAction.setExtendedAction(action); } try { EventServices eventManager = ServiceLocator.getEventServices(); eventManager.createAuditLog(userAction); return userAction; } catch (DataAccessException ex) { throw new ServiceException("Failed to create audit log: " + userAction, ex); } } }
mdw-services/src/com/centurylink/mdw/services/workflow/WorkflowServicesImpl.java
/* * Copyright (C) 2017 CenturyLink, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.centurylink.mdw.services.workflow; import com.centurylink.mdw.activity.types.GeneralActivity; import com.centurylink.mdw.app.Templates; import com.centurylink.mdw.cache.CachingException; import com.centurylink.mdw.cache.impl.PackageCache; import com.centurylink.mdw.common.service.Query; import com.centurylink.mdw.common.service.ServiceException; import com.centurylink.mdw.common.translator.impl.JavaObjectTranslator; import com.centurylink.mdw.common.translator.impl.StringDocumentTranslator; import com.centurylink.mdw.common.translator.impl.YamlTranslator; import com.centurylink.mdw.config.PropertyManager; import com.centurylink.mdw.constant.OwnerType; import com.centurylink.mdw.constant.PropertyNames; import com.centurylink.mdw.dataaccess.DataAccess; import com.centurylink.mdw.dataaccess.DataAccessException; import com.centurylink.mdw.dataaccess.DatabaseAccess; import com.centurylink.mdw.dataaccess.RuntimeDataAccess; import com.centurylink.mdw.dataaccess.db.CommonDataAccess; import com.centurylink.mdw.dataaccess.reports.*; import com.centurylink.mdw.model.JsonObject; import com.centurylink.mdw.model.Jsonable; import com.centurylink.mdw.model.StringDocument; import com.centurylink.mdw.model.Value; import com.centurylink.mdw.model.asset.Asset; import com.centurylink.mdw.model.asset.AssetHeader; import com.centurylink.mdw.model.asset.AssetInfo; import com.centurylink.mdw.model.asset.AssetVersionSpec; import com.centurylink.mdw.model.event.Event; import com.centurylink.mdw.model.event.EventInstance; import com.centurylink.mdw.model.listener.Listener; import com.centurylink.mdw.model.report.Hotspot; import com.centurylink.mdw.model.report.Insight; import com.centurylink.mdw.model.report.Timepoint; import com.centurylink.mdw.model.system.SysInfo; import com.centurylink.mdw.model.system.SysInfoCategory; import com.centurylink.mdw.model.task.TaskInstance; import com.centurylink.mdw.model.user.UserAction; import com.centurylink.mdw.model.user.UserAction.Action; import com.centurylink.mdw.model.variable.Document; import com.centurylink.mdw.model.variable.DocumentReference; import com.centurylink.mdw.model.variable.Variable; import com.centurylink.mdw.model.variable.VariableInstance; import com.centurylink.mdw.model.workflow.Package; import com.centurylink.mdw.model.workflow.Process; import com.centurylink.mdw.model.workflow.*; import com.centurylink.mdw.service.data.WorkflowDataAccess; import com.centurylink.mdw.service.data.process.EngineDataAccess; import com.centurylink.mdw.service.data.process.EngineDataAccessDB; import com.centurylink.mdw.service.data.process.ProcessCache; import com.centurylink.mdw.services.*; import com.centurylink.mdw.services.messenger.InternalMessenger; import com.centurylink.mdw.services.messenger.MessengerFactory; import com.centurylink.mdw.services.process.ProcessEngineDriver; import com.centurylink.mdw.services.process.ProcessExecutor; import com.centurylink.mdw.translator.JsonTranslator; import com.centurylink.mdw.translator.TranslationException; import com.centurylink.mdw.translator.VariableTranslator; import com.centurylink.mdw.translator.XmlDocumentTranslator; import com.centurylink.mdw.util.log.LoggerUtil; import com.centurylink.mdw.util.log.StandardLogger; import com.centurylink.mdw.util.timer.CodeTimer; import com.centurylink.mdw.xml.XmlBeanWrapper; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlOptions; import org.json.JSONException; import org.json.JSONObject; import org.yaml.snakeyaml.Yaml; import javax.xml.bind.JAXBElement; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.file.Files; import java.nio.file.Paths; import java.sql.SQLException; import java.text.ParseException; import java.util.*; public class WorkflowServicesImpl implements WorkflowServices { private static StandardLogger logger = LoggerUtil.getStandardLogger(); private WorkflowDataAccess getWorkflowDao() { return new WorkflowDataAccess(); } protected RuntimeDataAccess getRuntimeDataAccess() throws DataAccessException { return DataAccess.getRuntimeDataAccess(new DatabaseAccess(null)); } protected ProcessAggregation getProcessAggregation() { return new ProcessAggregation(); } protected ActivityAggregation getActivityAggregation() { return new ActivityAggregation(); } public Map<String,String> getAttributes(String ownerType, Long ownerId) throws ServiceException { try { return getWorkflowDao().getAttributes(ownerType, ownerId); } catch (SQLException ex) { throw new ServiceException("Failed to load attributes for " + ownerType + "/" + ownerId, ex); } } public void setAttributes(String ownerType, Long ownerId, Map<String,String> attributes) throws ServiceException { try { getWorkflowDao().setAttributes(ownerType, ownerId, attributes); } catch (Exception ex) { throw new ServiceException("Failed to set attributes for " + ownerType + "/" + ownerId, ex); } } /** * Update attributes without deleting all attributes for this ownerId first */ public void updateAttributes(String ownerType, Long ownerId, Map<String,String> attributes) throws ServiceException { try { for (Map.Entry<String, String> attribute : attributes.entrySet()) { String attributeName = attribute.getKey(); String attributeValue = attribute.getValue(); getWorkflowDao().setAttribute(ownerType, ownerId, attributeName, attributeValue); } } catch (SQLException ex) { throw new ServiceException("Failed to update attributes for " + ownerType + "/" + ownerId, ex); } } /** * Replace all existing values */ public void setValues(String ownerType, String ownerId, Map<String,String> values) throws ServiceException { try { CommonDataAccess dao = new CommonDataAccess(); dao.setValues(ownerType, ownerId, values); } catch (SQLException ex) { throw new ServiceException(ex.getMessage(), ex); } } /** * Update certain values */ public void updateValues(String ownerType, String ownerId, Map<String,String> values) throws ServiceException { try { CommonDataAccess dao = new CommonDataAccess(); for (String key : values.keySet()) dao.setValue(ownerType, ownerId, key, values.get(key)); } catch (SQLException ex) { throw new ServiceException(ex.getMessage(), ex); } } public Map<String,String> getValues(String ownerType, String ownerId) throws ServiceException { try { if (OwnerType.SYSTEM.equals(ownerType)) { if ("mdwProperties".equals(ownerId)) { Map<String,String> mdwProps = new HashMap<>(); SysInfoCategory cat = ServiceLocator.getSystemServices().getMdwProperties(); for (SysInfo sysInfo : cat.getSysInfos()) { mdwProps.put(sysInfo.getName(), sysInfo.getValue()); } return mdwProps; } else { throw new ServiceException(ServiceException.BAD_REQUEST, "Unsupported System values: " + ownerId); } } else { CommonDataAccess dao = new CommonDataAccess(); return dao.getValues(ownerType, ownerId); } } catch (SQLException ex) { throw new ServiceException(ex.getMessage(), ex); } } public String getValue(String ownerType, String ownerId, String name) throws ServiceException { try { if (OwnerType.SYSTEM.equals(ownerType)) { if ("mdwProperties".equals(ownerId)) { Map<String,String> mdwProps = new HashMap<>(); SysInfoCategory cat = ServiceLocator.getSystemServices().getMdwProperties(); for (SysInfo sysInfo : cat.getSysInfos()) { mdwProps.put(sysInfo.getName(), sysInfo.getValue()); } return mdwProps.get(name); } else { throw new ServiceException(ServiceException.BAD_REQUEST, "Unsupported System values: " + ownerId); } } else { CommonDataAccess dao = new CommonDataAccess(); return dao.getValue(ownerType, ownerId, name); } } catch (SQLException ex) { throw new ServiceException(ex.getMessage(), ex); } } public List<String> getValueHolderIds(String valueName, String valuePattern) throws ServiceException { return getValueHolderIds(valueName, valuePattern, null); } public List<String> getValueHolderIds(String valueName, String valuePattern, String ownerType) throws ServiceException { try { CommonDataAccess dao = new CommonDataAccess(); if (ownerType == null) return dao.getValueOwnerIds(valueName, valuePattern); else return dao.getValueOwnerIds(ownerType, valueName, valuePattern); } catch (SQLException ex) { throw new ServiceException(ex.getMessage(), ex); } } public void registerTaskWaitEvent(Long taskInstanceId, Event event) throws ServiceException { registerTaskWaitEvent(taskInstanceId, event.getId(), event.getCompletionCode() == null ? "FINISH" : event.getCompletionCode()); } public void registerTaskWaitEvent(Long taskInstanceId, String eventName) throws ServiceException { registerTaskWaitEvent(taskInstanceId, eventName, "FINISH"); } public void registerTaskWaitEvent(Long taskInstanceId, String eventName, String completionCode) throws ServiceException { try { TaskInstance taskInstance = ServiceLocator.getTaskServices().getInstance(taskInstanceId); if (taskInstance != null) { Long activityInstanceId = taskInstance.getActivityInstanceId(); EngineDataAccess edao = new EngineDataAccessDB(); InternalMessenger msgBroker = MessengerFactory.newInternalMessenger(); ProcessExecutor engine = new ProcessExecutor(edao, msgBroker, false); // When registering an event on a Task via this method, the following rules apply: // - Event cannot be a legacy "recurring" event (means there can be multiple waiter for same event) // - Event will not trigger notification if pre-arrived. Notification will occur when event is published after this registration occurs engine.createEventWaitInstance(activityInstanceId, eventName, completionCode, false, false, true); } else throw new ServiceException("Task Instance was not found for ID " + taskInstanceId); } catch (Exception ex) { throw new ServiceException(ex.getMessage(), ex); } } @Override public void actionActivity(Long activityInstanceId, String action, String completionCode, String user) throws ServiceException { EngineDataAccessDB dataAccess = null; try { UserAction userAction = auditLog(action, UserAction.Entity.ActivityInstance, activityInstanceId, user, completionCode); if (Action.Proceed.toString().equalsIgnoreCase(action)) { ServiceLocator.getEventServices().skipActivity(null, activityInstanceId, completionCode); } else if (Action.Retry.toString().equalsIgnoreCase(action) || Action.Fail.toString().equalsIgnoreCase(action)) { ActivityInstance activityVo = ServiceLocator.getEventServices().getActivityInstance(activityInstanceId); if (Action.Retry.toString().equalsIgnoreCase(action)) ServiceLocator.getEventServices().retryActivity(activityVo.getActivityId(), activityInstanceId); else if (activityVo.getEndDate() == null) {// Only fail it if not yet completed dataAccess = new EngineDataAccessDB(); dataAccess.getDatabaseAccess().openConnection(); dataAccess.setActivityInstanceStatus(activityVo, WorkStatus.STATUS_FAILED, "Manually Failed by user " + user); } } else if (Action.Resume.toString().equalsIgnoreCase(action)) { String eventName = "mdw.Resume-" + activityInstanceId; notify(eventName, userAction.getJson().toString(), 0); } else { throw new ServiceException("Unsupported action: '" + action + "' for activity " + activityInstanceId); } } catch (Exception ex) { throw new ServiceException(ex.getMessage(), ex); } finally { if (dataAccess != null) dataAccess.getDatabaseAccess().closeConnection(); } } @Override public ActivityList getActivities(Query query) throws ServiceException { try { CodeTimer timer = new CodeTimer(true); ActivityList list = getRuntimeDataAccess().getActivityInstanceList(query); timer.logTimingAndContinue("getRuntimeDataAccess().getActivityInstanceList()"); list = populateActivities(list, query); timer.stopAndLogTiming("WorkflowServicesImpl.populateActivities()"); return list; } catch (DataAccessException ex) { throw new ServiceException(500, "Error retrieving activity instance for query: " + query, ex); } } public ProcessInstance getProcess(Long instanceId) throws ServiceException { return getProcess(instanceId, false); } public ProcessInstance getProcess(Long instanceId, boolean withSubprocs) throws ServiceException { try { RuntimeDataAccess runtimeDataAccess = getRuntimeDataAccess(); ProcessInstance process = runtimeDataAccess.getProcessInstanceAll(instanceId); if (process == null) throw new ServiceException(ServiceException.NOT_FOUND, "Process instance not found: " + instanceId); if (withSubprocs) { // embedded subprocs Map<String,String> criteria = new HashMap<>(); criteria.put("owner", OwnerType.MAIN_PROCESS_INSTANCE); criteria.put("ownerId", process.getId().toString()); criteria.put("processId", process.getProcessId().toString()); ProcessList subprocList = runtimeDataAccess.getProcessInstanceList(criteria, 0, Query.MAX_ALL, "order by process_instance_id"); if (subprocList != null && subprocList.getItems() != null && subprocList.getItems().size() > 0) { List<ProcessInstance> subprocs = new ArrayList<>(); for (ProcessInstance subproc : subprocList.getItems()) { ProcessInstance fullsub = runtimeDataAccess.getProcessInstance(subproc.getId()); fullsub.setProcessId(Long.parseLong(subproc.getComment())); subprocs.add(fullsub); } process.setSubprocessInstances(subprocs); } } return process; } catch (DataAccessException ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, "Error retrieving process instance: " + instanceId + ": " + ex.getMessage(), ex); } } public ProcessInstance getMasterProcess(String masterRequestId) throws ServiceException { Query query = new Query(); query.setFilter("master", true); query.setFilter("masterRequestId", masterRequestId); query.setSort("process_instance_id"); query.setDescending(true); List<ProcessInstance> instances = getProcesses(query).getProcesses(); if (instances.isEmpty()) return null; else return getProcess(instances.get(0).getId()); } public Map<String,Value> getProcessValues(Long instanceId) throws ServiceException { return getProcessValues(instanceId, false); } public Map<String,Value> getProcessValues(Long instanceId, boolean includeEmpty) throws ServiceException { ProcessRuntimeContext runtimeContext = getContext(instanceId); Map<String,Value> values = new HashMap<>(); Map<String,Variable> varDefs = getVariableDefinitions(runtimeContext.getProcess().getVariables()); Map<String,Object> variables = runtimeContext.getVariables(); if (variables != null) { for (String key : variables.keySet()) { String stringVal = runtimeContext.getValueAsString(key); if (stringVal != null) { Variable varDef = varDefs.get(key); Value value; if (varDef != null) value = varDef.toValue(); else value = new Value(key); value.setValue(stringVal); values.put(key, value); } } } if (includeEmpty) { for (String name : varDefs.keySet()) { if (!values.containsKey(name)) values.put(name, varDefs.get(name).toValue()); } } return values; } protected Map<String,Variable> getVariableDefinitions(List<Variable> varList) { Map<String,Variable> varDefs = new HashMap<>(); if (varList != null) { for (Variable var : varList) varDefs.put(var.getName(), var); } return varDefs; } public Value getProcessValue(Long instanceId, String name) throws ServiceException { ProcessRuntimeContext runtimeContext = getContext(instanceId); Variable var = runtimeContext.getProcess().getVariable(name); if (var == null && !ProcessRuntimeContext.isExpression(name)) throw new ServiceException(ServiceException.NOT_FOUND, "No variable defined: " + name); String stringVal = null; if (var != null && VariableTranslator.isDocumentReferenceVariable(runtimeContext.getPackage(), var.getType())) { VariableInstance varInst = runtimeContext.getProcessInstance().getVariable(name); // ensure consistent formatting for doc values if (varInst != null && varInst.getStringValue() != null && varInst.getStringValue().startsWith("DOCUMENT:")) stringVal = getDocumentStringValue(new DocumentReference(varInst.getStringValue()).getDocumentId()); } else { stringVal = runtimeContext.getValueAsString(name); } if (stringVal == null) throw new ServiceException(ServiceException.NOT_FOUND, "No value '" + name + "' found for instance: " + instanceId); Variable varDef = getVariableDefinitions(runtimeContext.getProcess().getVariables()).get(name); Value value; if (varDef != null) value = varDef.toValue(); else value = new Value(name); value.setValue(stringVal); return value; } public ProcessRuntimeContext getContext(Long instanceId) throws ServiceException { return getContext(instanceId, false); } public ProcessRuntimeContext getContext(Long instanceId, Boolean embeddedVars) throws ServiceException { ProcessInstance instance = getProcess(instanceId); // Edge case where we want to get main process variables when we loaded embedded process instance // Applies to when looking/setting process variables in manual task located in embedded subproc if (instance.isEmbedded() && embeddedVars) instance.setVariables(getProcess(instance.getOwnerId()).getVariables()); Process process = null; if (instance.getProcessInstDefId() > 0L) process = ProcessCache.getProcessInstanceDefiniton(instance.getProcessId(), instance.getProcessInstDefId()); if (process == null) process = ProcessCache.getProcess(instance.getProcessId()); Package pkg = PackageCache.getProcessPackage(instance.getProcessId()); if (process == null) throw new ServiceException(ServiceException.NOT_FOUND, "Process definition not found for id: " + instance.getProcessId()); Map<String,Object> vars = new HashMap<>(); try { if (instance.getVariables() != null) { for (VariableInstance var : instance.getVariables()) { Object value = var.getData(); if (value instanceof DocumentReference) { try { Document docVO = getWorkflowDao().getDocument(((DocumentReference)value).getDocumentId()); value = docVO == null ? null : docVO.getObject(var.getType(), pkg); vars.put(var.getName(), value); } catch (TranslationException ex) { // parse error on one doc should not prevent other vars from populating logger.severeException("Error translating " + var.getName() + " for process instance " + instanceId, ex); } } else { vars.put(var.getName(), value); } } } return new ProcessRuntimeContext(pkg, process, instance, 0, vars); } catch (DataAccessException ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, ex.getMessage(), ex); } } @Override public ProcessList getProcesses(Query query) throws ServiceException { try { String procDefSpec = query.getFilter("definition"); // in form of AssetVersionSpec if (procDefSpec != null) { AssetVersionSpec spec = AssetVersionSpec.parse(procDefSpec); if (spec.getName().endsWith(".proc")) spec = new AssetVersionSpec(spec.getPackageName(), spec.getName().substring(0, spec.getName().length() - 5), spec.getVersion()); if (spec.isRange()) { List<Process> procDefs = ProcessCache.getProcessesSmart(spec); String[] procIds = new String[procDefs.size()]; for (int i = 0; i < procDefs.size(); i++) procIds[i] = procDefs.get(i).getId().toString(); query.setArrayFilter("processIds", procIds); } else { Process procDef = ProcessCache.getProcessSmart(spec); if (procDef == null) throw new ServiceException(ServiceException.NOT_FOUND, "Process definition not found for spec: " + procDefSpec); query.setFilter("processId", procDef.getId()); } } return getWorkflowDao().getProcessInstances(query); } catch (DataAccessException ex) { throw new ServiceException(500, "Error retrieving process instance for query: " + query, ex); } } public ProcessInstance getProcessForTrigger(Long triggerId) throws ServiceException { String ownerContent = getDocumentStringValue(triggerId); try { JSONObject json = new JsonObject(ownerContent); if (!json.has("runtimeContext")) throw new ServiceException(ServiceException.NOT_FOUND, "Trigger document does not have RuntimeContext information: " + triggerId); JSONObject runtimeContext = json.getJSONObject("runtimeContext"); long procInstId; if (runtimeContext.has("activityInstance")) procInstId = runtimeContext.getJSONObject("activityInstance").getLong("processInstanceId"); else if (runtimeContext.has("processInstance")) procInstId = runtimeContext.getJSONObject("processInstance").getLong("id"); else throw new ServiceException(ServiceException.NOT_FOUND, "Trigger document does not have instance information: " + triggerId); return getProcess(procInstId); } catch (JSONException ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, "Error retrieving triggerId: " + triggerId , ex); } } public Document getDocument(Long id) throws ServiceException { try { if (!getWorkflowDao().isDocument(id)) throw new ServiceException(ServiceException.NOT_FOUND, "Document not found: " + id); return getWorkflowDao().getDocument(id); } catch (Exception ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, "Error retrieving document: " + id, ex); } } @Override public ActivityInstance getActivity(Long instanceId) throws ServiceException { try { Query query = new Query(); query.setFilter("instanceId", instanceId); query.setFind(null); ActivityList list = getRuntimeDataAccess().getActivityInstanceList(query); if (list.getCount() > 0) { list = populateActivities(list, query); return list.getActivities().get(0); } else { return null; } } catch (Exception ex) { throw new ServiceException(500, "Error retrieving activity instance: " + instanceId + ": " + ex.getMessage(), ex); } } public List<ProcessAggregate> getTopProcesses(Query query) throws ServiceException { try { CodeTimer timer = new CodeTimer(true); List<ProcessAggregate> list = getProcessAggregation().getTops(query); timer.logTimingAndContinue("WorkflowServicesImpl.getTopProcesses()"); if ("status".equals(query.getFilter("by"))) { list = populateProcessStatuses(list); } else { list = populateProcesses(list); } timer.stopAndLogTiming("WorkflowServicesImpl.getTopProcesses()"); return list; } catch (DataAccessException ex) { throw new ServiceException(500, "Error retrieving top throughput processes: query=" + query, ex); } } public TreeMap<Date,List<ProcessAggregate>> getProcessBreakdown(Query query) throws ServiceException { try { TreeMap<Date,List<ProcessAggregate>> map = getProcessAggregation().getBreakdown(query); if (query.getFilters().get("processIds") != null) { for (Date date : map.keySet()) populateProcesses(map.get(date)); } return map; } catch (DataAccessException ex) { throw new ServiceException(500, "Error retrieving process breakdown: query=" + query, ex); } } public List<Insight> getProcessInsights(Query query) throws ServiceException { try { return new ProcessInsights().getInsights(query); } catch (SQLException | ParseException ex) { throw new ServiceException(500, "Error retrieving process insights: query=" + query, ex); } } public List<Timepoint> getProcessTrend(Query query) throws ServiceException { try { return new ProcessInsights().getTrend(query); } catch (SQLException | ParseException ex) { throw new ServiceException(500, "Error retrieving process trend: query=" + query, ex); } } public List<Hotspot> getProcessHotspots(Query query) throws ServiceException { try { return new ProcessHotspots().getHotspots(query); } catch (SQLException ex) { throw new ServiceException(500, "Error retrieving process hotspots: query=" + query, ex); } } /** * Fills in process header info, consulting latest instance comment if necessary. */ protected List<ProcessAggregate> populateProcesses(List<ProcessAggregate> processAggregates) throws DataAccessException { AggregateDataAccess dataAccess = null; for (ProcessAggregate pc : processAggregates) { Process process = ProcessCache.getProcess(pc.getId()); if (process == null) { logger.severe("Missing definition for process id: " + pc.getId()); pc.setDefinitionMissing(true); // may have been deleted -- infer from comments if (dataAccess == null) dataAccess = getProcessAggregation(); CodeTimer timer = new CodeTimer(true); String comments = getWorkflowDao().getLatestProcessInstanceComments(pc.getId()); timer.stopAndLogTiming("getLatestProcessInstanceComments()"); if (comments != null) { AssetHeader assetHeader = new AssetHeader(comments); pc.setName(assetHeader.getName()); pc.setVersion(assetHeader.getVersion()); pc.setPackageName(assetHeader.getPackageName()); } else { logger.severe("Unable to infer process name for: " + pc.getId()); pc.setName("Unknown (" + pc.getId() + ")"); } } else { pc.setName(process.getName()); pc.setVersion(Asset.formatVersion(process.getVersion())); pc.setPackageName(process.getPackageName()); } } return processAggregates; } protected List<ProcessAggregate> populateProcessStatuses(List<ProcessAggregate> processAggregates) { for (ProcessAggregate processAggregate : processAggregates) { processAggregate.setName(WorkStatuses.getName((int)processAggregate.getId())); } // add any empty statuses for (Integer statusCd : WorkStatuses.getWorkStatuses().keySet()) { if (!statusCd.equals(WorkStatus.STATUS_PENDING_PROCESS) && !statusCd.equals(WorkStatus.STATUS_HOLD)) { boolean found = processAggregates.stream().anyMatch(agg -> agg.getId() == statusCd); if (!found) { ProcessAggregate processAggregate = new ProcessAggregate(0); processAggregate.setId(statusCd); processAggregate.setCount(0); processAggregate.setName(WorkStatuses.getWorkStatuses().get(statusCd)); processAggregates.add(processAggregate); } } } return processAggregates; } /** * Fills in process header info, consulting latest instance comment if necessary. * @param query */ protected ActivityList populateActivities(ActivityList activityList, Query query) throws DataAccessException { AggregateDataAccess dataAccess = null; List<ActivityInstance> aList = activityList.getActivities(); ArrayList<ActivityInstance> matchActivities = new ArrayList<>(); String activityName = query.getFilter("activityName"); String decodedActName = ""; if (activityName != null) { try { decodedActName = java.net.URLDecoder.decode(activityName, "UTF-8"); } catch (UnsupportedEncodingException e) { logger.severe("Unable to decode: " + activityName); } } for (ActivityInstance activityInstance : aList) { Process process = ProcessCache.getProcess(activityInstance.getProcessId()); if (process == null) { logger.severe("Missing definition for process id: " + activityInstance.getProcessId()); activityInstance.setDefinitionMissing(true); // may have been deleted -- infer from comments if (dataAccess == null) dataAccess = getActivityAggregation(); CodeTimer timer = new CodeTimer(true); String comments = getWorkflowDao().getLatestProcessInstanceComments(activityInstance.getProcessId()); timer.stopAndLogTiming("getLatestProcessInstanceComments()"); if (comments != null) { AssetHeader assetHeader = new AssetHeader(comments); activityInstance.setProcessName(assetHeader.getName()); activityInstance.setProcessVersion(assetHeader.getVersion()); activityInstance.setPackageName(assetHeader.getPackageName()); } else { logger.severe("Unable to infer process name for: " + activityInstance.getProcessId()); activityInstance.setProcessName("Unknown (" + activityInstance.getProcessId() + ")"); } activityInstance.setName("Unknown (" + activityInstance.getDefinitionId() + ")"); } else { String logicalId = activityInstance.getDefinitionId(); Activity actdef = process.getActivityById(logicalId); if (actdef != null) { if (!decodedActName.isEmpty() && actdef.getName().startsWith(decodedActName)) matchActivities.add(activityInstance); activityInstance.setName(actdef.getName().replaceAll("\\r", "").replace('\n', ' ')); } else { activityInstance.setName("Unknown (" + activityInstance.getDefinitionId() + ")"); } activityInstance.setProcessName(process.getName()); activityInstance.setProcessVersion(Asset.formatVersion(process.getVersion())); activityInstance.setPackageName(process.getPackageName()); } } if (!decodedActName.isEmpty()) activityList.setActivities(matchActivities); activityList.setCount(activityList.getActivities().size()); activityList.setTotal(activityList.getActivities().size()); return activityList; } /** * Fills in process header info, consulting latest instance comment if necessary. */ protected List<ActivityAggregate> populateActivities(List<ActivityAggregate> activityCounts) throws DataAccessException { AggregateDataAccess dataAccess = null; for (ActivityAggregate ac : activityCounts) { Process process = ProcessCache.getProcess(ac.getProcessId()); if (process == null) { logger.severe("Missing definition for process id: " + ac.getProcessId()); ac.setDefinitionMissing(true); // may have been deleted -- infer from comments if (dataAccess == null) dataAccess = getActivityAggregation(); CodeTimer timer = new CodeTimer(true); String comments = getWorkflowDao().getLatestProcessInstanceComments(ac.getProcessId()); timer.stopAndLogTiming("getLatestProcessInstanceComments()"); if (comments != null) { AssetHeader assetHeader = new AssetHeader(comments); ac.setProcessName(assetHeader.getName()); ac.setActivityName(ac.getDefinitionId()); ac.setName(ac.getProcessName() + ": " + ac.getActivityName()); ac.setVersion(assetHeader.getVersion()); ac.setPackageName(assetHeader.getPackageName()); } else { logger.severe("Unable to infer process name for: " + ac.getProcessId()); ac.setProcessName("Unknown (" + ac.getProcessId() + ")"); } } else { ac.setProcessName(process.getName()); ac.setVersion(Asset.formatVersion(process.getVersion())); ac.setPackageName(process.getPackageName()); String logicalId = ac.getDefinitionId(); Activity actdef = process.getActivityById(logicalId); if (actdef != null) { String actName = actdef.getName().replaceAll("\\r", "").replace('\n', ' '); ac.setActivityName(actName); ac.setProcessName(actdef.getProcessName()); // in case subproc ac.setName(ac.getProcessName() + ": " + ac.getActivityName()); } else { ac.setName("Unknown (" + ac.getDefinitionId() + ")"); } } } return activityCounts; } protected List<ActivityAggregate> populateActivityStatuses(List<ActivityAggregate> activityAggregates) { for (ActivityAggregate activityAggregate : activityAggregates) { activityAggregate.setName(WorkStatuses.getName((int)activityAggregate.getId())); } // add any empty statuses int[] statusCds = new int[] {WorkStatus.STATUS_IN_PROGRESS, WorkStatus.STATUS_FAILED, WorkStatus.STATUS_WAITING}; for (int statusCd : statusCds) { boolean found = activityAggregates.stream().anyMatch(agg -> { return agg.getId() == statusCd; }); if (!found) { ActivityAggregate activityAggregate = new ActivityAggregate(0); activityAggregate.setId(statusCd); activityAggregate.setCount(0); activityAggregate.setName(WorkStatuses.getWorkStatuses().get(statusCd)); activityAggregates.add(activityAggregate); } } return activityAggregates; } public List<ActivityAggregate> getTopActivities(Query query) throws ServiceException { try { CodeTimer timer = new CodeTimer(true); List<ActivityAggregate> list = getActivityAggregation().getTops(query); timer.logTimingAndContinue("AggregateDataAccessVcs.getTopThroughputActivityInstances()"); if ("status".equals(query.getFilter("by"))) { list = populateActivityStatuses(list); } else { list = populateActivities(list); } timer.stopAndLogTiming("WorkflowServicesImpl.populate()"); return list; } catch (DataAccessException ex) { throw new ServiceException(500, "Error retrieving top throughput activities: query=" + query, ex); } } public TreeMap<Date,List<ActivityAggregate>> getActivityBreakdown(Query query) throws ServiceException { try { TreeMap<Date,List<ActivityAggregate>> map = getActivityAggregation().getBreakdown(query); if (query.getFilters().get("activityIds") != null) { for (Date date : map.keySet()) populateActivities(map.get(date)); } return map; } catch (DataAccessException ex) { throw new ServiceException(500, "Error retrieving activity instance breakdown: query=" + query, ex); } } public Process getProcessDefinition(String assetPath, Query query) throws ServiceException { int lastSlash = assetPath.lastIndexOf('/'); if (lastSlash <= 0) throw new ServiceException(ServiceException.BAD_REQUEST, "Bad asset path: " + assetPath); String processName = assetPath; //.substring(lastSlash + 1); if (assetPath.endsWith(".proc")) processName = processName.substring(0, processName.length() - ".proc".length()); int version = query == null ? 0 : query.getIntFilter("version"); if (version < 0) version = 0; boolean forUpdate = query == null ? false : query.getBooleanFilter("forUpdate"); Process process = ProcessCache.getProcess(processName, version); if (forUpdate) { // load from file try { byte[] bytes = Files.readAllBytes(Paths.get(process.getRawFile().getAbsolutePath())); process = new Process(new JsonObject(new String(bytes))); process.setName(processName.substring(lastSlash + 1)); process.setPackageName(processName.substring(0, lastSlash)); } catch (Exception ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, "Error reading process: " + process.getRawFile()); } } if (process == null) throw new ServiceException(ServiceException.NOT_FOUND, "Process definition not found: " + assetPath); return process; } public List<Process> getProcessDefinitions(Query query) throws ServiceException { try { String find = query.getFind(); if (find == null) { return ProcessCache.getAllProcesses(); } else { List<Process> found = new ArrayList<>(); for (Process processVO : ProcessCache.getAllProcesses()) { if (processVO.getName() != null && processVO.getName().startsWith(find)) found.add(processVO); else if (find.indexOf(".") > 0 && processVO.getPackageName() != null && processVO.getPackageName().startsWith(find)) found.add(processVO); } return found; } } catch (DataAccessException ex) { throw new ServiceException(500, ex.getMessage(), ex); } } public Process getProcessDefinition(Long id) { return ProcessCache.getProcess(id); } public ActivityList getActivityDefinitions(Query query) throws ServiceException { try { String find = query.getFind(); List<ActivityInstance> activityInstanceList = new ArrayList<>(); ActivityList found = new ActivityList(ActivityList.ACTIVITY_INSTANCES, activityInstanceList); if (find == null) { List<Process> processes = ProcessCache.getAllProcesses(); for (Process process : processes) { process = ProcessCache.getProcess(process.getId()); List<Activity> activities = process.getActivities(); for (Activity activityVO : activities) { if (activityVO.getName() != null && activityVO.getName().startsWith(find)) { ActivityInstance ai = new ActivityInstance(); ai.setId(activityVO.getId()); ai.setName(activityVO.getName()); ai.setDefinitionId(activityVO.getLogicalId()); ai.setProcessId(process.getId()); ai.setProcessName(process.getName()); ai.setProcessVersion(process.getVersionString()); activityInstanceList.add(ai); } } } } else { for (Process process : ProcessCache.getAllProcesses()) { process = ProcessCache.getProcess(process.getId()); List<Activity> activities = process.getActivities(); for (Activity activityVO : activities) { if (activityVO.getName() != null && activityVO.getName().startsWith(find)) { ActivityInstance ai = new ActivityInstance(); ai.setId(activityVO.getId()); ai.setName(activityVO.getName()); ai.setDefinitionId(activityVO.getLogicalId()); ai.setProcessId(process.getId()); ai.setProcessName(process.getName()); ai.setProcessVersion(process.getVersionString()); activityInstanceList.add(ai); } } } } found.setRetrieveDate(DatabaseAccess.getDbDate()); found.setCount(activityInstanceList.size()); found.setTotal(activityInstanceList.size()); return found; } catch (DataAccessException ex) { throw new ServiceException(500, ex.getMessage(), ex); } } private static List<ActivityImplementor> activityImplementors; /** * Does not include pagelet. * TODO: cache should be refreshable */ public List<ActivityImplementor> getImplementors() throws ServiceException { if (activityImplementors == null) { try { activityImplementors = DataAccess.getProcessLoader().getActivityImplementors(); for (ActivityImplementor impl : activityImplementors) { // qualify the icon location String icon = impl.getIcon(); if (icon != null && !icon.startsWith("shape:") && icon.indexOf('/') <= 0) { for (Package pkg : PackageCache.getPackages()) { for (Asset asset : pkg.getAssets()) { if (asset.getName().equals(icon)) { impl.setIcon(pkg.getName() + "/" + icon); break; } } } } impl.setPagelet(null); } AssetServices assetServices = ServiceLocator.getAssetServices(); Map<String,List<AssetInfo>> annotatedAssets = assetServices.getAssetsOfTypes(new String[]{"java", "kt"}); for (String packageName : annotatedAssets.keySet()) { Package pkg = PackageCache.getPackage(packageName); for (AssetInfo assetInfo : annotatedAssets.get(packageName)) { ActivityImplementor impl = getAnnotatedImpl(pkg, assetInfo); if (impl != null) activityImplementors.add(impl); } } } catch (CachingException ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, ex.getMessage(), ex); } catch (DataAccessException ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, ex.getMessage(), ex); } } return activityImplementors; } public ActivityImplementor getImplementor(String className) throws ServiceException { try { for (ActivityImplementor implementor : DataAccess.getProcessLoader().getActivityImplementors()) { String implClassName = implementor.getImplementorClass(); if (className == null) { if (implClassName == null) return implementor; } else if (implClassName.equals(className)) { return implementor; } } Package pkg = PackageCache.getPackage(className.substring(0, className.lastIndexOf('.'))); if (pkg != null) { AssetInfo assetInfo = ServiceLocator.getAssetServices().getImplAsset(className); if (assetInfo != null) return getAnnotatedImpl(pkg, assetInfo); } return null; } catch (DataAccessException ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, ex.getMessage(), ex); } } private ActivityImplementor getAnnotatedImpl(Package pkg, AssetInfo assetInfo) { String implClass = pkg.getName() + "." + assetInfo.getRootName(); try { String contents = new String(Files.readAllBytes(assetInfo.getFile().toPath())); if (contents.contains("@Activity")) { GeneralActivity activity = pkg.getActivityImplementor(implClass); com.centurylink.mdw.annotations.Activity annotation = activity.getClass().getAnnotation(com.centurylink.mdw.annotations.Activity.class); return new ActivityImplementor(implClass, annotation); } } catch (Exception ex) { logger.severeException("Cannot load " + implClass, ex); } return null; } public Long launchProcess(String name, String masterRequestId, String ownerType, Long ownerId, Map<String,Object> parameters) throws ServiceException { try { Process process = ProcessCache.getProcess(name); ProcessEngineDriver driver = new ProcessEngineDriver(); Map<String,String> params = translateParameters(process, parameters); return driver.startProcess(process.getId(), masterRequestId, ownerType, ownerId, params, null); } catch (Exception ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, ex.getMessage(), ex); } } public Long launchProcess(Process process, String masterRequestId, String ownerType, Long ownerId, Map<String,String> params) throws ServiceException { try { ProcessEngineDriver driver = new ProcessEngineDriver(); return driver.startProcess(process.getId(), masterRequestId, ownerType, ownerId, params, null); } catch (Exception ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, ex.getMessage(), ex); } } public Object invokeServiceProcess(String name, Object masterRequest, String masterRequestId, Map<String,Object> parameters, Map<String,String> headers) throws ServiceException { return invokeServiceProcess(name, masterRequest, masterRequestId, parameters, headers, null); } public Object invokeServiceProcess(String processName, Object masterRequest, String masterRequestId, Map<String,Object> parameters, Map<String,String> headers, Map<String,String> responseHeaders) throws ServiceException { try { Long docId = 0L; String request = null; Process processVO = ProcessCache.getProcess(processName, 0); Package pkg = PackageCache.getProcessPackage(processVO.getId()); if (masterRequest != null) { String docType = getDocType(masterRequest); EventServices eventMgr = ServiceLocator.getEventServices(); docId = eventMgr.createDocument(docType, OwnerType.LISTENER_REQUEST, 0L, masterRequest, pkg); request = VariableTranslator.realToString(pkg, docType, masterRequest); if (headers == null) headers = new HashMap<>(); headers.put(Listener.METAINFO_DOCUMENT_ID, docId.toString()); } Map<String,String> stringParams = translateParameters(processVO, parameters); String responseVarName = "response"; // currently not configurable ProcessEngineDriver engineDriver = new ProcessEngineDriver(); String resp = engineDriver.invokeService(processVO.getId(), OwnerType.DOCUMENT, docId, masterRequestId, request, stringParams, responseVarName, headers); Object response = resp; if (resp != null) { Variable var = processVO.getVariable(responseVarName); if (var != null && var.isOutput() && !var.isString()) { response = VariableTranslator.realToObject(pkg, var.getType(), resp); } } Variable responseHeadersVar = processVO.getVariable("responseHeaders"); if (responseHeaders != null && responseHeadersVar != null && responseHeadersVar.getType().equals("java.util.Map<String,String>")) { ProcessInstance processInstance = getMasterProcess(masterRequestId); if (processInstance != null) { VariableInstance respHeadersVar = processInstance.getVariable("responseHeaders"); if (respHeadersVar != null) { Document doc = getDocument(((DocumentReference)respHeadersVar.getData()).getDocumentId()); Map<?,?> respHeaders = (Map<?,?>) doc.getObject("java.util.Map<String,String>", PackageCache.getPackage(processInstance.getPackageName())); for (Object key : respHeaders.keySet()) responseHeaders.put(key.toString(), respHeaders.get(key).toString()); } } } return response; } catch (ServiceException ex) { throw ex; } catch (Exception ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, ex.getMessage(), ex); } } public String invokeServiceProcess(Process process, String masterRequestId, String ownerType, Long ownerId, Map<String,String> params) throws ServiceException { return invokeServiceProcess(process, masterRequestId, ownerType, ownerId, params, null); } public String invokeServiceProcess(Process process, String masterRequestId, String ownerType, Long ownerId, Map<String,String> params, Map<String,String> headers) throws ServiceException { try { ProcessEngineDriver driver = new ProcessEngineDriver(); String masterRequest = params == null ? null : params.get("request"); return driver.invokeService(process.getId(), ownerType, ownerId, masterRequestId, masterRequest, params, null, headers); } catch (Exception ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, ex.getMessage(), ex); } } /** * Saves document as raw StringDocument. */ public Integer notify(String event, String message, int delay) throws ServiceException { try { EventServices eventManager = ServiceLocator.getEventServices(); Long docId = eventManager.createDocument(StringDocument.class.getName(), OwnerType.INTERNAL_EVENT, 0L, message, null); return eventManager.notifyProcess(event, docId, message, delay); } catch (Exception ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, ex.getMessage(), ex); } } public Integer notify(Package runtimePackage, String eventName, Object eventMessage) throws ServiceException { int delay = PropertyManager.getIntegerProperty(PropertyNames.ACTIVITY_RESUME_DELAY, 2); return notify(runtimePackage, eventName, eventMessage, delay); } public Integer notify(Package runtimePackage, String eventName, Object eventMessage, int delay) throws ServiceException { try { Long docId = 0L; String message = null; if (eventMessage != null) { String docType = getDocType(eventMessage); EventServices eventMgr = ServiceLocator.getEventServices(); docId = eventMgr.createDocument(docType, OwnerType.LISTENER_REQUEST, 0L, eventMessage, runtimePackage); message = VariableTranslator.realToString(runtimePackage, docType, eventMessage); } EventServices eventManager = ServiceLocator.getEventServices(); return eventManager.notifyProcess(eventName, docId, message, delay); } catch (ServiceException ex) { throw ex; } catch (Exception ex) { logger.severeException(ex.getMessage(), ex); // TODO why not throw? return EventInstance.RESUME_STATUS_FAILURE; } } public void setVariable(Long processInstanceId, String varName, Object value) throws ServiceException { ProcessRuntimeContext runtimeContext = getContext(processInstanceId); if (runtimeContext == null) throw new ServiceException(ServiceException.NOT_FOUND, "Process instance not found: " + processInstanceId); setVariable(runtimeContext, varName, value); } public void setVariable(ProcessRuntimeContext context, String varName, Object value) throws ServiceException { Integer statusCode = context.getProcessInstance().getStatusCode(); if (WorkStatus.STATUS_COMPLETED.equals(statusCode) || WorkStatus.STATUS_CANCELLED.equals(statusCode) || WorkStatus.STATUS_FAILED.equals(statusCode)) { throw new ServiceException(ServiceException.BAD_REQUEST, "Cannot set value for process in final status: " + statusCode); } Variable var = context.getProcess().getVariable(varName); if (var == null) throw new ServiceException(ServiceException.NOT_FOUND, "Process variable not defined: " + varName); String type = var.getType(); if (VariableTranslator.isDocumentReferenceVariable(context.getPackage(), type)) { setDocumentValue(context, varName, value); } else { try { VariableInstance varInst = context.getProcessInstance().getVariable(varName); WorkflowDataAccess workflowDataAccess = getWorkflowDao(); if (varInst == null) { varInst = new VariableInstance(); varInst.setName(varName); varInst.setVariableId(var.getId()); varInst.setType(type); if (value != null && !value.equals("")) { if (value instanceof String) varInst.setStringValue((String)value); else varInst.setData(value); Long procInstId = context.getProcessInstance().isEmbedded() ? context.getProcessInstance().getOwnerId() : context.getProcessInstanceId(); workflowDataAccess.createVariable(procInstId, varInst); } } else { if (value == null || value.equals("")) { workflowDataAccess.deleteVariable(varInst); } else { if (value instanceof String) varInst.setStringValue((String)value); else varInst.setData(value); workflowDataAccess.updateVariable(varInst); } } } catch (SQLException ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, "Error updating " + varName + " for process: " + context.getProcessInstanceId(), ex); } } } public void setVariables(Long processInstanceId, Map<String,Object> values) throws ServiceException { ProcessRuntimeContext runtimeContext = getContext(processInstanceId); if (runtimeContext == null) throw new ServiceException(ServiceException.NOT_FOUND, "Process instance not found: " + processInstanceId); setVariables(runtimeContext, values); } public void setVariables(ProcessRuntimeContext context, Map<String,Object> values) throws ServiceException { for (String name : values.keySet()) { setVariable(context, name, values.get(name)); } } public void setDocumentValue(ProcessRuntimeContext context, String varName, Object value) throws ServiceException { VariableInstance varInst = context.getProcessInstance().getVariable(varName); if (varInst == null && value != null && !value.equals("")) { createDocument(context, varName, value); } else { if (value == null || value.equals("")) { try { // TODO: delete doc content also getWorkflowDao().deleteVariable(varInst); } catch (SQLException ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, "Error deleting " + varName + " for process: " + context.getProcessInstanceId(), ex); } } else { updateDocument(context, varName, value); } } } /** * TODO: Many places fail to set the ownerId for documents owned by VARIABLE_INSTANCE, * and these need to be updated to use this method. */ public void createDocument(ProcessRuntimeContext context, String varName, Object value) throws ServiceException { String type = context.getProcess().getVariable(varName).getType(); EventServices eventMgr = ServiceLocator.getEventServices(); Long procInstId = context.getProcessInstance().isEmbedded() ? context.getProcessInstance().getOwnerId() : context.getProcessInstanceId(); try { Long docId = eventMgr.createDocument(type, OwnerType.PROCESS_INSTANCE, procInstId, value, context.getPackage()); VariableInstance varInst = eventMgr.setVariableInstance(procInstId, varName, new DocumentReference(docId)); eventMgr.updateDocumentInfo(docId, type, OwnerType.VARIABLE_INSTANCE, varInst.getInstanceId()); } catch (DataAccessException ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, "Error creating document for process: " + procInstId, ex); } } public ProcessRun runProcess(ProcessRun runRequest) throws ServiceException, JSONException { Long definitionId = runRequest.getDefinitionId(); if (definitionId == null) throw new ServiceException(ServiceException.BAD_REQUEST, "Missing definitionId"); Process proc = getProcessDefinition(definitionId); if (proc == null) throw new ServiceException(ServiceException.NOT_FOUND, "Process definition not found for id: " + definitionId); ProcessRun actualRun = new ProcessRun(runRequest.getJson()); // clone Long runId = runRequest.getId(); if (runId == null) { runId = System.nanoTime(); actualRun.setId(runId); } String masterRequestId = runRequest.getMasterRequestId(); if (masterRequestId == null) { masterRequestId = runId.toString(); actualRun.setMasterRequestId(masterRequestId); } String ownerType = runRequest.getOwnerType(); Long ownerId = runRequest.getOwnerId(); if (ownerType == null) { if (ownerId != null) throw new ServiceException(ServiceException.BAD_REQUEST, "ownerId not allowed without ownerType"); EventServices eventMgr = ServiceLocator.getEventServices(); try { ownerType = OwnerType.DOCUMENT; actualRun.setOwnerType(ownerType); ownerId = eventMgr.createDocument(JSONObject.class.getName(), OwnerType.PROCESS_RUN, runId, runRequest.getJson(), PackageCache.getPackage(proc.getPackageName())); actualRun.setOwnerId(ownerId); } catch (DataAccessException ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, "Error creating document for run id: " + runId); } } else if (ownerId == null) throw new ServiceException(ServiceException.BAD_REQUEST, "ownerType not allowed without ownerId"); Map<String,String> params = new HashMap<>(); if (runRequest.getValues() != null) { for (String name : runRequest.getValues().keySet()) { Value value = runRequest.getValues().get(name); if (value.getValue() != null) params.put(name, value.getValue()); } } if (proc.isService()) { Map<String,String> headers = new HashMap<>(); invokeServiceProcess(proc, masterRequestId, ownerType, ownerId, params, headers); String instIdStr = headers.get(Listener.METAINFO_MDW_PROCESS_INSTANCE_ID); if (instIdStr != null) actualRun.setInstanceId(Long.parseLong(instIdStr)); } else { Long instanceId = launchProcess(proc, masterRequestId, ownerType, ownerId, params); actualRun.setInstanceId(instanceId); } return actualRun; } public void updateDocument(ProcessRuntimeContext context, String varName, Object value) throws ServiceException { EventServices eventMgr = ServiceLocator.getEventServices(); VariableInstance varInst = context.getProcessInstance().getVariable(varName); if (varInst == null) throw new ServiceException(ServiceException.NOT_FOUND, varName + " not found for process: " + context.getProcessInstanceId()); try { eventMgr.updateDocumentContent(varInst.getDocumentId(), value, varInst.getType(), context.getPackage()); } catch (DataAccessException ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, "Error updating document: " + varInst.getDocumentId()); } } private Map<String,String> translateParameters(Process process, Map<String,Object> parameters) throws ProcessException { Map<String,String> stringParams = new HashMap<String,String>(); if (parameters != null) { for (String key : parameters.keySet()) { Object val = parameters.get(key); Variable vo = process.getVariable(key); if (vo == null) throw new ProcessException("Variable '" + key + "' not found for process: " + process.getName() + " v" + process.getVersionString() + "(id=" + process.getId() + ")"); String translated; if (val instanceof String) translated = (String)val; else { Package pkg = PackageCache.getProcessPackage(process.getId()); if (VariableTranslator.isDocumentReferenceVariable(pkg, vo.getType())) { translated = VariableTranslator.realToString(pkg, vo.getType(), val); } else { translated = VariableTranslator.toString(PackageCache.getProcessPackage(process.getId()), vo.getType(), val); } } stringParams.put(key, translated); } } return stringParams; } /** * TODO: There's gotta be a better way */ public String getDocType(Object docObj) { if (docObj instanceof String || docObj instanceof StringDocument) return StringDocument.class.getName(); else if (docObj instanceof XmlObject) return XmlObject.class.getName(); else if (docObj instanceof XmlBeanWrapper) return XmlBeanWrapper.class.getName(); else if (docObj instanceof groovy.util.Node) return groovy.util.Node.class.getName(); else if (docObj instanceof JAXBElement) return JAXBElement.class.getName(); else if (docObj instanceof Document) return Document.class.getName(); else if (docObj instanceof JSONObject) return JSONObject.class.getName(); else if (docObj.getClass().getName().equals("org.apache.camel.component.cxf.CxfPayload")) return "org.apache.camel.component.cxf.CxfPayload"; else if (docObj instanceof Jsonable) return Jsonable.class.getName(); else if (docObj instanceof Yaml) return Yaml.class.getName(); else return Object.class.getName(); } @SuppressWarnings("deprecation") public String getDocumentStringValue(Long id) throws ServiceException { try { Document doc = getWorkflowDao().getDocument(id); if (doc.getDocumentType() == null) throw new ServiceException(ServiceException.INTERNAL_ERROR, "Unable to determine document type."); // check raw content for parsability if (doc.getContent() == null || doc.getContent().isEmpty()) return doc.getContent(); Package pkg = getPackage(doc); com.centurylink.mdw.variable.VariableTranslator trans = VariableTranslator.getTranslator(pkg, doc.getDocumentType()); if (trans instanceof JavaObjectTranslator) { Object obj = doc.getObject(Object.class.getName(), pkg); return obj.toString(); } else if (trans instanceof StringDocumentTranslator) { return doc.getContent(); } else if (trans instanceof XmlDocumentTranslator && !(trans instanceof YamlTranslator)) { org.w3c.dom.Document domDoc = ((XmlDocumentTranslator)trans).toDomDocument(doc.getObject(doc.getDocumentType(), pkg)); XmlObject xmlBean = XmlObject.Factory.parse(domDoc); return xmlBean.xmlText(new XmlOptions().setSavePrettyPrint().setSavePrettyPrintIndent(4)); } else if (trans instanceof JsonTranslator && !(trans instanceof YamlTranslator)) { JSONObject jsonObj = ((JsonTranslator)trans).toJson(doc.getObject(doc.getDocumentType(), pkg)); if (jsonObj instanceof JsonObject) return jsonObj.toString(2); else return new JsonObject(jsonObj.toString()).toString(2); // reformat for predictable prop ordering } return doc.getContent(pkg); } catch (ServiceException ex) { throw ex; } catch (Exception ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, "Error retrieving document: " + id, ex); } } private Package getPackage(Document docVO) throws ServiceException { try { EventServices eventMgr = ServiceLocator.getEventServices(); if (docVO.getOwnerId() == 0) // eg: sdwf request headers return null; if (docVO.getOwnerType().equals(OwnerType.VARIABLE_INSTANCE)) { VariableInstance varInstInf = eventMgr.getVariableInstance(docVO.getOwnerId()); Long procInstId = varInstInf.getProcessInstanceId(); ProcessInstance procInstVO = eventMgr.getProcessInstance(procInstId); if (procInstVO != null) return PackageCache.getProcessPackage(procInstVO.getProcessId()); } else if (docVO.getOwnerType().equals(OwnerType.PROCESS_INSTANCE)) { Long procInstId = docVO.getOwnerId(); ProcessInstance procInstVO = eventMgr.getProcessInstance(procInstId); if (procInstVO != null) return PackageCache.getProcessPackage(procInstVO.getProcessId()); } else if (docVO.getOwnerType().equals("Designer")) { // test case, etc return PackageCache.getProcessPackage(docVO.getOwnerId()); } return null; } catch (Exception ex) { throw new ServiceException(ex.getMessage(), ex); } } public void createProcess(String assetPath, Query query) throws ServiceException, IOException { if (!assetPath.endsWith(".proc")) assetPath += ".proc"; String template = query.getFilter("template"); if (template == null) throw new ServiceException(ServiceException.BAD_REQUEST, "Missing param: template"); byte[] content = Templates.getBytes("assets/" + template + ".proc"); if (content == null) throw new ServiceException(ServiceException.NOT_FOUND, "Template not found: " + template); ServiceLocator.getAssetServices().createAsset(assetPath, content); } public Process getInstanceDefinition(String assetPath, Long instanceId) throws ServiceException { EngineDataAccessDB dataAccess = new EngineDataAccessDB(); try { dataAccess.getDatabaseAccess().openConnection(); ProcessInstance procInst = dataAccess.getProcessInstance(instanceId); // We need the processID if (procInst.getProcessInstDefId() > 0L) { Process process = ProcessCache.getProcessInstanceDefiniton(procInst.getProcessId(), procInst.getProcessInstDefId()); if (process.getQualifiedName().equals(assetPath)) // Make sure instanceId is for requested assetPath return process; } return null; } catch (SQLException ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, "Error retrieving instance document " + assetPath + ": " + instanceId); } finally { if (dataAccess.getDatabaseAccess().connectionIsOpen()) dataAccess.getDatabaseAccess().closeConnection(); } } public void saveInstanceDefinition(String assetPath, Long instanceId, Process process) throws ServiceException { EngineDataAccessDB dataAccess = new EngineDataAccessDB(); try { EventServices eventServices = ServiceLocator.getEventServices(); dataAccess.getDatabaseAccess().openConnection(); ProcessInstance procInst = dataAccess.getProcessInstance(instanceId); long docId = procInst.getProcessInstDefId(); if (docId == 0L) { docId = eventServices.createDocument(Jsonable.class.getName(), OwnerType.PROCESS_INSTANCE_DEF, instanceId, process, PackageCache.getPackage(process.getPackageName())); String[] fields = new String[]{"COMMENTS"}; String comment = procInst.getComment() == null ? "" : procInst.getComment(); Object[] args = new Object[]{comment + "|HasInstanceDef|" + docId, null}; dataAccess.updateTableRow("process_instance", "process_instance_id", instanceId, fields, args); } else { eventServices.updateDocumentContent(docId, process, Jsonable.class.getName(), PackageCache.getPackage(process.getPackageName())); } // Update any embedded Sub processes to indicate they have instance definition for (ProcessInstance inst : dataAccess.getProcessInstances(procInst.getProcessId(), OwnerType.MAIN_PROCESS_INSTANCE, procInst.getId())) { String[] fields = new String[]{"COMMENTS"}; String comment = inst.getComment() == null ? "" : inst.getComment(); Object[] args = new Object[]{comment + "|HasInstanceDef|" + docId, null}; dataAccess.updateTableRow("process_instance", "process_instance_id", inst.getId(), fields, args); } } catch (DataAccessException | SQLException ex) { throw new ServiceException(ServiceException.INTERNAL_ERROR, "Error creating process instance definition " + assetPath + ": " + instanceId, ex); } finally { if (dataAccess.getDatabaseAccess().connectionIsOpen()) dataAccess.getDatabaseAccess().closeConnection(); } } protected UserAction auditLog(String action, UserAction.Entity entity, Long entityId, String user, String completionCode) throws ServiceException { UserAction userAction = new UserAction(user, UserAction.getAction(action), entity, entityId, null); userAction.setSource("Workflow Services"); userAction.setDestination(completionCode); if (userAction.getAction().equals(UserAction.Action.Other)) { userAction.setExtendedAction(action); } try { EventServices eventManager = ServiceLocator.getEventServices(); eventManager.createAuditLog(userAction); return userAction; } catch (DataAccessException ex) { throw new ServiceException("Failed to create audit log: " + userAction, ex); } } }
Issue #640
mdw-services/src/com/centurylink/mdw/services/workflow/WorkflowServicesImpl.java
Issue #640
<ide><path>dw-services/src/com/centurylink/mdw/services/workflow/WorkflowServicesImpl.java <ide> if (!decodedActName.isEmpty()) <ide> activityList.setActivities(matchActivities); <ide> activityList.setCount(activityList.getActivities().size()); <del> activityList.setTotal(activityList.getActivities().size()); <add> if (activityList.getTotal() <= 0L) <add> activityList.setTotal(activityList.getActivities().size()); <ide> return activityList; <ide> } <ide>
Java
bsd-3-clause
ff55359871fe1e09d99b931759832ae7948558a6
0
bdezonia/zorbage,bdezonia/zorbage
/* * Zorbage: an algebraic data hierarchy for use in numeric processing. * * Copyright (C) 2016-2018 Barry DeZonia * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package nom.bdezonia.zorbage.algorithm; import static org.junit.Assert.assertEquals; import org.junit.Test; import nom.bdezonia.zorbage.groups.G; import nom.bdezonia.zorbage.type.ctor.StorageConstruction; import nom.bdezonia.zorbage.type.data.float64.complex.ComplexFloat64Member; import nom.bdezonia.zorbage.type.data.float64.complex.ComplexFloat64VectorMember; /** * * @author Barry DeZonia * */ public class TestRModuleConjugate { @Test public void test() { //TODO: fix this crash: // ComplexFloat64VectorMember a = G.CDBL_VEC.construct("[{1,0},{2,-7},{3,5}]"); ComplexFloat64Member value = G.CDBL.construct(); ComplexFloat64VectorMember a = G.CDBL_VEC.construct(StorageConstruction.MEM_ARRAY,3); value.setR(1); value.setI(0); a.setV(0, value); value.setR(2); value.setI(-7); a.setV(1, value); value.setR(3); value.setI(5); a.setV(2, value); ComplexFloat64VectorMember b = G.CDBL_VEC.construct(); RModuleConjugate.compute(G.CDBL, a, b); b.v(0, value); assertEquals(1, value.r(), 0); assertEquals(0, value.i(), 0); b.v(1, value); assertEquals(2, value.r(), 0); assertEquals(7, value.i(), 0); b.v(2, value); assertEquals(3, value.r(), 0); assertEquals(-5, value.i(), 0); } }
src/test/java/nom/bdezonia/zorbage/algorithm/TestRModuleConjugate.java
package nom.bdezonia.zorbage.algorithm; class TestRModuleConjugate {}
Test RModuleConjugate algorithm
src/test/java/nom/bdezonia/zorbage/algorithm/TestRModuleConjugate.java
Test RModuleConjugate algorithm
<ide><path>rc/test/java/nom/bdezonia/zorbage/algorithm/TestRModuleConjugate.java <del>package nom.bdezonia.zorbage.algorithm; class TestRModuleConjugate {} <add>/* <add> * Zorbage: an algebraic data hierarchy for use in numeric processing. <add> * <add> * Copyright (C) 2016-2018 Barry DeZonia <add> * <add> * Redistribution and use in source and binary forms, with or without <add> * modification, are permitted provided that the following conditions are met: <add> * <add> * 1. Redistributions of source code must retain the above copyright notice, <add> * this list of conditions and the following disclaimer. <add> * 2. Redistributions in binary form must reproduce the above copyright notice, <add> * this list of conditions and the following disclaimer in the documentation <add> * and/or other materials provided with the distribution. <add> * <add> * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" <add> * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE <add> * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE <add> * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE <add> * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR <add> * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF <add> * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS <add> * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN <add> * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) <add> * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE <add> * POSSIBILITY OF SUCH DAMAGE. <add> */ <add>package nom.bdezonia.zorbage.algorithm; <add> <add>import static org.junit.Assert.assertEquals; <add> <add>import org.junit.Test; <add> <add>import nom.bdezonia.zorbage.groups.G; <add>import nom.bdezonia.zorbage.type.ctor.StorageConstruction; <add>import nom.bdezonia.zorbage.type.data.float64.complex.ComplexFloat64Member; <add>import nom.bdezonia.zorbage.type.data.float64.complex.ComplexFloat64VectorMember; <add> <add>/** <add> * <add> * @author Barry DeZonia <add> * <add> */ <add>public class TestRModuleConjugate { <add> <add> @Test <add> public void test() { <add> //TODO: fix this crash: <add> // ComplexFloat64VectorMember a = G.CDBL_VEC.construct("[{1,0},{2,-7},{3,5}]"); <add> ComplexFloat64Member value = G.CDBL.construct(); <add> ComplexFloat64VectorMember a = G.CDBL_VEC.construct(StorageConstruction.MEM_ARRAY,3); <add> value.setR(1); <add> value.setI(0); <add> a.setV(0, value); <add> value.setR(2); <add> value.setI(-7); <add> a.setV(1, value); <add> value.setR(3); <add> value.setI(5); <add> a.setV(2, value); <add> ComplexFloat64VectorMember b = G.CDBL_VEC.construct(); <add> RModuleConjugate.compute(G.CDBL, a, b); <add> b.v(0, value); <add> assertEquals(1, value.r(), 0); <add> assertEquals(0, value.i(), 0); <add> b.v(1, value); <add> assertEquals(2, value.r(), 0); <add> assertEquals(7, value.i(), 0); <add> b.v(2, value); <add> assertEquals(3, value.r(), 0); <add> assertEquals(-5, value.i(), 0); <add> } <add>}
Java
mit
761853bb08ceb0430e15130f46104600f3fa247e
0
classgraph/classgraph,lukehutch/fast-classpath-scanner,lukehutch/fast-classpath-scanner
/* * This file is part of FastClasspathScanner. * * Author: Luke Hutchison * * Hosted at: https://github.com/lukehutch/fast-classpath-scanner * * -- * * The MIT License (MIT) * * Copyright (c) 2016 Luke Hutchison * * 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 io.github.lukehutch.fastclasspathscanner.scanner; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutionException; import java.util.zip.ZipEntry; import io.github.lukehutch.fastclasspathscanner.scanner.ScanSpec.FileMatchProcessorWrapper; import io.github.lukehutch.fastclasspathscanner.utils.ClasspathUtils; import io.github.lukehutch.fastclasspathscanner.utils.InterruptionChecker; import io.github.lukehutch.fastclasspathscanner.utils.LogNode; import io.github.lukehutch.fastclasspathscanner.utils.MultiMapKeyToList; import io.github.lukehutch.fastclasspathscanner.utils.NestedJarHandler; import io.github.lukehutch.fastclasspathscanner.utils.WorkQueue; /** A classpath element (a directory or jarfile on the classpath). */ abstract class ClasspathElement { /** The classpath element path. */ final ClasspathRelativePath classpathEltPath; /** * If non-null, contains a list of resolved paths for any classpath element roots nested inside this classpath * element. (Scanning should stop at a nested classpath element root, otherwise that subtree will be scanned * more than once.) N.B. contains only the nested part of the resolved path (the common prefix is removed). Also * includes a trailing '/', since only nested directory classpath elements need to be caught (nested jars do not * need to be caught, because we don't scan jars-within-jars unless the inner jar is explicitly listed on the * classpath). */ Set<String> nestedClasspathRoots; /** True if there was an exception when trying to open this classpath element (e.g. a corrupt ZipFile). */ boolean ioExceptionOnOpen; /** * The child classpath elements. These are the entries obtained from Class-Path entries in the manifest file, if * this classpath element is a jarfile. */ List<ClasspathRelativePath> childClasspathElts; /** The scan spec. */ final ScanSpec scanSpec; /** * If true, recursively scan directores, and iterate through ZipEntries inside ZipFiles looking for whitelisted * file and classfile matches. If false, only find unique classpath elements. */ private final boolean scanFiles; /** * Used to detect interruption of threads, and to shut down all workers in the case of interruption or execution * exceptions. */ protected InterruptionChecker interruptionChecker; /** The list of classpath resources that matched for each FileMatchProcessor. */ protected MultiMapKeyToList<FileMatchProcessorWrapper, ClasspathResource> fileMatches; /** The list of whitelisted classfiles found within this classpath resource, if scanFiles is true. */ protected List<ClasspathResource> classfileMatches; /** The map from File to last modified timestamp, if scanFiles is true. */ protected Map<File, Long> fileToLastModified; /** A classpath element (a directory or jarfile on the classpath). */ ClasspathElement(final ClasspathRelativePath classpathEltPath, final ScanSpec scanSpec, final boolean scanFiles, final InterruptionChecker interruptionChecker) { this.classpathEltPath = classpathEltPath; this.scanSpec = scanSpec; this.scanFiles = scanFiles; this.interruptionChecker = interruptionChecker; } /** Return the classpath element's path. */ @Override public String toString() { return getClasspathElementFilePath(); } /** Return the classpath element's URL */ public URL getClasspathElementURL() { try { return getClasspathElementFile().toURI().toURL(); } catch (final MalformedURLException e) { // Shouldn't happen; File objects should always be able to be turned into URIs and then URLs throw new RuntimeException(e); } } /** Return the classpath element's file (directory or jarfile) */ public File getClasspathElementFile() { try { return classpathEltPath.getFile(); } catch (final IOException e) { // Shouldn't happen; files have already been screened for IOException during canonicalization throw new RuntimeException(e); } } /** The path for this classpath element, possibly including a '!' jar-internal path suffix. */ public String getClasspathElementFilePath() { return classpathEltPath.toString(); } /** Get the ClassLoader(s) to use when trying to load the class. */ public ClassLoader[] getClassLoaders() { return classpathEltPath.getClassLoaders(); } /** * Factory for creating a ClasspathElementDir singleton for directory classpath entries or a ClasspathElementZip * singleton for jarfile classpath entries. */ static ClasspathElement newInstance(final ClasspathRelativePath classpathRelativePath, final boolean scanFiles, final ScanSpec scanSpec, final NestedJarHandler nestedJarHandler, final WorkQueue<ClasspathRelativePath> workQueue, final InterruptionChecker interruptionChecker, final LogNode log) { boolean isDir; String canonicalPath; File file; try { file = classpathRelativePath.getFile(); isDir = classpathRelativePath.isDirectory(); canonicalPath = classpathRelativePath.getCanonicalPath(); } catch (final IOException e) { if (log != null) { log.log("Exception while trying to canonicalize path " + classpathRelativePath.getResolvedPath(), e); } return null; } final LogNode logNode = log == null ? null : log.log(canonicalPath, "Scanning " + (isDir ? "directory " : "jarfile ") + "classpath entry " + classpathRelativePath + (file.getPath().equals(canonicalPath) ? "" : " ; canonical path: " + canonicalPath)); final ClasspathElement newInstance = isDir ? new ClasspathElementDir(classpathRelativePath, scanSpec, scanFiles, interruptionChecker, logNode) : new ClasspathElementZip(classpathRelativePath, scanSpec, scanFiles, nestedJarHandler, workQueue, interruptionChecker, logNode); if (logNode != null) { logNode.addElapsedTime(); } return newInstance; } /** * The combination of a classpath element and a relative path within this classpath element. */ static class ClasspathResource { final File classpathEltFile; final String pathRelativeToClasspathElt; final String pathRelativeToClasspathPrefix; private ClasspathResource(final File classpathEltFile, final String pathRelativeToClasspathElt, final String pathRelativeToClasspathPrefix) { this.classpathEltFile = classpathEltFile; this.pathRelativeToClasspathElt = pathRelativeToClasspathElt; this.pathRelativeToClasspathPrefix = pathRelativeToClasspathPrefix; } static class ClasspathResourceInDir extends ClasspathResource { final File relativePathFile; ClasspathResourceInDir(final File classpathEltFile, final String pathRelativeToClasspathElt, final File relativePathFile) { super(classpathEltFile, pathRelativeToClasspathElt, pathRelativeToClasspathElt); this.relativePathFile = relativePathFile; } @Override public String toString() { return ClasspathUtils.getClasspathResourceURL(classpathEltFile, pathRelativeToClasspathElt) .toString(); } } static class ClasspathResourceInZipFile extends ClasspathResource { final ZipEntry zipEntry; ClasspathResourceInZipFile(final File classpathEltFile, final String pathRelativeToClasspathElt, final String pathRelativeToClasspathPrefix, final ZipEntry zipEntry) { super(classpathEltFile, pathRelativeToClasspathElt, pathRelativeToClasspathPrefix); this.zipEntry = zipEntry; } @Override public String toString() { return ClasspathUtils.getClasspathResourceURL(classpathEltFile, pathRelativeToClasspathElt) .toString(); } } } /** Get the number of classfile matches. */ public int getNumClassfileMatches() { return classfileMatches == null ? 0 : classfileMatches.size(); } /** * Apply relative path masking within this classpath resource -- remove relative paths that were found in an * earlier classpath element. */ void maskFiles(final int classpathIdx, final HashSet<String> classpathRelativePathsFound, final LogNode log) { if (!scanFiles) { // Should not happen throw new IllegalArgumentException("scanFiles is false"); } // Take the union of classfile and file match relative paths, since matches can be in both lists // if a user adds a custom file path matcher that matches paths ending in ".class" final HashSet<String> allMatchingRelativePathsForThisClasspathElement = new HashSet<>(); for (final ClasspathResource res : classfileMatches) { allMatchingRelativePathsForThisClasspathElement.add(res.pathRelativeToClasspathPrefix); } for (final Entry<FileMatchProcessorWrapper, List<ClasspathResource>> ent : fileMatches.entrySet()) { for (final ClasspathResource classpathResource : ent.getValue()) { allMatchingRelativePathsForThisClasspathElement .add(classpathResource.pathRelativeToClasspathPrefix); } } // See which of these paths are masked, if any final HashSet<String> maskedRelativePaths = new HashSet<>(); for (final String match : allMatchingRelativePathsForThisClasspathElement) { if (classpathRelativePathsFound.contains(match)) { maskedRelativePaths.add(match); } } if (!maskedRelativePaths.isEmpty()) { // Replace the lists of matching resources with filtered versions with masked paths removed final List<ClasspathResource> filteredClassfileMatches = new ArrayList<>(); for (final ClasspathResource classfileMatch : classfileMatches) { if (!maskedRelativePaths.contains(classfileMatch.pathRelativeToClasspathPrefix)) { filteredClassfileMatches.add(classfileMatch); } else { if (log != null) { log.log(String.format("%06d-1", classpathIdx), "Ignoring duplicate (masked) class " + classfileMatch.pathRelativeToClasspathPrefix .substring(0, classfileMatch.pathRelativeToClasspathPrefix.length() - 6) .replace('/', '.') + " for classpath element " + classfileMatch); } } } classfileMatches = filteredClassfileMatches; final MultiMapKeyToList<FileMatchProcessorWrapper, ClasspathResource> filteredFileMatches = // new MultiMapKeyToList<>(); for (final Entry<FileMatchProcessorWrapper, List<ClasspathResource>> ent : fileMatches.entrySet()) { for (final ClasspathResource fileMatch : ent.getValue()) { if (!maskedRelativePaths.contains(fileMatch.pathRelativeToClasspathPrefix)) { filteredFileMatches.put(ent.getKey(), fileMatch); } else { if (log != null) { log.log(String.format("%06d-1", classpathIdx), "Ignoring duplicate (masked) file path " + fileMatch.pathRelativeToClasspathPrefix + " in classpath element " + fileMatch); } } } } fileMatches = filteredFileMatches; } classpathRelativePathsFound.addAll(allMatchingRelativePathsForThisClasspathElement); } // ------------------------------------------------------------------------------------------------------------- /** Call FileMatchProcessors for any whitelisted matches found within this classpath element. */ void callFileMatchProcessors(final ScanResult scanResult, final LogNode log) throws InterruptedException, ExecutionException { for (final Entry<FileMatchProcessorWrapper, List<ClasspathResource>> ent : fileMatches.entrySet()) { final FileMatchProcessorWrapper fileMatchProcessorWrapper = ent.getKey(); for (final ClasspathResource fileMatch : ent.getValue()) { try { final LogNode logNode = log == null ? null : log.log("Calling MatchProcessor for matching file " + fileMatch); openInputStreamAndProcessFileMatch(fileMatch, fileMatchProcessorWrapper); if (logNode != null) { logNode.addElapsedTime(); } } catch (final IOException e) { if (log != null) { log.log("Exception while opening file " + fileMatch, e); } } catch (final Throwable e) { if (log != null) { log.log("Exception while calling FileMatchProcessor for file " + fileMatch, e); } scanResult.addMatchProcessorException(e); } interruptionChecker.check(); } } } /** * Open an input stream and call a FileMatchProcessor on a specific whitelisted match found within this * classpath element. Implemented in the directory- and zipfile-specific sublclasses. */ protected abstract void openInputStreamAndProcessFileMatch(ClasspathResource fileMatch, FileMatchProcessorWrapper fileMatchProcessorWrapper) throws IOException; // ------------------------------------------------------------------------------------------------------------- /** Parse any classfiles for any whitelisted classes found within this classpath element. */ void parseClassfiles(final ClassfileBinaryParser classfileBinaryParser, final int classfileStartIdx, final int classfileEndIdx, final ConcurrentHashMap<String, String> stringInternMap, final ConcurrentLinkedQueue<ClassInfoUnlinked> classInfoUnlinked, final LogNode log) throws Exception { for (int i = classfileStartIdx; i < classfileEndIdx; i++) { final ClasspathResource classfileResource = classfileMatches.get(i); try { final LogNode logNode = log == null ? null : log.log("Parsing classfile " + classfileResource); openInputStreamAndParseClassfile(classfileResource, classfileBinaryParser, scanSpec, stringInternMap, classInfoUnlinked, logNode); if (logNode != null) { logNode.addElapsedTime(); } } catch (final IOException e) { if (log != null) { log.log("IOException while attempting to read classfile " + classfileResource + " -- skipping", e); } } catch (final Exception e) { if (log != null) { log.log("Exception while parsing classfile " + classfileResource, e); } // Re-throw throw e; } interruptionChecker.check(); } } /** * Open an input stream and parse a specific classfile found within this classpath element. Implemented in the * directory- and zipfile-specific sublclasses. */ protected abstract void openInputStreamAndParseClassfile(final ClasspathResource classfileResource, final ClassfileBinaryParser classfileBinaryParser, final ScanSpec scanSpec, final ConcurrentHashMap<String, String> stringInternMap, final ConcurrentLinkedQueue<ClassInfoUnlinked> classInfoUnlinked, final LogNode log) throws IOException, InterruptedException; // ------------------------------------------------------------------------------------------------------------- /** Scan the classpath element */ public abstract void scanPaths(LogNode log); /** Close the classpath element's resources. (Used by zipfile-specific subclass.) */ public abstract void close(); }
src/main/java/io/github/lukehutch/fastclasspathscanner/scanner/ClasspathElement.java
/* * This file is part of FastClasspathScanner. * * Author: Luke Hutchison * * Hosted at: https://github.com/lukehutch/fast-classpath-scanner * * -- * * The MIT License (MIT) * * Copyright (c) 2016 Luke Hutchison * * 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 io.github.lukehutch.fastclasspathscanner.scanner; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutionException; import java.util.zip.ZipEntry; import io.github.lukehutch.fastclasspathscanner.scanner.ScanSpec.FileMatchProcessorWrapper; import io.github.lukehutch.fastclasspathscanner.utils.ClasspathUtils; import io.github.lukehutch.fastclasspathscanner.utils.InterruptionChecker; import io.github.lukehutch.fastclasspathscanner.utils.LogNode; import io.github.lukehutch.fastclasspathscanner.utils.MultiMapKeyToList; import io.github.lukehutch.fastclasspathscanner.utils.NestedJarHandler; import io.github.lukehutch.fastclasspathscanner.utils.WorkQueue; /** A classpath element (a directory or jarfile on the classpath). */ abstract class ClasspathElement { /** The classpath element path. */ final ClasspathRelativePath classpathEltPath; /** * If non-null, contains a list of resolved paths for any classpath element roots nested inside this classpath * element. (Scanning should stop at a nested classpath element root, otherwise that subtree will be scanned * more than once.) N.B. contains only the nested part of the resolved path (the common prefix is removed). Also * includes a trailing '/', since only nested directory classpath elements need to be caught (nested jars do not * need to be caught, because we don't scan jars-within-jars unless the inner jar is explicitly listed on the * classpath). */ Set<String> nestedClasspathRoots; /** True if there was an exception when trying to open this classpath element (e.g. a corrupt ZipFile). */ boolean ioExceptionOnOpen; /** * The child classpath elements. These are the entries obtained from Class-Path entries in the manifest file, if * this classpath element is a jarfile. */ List<ClasspathRelativePath> childClasspathElts; /** The scan spec. */ final ScanSpec scanSpec; /** * If true, recursively scan directores, and iterate through ZipEntries inside ZipFiles looking for whitelisted * file and classfile matches. If false, only find unique classpath elements. */ private final boolean scanFiles; /** * Used to detect interruption of threads, and to shut down all workers in the case of interruption or execution * exceptions. */ protected InterruptionChecker interruptionChecker; /** The list of classpath resources that matched for each FileMatchProcessor. */ protected MultiMapKeyToList<FileMatchProcessorWrapper, ClasspathResource> fileMatches; /** The list of whitelisted classfiles found within this classpath resource, if scanFiles is true. */ protected List<ClasspathResource> classfileMatches; /** The map from File to last modified timestamp, if scanFiles is true. */ protected Map<File, Long> fileToLastModified; /** A classpath element (a directory or jarfile on the classpath). */ ClasspathElement(final ClasspathRelativePath classpathEltPath, final ScanSpec scanSpec, final boolean scanFiles, final InterruptionChecker interruptionChecker) { this.classpathEltPath = classpathEltPath; this.scanSpec = scanSpec; this.scanFiles = scanFiles; this.interruptionChecker = interruptionChecker; } /** Return the classpath element's path. */ @Override public String toString() { return getClasspathElementFilePath(); } /** Return the classpath element's URL */ public URL getClasspathElementURL() { try { return getClasspathElementFile().toURI().toURL(); } catch (final MalformedURLException e) { // Shouldn't happen; File objects should always be able to be turned into URIs and then URLs throw new RuntimeException(e); } } /** Return the classpath element's file (directory or jarfile) */ public File getClasspathElementFile() { try { return classpathEltPath.getFile(); } catch (final IOException e) { // Shouldn't happen; files have already been screened for IOException during canonicalization throw new RuntimeException(e); } } /** The path for this classpath element, possibly including a '!' jar-internal path suffix. */ public String getClasspathElementFilePath() { return classpathEltPath.toString(); } /** Get the ClassLoader(s) to use when trying to load the class. */ public ClassLoader[] getClassLoaders() { return classpathEltPath.getClassLoaders(); } /** * Factory for creating a ClasspathElementDir singleton for directory classpath entries or a ClasspathElementZip * singleton for jarfile classpath entries. */ static ClasspathElement newInstance(final ClasspathRelativePath classpathRelativePath, final boolean scanFiles, final ScanSpec scanSpec, final NestedJarHandler nestedJarHandler, final WorkQueue<ClasspathRelativePath> workQueue, final InterruptionChecker interruptionChecker, final LogNode log) { boolean isDir; String canonicalPath; File file; try { file = classpathRelativePath.getFile(); isDir = classpathRelativePath.isDirectory(); canonicalPath = classpathRelativePath.getCanonicalPath(); } catch (final IOException e) { if (log != null) { log.log("Exception while trying to canonicalize path " + classpathRelativePath.getResolvedPath(), e); } return null; } final LogNode logNode = log == null ? null : log.log(canonicalPath, "Scanning " + (isDir ? "directory " : "jarfile ") + "classpath entry " + classpathRelativePath + (file.getPath().equals(canonicalPath) ? "" : " ; canonical path: " + canonicalPath)); final ClasspathElement newInstance = isDir ? new ClasspathElementDir(classpathRelativePath, scanSpec, scanFiles, interruptionChecker, logNode) : new ClasspathElementZip(classpathRelativePath, scanSpec, scanFiles, nestedJarHandler, workQueue, interruptionChecker, logNode); if (logNode != null) { logNode.addElapsedTime(); } return newInstance; } /** * The combination of a classpath element and a relative path within this classpath element. */ static class ClasspathResource { final File classpathEltFile; final String pathRelativeToClasspathElt; final String pathRelativeToClasspathPrefix; private ClasspathResource(final File classpathEltFile, final String pathRelativeToClasspathElt, final String pathRelativeToClasspathPrefix) { this.classpathEltFile = classpathEltFile; this.pathRelativeToClasspathElt = pathRelativeToClasspathElt; this.pathRelativeToClasspathPrefix = pathRelativeToClasspathPrefix; } static class ClasspathResourceInDir extends ClasspathResource { final File relativePathFile; ClasspathResourceInDir(final File classpathEltFile, final String pathRelativeToClasspathElt, final File relativePathFile) { super(classpathEltFile, pathRelativeToClasspathElt, pathRelativeToClasspathElt); this.relativePathFile = relativePathFile; } @Override public String toString() { return ClasspathUtils.getClasspathResourceURL(classpathEltFile, pathRelativeToClasspathElt) .toString(); } } static class ClasspathResourceInZipFile extends ClasspathResource { final ZipEntry zipEntry; ClasspathResourceInZipFile(final File classpathEltFile, final String pathRelativeToClasspathElt, final String pathRelativeToClasspathPrefix, final ZipEntry zipEntry) { super(classpathEltFile, pathRelativeToClasspathElt, pathRelativeToClasspathPrefix); this.zipEntry = zipEntry; } @Override public String toString() { return ClasspathUtils.getClasspathResourceURL(classpathEltFile, pathRelativeToClasspathElt) .toString(); } } } /** Get the number of classfile matches. */ public int getNumClassfileMatches() { return classfileMatches == null ? 0 : classfileMatches.size(); } /** * Apply relative path masking within this classpath resource -- remove relative paths that were found in an * earlier classpath element. */ void maskFiles(final int classpathIdx, final HashSet<String> classpathRelativePathsFound, final LogNode log) { if (!scanFiles) { // Should not happen throw new IllegalArgumentException("scanFiles is false"); } // Take the union of classfile and file match relative paths, since matches can be in both lists // if a user adds a custom file path matcher that matches paths ending in ".class" final HashSet<String> allMatchingRelativePathsForThisClasspathElement = new HashSet<>(); for (final ClasspathResource res : classfileMatches) { allMatchingRelativePathsForThisClasspathElement.add(res.pathRelativeToClasspathPrefix); } for (final Entry<FileMatchProcessorWrapper, List<ClasspathResource>> ent : fileMatches.entrySet()) { for (final ClasspathResource classpathResource : ent.getValue()) { allMatchingRelativePathsForThisClasspathElement .add(classpathResource.pathRelativeToClasspathPrefix); } } // See which of these paths are masked, if any final HashSet<String> maskedRelativePaths = new HashSet<>(); for (final String match : allMatchingRelativePathsForThisClasspathElement) { if (classpathRelativePathsFound.contains(match)) { maskedRelativePaths.add(match); } } if (!maskedRelativePaths.isEmpty()) { // Replace the lists of matching resources with filtered versions with masked paths removed final List<ClasspathResource> filteredClassfileMatches = new ArrayList<>(); for (final ClasspathResource classfileMatch : classfileMatches) { if (!maskedRelativePaths.contains(classfileMatch.pathRelativeToClasspathPrefix)) { filteredClassfileMatches.add(classfileMatch); } else { if (log != null) { log.log(String.format("%06d-1", classpathIdx), "Ignoring duplicate (masked) class " + classfileMatch.pathRelativeToClasspathPrefix.replace('/', '.') + " for classpath element " + classfileMatch); } } } classfileMatches = filteredClassfileMatches; final MultiMapKeyToList<FileMatchProcessorWrapper, ClasspathResource> filteredFileMatches = // new MultiMapKeyToList<>(); for (final Entry<FileMatchProcessorWrapper, List<ClasspathResource>> ent : fileMatches.entrySet()) { for (final ClasspathResource fileMatch : ent.getValue()) { if (!maskedRelativePaths.contains(fileMatch.pathRelativeToClasspathPrefix)) { filteredFileMatches.put(ent.getKey(), fileMatch); } else { if (log != null) { log.log(String.format("%06d-1", classpathIdx), "Ignoring duplicate (masked) file path " + fileMatch.pathRelativeToClasspathPrefix + " in classpath element " + fileMatch); } } } } fileMatches = filteredFileMatches; } classpathRelativePathsFound.addAll(allMatchingRelativePathsForThisClasspathElement); } // ------------------------------------------------------------------------------------------------------------- /** Call FileMatchProcessors for any whitelisted matches found within this classpath element. */ void callFileMatchProcessors(final ScanResult scanResult, final LogNode log) throws InterruptedException, ExecutionException { for (final Entry<FileMatchProcessorWrapper, List<ClasspathResource>> ent : fileMatches.entrySet()) { final FileMatchProcessorWrapper fileMatchProcessorWrapper = ent.getKey(); for (final ClasspathResource fileMatch : ent.getValue()) { try { final LogNode logNode = log == null ? null : log.log("Calling MatchProcessor for matching file " + fileMatch); openInputStreamAndProcessFileMatch(fileMatch, fileMatchProcessorWrapper); if (logNode != null) { logNode.addElapsedTime(); } } catch (final IOException e) { if (log != null) { log.log("Exception while opening file " + fileMatch, e); } } catch (final Throwable e) { if (log != null) { log.log("Exception while calling FileMatchProcessor for file " + fileMatch, e); } scanResult.addMatchProcessorException(e); } interruptionChecker.check(); } } } /** * Open an input stream and call a FileMatchProcessor on a specific whitelisted match found within this * classpath element. Implemented in the directory- and zipfile-specific sublclasses. */ protected abstract void openInputStreamAndProcessFileMatch(ClasspathResource fileMatch, FileMatchProcessorWrapper fileMatchProcessorWrapper) throws IOException; // ------------------------------------------------------------------------------------------------------------- /** Parse any classfiles for any whitelisted classes found within this classpath element. */ void parseClassfiles(final ClassfileBinaryParser classfileBinaryParser, final int classfileStartIdx, final int classfileEndIdx, final ConcurrentHashMap<String, String> stringInternMap, final ConcurrentLinkedQueue<ClassInfoUnlinked> classInfoUnlinked, final LogNode log) throws Exception { for (int i = classfileStartIdx; i < classfileEndIdx; i++) { final ClasspathResource classfileResource = classfileMatches.get(i); try { final LogNode logNode = log == null ? null : log.log("Parsing classfile " + classfileResource); openInputStreamAndParseClassfile(classfileResource, classfileBinaryParser, scanSpec, stringInternMap, classInfoUnlinked, logNode); if (logNode != null) { logNode.addElapsedTime(); } } catch (final IOException e) { if (log != null) { log.log("IOException while attempting to read classfile " + classfileResource + " -- skipping", e); } } catch (final Exception e) { if (log != null) { log.log("Exception while parsing classfile " + classfileResource, e); } // Re-throw throw e; } interruptionChecker.check(); } } /** * Open an input stream and parse a specific classfile found within this classpath element. Implemented in the * directory- and zipfile-specific sublclasses. */ protected abstract void openInputStreamAndParseClassfile(final ClasspathResource classfileResource, final ClassfileBinaryParser classfileBinaryParser, final ScanSpec scanSpec, final ConcurrentHashMap<String, String> stringInternMap, final ConcurrentLinkedQueue<ClassInfoUnlinked> classInfoUnlinked, final LogNode log) throws IOException, InterruptedException; // ------------------------------------------------------------------------------------------------------------- /** Scan the classpath element */ public abstract void scanPaths(LogNode log); /** Close the classpath element's resources. (Used by zipfile-specific subclass.) */ public abstract void close(); }
Improve log message
src/main/java/io/github/lukehutch/fastclasspathscanner/scanner/ClasspathElement.java
Improve log message
<ide><path>rc/main/java/io/github/lukehutch/fastclasspathscanner/scanner/ClasspathElement.java <ide> } else { <ide> if (log != null) { <ide> log.log(String.format("%06d-1", classpathIdx), <del> "Ignoring duplicate (masked) class " <del> + classfileMatch.pathRelativeToClasspathPrefix.replace('/', '.') <del> + " for classpath element " + classfileMatch); <add> "Ignoring duplicate (masked) class " + classfileMatch.pathRelativeToClasspathPrefix <add> .substring(0, classfileMatch.pathRelativeToClasspathPrefix.length() - 6) <add> .replace('/', '.') + " for classpath element " + classfileMatch); <ide> } <ide> } <ide> }
Java
mit
b6cad88c81a45f7e6d250c72812f7377025b205a
0
GluuFederation/oxAuth,GluuFederation/oxAuth,GluuFederation/oxAuth,GluuFederation/oxAuth,GluuFederation/oxAuth
package org.xdi.oxauth.model.ldap; import org.gluu.site.ldap.persistence.annotation.LdapAttribute; import org.gluu.site.ldap.persistence.annotation.LdapDN; import org.gluu.site.ldap.persistence.annotation.LdapEntry; import org.gluu.site.ldap.persistence.annotation.LdapObjectClass; import java.io.Serializable; /** * @author Javier Rojas Blum * @version October 16, 2015 */ @LdapEntry @LdapObjectClass(values = {"top", "oxClientAuthorizations"}) public class ClientAuthorizations implements Serializable { @LdapDN private String dn; @LdapAttribute(name = "oxId") private String id; @LdapAttribute(name = "oxAuthClientId") private String clientId; @LdapAttribute(name = "oxAuthScope") private String[] scopes; public String getDn() { return dn; } public void setDn(String dn) { this.dn = dn; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String[] getScopes() { return scopes; } public void setScopes(String[] scopes) { this.scopes = scopes; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ClientAuthorizations that = (ClientAuthorizations) o; if (!dn.equals(that.dn)) return false; if (!id.equals(that.id)) return false; return true; } @Override public int hashCode() { int result = dn.hashCode(); result = 31 * result + id.hashCode(); return result; } }
Server/src/main/java/org/xdi/oxauth/model/ldap/ClientAuthorizations.java
package org.xdi.oxauth.model.ldap; import org.gluu.site.ldap.persistence.annotation.LdapAttribute; import org.gluu.site.ldap.persistence.annotation.LdapDN; import org.gluu.site.ldap.persistence.annotation.LdapEntry; import org.gluu.site.ldap.persistence.annotation.LdapObjectClass; /** * @author Javier Rojas Blum * @version October 16, 2015 */ @LdapEntry @LdapObjectClass(values = {"top", "oxClientAuthorizations"}) public class ClientAuthorizations { @LdapDN private String dn; @LdapAttribute(name = "oxId") private String id; @LdapAttribute(name = "oxAuthClientId") private String clientId; @LdapAttribute(name = "oxAuthScope") private String[] scopes; public String getDn() { return dn; } public void setDn(String dn) { this.dn = dn; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String[] getScopes() { return scopes; } public void setScopes(String[] scopes) { this.scopes = scopes; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ClientAuthorizations that = (ClientAuthorizations) o; if (!dn.equals(that.dn)) return false; if (!id.equals(that.id)) return false; return true; } @Override public int hashCode() { int result = dn.hashCode(); result = 31 * result + id.hashCode(); return result; } }
#924 (4.0) : made ClientAuthorizations serializable (otherwise it will not work with redis) https://github.com/GluuFederation/oxAuth/issues/924 (cherry picked from commit 143b892)
Server/src/main/java/org/xdi/oxauth/model/ldap/ClientAuthorizations.java
#924 (4.0) : made ClientAuthorizations serializable (otherwise it will not work with redis)
<ide><path>erver/src/main/java/org/xdi/oxauth/model/ldap/ClientAuthorizations.java <ide> import org.gluu.site.ldap.persistence.annotation.LdapEntry; <ide> import org.gluu.site.ldap.persistence.annotation.LdapObjectClass; <ide> <add>import java.io.Serializable; <add> <ide> /** <ide> * @author Javier Rojas Blum <ide> * @version October 16, 2015 <ide> */ <ide> @LdapEntry <ide> @LdapObjectClass(values = {"top", "oxClientAuthorizations"}) <del>public class ClientAuthorizations { <add>public class ClientAuthorizations implements Serializable { <ide> <ide> @LdapDN <ide> private String dn;
Java
bsd-3-clause
b76fce1bc3052aa5522ffaf7e9bf4d0fbb9523cf
0
fbastian/owltools,dhimmel/owltools,dhimmel/owltools,owlcollab/owltools,fbastian/owltools,fbastian/owltools,owlcollab/owltools,fbastian/owltools,dhimmel/owltools,owlcollab/owltools,fbastian/owltools,dhimmel/owltools,dhimmel/owltools,owlcollab/owltools,owlcollab/owltools,dhimmel/owltools,fbastian/owltools,owlcollab/owltools
package owltools.io; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.PrintWriter; import java.io.StringWriter; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.obolibrary.obo2owl.Obo2Owl; import org.obolibrary.oboformat.model.OBODoc; import org.obolibrary.oboformat.parser.OBOFormatParser; import org.semanticweb.owlapi.model.OWLAxiom; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyFormat; import owltools.OWLToolsTestBasics; import owltools.graph.OWLGraphEdge; import owltools.graph.OWLGraphWrapper; public class OWLGsonRendererTest extends OWLToolsTestBasics { @Rule public TemporaryFolder folder= new TemporaryFolder(); private static final boolean RENDER_FLAG = true; @Test public void testAxioms() throws Exception{ OWLGraphWrapper wrapper = getOBO2OWLOntologyWrapper("caro.obo"); final StringWriter stringWriter = new StringWriter(); OWLGsonRenderer gr = new OWLGsonRenderer(new PrintWriter(stringWriter)); OWLOntology ont = wrapper.getSourceOntology(); for (OWLAxiom a : ont.getAxioms()) { gr.render(a); } if (RENDER_FLAG) { System.out.println(stringWriter.toString()); } } @Test public void testGEdges() throws Exception{ OWLGraphWrapper wrapper = getOBO2OWLOntologyWrapper("caro.obo"); final StringWriter stringWriter = new StringWriter(); OWLGsonRenderer gr = new OWLGsonRenderer(new PrintWriter(stringWriter)); OWLOntology ont = wrapper.getSourceOntology(); for (OWLClass c : ont.getClassesInSignature()) { for (OWLGraphEdge e : wrapper.getOutgoingEdgesClosure(c)) { gr.render(e); } } if (RENDER_FLAG) { System.out.println(stringWriter.toString()); } } @Test public void testOnt() throws Exception{ OWLGraphWrapper wrapper = getOBO2OWLOntologyWrapper("caro.obo"); final StringWriter stringWriter = new StringWriter(); OWLGsonRenderer gr = new OWLGsonRenderer(new PrintWriter(stringWriter)); gr.render(wrapper.getSourceOntology()); if (RENDER_FLAG) { System.out.println(stringWriter.toString()); ParserWrapper pw = new ParserWrapper(); OWLOntologyFormat owlFormat = new OWLJSONFormat(); File foo = folder.newFile("foo.json"); pw.saveOWL(wrapper.getSourceOntology(), owlFormat , foo.getAbsolutePath()); } } private OWLGraphWrapper getOBO2OWLOntologyWrapper(String file) throws Exception{ OBOFormatParser p = new OBOFormatParser(); OBODoc obodoc = p.parse(new BufferedReader(new FileReader(getResource(file)))); Obo2Owl bridge = new Obo2Owl(); OWLOntology ontology = bridge.convert(obodoc); OWLGraphWrapper wrapper = new OWLGraphWrapper(ontology); return wrapper; } }
OWLTools-Core/src/test/java/owltools/io/OWLGsonRendererTest.java
package owltools.io; import java.io.BufferedReader; import java.io.FileReader; import java.io.PrintWriter; import java.io.StringWriter; import org.junit.Test; import org.obolibrary.obo2owl.Obo2Owl; import org.obolibrary.oboformat.model.OBODoc; import org.obolibrary.oboformat.parser.OBOFormatParser; import org.semanticweb.owlapi.model.OWLAxiom; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyFormat; import owltools.OWLToolsTestBasics; import owltools.graph.OWLGraphEdge; import owltools.graph.OWLGraphWrapper; public class OWLGsonRendererTest extends OWLToolsTestBasics { private static final boolean RENDER_FLAG = true; @Test public void testAxioms() throws Exception{ OWLGraphWrapper wrapper = getOBO2OWLOntologyWrapper("caro.obo"); final StringWriter stringWriter = new StringWriter(); OWLGsonRenderer gr = new OWLGsonRenderer(new PrintWriter(stringWriter)); OWLOntology ont = wrapper.getSourceOntology(); for (OWLAxiom a : ont.getAxioms()) { gr.render(a); } if (RENDER_FLAG) { System.out.println(stringWriter.toString()); } } @Test public void testGEdges() throws Exception{ OWLGraphWrapper wrapper = getOBO2OWLOntologyWrapper("caro.obo"); final StringWriter stringWriter = new StringWriter(); OWLGsonRenderer gr = new OWLGsonRenderer(new PrintWriter(stringWriter)); OWLOntology ont = wrapper.getSourceOntology(); for (OWLClass c : ont.getClassesInSignature()) { for (OWLGraphEdge e : wrapper.getOutgoingEdgesClosure(c)) { gr.render(e); } } if (RENDER_FLAG) { System.out.println(stringWriter.toString()); } } @Test public void testOnt() throws Exception{ OWLGraphWrapper wrapper = getOBO2OWLOntologyWrapper("caro.obo"); final StringWriter stringWriter = new StringWriter(); OWLGsonRenderer gr = new OWLGsonRenderer(new PrintWriter(stringWriter)); gr.render(wrapper.getSourceOntology()); if (RENDER_FLAG) { System.out.println(stringWriter.toString()); ParserWrapper pw = new ParserWrapper(); OWLOntologyFormat owlFormat = new OWLJSONFormat(); pw.saveOWL(wrapper.getSourceOntology(), owlFormat , "/tmp/foo.json"); } } private OWLGraphWrapper getOBO2OWLOntologyWrapper(String file) throws Exception{ OBOFormatParser p = new OBOFormatParser(); OBODoc obodoc = p.parse(new BufferedReader(new FileReader(getResource(file)))); Obo2Owl bridge = new Obo2Owl(); OWLOntology ontology = bridge.convert(obodoc); OWLGraphWrapper wrapper = new OWLGraphWrapper(ontology); return wrapper; } }
remove hard-coded file path for test, issue #119
OWLTools-Core/src/test/java/owltools/io/OWLGsonRendererTest.java
remove hard-coded file path for test, issue #119
<ide><path>WLTools-Core/src/test/java/owltools/io/OWLGsonRendererTest.java <ide> package owltools.io; <ide> <ide> import java.io.BufferedReader; <add>import java.io.File; <ide> import java.io.FileReader; <ide> import java.io.PrintWriter; <ide> import java.io.StringWriter; <ide> <add>import org.junit.Rule; <ide> import org.junit.Test; <add>import org.junit.rules.TemporaryFolder; <ide> import org.obolibrary.obo2owl.Obo2Owl; <ide> import org.obolibrary.oboformat.model.OBODoc; <ide> import org.obolibrary.oboformat.parser.OBOFormatParser; <ide> import owltools.graph.OWLGraphWrapper; <ide> <ide> public class OWLGsonRendererTest extends OWLToolsTestBasics { <add> <add> @Rule <add> public TemporaryFolder folder= new TemporaryFolder(); <ide> <ide> private static final boolean RENDER_FLAG = true; <ide> <ide> System.out.println(stringWriter.toString()); <ide> ParserWrapper pw = new ParserWrapper(); <ide> OWLOntologyFormat owlFormat = new OWLJSONFormat(); <del> pw.saveOWL(wrapper.getSourceOntology(), owlFormat , "/tmp/foo.json"); <add> File foo = folder.newFile("foo.json"); <add> pw.saveOWL(wrapper.getSourceOntology(), owlFormat , foo.getAbsolutePath()); <ide> } <ide> } <ide>
Java
apache-2.0
58ad72921ea857d4a86c0179e5e112cd9efaeb6d
0
andrhamm/Singularity,hs-jenkins-bot/Singularity,hs-jenkins-bot/Singularity,tejasmanohar/Singularity,stevenschlansker/Singularity,grepsr/Singularity,andrhamm/Singularity,hs-jenkins-bot/Singularity,grepsr/Singularity,stevenschlansker/Singularity,HubSpot/Singularity,calebTomlinson/Singularity,hs-jenkins-bot/Singularity,tejasmanohar/Singularity,hs-jenkins-bot/Singularity,evertrue/Singularity,HubSpot/Singularity,HubSpot/Singularity,evertrue/Singularity,grepsr/Singularity,acbellini/Singularity,HubSpot/Singularity,evertrue/Singularity,acbellini/Singularity,stevenschlansker/Singularity,stevenschlansker/Singularity,stevenschlansker/Singularity,evertrue/Singularity,stevenschlansker/Singularity,calebTomlinson/Singularity,evertrue/Singularity,andrhamm/Singularity,andrhamm/Singularity,HubSpot/Singularity,acbellini/Singularity,calebTomlinson/Singularity,grepsr/Singularity,grepsr/Singularity,acbellini/Singularity,tejasmanohar/Singularity,grepsr/Singularity,calebTomlinson/Singularity,acbellini/Singularity,tejasmanohar/Singularity,calebTomlinson/Singularity,acbellini/Singularity,andrhamm/Singularity,tejasmanohar/Singularity,calebTomlinson/Singularity,tejasmanohar/Singularity,evertrue/Singularity
package com.hubspot.singularity.client; import static com.google.common.base.Preconditions.checkNotNull; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import javax.inject.Provider; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap.Builder; import com.google.common.collect.Lists; import com.google.inject.Inject; import com.google.inject.name.Named; import com.hubspot.horizon.HttpClient; import com.hubspot.horizon.HttpRequest; import com.hubspot.horizon.HttpRequest.Method; import com.hubspot.horizon.HttpResponse; import com.hubspot.mesos.json.MesosFileChunkObject; import com.hubspot.singularity.MachineState; import com.hubspot.singularity.SingularityCreateResult; import com.hubspot.singularity.SingularityDeleteResult; import com.hubspot.singularity.SingularityDeploy; import com.hubspot.singularity.SingularityDeployHistory; import com.hubspot.singularity.SingularityDeployKey; import com.hubspot.singularity.SingularityDeployUpdate; import com.hubspot.singularity.SingularityPendingRequest; import com.hubspot.singularity.SingularityRack; import com.hubspot.singularity.SingularityRequest; import com.hubspot.singularity.SingularityRequestCleanup; import com.hubspot.singularity.SingularityRequestHistory; import com.hubspot.singularity.SingularityRequestParent; import com.hubspot.singularity.SingularitySandbox; import com.hubspot.singularity.SingularitySlave; import com.hubspot.singularity.SingularityState; import com.hubspot.singularity.SingularityTask; import com.hubspot.singularity.SingularityTaskCleanupResult; import com.hubspot.singularity.SingularityTaskHistory; import com.hubspot.singularity.SingularityTaskHistoryUpdate; import com.hubspot.singularity.SingularityTaskIdHistory; import com.hubspot.singularity.SingularityTaskRequest; import com.hubspot.singularity.SingularityWebhook; import com.hubspot.singularity.api.SingularityDeployRequest; public class SingularityClient { private static final Logger LOG = LoggerFactory.getLogger(SingularityClient.class); private static final String STATE_FORMAT = "http://%s/%s/state"; private static final String RACKS_FORMAT = "http://%s/%s/racks"; private static final String RACKS_GET_ACTIVE_FORMAT = RACKS_FORMAT + "/active"; private static final String RACKS_GET_DEAD_FORMAT = RACKS_FORMAT + "/dead"; private static final String RACKS_GET_DECOMISSIONING_FORMAT = RACKS_FORMAT + "/decomissioning"; private static final String RACKS_DECOMISSION_FORMAT = RACKS_FORMAT + "/rack/%s/decomission"; private static final String RACKS_DELETE_DEAD_FORMAT = RACKS_FORMAT + "/rack/%s/dead"; private static final String RACKS_DELETE_DECOMISSIONING_FORMAT = RACKS_FORMAT + "/rack/%s/decomissioning"; private static final String SLAVES_FORMAT = "http://%s/%s/slaves"; private static final String SLAVES_DECOMISSION_FORMAT = SLAVES_FORMAT + "/slave/%s/decommission"; private static final String SLAVES_DELETE_FORMAT = SLAVES_FORMAT + "/slave/%s/decomissioning"; private static final String TASKS_FORMAT = "http://%s/%s/tasks"; private static final String TASKS_KILL_TASK_FORMAT = TASKS_FORMAT + "/task/%s"; private static final String TASKS_GET_ACTIVE_FORMAT = TASKS_FORMAT + "/active"; private static final String TASKS_GET_ACTIVE_ON_SLAVE_FORMAT = TASKS_FORMAT + "/active/slave/%s"; private static final String TASKS_GET_SCHEDULED_FORMAT = TASKS_FORMAT + "/scheduled"; private static final String HISTORY_FORMAT = "http://%s/%s/history"; private static final String TASK_HISTORY_FORMAT = HISTORY_FORMAT + "/task/%s"; private static final String REQUEST_ACTIVE_TASKS_HISTORY_FORMAT = HISTORY_FORMAT + "/request/%s/tasks/active"; private static final String REQUEST_INACTIVE_TASKS_HISTORY_FORMAT = HISTORY_FORMAT + "/request/%s/tasks"; private static final String REQUEST_DEPLOY_HISTORY_FORMAT = HISTORY_FORMAT + "/request/%s/deploy/%s"; private static final String REQUESTS_FORMAT = "http://%s/%s/requests"; private static final String REQUESTS_GET_ACTIVE_FORMAT = REQUESTS_FORMAT + "/active"; private static final String REQUESTS_GET_PAUSED_FORMAT = REQUESTS_FORMAT + "/paused"; private static final String REQUESTS_GET_COOLDOWN_FORMAT = REQUESTS_FORMAT + "/cooldown"; private static final String REQUESTS_GET_PENDING_FORMAT = REQUESTS_FORMAT + "/queued/pending"; private static final String REQUESTS_GET_CLEANUP_FORMAT = REQUESTS_FORMAT + "/queued/cleanup"; private static final String REQUEST_GET_FORMAT = REQUESTS_FORMAT + "/request/%s"; private static final String REQUEST_CREATE_OR_UPDATE_FORMAT = REQUESTS_FORMAT; private static final String REQUEST_DELETE_ACTIVE_FORMAT = REQUESTS_FORMAT + "/request/%s"; private static final String REQUEST_DELETE_PAUSED_FORMAT = REQUESTS_FORMAT + "/request/%s/paused"; private static final String REQUEST_BOUNCE_FORMAT = REQUESTS_FORMAT + "/request/%s/bounce"; private static final String REQUEST_PAUSE_FORMAT = REQUESTS_FORMAT + "/request/%s/pause"; private static final String DEPLOYS_FORMAT = "http://%s/%s/deploys"; private static final String DELETE_DEPLOY_FORMAT = DEPLOYS_FORMAT + "/deploy/%s/request/%s"; private static final String WEBHOOKS_FORMAT = "http://%s/%s/webhooks"; private static final String WEBHOOKS_DELETE_FORMAT = WEBHOOKS_FORMAT +"/%s"; private static final String WEBHOOKS_GET_QUEUED_DEPLOY_UPDATES_FORMAT = WEBHOOKS_FORMAT + "/deploy/%s"; private static final String WEBHOOKS_GET_QUEUED_REQUEST_UPDATES_FORMAT = WEBHOOKS_FORMAT + "/request/%s"; private static final String WEBHOOKS_GET_QUEUED_TASK_UPDATES_FORMAT = WEBHOOKS_FORMAT + "/task/%s"; private static final String SANDBOX_FORMAT = "http://%s/%s/sandbox"; private static final String SANDBOX_BROWSE_FORMAT = SANDBOX_FORMAT + "/%s/browse"; private static final String SANDBOX_READ_FILE_FORMAT = SANDBOX_FORMAT + "/%s/read"; private static final TypeReference<Collection<SingularityRequest>> REQUESTS_COLLECTION = new TypeReference<Collection<SingularityRequest>>() {}; private static final TypeReference<Collection<SingularityPendingRequest>> PENDING_REQUESTS_COLLECTION = new TypeReference<Collection<SingularityPendingRequest>>() {}; private static final TypeReference<Collection<SingularityRequestCleanup>> CLEANUP_REQUESTS_COLLECTION = new TypeReference<Collection<SingularityRequestCleanup>>() {}; private static final TypeReference<Collection<SingularityTask>> TASKS_COLLECTION = new TypeReference<Collection<SingularityTask>>() {}; private static final TypeReference<Collection<SingularityTaskIdHistory>> TASKID_HISTORY_COLLECTION = new TypeReference<Collection<SingularityTaskIdHistory>>() {}; private static final TypeReference<Collection<SingularityRack>> RACKS_COLLECTION = new TypeReference<Collection<SingularityRack>>() {}; private static final TypeReference<Collection<SingularitySlave>> SLAVES_COLLECTION = new TypeReference<Collection<SingularitySlave>>() {}; private static final TypeReference<Collection<SingularityWebhook>> WEBHOOKS_COLLECTION = new TypeReference<Collection<SingularityWebhook>>() {}; private static final TypeReference<Collection<SingularityDeployUpdate>> DEPLOY_UPDATES_COLLECTION = new TypeReference<Collection<SingularityDeployUpdate>>() {}; private static final TypeReference<Collection<SingularityRequestHistory>> REQUEST_UPDATES_COLLECTION = new TypeReference<Collection<SingularityRequestHistory>>() {}; private static final TypeReference<Collection<SingularityTaskHistoryUpdate>> TASK_UPDATES_COLLECTION = new TypeReference<Collection<SingularityTaskHistoryUpdate>>() {}; private static final TypeReference<Collection<SingularityTaskRequest>> TASKS_REQUEST_COLLECTION = new TypeReference<Collection<SingularityTaskRequest>>() {}; private final Random random; private final Provider<List<String>> hostsProvider; private final String contextPath; private final HttpClient httpClient; @Inject @Deprecated public SingularityClient(@Named(SingularityClientModule.CONTEXT_PATH) String contextPath, @Named(SingularityClientModule.HTTP_CLIENT_NAME) HttpClient httpClient, @Named(SingularityClientModule.HOSTS_PROPERTY_NAME) String hosts) { this(contextPath, httpClient, Arrays.asList(hosts.split(","))); } public SingularityClient(String contextPath, HttpClient httpClient, List<String> hosts) { this(contextPath, httpClient, ProviderUtils.<List<String>>of(ImmutableList.copyOf(hosts))); } public SingularityClient(String contextPath, HttpClient httpClient, Provider<List<String>> hostsProvider) { this.httpClient = httpClient; this.contextPath = contextPath; this.hostsProvider = hostsProvider; this.random = new Random(); } private String getHost() { final List<String> hosts = hostsProvider.get(); return hosts.get(random.nextInt(hosts.size())); } private void checkResponse(String type, HttpResponse response) { if (response.isError()) { throw fail(type, response); } } private SingularityClientException fail(String type, HttpResponse response) { String body = ""; try { body = response.getAsString(); } catch (Exception e) { LOG.warn("Unable to read body", e); } String uri = ""; try { uri = response.getRequest().getUrl().toString(); } catch (Exception e) { LOG.warn("Unable to read uri", e); } throw new SingularityClientException(String.format("Failed '%s' action on Singularity (%s) - code: %s, %s", type, uri, response.getStatusCode(), body), response.getStatusCode()); } private <T> Optional<T> getSingle(String uri, String type, String id, Class<T> clazz) { return getSingleWithParams(uri, type, id, Optional.<Map<String, Object>>absent(), clazz); } private <T> Optional<T> getSingleWithParams(String uri, String type, String id, Optional<Map<String, Object>> queryParams, Class<T> clazz) { checkNotNull(id, String.format("Provide a %s id", type)); LOG.info("Getting {} {} from {}", type, id, uri); final long start = System.currentTimeMillis(); HttpRequest.Builder requestBuilder = HttpRequest.newBuilder() .setUrl(uri); if (queryParams.isPresent()) { addQueryParams(requestBuilder, queryParams.get()); } HttpResponse response = httpClient.execute(requestBuilder.build()); if (response.getStatusCode() == 404) { return Optional.absent(); } checkResponse(type, response); LOG.info("Got {} {} in {}ms", type, id, System.currentTimeMillis() - start); return Optional.fromNullable(response.getAs(clazz)); } private <T> Collection<T> getCollection(String uri, String type, TypeReference<Collection<T>> typeReference) { return getCollectionWithParams(uri, type, Optional.<Map<String, Object>>absent(), typeReference); } private <T> Collection<T> getCollectionWithParams(String uri, String type, Optional<Map<String, Object>> queryParams, TypeReference<Collection<T>> typeReference) { LOG.info("Getting all {} from {}", type, uri); final long start = System.currentTimeMillis(); HttpRequest.Builder requestBuilder = HttpRequest.newBuilder() .setUrl(uri); if (queryParams.isPresent()) { addQueryParams(requestBuilder, queryParams.get()); } HttpResponse response = httpClient.execute(requestBuilder.build()); if (response.getStatusCode() == 404) { return ImmutableList.of(); } checkResponse(type, response); LOG.info("Got {} in {}ms", type, System.currentTimeMillis() - start); return response.getAs(typeReference); } private void addQueryParams(HttpRequest.Builder requestBuilder, Map<String, Object> queryParams) { for (Entry<String, Object> queryParamEntry : queryParams.entrySet()) { if (queryParamEntry.getValue() instanceof String) { requestBuilder.addQueryParam(queryParamEntry.getKey(), (String) queryParamEntry.getValue()); } else if (queryParamEntry.getValue() instanceof Integer) { requestBuilder.addQueryParam(queryParamEntry.getKey(), (Integer) queryParamEntry.getValue()); } else if (queryParamEntry.getValue() instanceof Long) { requestBuilder.addQueryParam(queryParamEntry.getKey(), (Long) queryParamEntry.getValue()); } else if (queryParamEntry.getValue() instanceof Boolean) { requestBuilder.addQueryParam(queryParamEntry.getKey(), (Boolean) queryParamEntry.getValue()); } else { throw new RuntimeException(String.format("The type '%s' of query param %s is not supported. Only String, long, int and boolean values are supported", queryParamEntry.getValue().getClass().getName(), queryParamEntry.getKey())); } } } private <T> void delete(String uri, String type, String id, Optional<String> user) { delete(uri, type, id, user, Optional.<Class<T>> absent()); } private <T> Optional<T> delete(String uri, String type, String id, Optional<String> user, Optional<Class<T>> clazz) { LOG.info("Deleting {} {} from {}", type, id, uri); final long start = System.currentTimeMillis(); HttpRequest.Builder request = HttpRequest.newBuilder().setUrl(uri).setMethod(Method.DELETE); if (user.isPresent()) { request.addQueryParam("user", user.get()); } HttpResponse response = httpClient.execute(request.build()); if (response.getStatusCode() == 404) { LOG.info("{} ({}) was not found", type, id); return Optional.absent(); } checkResponse(type, response); LOG.info("Deleted {} ({}) from Singularity in %sms", type, id, System.currentTimeMillis() - start); if (clazz.isPresent()) { return Optional.of(response.getAs(clazz.get())); } return Optional.absent(); } private <T> Optional<T> post(String uri, String type, Optional<?> body, Optional<String> user, Optional<Class<T>> clazz) { try { HttpResponse response = post(uri, type, body, user); if (clazz.isPresent()) { return Optional.of(response.getAs(clazz.get())); } } catch (Exception e) { LOG.warn("Http post failed", e); } return Optional.<T>absent(); } private HttpResponse post(String uri, String type, Optional<?> body, Optional<String> user) { LOG.info("Posting {} to {}", type, uri); final long start = System.currentTimeMillis(); HttpRequest.Builder request = HttpRequest.newBuilder().setUrl(uri).setMethod(Method.POST); if (user.isPresent()) { request.addQueryParam("user", user.get()); } if (body.isPresent()) { request.setBody(body.get()); } HttpResponse response = httpClient.execute(request.build()); checkResponse(type, response); LOG.info("Successfully posted {} in {}ms", type, System.currentTimeMillis() - start); return response; } // // GLOBAL // public SingularityState getState(Optional<Boolean> skipCache, Optional<Boolean> includeRequestIds) { final String uri = String.format(STATE_FORMAT, getHost(), contextPath); LOG.info("Fetching state from {}", uri); final long start = System.currentTimeMillis(); HttpRequest.Builder request = HttpRequest.newBuilder().setUrl(uri); if (skipCache.isPresent()) { request.addQueryParam("skipCache", skipCache.get().booleanValue()); } if (includeRequestIds.isPresent()) { request.addQueryParam("includeRequestIds", includeRequestIds.get().booleanValue()); } HttpResponse response = httpClient.execute(request.build()); checkResponse("state", response); LOG.info("Got state in {}ms", System.currentTimeMillis() - start); return response.getAs(SingularityState.class); } // // ACTIONS ON A SINGLE SINGULARITY REQUEST // public Optional<SingularityRequestParent> getSingularityRequest(String requestId) { final String singularityApiRequestUri = String.format(REQUEST_GET_FORMAT, getHost(), contextPath, requestId); return getSingle(singularityApiRequestUri, "request", requestId, SingularityRequestParent.class); } public void createOrUpdateSingularityRequest(SingularityRequest request, Optional<String> user) { checkNotNull(request.getId(), "A posted Singularity Request must have an id"); final String requestUri = String.format(REQUEST_CREATE_OR_UPDATE_FORMAT, getHost(), contextPath); post(requestUri, String.format("request %s", request.getId()), Optional.of(request), user); } /** * Delete a singularity request that is active. * If the deletion is successful the deleted singularity request is returned. * If the request to be deleted is not found {code Optional.absent()} is returned * If an error occurs during deletion an exception is returned * If the singularity request to be deleted is paused the deletion will fail with an exception * If you want to delete a paused singularity request use the provided {@link SingularityClient#deletePausedSingularityRequest} * * @param requestId * the id of the singularity request to delete * @param user * the ... * @return * the singularity request that was deleted */ public Optional<SingularityRequest> deleteActiveSingularityRequest(String requestId, Optional<String> user) { final String requestUri = String.format(REQUEST_DELETE_ACTIVE_FORMAT, getHost(), contextPath, requestId); return delete(requestUri, "active request", requestId, user, Optional.of(SingularityRequest.class)); } public Optional<SingularityRequest> deletePausedSingularityRequest(String requestId, Optional<String> user) { final String requestUri = String.format(REQUEST_DELETE_PAUSED_FORMAT, getHost(), contextPath, requestId); return delete(requestUri, "paused request", requestId, user, Optional.of(SingularityRequest.class)); } public void pauseSingularityRequest(String requestId, Optional<String> user) { final String requestUri = String.format(REQUEST_PAUSE_FORMAT, getHost(), contextPath, requestId); post(requestUri, String.format("pause of request %s", requestId), Optional.absent(), user); } public void bounceSingularityRequest(String requestId, Optional<String> user) { final String requestUri = String.format(REQUEST_BOUNCE_FORMAT, getHost(), contextPath, requestId); post(requestUri, String.format("bounce of request %s", requestId), Optional.absent(), user); } // // ACTIONS ON A DEPLOY FOR A SINGULARITY REQUEST // public SingularityRequestParent createDeployForSingularityRequest(String requestId, SingularityDeploy pendingDeploy, Optional<Boolean> deployUnpause, Optional<String> user) { final String requestUri = String.format(DEPLOYS_FORMAT, getHost(), contextPath); List<Pair<String, String>> queryParams = Lists.newArrayList(); if (user.isPresent()) { queryParams.add(Pair.of("user", user.get())); } if (deployUnpause.isPresent()) { queryParams.add(Pair.of("deployUnpause", Boolean.toString(deployUnpause.get()))); } HttpResponse response = post(requestUri, String.format("new deploy %s", new SingularityDeployKey(requestId, pendingDeploy.getId())), Optional.of(new SingularityDeployRequest(pendingDeploy, user, deployUnpause)), Optional.<String> absent()); return getAndLogRequestAndDeployStatus(response.getAs(SingularityRequestParent.class)); } private SingularityRequestParent getAndLogRequestAndDeployStatus(SingularityRequestParent singularityRequestParent) { String activeDeployId = singularityRequestParent.getActiveDeploy().isPresent() ? singularityRequestParent.getActiveDeploy().get().getId() : "No Active Deploy"; String pendingDeployId = singularityRequestParent.getPendingDeploy().isPresent() ? singularityRequestParent.getPendingDeploy().get().getId() : "No Pending deploy"; LOG.info("Deploy status: Singularity request {} -> pending deploy: '{}', active deploy: '{}'", singularityRequestParent.getRequest().getId(), pendingDeployId, activeDeployId); return singularityRequestParent; } public SingularityRequestParent cancelPendingDeployForSingularityRequest(String requestId, String deployId, Optional<String> user) { final String requestUri = String.format(DELETE_DEPLOY_FORMAT, getHost(), contextPath, deployId, requestId); SingularityRequestParent singularityRequestParent = delete(requestUri, "pending deploy", new SingularityDeployKey(requestId, deployId).getId(), user, Optional.of(SingularityRequestParent.class)).get(); return getAndLogRequestAndDeployStatus(singularityRequestParent); } /** * Get all singularity requests that their state is either ACTIVE, PAUSED or COOLDOWN * * For the requests that are pending to become ACTIVE use: * {@link SingularityClient#getPendingSingularityRequests()} * * For the requests that are cleaning up use: * {@link SingularityClient#getCleanupSingularityRequests()} * * * Use {@link SingularityClient#getActiveSingularityRequests()}, {@link SingularityClient#getPausedSingularityRequests()}, * {@link SingularityClient#getCoolDownSingularityRequests()} respectively to get only the ACTIVE, PAUSED or COOLDOWN requests. * * @return * returns all the [ACTIVE, PAUSED, COOLDOWN] {@link SingularityRequest} instances. * */ public Collection<SingularityRequest> getSingularityRequests() { final String requestUri = String.format(REQUESTS_FORMAT, getHost(), contextPath); return getCollection(requestUri, "[ACTIVE, PAUSED, COOLDOWN] requests", REQUESTS_COLLECTION); } /** * Get all requests that their state is ACTIVE * * @return * All ACTIVE {@link SingularityRequest} instances */ public Collection<SingularityRequest> getActiveSingularityRequests() { final String requestUri = String.format(REQUESTS_GET_ACTIVE_FORMAT, getHost(), contextPath); return getCollection(requestUri, "ACTIVE requests", REQUESTS_COLLECTION); } /** * Get all requests that their state is PAUSED * ACTIVE requests are paused by users, which is equivalent to stop their tasks from running without undeploying them * * @return * All PAUSED {@link SingularityRequest} instances */ public Collection<SingularityRequest> getPausedSingularityRequests() { final String requestUri = String.format(REQUESTS_GET_PAUSED_FORMAT, getHost(), contextPath); return getCollection(requestUri, "PAUSED requests", REQUESTS_COLLECTION); } /** * Get all requests that has been set to a COOLDOWN state by singularity * * @return * All {@link SingularityRequest} instances that their state is COOLDOWN */ public Collection<SingularityRequest> getCoolDownSingularityRequests() { final String requestUri = String.format(REQUESTS_GET_COOLDOWN_FORMAT, getHost(), contextPath); return getCollection(requestUri, "COOLDOWN requests", REQUESTS_COLLECTION); } /** * Get all requests that are pending to become ACTIVE * * @return * A collection of {@link SingularityPendingRequest} instances that hold information about the singularity requests that are pending to become ACTIVE */ public Collection<SingularityPendingRequest> getPendingSingularityRequests() { final String requestUri = String.format(REQUESTS_GET_PENDING_FORMAT, getHost(), contextPath); return getCollection(requestUri, "pending requests", PENDING_REQUESTS_COLLECTION); } /** * Get all requests that are cleaning up * Requests that are cleaning up are those that have been marked for removal and their tasks are being stopped/removed * before they are being removed. So after their have been cleaned up, these request cease to exist in Singularity. * * @return * A collection of {@link SingularityRequestCleanup} instances that hold information about all singularity requests * that are marked for deletion and are currently cleaning up. */ public Collection<SingularityRequestCleanup> getCleanupSingularityRequests() { final String requestUri = String.format(REQUESTS_GET_CLEANUP_FORMAT, getHost(), contextPath); return getCollection(requestUri, "cleaning requests", CLEANUP_REQUESTS_COLLECTION); } // // SINGULARITY TASK COLLECTIONS // // // ACTIVE TASKS // public Collection<SingularityTask> getActiveTasks() { final String requestUri = String.format(TASKS_GET_ACTIVE_FORMAT, getHost(), contextPath); return getCollection(requestUri, "active tasks", TASKS_COLLECTION); } public Collection<SingularityTask> getActiveTasksOnSlave(final String slaveId) { final String requestUri = String.format(TASKS_GET_ACTIVE_ON_SLAVE_FORMAT, getHost(), contextPath, slaveId); return getCollection(requestUri, String.format("active tasks on slave %s", slaveId), TASKS_COLLECTION); } public Optional<SingularityTaskCleanupResult> killTask(String taskId, Optional<String> user) { final String requestUri = String.format(TASKS_KILL_TASK_FORMAT, getHost(), contextPath, taskId); return delete(requestUri, "task", taskId, user, Optional.of(SingularityTaskCleanupResult.class)); } // // SCHEDULED TASKS // public Collection<SingularityTaskRequest> getScheduledTasks() { final String requestUri = String.format(TASKS_GET_SCHEDULED_FORMAT, getHost(), contextPath); return getCollection(requestUri, "scheduled tasks", TASKS_REQUEST_COLLECTION); } // // RACKS // public Collection<SingularityRack> getActiveRacks() { return getRacks(RACKS_GET_ACTIVE_FORMAT, "active"); } public Collection<SingularityRack> getDeadRacks() { return getRacks(RACKS_GET_DEAD_FORMAT, "dead"); } public Collection<SingularityRack> getDecomissioningRacks() { return getRacks(RACKS_GET_DECOMISSIONING_FORMAT, "decomissioning"); } private Collection<SingularityRack> getRacks(String format, String type) { final String requestUri = String.format(format, getHost(), contextPath); return getCollection(requestUri, String.format("%s racks", type), RACKS_COLLECTION); } public void decomissionRack(String rackId, Optional<String> user) { final String requestUri = String.format(RACKS_DECOMISSION_FORMAT, getHost(), contextPath, rackId); post(requestUri, String.format("decomission rack %s", rackId), Optional.absent(), user); } public void deleteDecomissioningRack(String rackId, Optional<String> user) { final String requestUri = String.format(RACKS_DELETE_DECOMISSIONING_FORMAT, getHost(), contextPath, rackId); delete(requestUri, "rack", rackId, user); } public void deleteDeadRack(String rackId, Optional<String> user) { final String requestUri = String.format(RACKS_DELETE_DEAD_FORMAT, getHost(), contextPath, rackId); delete(requestUri, "dead rack", rackId, user); } // // SLAVES // /** * Use {@link getSlaves} specifying the desired slave state to filter by * */ @Deprecated public Collection<SingularitySlave> getActiveSlaves() { return getSlaves(Optional.of(MachineState.ACTIVE)); } /** * Use {@link getSlaves} specifying the desired slave state to filter by * */ @Deprecated public Collection<SingularitySlave> getDeadSlaves() { return getSlaves(Optional.of(MachineState.DEAD)); } /** * Use {@link getSlaves} specifying the desired slave state to filter by * */ @Deprecated public Collection<SingularitySlave> getDecomissioningSlaves() { return getSlaves(Optional.of(MachineState.DECOMMISSIONING)); } /** * Retrieve the list of all known slaves, optionally filtering by a particular slave state * * @param slaveState * Optionally specify a particular state to filter slaves by * @return * A collection of {@link SingularitySlave} */ public Collection<SingularitySlave> getSlaves(Optional<MachineState> slaveState) { final String requestUri = String.format(SLAVES_FORMAT, getHost(), contextPath); Optional<Map<String, Object>> maybeQueryParams = Optional.<Map<String, Object>>absent(); String type = "slaves"; if (slaveState.isPresent()) { maybeQueryParams = Optional.<Map<String, Object>>of(ImmutableMap.<String, Object>of("state", slaveState.get())); type = String.format("%s slaves", slaveState.get().toString()); } return getCollectionWithParams(requestUri, type, maybeQueryParams, SLAVES_COLLECTION); } public void decomissionSlave(String slaveId, Optional<String> user) { final String requestUri = String.format(SLAVES_DECOMISSION_FORMAT, getHost(), contextPath, slaveId); post(requestUri, String.format("decomission slave %s", slaveId), Optional.absent(), user); } public void deleteSlave(String slaveId, Optional<String> user) { final String requestUri = String.format(SLAVES_DELETE_FORMAT, getHost(), contextPath, slaveId); delete(requestUri, "deleting slave", slaveId, user); } // // TASK HISTORY // public Optional<SingularityTaskHistory> getHistoryForTask(String taskId) { final String requestUri = String.format(TASK_HISTORY_FORMAT, getHost(), contextPath, taskId); return getSingle(requestUri, "task history", taskId, SingularityTaskHistory.class); } public Collection<SingularityTaskIdHistory> getActiveTaskHistoryForRequest(String requestId) { final String requestUri = String.format(REQUEST_ACTIVE_TASKS_HISTORY_FORMAT, getHost(), contextPath, requestId); final String type = String.format("active task history for %s", requestId); return getCollection(requestUri, type, TASKID_HISTORY_COLLECTION); } public Collection<SingularityTaskIdHistory> getInactiveTaskHistoryForRequest(String requestId) { final String requestUri = String.format(REQUEST_INACTIVE_TASKS_HISTORY_FORMAT, getHost(), contextPath, requestId); final String type = String.format("inactive (failed, killed, lost) task history for request %s", requestId); return getCollection(requestUri, type, TASKID_HISTORY_COLLECTION); } public Optional<SingularityDeployHistory> getHistoryForRequestDeploy(String requestId, String deployId) { final String requestUri = String.format(REQUEST_DEPLOY_HISTORY_FORMAT, getHost(), contextPath, requestId, deployId); return getSingle(requestUri, "deploy history", new SingularityDeployKey(requestId, deployId).getId(), SingularityDeployHistory.class); } // // WEBHOOKS // public Optional<SingularityCreateResult> addWebhook(SingularityWebhook webhook, Optional<String> user) { final String requestUri = String.format(WEBHOOKS_FORMAT, getHost(), contextPath); return post(requestUri, String.format("webhook %s", webhook.getUri()), Optional.of(webhook), user, Optional.of(SingularityCreateResult.class)); } public Optional<SingularityDeleteResult> deleteWebhook(String webhookId, Optional<String> user) { final String requestUri = String.format(WEBHOOKS_DELETE_FORMAT, getHost(), contextPath, webhookId); return delete(requestUri, String.format("webhook with id %s", webhookId), webhookId, user, Optional.of(SingularityDeleteResult.class)); } public Collection<SingularityWebhook> getActiveWebhook() { final String requestUri = String.format(WEBHOOKS_FORMAT, getHost(), contextPath); return getCollection(requestUri, "active webhooks", WEBHOOKS_COLLECTION); } public Collection<SingularityDeployUpdate> getQueuedDeployUpdates(String webhookId) { final String requestUri = String.format(WEBHOOKS_GET_QUEUED_DEPLOY_UPDATES_FORMAT, getHost(), contextPath, webhookId); return getCollection(requestUri, "deploy updates", DEPLOY_UPDATES_COLLECTION); } public Collection<SingularityRequestHistory> getQueuedRequestUpdates(String webhookId) { final String requestUri = String.format(WEBHOOKS_GET_QUEUED_REQUEST_UPDATES_FORMAT, getHost(), contextPath, webhookId); return getCollection(requestUri, "request updates", REQUEST_UPDATES_COLLECTION); } public Collection<SingularityTaskHistoryUpdate> getQueuedTaskUpdates(String webhookId) { final String requestUri = String.format(WEBHOOKS_GET_QUEUED_TASK_UPDATES_FORMAT, getHost(), contextPath, webhookId); return getCollection(requestUri, "request updates", TASK_UPDATES_COLLECTION); } // // SANDBOX // /** * Retrieve information about a specific task's sandbox * * @param taskId * The task ID to browse * @param path * The path to browse from. * if not specified it will browse from the sandbox root. * @return * A {@link SingularitySandbox} object that captures the information for the path to a specific task's Mesos sandbox */ public Optional<SingularitySandbox> browseTaskSandBox(String taskId, String path) { final String requestUrl = String.format(SANDBOX_BROWSE_FORMAT, getHost(), contextPath, taskId); return getSingleWithParams(requestUrl, "browse sandbox for task", taskId, Optional.<Map<String, Object>>of(ImmutableMap.<String, Object>of("path", path)), SingularitySandbox.class); } /** * Retrieve part of the contents of a file in a specific task's sandbox. * * @param taskId * The task ID of the sandbox to read from * @param path * The path to the file to be read. Relative to the sandbox root (without a leading slash) * @param grep * Optional string to grep for * @param offset * Byte offset to start reading from * @param length * Maximum number of bytes to read * @return * A {@link MesosFileChunkObject} that contains the requested partial file contents */ public Optional<MesosFileChunkObject> readSandBoxFile(String taskId, String path, Optional<String> grep, Optional<Long> offset, Optional<Long> length) { final String requestUrl = String.format(SANDBOX_READ_FILE_FORMAT, getHost(), contextPath, taskId); Builder<String, Object> queryParamBuider = ImmutableMap.<String, Object>builder().put("path", path); if (grep.isPresent()) { queryParamBuider.put("grep", grep.get()); } if (offset.isPresent()) { queryParamBuider.put("offset", offset.get()); } if (length.isPresent()) { queryParamBuider.put("length", length.get()); } return getSingleWithParams(requestUrl, "Read sandbox file for task", taskId, Optional.<Map<String, Object>>of(queryParamBuider.build()), MesosFileChunkObject.class); } }
SingularityClient/src/main/java/com/hubspot/singularity/client/SingularityClient.java
package com.hubspot.singularity.client; import static com.google.common.base.Preconditions.checkNotNull; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import javax.annotation.Nonnull; import javax.inject.Provider; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap.Builder; import com.google.common.collect.Lists; import com.google.inject.Inject; import com.google.inject.name.Named; import com.hubspot.horizon.HttpClient; import com.hubspot.horizon.HttpRequest; import com.hubspot.horizon.HttpRequest.Method; import com.hubspot.horizon.HttpResponse; import com.hubspot.mesos.json.MesosFileChunkObject; import com.hubspot.singularity.MachineState; import com.hubspot.singularity.SingularityCreateResult; import com.hubspot.singularity.SingularityDeleteResult; import com.hubspot.singularity.SingularityDeploy; import com.hubspot.singularity.SingularityDeployHistory; import com.hubspot.singularity.SingularityDeployKey; import com.hubspot.singularity.SingularityDeployUpdate; import com.hubspot.singularity.SingularityPendingRequest; import com.hubspot.singularity.SingularityRack; import com.hubspot.singularity.SingularityRequest; import com.hubspot.singularity.SingularityRequestCleanup; import com.hubspot.singularity.SingularityRequestHistory; import com.hubspot.singularity.SingularityRequestParent; import com.hubspot.singularity.SingularitySandbox; import com.hubspot.singularity.SingularitySlave; import com.hubspot.singularity.SingularityState; import com.hubspot.singularity.SingularityTask; import com.hubspot.singularity.SingularityTaskCleanupResult; import com.hubspot.singularity.SingularityTaskHistory; import com.hubspot.singularity.SingularityTaskHistoryUpdate; import com.hubspot.singularity.SingularityTaskIdHistory; import com.hubspot.singularity.SingularityTaskRequest; import com.hubspot.singularity.SingularityWebhook; import com.hubspot.singularity.api.SingularityDeployRequest; public class SingularityClient { private static final Logger LOG = LoggerFactory.getLogger(SingularityClient.class); private static final String STATE_FORMAT = "http://%s/%s/state"; private static final String RACKS_FORMAT = "http://%s/%s/racks"; private static final String RACKS_GET_ACTIVE_FORMAT = RACKS_FORMAT + "/active"; private static final String RACKS_GET_DEAD_FORMAT = RACKS_FORMAT + "/dead"; private static final String RACKS_GET_DECOMISSIONING_FORMAT = RACKS_FORMAT + "/decomissioning"; private static final String RACKS_DECOMISSION_FORMAT = RACKS_FORMAT + "/rack/%s/decomission"; private static final String RACKS_DELETE_DEAD_FORMAT = RACKS_FORMAT + "/rack/%s/dead"; private static final String RACKS_DELETE_DECOMISSIONING_FORMAT = RACKS_FORMAT + "/rack/%s/decomissioning"; private static final String SLAVES_FORMAT = "http://%s/%s/slaves"; private static final String SLAVES_DECOMISSION_FORMAT = SLAVES_FORMAT + "/slave/%s/decommission"; private static final String SLAVES_DELETE_FORMAT = SLAVES_FORMAT + "/slave/%s/decomissioning"; private static final String TASKS_FORMAT = "http://%s/%s/tasks"; private static final String TASKS_KILL_TASK_FORMAT = TASKS_FORMAT + "/task/%s"; private static final String TASKS_GET_ACTIVE_FORMAT = TASKS_FORMAT + "/active"; private static final String TASKS_GET_ACTIVE_ON_SLAVE_FORMAT = TASKS_FORMAT + "/active/slave/%s"; private static final String TASKS_GET_SCHEDULED_FORMAT = TASKS_FORMAT + "/scheduled"; private static final String HISTORY_FORMAT = "http://%s/%s/history"; private static final String TASK_HISTORY_FORMAT = HISTORY_FORMAT + "/task/%s"; private static final String REQUEST_ACTIVE_TASKS_HISTORY_FORMAT = HISTORY_FORMAT + "/request/%s/tasks/active"; private static final String REQUEST_INACTIVE_TASKS_HISTORY_FORMAT = HISTORY_FORMAT + "/request/%s/tasks"; private static final String REQUEST_DEPLOY_HISTORY_FORMAT = HISTORY_FORMAT + "/request/%s/deploy/%s"; private static final String REQUESTS_FORMAT = "http://%s/%s/requests"; private static final String REQUESTS_GET_ACTIVE_FORMAT = REQUESTS_FORMAT + "/active"; private static final String REQUESTS_GET_PAUSED_FORMAT = REQUESTS_FORMAT + "/paused"; private static final String REQUESTS_GET_COOLDOWN_FORMAT = REQUESTS_FORMAT + "/cooldown"; private static final String REQUESTS_GET_PENDING_FORMAT = REQUESTS_FORMAT + "/queued/pending"; private static final String REQUESTS_GET_CLEANUP_FORMAT = REQUESTS_FORMAT + "/queued/cleanup"; private static final String REQUEST_GET_FORMAT = REQUESTS_FORMAT + "/request/%s"; private static final String REQUEST_CREATE_OR_UPDATE_FORMAT = REQUESTS_FORMAT; private static final String REQUEST_DELETE_ACTIVE_FORMAT = REQUESTS_FORMAT + "/request/%s"; private static final String REQUEST_DELETE_PAUSED_FORMAT = REQUESTS_FORMAT + "/request/%s/paused"; private static final String REQUEST_BOUNCE_FORMAT = REQUESTS_FORMAT + "/request/%s/bounce"; private static final String REQUEST_PAUSE_FORMAT = REQUESTS_FORMAT + "/request/%s/pause"; private static final String DEPLOYS_FORMAT = "http://%s/%s/deploys"; private static final String DELETE_DEPLOY_FORMAT = DEPLOYS_FORMAT + "/deploy/%s/request/%s"; private static final String WEBHOOKS_FORMAT = "http://%s/%s/webhooks"; private static final String WEBHOOKS_DELETE_FORMAT = WEBHOOKS_FORMAT +"/%s"; private static final String WEBHOOKS_GET_QUEUED_DEPLOY_UPDATES_FORMAT = WEBHOOKS_FORMAT + "/deploy/%s"; private static final String WEBHOOKS_GET_QUEUED_REQUEST_UPDATES_FORMAT = WEBHOOKS_FORMAT + "/request/%s"; private static final String WEBHOOKS_GET_QUEUED_TASK_UPDATES_FORMAT = WEBHOOKS_FORMAT + "/task/%s"; private static final String SANDBOX_FORMAT = "http://%s/%s/sandbox"; private static final String SANDBOX_BROWSE_FORMAT = SANDBOX_FORMAT + "/%s/browse"; private static final String SANDBOX_READ_FILE_FORMAT = SANDBOX_FORMAT + "/%s/read"; private static final TypeReference<Collection<SingularityRequest>> REQUESTS_COLLECTION = new TypeReference<Collection<SingularityRequest>>() {}; private static final TypeReference<Collection<SingularityPendingRequest>> PENDING_REQUESTS_COLLECTION = new TypeReference<Collection<SingularityPendingRequest>>() {}; private static final TypeReference<Collection<SingularityRequestCleanup>> CLEANUP_REQUESTS_COLLECTION = new TypeReference<Collection<SingularityRequestCleanup>>() {}; private static final TypeReference<Collection<SingularityTask>> TASKS_COLLECTION = new TypeReference<Collection<SingularityTask>>() {}; private static final TypeReference<Collection<SingularityTaskIdHistory>> TASKID_HISTORY_COLLECTION = new TypeReference<Collection<SingularityTaskIdHistory>>() {}; private static final TypeReference<Collection<SingularityRack>> RACKS_COLLECTION = new TypeReference<Collection<SingularityRack>>() {}; private static final TypeReference<Collection<SingularitySlave>> SLAVES_COLLECTION = new TypeReference<Collection<SingularitySlave>>() {}; private static final TypeReference<Collection<SingularityWebhook>> WEBHOOKS_COLLECTION = new TypeReference<Collection<SingularityWebhook>>() {}; private static final TypeReference<Collection<SingularityDeployUpdate>> DEPLOY_UPDATES_COLLECTION = new TypeReference<Collection<SingularityDeployUpdate>>() {}; private static final TypeReference<Collection<SingularityRequestHistory>> REQUEST_UPDATES_COLLECTION = new TypeReference<Collection<SingularityRequestHistory>>() {}; private static final TypeReference<Collection<SingularityTaskHistoryUpdate>> TASK_UPDATES_COLLECTION = new TypeReference<Collection<SingularityTaskHistoryUpdate>>() {}; private static final TypeReference<Collection<SingularityTaskRequest>> TASKS_REQUEST_COLLECTION = new TypeReference<Collection<SingularityTaskRequest>>() {}; private final Random random; private final Provider<List<String>> hostsProvider; private final String contextPath; private final HttpClient httpClient; @Inject @Deprecated public SingularityClient(@Named(SingularityClientModule.CONTEXT_PATH) String contextPath, @Named(SingularityClientModule.HTTP_CLIENT_NAME) HttpClient httpClient, @Named(SingularityClientModule.HOSTS_PROPERTY_NAME) String hosts) { this(contextPath, httpClient, Arrays.asList(hosts.split(","))); } public SingularityClient(String contextPath, HttpClient httpClient, List<String> hosts) { this(contextPath, httpClient, ProviderUtils.<List<String>>of(ImmutableList.copyOf(hosts))); } public SingularityClient(String contextPath, HttpClient httpClient, Provider<List<String>> hostsProvider) { this.httpClient = httpClient; this.contextPath = contextPath; this.hostsProvider = hostsProvider; this.random = new Random(); } private String getHost() { final List<String> hosts = hostsProvider.get(); return hosts.get(random.nextInt(hosts.size())); } private void checkResponse(String type, HttpResponse response) { if (response.isError()) { throw fail(type, response); } } private SingularityClientException fail(String type, HttpResponse response) { String body = ""; try { body = response.getAsString(); } catch (Exception e) { LOG.warn("Unable to read body", e); } String uri = ""; try { uri = response.getRequest().getUrl().toString(); } catch (Exception e) { LOG.warn("Unable to read uri", e); } throw new SingularityClientException(String.format("Failed '%s' action on Singularity (%s) - code: %s, %s", type, uri, response.getStatusCode(), body), response.getStatusCode()); } private <T> Optional<T> getSingle(String uri, String type, String id, Class<T> clazz) { return getSingleWithParams(uri, type, id, Optional.<Map<String, Object>>absent(), clazz); } private <T> Optional<T> getSingleWithParams(String uri, String type, String id, Optional<Map<String, Object>> queryParams, Class<T> clazz) { checkNotNull(id, String.format("Provide a %s id", type)); LOG.info("Getting {} {} from {}", type, id, uri); final long start = System.currentTimeMillis(); HttpRequest.Builder requestBuilder = HttpRequest.newBuilder() .setUrl(uri); if (queryParams.isPresent()) { addQueryParams(requestBuilder, queryParams.get()); } HttpResponse response = httpClient.execute(requestBuilder.build()); if (response.getStatusCode() == 404) { return Optional.absent(); } checkResponse(type, response); LOG.info("Got {} {} in {}ms", type, id, System.currentTimeMillis() - start); return Optional.fromNullable(response.getAs(clazz)); } private <T> Collection<T> getCollection(String uri, String type, TypeReference<Collection<T>> typeReference) { return getCollectionWithParams(uri, type, Optional.<Map<String, Object>>absent(), typeReference); } private <T> Collection<T> getCollectionWithParams(String uri, String type, Optional<Map<String, Object>> queryParams, TypeReference<Collection<T>> typeReference) { LOG.info("Getting all {} from {}", type, uri); final long start = System.currentTimeMillis(); HttpRequest.Builder requestBuilder = HttpRequest.newBuilder() .setUrl(uri); if (queryParams.isPresent()) { addQueryParams(requestBuilder, queryParams.get()); } HttpResponse response = httpClient.execute(requestBuilder.build()); if (response.getStatusCode() == 404) { return ImmutableList.of(); } checkResponse(type, response); LOG.info("Got {} in {}ms", type, System.currentTimeMillis() - start); return response.getAs(typeReference); } private void addQueryParams(@Nonnull HttpRequest.Builder requestBuilder, @Nonnull Map<String, Object> queryParams) { for (Entry<String, Object> queryParamEntry : queryParams.entrySet()) { if (queryParamEntry.getValue() instanceof String) { requestBuilder.addQueryParam(queryParamEntry.getKey(), (String) queryParamEntry.getValue()); } else if (queryParamEntry.getValue() instanceof Integer) { requestBuilder.addQueryParam(queryParamEntry.getKey(), (Integer) queryParamEntry.getValue()); } else if (queryParamEntry.getValue() instanceof Long) { requestBuilder.addQueryParam(queryParamEntry.getKey(), (Long) queryParamEntry.getValue()); } else if (queryParamEntry.getValue() instanceof Boolean) { requestBuilder.addQueryParam(queryParamEntry.getKey(), (Boolean) queryParamEntry.getValue()); } else { throw new RuntimeException(String.format("The type '%s' of query param %s is not supported. Only String, long, int and boolean values are supported", queryParamEntry.getValue().getClass().getName(), queryParamEntry.getKey())); } } } private <T> void delete(String uri, String type, String id, Optional<String> user) { delete(uri, type, id, user, Optional.<Class<T>> absent()); } private <T> Optional<T> delete(String uri, String type, String id, Optional<String> user, Optional<Class<T>> clazz) { LOG.info("Deleting {} {} from {}", type, id, uri); final long start = System.currentTimeMillis(); HttpRequest.Builder request = HttpRequest.newBuilder().setUrl(uri).setMethod(Method.DELETE); if (user.isPresent()) { request.addQueryParam("user", user.get()); } HttpResponse response = httpClient.execute(request.build()); if (response.getStatusCode() == 404) { LOG.info("{} ({}) was not found", type, id); return Optional.absent(); } checkResponse(type, response); LOG.info("Deleted {} ({}) from Singularity in %sms", type, id, System.currentTimeMillis() - start); if (clazz.isPresent()) { return Optional.of(response.getAs(clazz.get())); } return Optional.absent(); } private <T> Optional<T> post(String uri, String type, Optional<?> body, Optional<String> user, Optional<Class<T>> clazz) { try { HttpResponse response = post(uri, type, body, user); if (clazz.isPresent()) { return Optional.of(response.getAs(clazz.get())); } } catch (Exception e) { LOG.warn("Http post failed", e); } return Optional.<T>absent(); } private HttpResponse post(String uri, String type, Optional<?> body, Optional<String> user) { LOG.info("Posting {} to {}", type, uri); final long start = System.currentTimeMillis(); HttpRequest.Builder request = HttpRequest.newBuilder().setUrl(uri).setMethod(Method.POST); if (user.isPresent()) { request.addQueryParam("user", user.get()); } if (body.isPresent()) { request.setBody(body.get()); } HttpResponse response = httpClient.execute(request.build()); checkResponse(type, response); LOG.info("Successfully posted {} in {}ms", type, System.currentTimeMillis() - start); return response; } // // GLOBAL // public SingularityState getState(Optional<Boolean> skipCache, Optional<Boolean> includeRequestIds) { final String uri = String.format(STATE_FORMAT, getHost(), contextPath); LOG.info("Fetching state from {}", uri); final long start = System.currentTimeMillis(); HttpRequest.Builder request = HttpRequest.newBuilder().setUrl(uri); if (skipCache.isPresent()) { request.addQueryParam("skipCache", skipCache.get().booleanValue()); } if (includeRequestIds.isPresent()) { request.addQueryParam("includeRequestIds", includeRequestIds.get().booleanValue()); } HttpResponse response = httpClient.execute(request.build()); checkResponse("state", response); LOG.info("Got state in {}ms", System.currentTimeMillis() - start); return response.getAs(SingularityState.class); } // // ACTIONS ON A SINGLE SINGULARITY REQUEST // public Optional<SingularityRequestParent> getSingularityRequest(String requestId) { final String singularityApiRequestUri = String.format(REQUEST_GET_FORMAT, getHost(), contextPath, requestId); return getSingle(singularityApiRequestUri, "request", requestId, SingularityRequestParent.class); } public void createOrUpdateSingularityRequest(SingularityRequest request, Optional<String> user) { checkNotNull(request.getId(), "A posted Singularity Request must have an id"); final String requestUri = String.format(REQUEST_CREATE_OR_UPDATE_FORMAT, getHost(), contextPath); post(requestUri, String.format("request %s", request.getId()), Optional.of(request), user); } /** * Delete a singularity request that is active. * If the deletion is successful the deleted singularity request is returned. * If the request to be deleted is not found {code Optional.absent()} is returned * If an error occurs during deletion an exception is returned * If the singularity request to be deleted is paused the deletion will fail with an exception * If you want to delete a paused singularity request use the provided {@link SingularityClient#deletePausedSingularityRequest} * * @param requestId * the id of the singularity request to delete * @param user * the ... * @return * the singularity request that was deleted */ public Optional<SingularityRequest> deleteActiveSingularityRequest(String requestId, Optional<String> user) { final String requestUri = String.format(REQUEST_DELETE_ACTIVE_FORMAT, getHost(), contextPath, requestId); return delete(requestUri, "active request", requestId, user, Optional.of(SingularityRequest.class)); } public Optional<SingularityRequest> deletePausedSingularityRequest(String requestId, Optional<String> user) { final String requestUri = String.format(REQUEST_DELETE_PAUSED_FORMAT, getHost(), contextPath, requestId); return delete(requestUri, "paused request", requestId, user, Optional.of(SingularityRequest.class)); } public void pauseSingularityRequest(String requestId, Optional<String> user) { final String requestUri = String.format(REQUEST_PAUSE_FORMAT, getHost(), contextPath, requestId); post(requestUri, String.format("pause of request %s", requestId), Optional.absent(), user); } public void bounceSingularityRequest(String requestId, Optional<String> user) { final String requestUri = String.format(REQUEST_BOUNCE_FORMAT, getHost(), contextPath, requestId); post(requestUri, String.format("bounce of request %s", requestId), Optional.absent(), user); } // // ACTIONS ON A DEPLOY FOR A SINGULARITY REQUEST // public SingularityRequestParent createDeployForSingularityRequest(String requestId, SingularityDeploy pendingDeploy, Optional<Boolean> deployUnpause, Optional<String> user) { final String requestUri = String.format(DEPLOYS_FORMAT, getHost(), contextPath); List<Pair<String, String>> queryParams = Lists.newArrayList(); if (user.isPresent()) { queryParams.add(Pair.of("user", user.get())); } if (deployUnpause.isPresent()) { queryParams.add(Pair.of("deployUnpause", Boolean.toString(deployUnpause.get()))); } HttpResponse response = post(requestUri, String.format("new deploy %s", new SingularityDeployKey(requestId, pendingDeploy.getId())), Optional.of(new SingularityDeployRequest(pendingDeploy, user, deployUnpause)), Optional.<String> absent()); return getAndLogRequestAndDeployStatus(response.getAs(SingularityRequestParent.class)); } private SingularityRequestParent getAndLogRequestAndDeployStatus(SingularityRequestParent singularityRequestParent) { String activeDeployId = singularityRequestParent.getActiveDeploy().isPresent() ? singularityRequestParent.getActiveDeploy().get().getId() : "No Active Deploy"; String pendingDeployId = singularityRequestParent.getPendingDeploy().isPresent() ? singularityRequestParent.getPendingDeploy().get().getId() : "No Pending deploy"; LOG.info("Deploy status: Singularity request {} -> pending deploy: '{}', active deploy: '{}'", singularityRequestParent.getRequest().getId(), pendingDeployId, activeDeployId); return singularityRequestParent; } public SingularityRequestParent cancelPendingDeployForSingularityRequest(String requestId, String deployId, Optional<String> user) { final String requestUri = String.format(DELETE_DEPLOY_FORMAT, getHost(), contextPath, deployId, requestId); SingularityRequestParent singularityRequestParent = delete(requestUri, "pending deploy", new SingularityDeployKey(requestId, deployId).getId(), user, Optional.of(SingularityRequestParent.class)).get(); return getAndLogRequestAndDeployStatus(singularityRequestParent); } /** * Get all singularity requests that their state is either ACTIVE, PAUSED or COOLDOWN * * For the requests that are pending to become ACTIVE use: * {@link SingularityClient#getPendingSingularityRequests()} * * For the requests that are cleaning up use: * {@link SingularityClient#getCleanupSingularityRequests()} * * * Use {@link SingularityClient#getActiveSingularityRequests()}, {@link SingularityClient#getPausedSingularityRequests()}, * {@link SingularityClient#getCoolDownSingularityRequests()} respectively to get only the ACTIVE, PAUSED or COOLDOWN requests. * * @return * returns all the [ACTIVE, PAUSED, COOLDOWN] {@link SingularityRequest} instances. * */ public Collection<SingularityRequest> getSingularityRequests() { final String requestUri = String.format(REQUESTS_FORMAT, getHost(), contextPath); return getCollection(requestUri, "[ACTIVE, PAUSED, COOLDOWN] requests", REQUESTS_COLLECTION); } /** * Get all requests that their state is ACTIVE * * @return * All ACTIVE {@link SingularityRequest} instances */ public Collection<SingularityRequest> getActiveSingularityRequests() { final String requestUri = String.format(REQUESTS_GET_ACTIVE_FORMAT, getHost(), contextPath); return getCollection(requestUri, "ACTIVE requests", REQUESTS_COLLECTION); } /** * Get all requests that their state is PAUSED * ACTIVE requests are paused by users, which is equivalent to stop their tasks from running without undeploying them * * @return * All PAUSED {@link SingularityRequest} instances */ public Collection<SingularityRequest> getPausedSingularityRequests() { final String requestUri = String.format(REQUESTS_GET_PAUSED_FORMAT, getHost(), contextPath); return getCollection(requestUri, "PAUSED requests", REQUESTS_COLLECTION); } /** * Get all requests that has been set to a COOLDOWN state by singularity * * @return * All {@link SingularityRequest} instances that their state is COOLDOWN */ public Collection<SingularityRequest> getCoolDownSingularityRequests() { final String requestUri = String.format(REQUESTS_GET_COOLDOWN_FORMAT, getHost(), contextPath); return getCollection(requestUri, "COOLDOWN requests", REQUESTS_COLLECTION); } /** * Get all requests that are pending to become ACTIVE * * @return * A collection of {@link SingularityPendingRequest} instances that hold information about the singularity requests that are pending to become ACTIVE */ public Collection<SingularityPendingRequest> getPendingSingularityRequests() { final String requestUri = String.format(REQUESTS_GET_PENDING_FORMAT, getHost(), contextPath); return getCollection(requestUri, "pending requests", PENDING_REQUESTS_COLLECTION); } /** * Get all requests that are cleaning up * Requests that are cleaning up are those that have been marked for removal and their tasks are being stopped/removed * before they are being removed. So after their have been cleaned up, these request cease to exist in Singularity. * * @return * A collection of {@link SingularityRequestCleanup} instances that hold information about all singularity requests * that are marked for deletion and are currently cleaning up. */ public Collection<SingularityRequestCleanup> getCleanupSingularityRequests() { final String requestUri = String.format(REQUESTS_GET_CLEANUP_FORMAT, getHost(), contextPath); return getCollection(requestUri, "cleaning requests", CLEANUP_REQUESTS_COLLECTION); } // // SINGULARITY TASK COLLECTIONS // // // ACTIVE TASKS // public Collection<SingularityTask> getActiveTasks() { final String requestUri = String.format(TASKS_GET_ACTIVE_FORMAT, getHost(), contextPath); return getCollection(requestUri, "active tasks", TASKS_COLLECTION); } public Collection<SingularityTask> getActiveTasksOnSlave(final String slaveId) { final String requestUri = String.format(TASKS_GET_ACTIVE_ON_SLAVE_FORMAT, getHost(), contextPath, slaveId); return getCollection(requestUri, String.format("active tasks on slave %s", slaveId), TASKS_COLLECTION); } public Optional<SingularityTaskCleanupResult> killTask(String taskId, Optional<String> user) { final String requestUri = String.format(TASKS_KILL_TASK_FORMAT, getHost(), contextPath, taskId); return delete(requestUri, "task", taskId, user, Optional.of(SingularityTaskCleanupResult.class)); } // // SCHEDULED TASKS // public Collection<SingularityTaskRequest> getScheduledTasks() { final String requestUri = String.format(TASKS_GET_SCHEDULED_FORMAT, getHost(), contextPath); return getCollection(requestUri, "scheduled tasks", TASKS_REQUEST_COLLECTION); } // // RACKS // public Collection<SingularityRack> getActiveRacks() { return getRacks(RACKS_GET_ACTIVE_FORMAT, "active"); } public Collection<SingularityRack> getDeadRacks() { return getRacks(RACKS_GET_DEAD_FORMAT, "dead"); } public Collection<SingularityRack> getDecomissioningRacks() { return getRacks(RACKS_GET_DECOMISSIONING_FORMAT, "decomissioning"); } private Collection<SingularityRack> getRacks(String format, String type) { final String requestUri = String.format(format, getHost(), contextPath); return getCollection(requestUri, String.format("%s racks", type), RACKS_COLLECTION); } public void decomissionRack(String rackId, Optional<String> user) { final String requestUri = String.format(RACKS_DECOMISSION_FORMAT, getHost(), contextPath, rackId); post(requestUri, String.format("decomission rack %s", rackId), Optional.absent(), user); } public void deleteDecomissioningRack(String rackId, Optional<String> user) { final String requestUri = String.format(RACKS_DELETE_DECOMISSIONING_FORMAT, getHost(), contextPath, rackId); delete(requestUri, "rack", rackId, user); } public void deleteDeadRack(String rackId, Optional<String> user) { final String requestUri = String.format(RACKS_DELETE_DEAD_FORMAT, getHost(), contextPath, rackId); delete(requestUri, "dead rack", rackId, user); } // // SLAVES // /** * Use {@link getSlaves} specifying the desired slave state to filter by * */ @Deprecated public Collection<SingularitySlave> getActiveSlaves() { return getSlaves(Optional.of(MachineState.ACTIVE)); } /** * Use {@link getSlaves} specifying the desired slave state to filter by * */ @Deprecated public Collection<SingularitySlave> getDeadSlaves() { return getSlaves(Optional.of(MachineState.DEAD)); } /** * Use {@link getSlaves} specifying the desired slave state to filter by * */ @Deprecated public Collection<SingularitySlave> getDecomissioningSlaves() { return getSlaves(Optional.of(MachineState.DECOMMISSIONING)); } /** * Retrieve the list of all known slaves, optionally filtering by a particular slave state * * @param slaveState * Optionally specify a particular state to filter slaves by * @return * A collection of {@link SingularitySlave} */ public Collection<SingularitySlave> getSlaves(Optional<MachineState> slaveState) { final String requestUri = String.format(SLAVES_FORMAT, getHost(), contextPath); Optional<Map<String, Object>> maybeQueryParams = Optional.<Map<String, Object>>absent(); String type = "slaves"; if (slaveState.isPresent()) { maybeQueryParams = Optional.<Map<String, Object>>of(ImmutableMap.<String, Object>of("state", slaveState.get())); type = String.format("%s slaves", slaveState.get().toString()); } return getCollectionWithParams(requestUri, type, maybeQueryParams, SLAVES_COLLECTION); } public void decomissionSlave(String slaveId, Optional<String> user) { final String requestUri = String.format(SLAVES_DECOMISSION_FORMAT, getHost(), contextPath, slaveId); post(requestUri, String.format("decomission slave %s", slaveId), Optional.absent(), user); } public void deleteSlave(String slaveId, Optional<String> user) { final String requestUri = String.format(SLAVES_DELETE_FORMAT, getHost(), contextPath, slaveId); delete(requestUri, "deleting slave", slaveId, user); } // // TASK HISTORY // public Optional<SingularityTaskHistory> getHistoryForTask(String taskId) { final String requestUri = String.format(TASK_HISTORY_FORMAT, getHost(), contextPath, taskId); return getSingle(requestUri, "task history", taskId, SingularityTaskHistory.class); } public Collection<SingularityTaskIdHistory> getActiveTaskHistoryForRequest(String requestId) { final String requestUri = String.format(REQUEST_ACTIVE_TASKS_HISTORY_FORMAT, getHost(), contextPath, requestId); final String type = String.format("active task history for %s", requestId); return getCollection(requestUri, type, TASKID_HISTORY_COLLECTION); } public Collection<SingularityTaskIdHistory> getInactiveTaskHistoryForRequest(String requestId) { final String requestUri = String.format(REQUEST_INACTIVE_TASKS_HISTORY_FORMAT, getHost(), contextPath, requestId); final String type = String.format("inactive (failed, killed, lost) task history for request %s", requestId); return getCollection(requestUri, type, TASKID_HISTORY_COLLECTION); } public Optional<SingularityDeployHistory> getHistoryForRequestDeploy(String requestId, String deployId) { final String requestUri = String.format(REQUEST_DEPLOY_HISTORY_FORMAT, getHost(), contextPath, requestId, deployId); return getSingle(requestUri, "deploy history", new SingularityDeployKey(requestId, deployId).getId(), SingularityDeployHistory.class); } // // WEBHOOKS // public Optional<SingularityCreateResult> addWebhook(SingularityWebhook webhook, Optional<String> user) { final String requestUri = String.format(WEBHOOKS_FORMAT, getHost(), contextPath); return post(requestUri, String.format("webhook %s", webhook.getUri()), Optional.of(webhook), user, Optional.of(SingularityCreateResult.class)); } public Optional<SingularityDeleteResult> deleteWebhook(String webhookId, Optional<String> user) { final String requestUri = String.format(WEBHOOKS_DELETE_FORMAT, getHost(), contextPath, webhookId); return delete(requestUri, String.format("webhook with id %s", webhookId), webhookId, user, Optional.of(SingularityDeleteResult.class)); } public Collection<SingularityWebhook> getActiveWebhook() { final String requestUri = String.format(WEBHOOKS_FORMAT, getHost(), contextPath); return getCollection(requestUri, "active webhooks", WEBHOOKS_COLLECTION); } public Collection<SingularityDeployUpdate> getQueuedDeployUpdates(String webhookId) { final String requestUri = String.format(WEBHOOKS_GET_QUEUED_DEPLOY_UPDATES_FORMAT, getHost(), contextPath, webhookId); return getCollection(requestUri, "deploy updates", DEPLOY_UPDATES_COLLECTION); } public Collection<SingularityRequestHistory> getQueuedRequestUpdates(String webhookId) { final String requestUri = String.format(WEBHOOKS_GET_QUEUED_REQUEST_UPDATES_FORMAT, getHost(), contextPath, webhookId); return getCollection(requestUri, "request updates", REQUEST_UPDATES_COLLECTION); } public Collection<SingularityTaskHistoryUpdate> getQueuedTaskUpdates(String webhookId) { final String requestUri = String.format(WEBHOOKS_GET_QUEUED_TASK_UPDATES_FORMAT, getHost(), contextPath, webhookId); return getCollection(requestUri, "request updates", TASK_UPDATES_COLLECTION); } // // SANDBOX // /** * Retrieve information about a specific task's sandbox * * @param taskId * The task ID to browse * @param path * The path to browse from. * if not specified it will browse from the sandbox root. * @return * A {@link SingularitySandbox} object that captures the information for the path to a specific task's Mesos sandbox */ public Optional<SingularitySandbox> browseTaskSandBox(String taskId, String path) { final String requestUrl = String.format(SANDBOX_BROWSE_FORMAT, getHost(), contextPath, taskId); return getSingleWithParams(requestUrl, "browse sandbox for task", taskId, Optional.<Map<String, Object>>of(ImmutableMap.<String, Object>of("path", path)), SingularitySandbox.class); } /** * Retrieve part of the contents of a file in a specific task's sandbox. * * @param taskId * The task ID of the sandbox to read from * @param path * The path to the file to be read. Relative to the sandbox root (without a leading slash) * @param grep * Optional string to grep for * @param offset * Byte offset to start reading from * @param length * Maximum number of bytes to read * @return * A {@link MesosFileChunkObject} that contains the requested partial file contents */ public Optional<MesosFileChunkObject> readSandBoxFile(String taskId, String path, Optional<String> grep, Optional<Long> offset, Optional<Long> length) { final String requestUrl = String.format(SANDBOX_READ_FILE_FORMAT, getHost(), contextPath, taskId); Builder<String, Object> queryParamBuider = ImmutableMap.<String, Object>builder().put("path", path); if (grep.isPresent()) { queryParamBuider.put("grep", grep.get()); } if (offset.isPresent()) { queryParamBuider.put("offset", offset.get()); } if (length.isPresent()) { queryParamBuider.put("length", length.get()); } return getSingleWithParams(requestUrl, "Read sandbox file for task", taskId, Optional.<Map<String, Object>>of(queryParamBuider.build()), MesosFileChunkObject.class); } }
The Nonnull annotation causes a dependency analysis failure for com.google.code.findbugs:annotations:jar ???? Will resolve at another time...
SingularityClient/src/main/java/com/hubspot/singularity/client/SingularityClient.java
The Nonnull annotation causes a dependency analysis failure for com.google.code.findbugs:annotations:jar ???? Will resolve at another time...
<ide><path>ingularityClient/src/main/java/com/hubspot/singularity/client/SingularityClient.java <ide> import java.util.Map.Entry; <ide> import java.util.Random; <ide> <del>import javax.annotation.Nonnull; <ide> import javax.inject.Provider; <ide> <ide> import org.apache.commons.lang3.tuple.Pair; <ide> return response.getAs(typeReference); <ide> } <ide> <del> private void addQueryParams(@Nonnull HttpRequest.Builder requestBuilder, @Nonnull Map<String, Object> queryParams) { <add> private void addQueryParams(HttpRequest.Builder requestBuilder, Map<String, Object> queryParams) { <ide> for (Entry<String, Object> queryParamEntry : queryParams.entrySet()) { <ide> if (queryParamEntry.getValue() instanceof String) { <ide> requestBuilder.addQueryParam(queryParamEntry.getKey(), (String) queryParamEntry.getValue());
Java
apache-2.0
6dc2b2546bb59bac7ed3c0c9abb5dc5962b8c3dd
0
this/carbon-uuf,manuranga/carbon-uuf,rasika90/carbon-uuf,manuranga/carbon-uuf,this/carbon-uuf,this/carbon-uuf,manuranga/carbon-uuf,Shan1024/carbon-uuf,manuranga/carbon-uuf,wso2/carbon-uuf,Shan1024/carbon-uuf,wso2/carbon-uuf,sajithar/carbon-uuf,Shan1024/carbon-uuf,wso2/carbon-uuf,rasika90/carbon-uuf,wso2/carbon-uuf,sajithar/carbon-uuf,Shan1024/carbon-uuf,rasika90/carbon-uuf,this/carbon-uuf
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.uuf.core; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.QueryStringDecoder; import org.wso2.carbon.uuf.core.auth.SessionRegistry; import org.wso2.carbon.uuf.core.exception.FragmentNotFoundException; import org.wso2.carbon.uuf.core.exception.PageNotFoundException; import org.wso2.carbon.uuf.model.MapModel; import org.wso2.carbon.uuf.model.Model; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; public class App { private final String context; private final Map<String, Component> components; private final Component rootComponent; private final SessionRegistry sessionRegistry; private static final String FRAGMENTS_URI_PREFIX = "/fragments/"; public App(String context, Set<Component> components, SessionRegistry sessionRegistry) { if (!context.startsWith("/")) { throw new IllegalArgumentException("App context must start with a '/'."); } this.context = context; this.components = components.stream().collect(Collectors.toMap(Component::getContext, cmp -> cmp)); this.rootComponent = this.components.get(Component.ROOT_COMPONENT_CONTEXT); this.sessionRegistry = sessionRegistry; } public String renderPage(String uriWithoutContext, RequestLookup requestLookup) { API api = new API(sessionRegistry); // First try to render the page with root component. Optional<String> output = rootComponent.renderPage(uriWithoutContext, requestLookup, api); if (output.isPresent()) { return output.get(); } // Since root components doesn't have the page, try with other components. for (Map.Entry<String, Component> entry : components.entrySet()) { if (uriWithoutContext.startsWith(entry.getKey())) { Component component = entry.getValue(); String pageUri = uriWithoutContext.substring(component.getName().length()); output = component.renderPage(pageUri, requestLookup, api); if (output.isPresent()) { return output.get(); } break; } } throw new PageNotFoundException("Requested page '" + uriWithoutContext + "' does not exists."); } public static boolean isFragmentsUri(String uriWithoutContext) { return uriWithoutContext.startsWith(FRAGMENTS_URI_PREFIX); } /** * Returns rendered output of this fragment uri. This method intended to use for serving AJAX requests. * * @param uriWithoutAppContext fragment uri * @param requestLookup request lookup * @return rendered output */ public String renderFragment(String uriWithoutAppContext, RequestLookup requestLookup) { API api = new API(sessionRegistry); int queryParamsPos = uriWithoutAppContext.indexOf("?"); String fragmentName = (queryParamsPos > -1) ? uriWithoutAppContext.substring(FRAGMENTS_URI_PREFIX.length(), queryParamsPos) : uriWithoutAppContext.substring(FRAGMENTS_URI_PREFIX.length()); if (!NameUtils.isFullyQualifiedName(fragmentName)) { fragmentName = NameUtils.getFullyQualifiedName(Component.ROOT_COMPONENT_NAME, fragmentName); } Model model = createModel(requestLookup.getRequest()); // First try to render the fragment with root component. ComponentLookup componentLookup = rootComponent.getLookup(); Optional<Fragment> fragment = rootComponent.getLookup().getFragment(fragmentName); if (fragment.isPresent()) { return fragment.get().render(model, componentLookup, requestLookup, api); } // Since root components doesn't have the fragment, try with other components. String componentName = NameUtils.getComponentName(fragmentName); for (Map.Entry<String, Component> entry : components.entrySet()) { if (componentName.startsWith(entry.getKey())) { Component component = entry.getValue(); componentLookup = component.getLookup(); fragment = componentLookup.getFragment(fragmentName); if (fragment.isPresent()) { return fragment.get().render(new MapModel(new HashMap<>()), componentLookup, requestLookup, api); } break; } } throw new FragmentNotFoundException("Requested fragment '" + uriWithoutAppContext + "' does not exists."); } private Model createModel(HttpRequest httpRequest) { QueryStringDecoder decoder = new QueryStringDecoder(httpRequest.getUri()); Map<String, List<String>> parameters = decoder.parameters(); Iterator<Map.Entry<String, List<String>>> paramsIterator = parameters.entrySet().iterator(); HashMap<String, Object> uriParams = new HashMap<>(); while (paramsIterator.hasNext()) { Map.Entry<String, List<String>> currentParam = paramsIterator.next(); List<String> paramValues = currentParam.getValue(); Object newParamValue = (paramValues.size() == 1) ? paramValues.get(0) : paramValues; uriParams.put(currentParam.getKey(), newParamValue); } HashMap<String, Object> context = new HashMap<>(); context.put("uriParams", uriParams); return new MapModel(context); } public boolean hasPage(String uri) { if (rootComponent.hasPage(uri)) { return true; } int firstSlash = uri.indexOf('/', 1); if (firstSlash > 0) { String componentContext = uri.substring(0, firstSlash); Component component = components.get(componentContext); if (component != null) { return component.hasPage(uri.substring(firstSlash)); } } return false; } public Map<String, Component> getComponents() { return components; } public SessionRegistry getSessionRegistry() { return sessionRegistry; } public String getContext() { return context; } @Override public String toString() { return "{\"context\": \"" + context + "\"}"; } }
uuf-core/src/main/java/org/wso2/carbon/uuf/core/App.java
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.uuf.core; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.QueryStringDecoder; import org.wso2.carbon.uuf.core.auth.SessionRegistry; import org.wso2.carbon.uuf.core.exception.FragmentNotFoundException; import org.wso2.carbon.uuf.core.exception.PageNotFoundException; import org.wso2.carbon.uuf.model.MapModel; import org.wso2.carbon.uuf.model.Model; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; public class App { private final String context; private final Map<String, Component> components; private final Component rootComponent; private final SessionRegistry sessionRegistry; private static final String FRAGMENTS_URI_PREFIX = "/fragments/"; public App(String context, Set<Component> components, SessionRegistry sessionRegistry) { if (!context.startsWith("/")) { throw new IllegalArgumentException("App context must start with a '/'."); } this.context = context; this.components = components.stream().collect(Collectors.toMap(Component::getContext, cmp -> cmp)); this.rootComponent = this.components.get(Component.ROOT_COMPONENT_CONTEXT); this.sessionRegistry = sessionRegistry; } public String renderPage(String uriWithoutContext, RequestLookup requestLookup) { API api = new API(sessionRegistry); // First try to render the page with root component. Optional<String> output = rootComponent.renderPage(uriWithoutContext, requestLookup, api); if (output.isPresent()) { return output.get(); } // Since root components doesn't have the page, try with other components. for (Map.Entry<String, Component> entry : components.entrySet()) { if (uriWithoutContext.startsWith(entry.getKey())) { Component component = entry.getValue(); String pageUri = uriWithoutContext.substring(component.getName().length()); output = component.renderPage(pageUri, requestLookup, api); if (output.isPresent()) { return output.get(); } break; } } throw new PageNotFoundException("Requested page '" + uriWithoutContext + "' does not exists."); } public static boolean isFragmentsUri(String uriWithoutContext) { return uriWithoutContext.startsWith(FRAGMENTS_URI_PREFIX); } /** * Returns rendered output of this fragment uri. This method intended to use for serving AJAX requests. * * @param uriWithoutAppContext fragment uri * @param requestLookup request lookup * @return rendered output */ public String renderFragment(String uriWithoutAppContext, RequestLookup requestLookup) { API api = new API(sessionRegistry); int queryParamsPos = uriWithoutAppContext.indexOf("?"); String fragmentName = (queryParamsPos > -1) ? uriWithoutAppContext.substring(FRAGMENTS_URI_PREFIX.length(), queryParamsPos) : uriWithoutAppContext.substring(FRAGMENTS_URI_PREFIX.length()); if (!NameUtils.isFullyQualifiedName(fragmentName)) { fragmentName = NameUtils.getFullyQualifiedName(Component.ROOT_COMPONENT_NAME, fragmentName); } Model model = createModel(requestLookup.getRequest()); // First try to render the fragment with root component. ComponentLookup componentLookup = rootComponent.getLookup(); Optional<Fragment> fragment = rootComponent.getLookup().getFragment(fragmentName); if (fragment.isPresent()) { return fragment.get().render(model, componentLookup, requestLookup, api); } // Since root components doesn't have the fragment, try with other components. String componentName = NameUtils.getComponentName(fragmentName); for (Map.Entry<String, Component> entry : components.entrySet()) { if (componentName.startsWith(entry.getKey())) { Component component = entry.getValue(); componentLookup = component.getLookup(); fragment = componentLookup.getFragment(fragmentName); if (fragment.isPresent()) { return fragment.get().render(new MapModel(new HashMap<>()), componentLookup, requestLookup, api); } break; } } throw new FragmentNotFoundException("Requested fragment '" + uriWithoutAppContext + "' does not exists."); } private Model createModel(HttpRequest httpRequest) { QueryStringDecoder decoder = new QueryStringDecoder(httpRequest.getUri()); Map<String, List<String>> parameters = decoder.parameters(); Iterator<String> paramsIterator = parameters.keySet().iterator(); HashMap<String, Object> uriParams = new HashMap<>(); while (paramsIterator.hasNext()) { String currentParam = paramsIterator.next(); List<String> paramValues = parameters.get(currentParam); Object newParamValue = (paramValues.size() == 1) ? paramValues.get(0) : paramValues; uriParams.put(currentParam, newParamValue); } HashMap<String, Object> context = new HashMap<>(); context.put("uriParams", uriParams); return new MapModel(context); } public boolean hasPage(String uri) { if (rootComponent.hasPage(uri)) { return true; } int firstSlash = uri.indexOf('/', 1); if (firstSlash > 0) { String componentContext = uri.substring(0, firstSlash); Component component = components.get(componentContext); if (component != null) { return component.hasPage(uri.substring(firstSlash)); } } return false; } public Map<String, Component> getComponents() { return components; } public SessionRegistry getSessionRegistry() { return sessionRegistry; } public String getContext() { return context; } @Override public String toString() { return "{\"context\": \"" + context + "\"}"; } }
Fixing FindBug performance issue
uuf-core/src/main/java/org/wso2/carbon/uuf/core/App.java
Fixing FindBug performance issue
<ide><path>uf-core/src/main/java/org/wso2/carbon/uuf/core/App.java <ide> private Model createModel(HttpRequest httpRequest) { <ide> QueryStringDecoder decoder = new QueryStringDecoder(httpRequest.getUri()); <ide> Map<String, List<String>> parameters = decoder.parameters(); <del> Iterator<String> paramsIterator = parameters.keySet().iterator(); <add> Iterator<Map.Entry<String, List<String>>> paramsIterator = parameters.entrySet().iterator(); <ide> HashMap<String, Object> uriParams = new HashMap<>(); <ide> while (paramsIterator.hasNext()) { <del> String currentParam = paramsIterator.next(); <del> List<String> paramValues = parameters.get(currentParam); <add> Map.Entry<String, List<String>> currentParam = paramsIterator.next(); <add> List<String> paramValues = currentParam.getValue(); <ide> Object newParamValue = (paramValues.size() == 1) ? paramValues.get(0) : paramValues; <del> uriParams.put(currentParam, newParamValue); <add> uriParams.put(currentParam.getKey(), newParamValue); <ide> } <ide> HashMap<String, Object> context = new HashMap<>(); <ide> context.put("uriParams", uriParams);
Java
lgpl-2.1
48f93691e74fbd42d949634dc8dc6be1b306a858
0
zebrafishmine/intermine,zebrafishmine/intermine,justincc/intermine,JoeCarlson/intermine,elsiklab/intermine,justincc/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,zebrafishmine/intermine,elsiklab/intermine,JoeCarlson/intermine,joshkh/intermine,drhee/toxoMine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,elsiklab/intermine,zebrafishmine/intermine,tomck/intermine,joshkh/intermine,JoeCarlson/intermine,tomck/intermine,justincc/intermine,elsiklab/intermine,JoeCarlson/intermine,kimrutherford/intermine,drhee/toxoMine,justincc/intermine,tomck/intermine,elsiklab/intermine,kimrutherford/intermine,drhee/toxoMine,drhee/toxoMine,kimrutherford/intermine,elsiklab/intermine,zebrafishmine/intermine,justincc/intermine,justincc/intermine,zebrafishmine/intermine,tomck/intermine,drhee/toxoMine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,tomck/intermine,drhee/toxoMine,kimrutherford/intermine,joshkh/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,justincc/intermine,joshkh/intermine,drhee/toxoMine,kimrutherford/intermine,tomck/intermine,JoeCarlson/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,drhee/toxoMine,tomck/intermine,JoeCarlson/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,joshkh/intermine,zebrafishmine/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,drhee/toxoMine,joshkh/intermine,elsiklab/intermine,joshkh/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,tomck/intermine
package org.intermine.util; /* * Copyright (C) 2002-2004 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import junit.framework.TestCase; import java.sql.Connection; import java.sql.Statement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.Set; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Date; import java.math.BigDecimal; import java.math.BigInteger; import org.intermine.sql.DatabaseFactory; import org.intermine.metadata.Model; import org.intermine.metadata.ClassDescriptor; import org.intermine.metadata.FieldDescriptor; import org.intermine.metadata.AttributeDescriptor; import org.intermine.metadata.ReferenceDescriptor; import org.intermine.metadata.CollectionDescriptor; import org.intermine.sql.Database; import org.intermine.model.testmodel.*; import org.intermine.model.InterMineObject; public class DatabaseUtilTest extends TestCase { private Connection con; private Database db; private String uri = "http://www.intermine.org/model/testmodel"; public DatabaseUtilTest(String arg1) { super(arg1); } public void setUp() throws Exception { db = DatabaseFactory.getDatabase("db.unittest"); con = db.getConnection(); } public void tearDown() throws Exception { con.close(); } protected void createTable() throws Exception { try { dropTable(); } catch (SQLException e) { con.rollback(); } con.createStatement().execute("CREATE TABLE table1(col1 int)"); con.commit(); } protected void dropTable() throws Exception { con.createStatement().execute("DROP TABLE table1"); con.commit(); } public void testTableExistsNullConnection() throws Exception { try { DatabaseUtil.tableExists(null, "table1"); fail("Expected: NullPointerException"); } catch (NullPointerException e) { } } public void testTableExistsNullTable() throws Exception { try { DatabaseUtil.tableExists(con, null); fail("Expected: NullPointerException"); } catch (NullPointerException e) { } } public void testTableExists() throws Exception { synchronized (con) { createTable(); assertTrue(DatabaseUtil.tableExists(con, "table1")); dropTable(); } } public void testTableNotExists() throws Exception { synchronized (con) { try { con.createStatement().execute("DROP TABLE table2"); con.commit(); } catch (SQLException e) { con.rollback(); } createTable(); assertTrue(!(DatabaseUtil.tableExists(con, "table2"))); dropTable(); } } public void testGetTableNameOne() throws Exception { ClassDescriptor cld = new ClassDescriptor("Class1", null, false, new HashSet(), new HashSet(), new HashSet()); Model model1 = new Model("test1", uri, new HashSet(Arrays.asList(new Object[] {cld}))); assertEquals("Class1", DatabaseUtil.getTableName(cld)); } public void testGetTableNameTwo() throws Exception { ClassDescriptor cld = new ClassDescriptor("Array", null, false, new HashSet(), new HashSet(), new HashSet()); Model model1 = new Model("test1", uri, new HashSet(Arrays.asList(new Object[] {cld}))); assertEquals("intermine_Array", DatabaseUtil.getTableName(cld)); } public void testGetColumnName() throws Exception { FieldDescriptor attr = new AttributeDescriptor("attr1", "int"); assertEquals(DatabaseUtil.generateSqlCompatibleName("attr1"), DatabaseUtil.getColumnName(attr)); } public void testGetIndirectionTableNameRef() throws Exception { CollectionDescriptor col1 = new CollectionDescriptor("col1", "Class2", "ref1", false); Set cols = new HashSet(Arrays.asList(new Object[] {col1})); ClassDescriptor cld1 = new ClassDescriptor("Class1", null, false, new HashSet(), new HashSet(), cols); ReferenceDescriptor ref1 = new ReferenceDescriptor("ref1", "Class1", null); Set refs = new HashSet(Arrays.asList(new Object[] {ref1})); ClassDescriptor cld2 = new ClassDescriptor("Class2", null, false, new HashSet(), refs, new HashSet()); Set clds = new HashSet(Arrays.asList(new Object[] {cld1, cld2})); Model model = new Model("test", uri, clds); try { DatabaseUtil.getIndirectionTableName(col1); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { } } public void testGetIndirectionTableNameNull() throws Exception { CollectionDescriptor col1 = new CollectionDescriptor("col1", "Class2", null, false); Set cols = new HashSet(Arrays.asList(new Object[] {col1})); ClassDescriptor cld1 = new ClassDescriptor("Class1", null, false, new HashSet(), new HashSet(), cols); ClassDescriptor cld2 = new ClassDescriptor("Class2", null, false, new HashSet(), new HashSet(), new HashSet()); Set clds = new HashSet(Arrays.asList(new Object[] {cld1, cld2})); Model model = new Model("test", uri, clds); assertEquals("Class1Col1", DatabaseUtil.getIndirectionTableName(col1)); assertEquals("Col1", DatabaseUtil.getInwardIndirectionColumnName(col1)); assertEquals("Class1", DatabaseUtil.getOutwardIndirectionColumnName(col1)); } public void testGetIndirectionTableNameCol() throws Exception { CollectionDescriptor col1 = new CollectionDescriptor("col1", "Class2", "col2", false); Set cols = new HashSet(Arrays.asList(new Object[] {col1})); ClassDescriptor cld1 = new ClassDescriptor("Class1", null, false, new HashSet(), new HashSet(), cols); CollectionDescriptor col2 = new CollectionDescriptor("col2", "Class1", "col1", false); cols = new HashSet(Arrays.asList(new Object[] {col2})); ClassDescriptor cld2 = new ClassDescriptor("Class2", null, false, new HashSet(), new HashSet(), cols); Set clds = new HashSet(Arrays.asList(new Object[] {cld1, cld2})); Model model = new Model("test", uri, clds); assertEquals("Col1Col2", DatabaseUtil.getIndirectionTableName(col1)); assertEquals("Col1", DatabaseUtil.getInwardIndirectionColumnName(col1)); assertEquals("Col2", DatabaseUtil.getOutwardIndirectionColumnName(col1)); } public void testGenerateSqlCompatibleName() throws Exception { assertEquals("intermine_end", DatabaseUtil.generateSqlCompatibleName("end")); assertEquals("intermine_intermine_end", DatabaseUtil.generateSqlCompatibleName("intermine_end")); assertEquals("id", DatabaseUtil.generateSqlCompatibleName("id")); assertEquals("index", DatabaseUtil.generateSqlCompatibleName("index")); assertEquals("intermine_order", DatabaseUtil.generateSqlCompatibleName("order")); assertEquals("intermine_full", DatabaseUtil.generateSqlCompatibleName("full")); assertEquals("intermine_offset", DatabaseUtil.generateSqlCompatibleName("offset")); assertEquals("some_string", DatabaseUtil.generateSqlCompatibleName("some_string")); try { DatabaseUtil.generateSqlCompatibleName(null); fail("Expected NullPointerException"); } catch (NullPointerException e) { } } public void testCreateBagTable() throws Exception { Collection bag = new HashSet(); bag.add(new Integer(-10000)); bag.add(new Integer(0)); bag.add(new Integer(10000)); bag.add(new Long(-10000)); bag.add(new Long(0)); bag.add(new Long(10000)); bag.add(new Short((short) -10000)); bag.add(new Short((short) 0)); bag.add(new Short((short) 10000)); bag.add(new BigDecimal(-10000.0)); bag.add(new BigDecimal(0.0)); bag.add(new BigDecimal(10000.0)); bag.add(new Float(-10000.0)); bag.add(new Float(0.0)); bag.add(new Float(10000.0)); bag.add(new Double(-10000.0)); bag.add(new Double(0.0)); bag.add(new Double(10000.0)); bag.add(new String()); bag.add(new String("a String with spaces")); bag.add(new String("123456")); bag.add(new String("123456.7")); bag.add(new Boolean(true)); bag.add(new Boolean(false)); bag.add(new Date(999999)); bag.add(new Date(100)); Employee employee = (Employee) DynamicUtil.createObject(Collections.singleton(Employee.class)); employee.setId(new Integer(5000)); bag.add(employee); Manager manager = (Manager) DynamicUtil.createObject(Collections.singleton(Manager.class)); manager.setId(new Integer(5001)); bag.add(manager); Company company = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); company.setId(new Integer(6000)); bag.add(company); // this shouldn't appear in any table bag.add(BigInteger.ONE); DatabaseUtil.createBagTable(db, con, "integer_table", bag, Integer.class); DatabaseUtil.createBagTable(db, con, "long_table", bag, Long.class); DatabaseUtil.createBagTable(db, con, "short_table", bag, Short.class); DatabaseUtil.createBagTable(db, con, "bigdecimal_table", bag, BigDecimal.class); DatabaseUtil.createBagTable(db, con, "float_table", bag, Float.class); DatabaseUtil.createBagTable(db, con, "double_table", bag, Double.class); DatabaseUtil.createBagTable(db, con, "string_table", bag, String.class); DatabaseUtil.createBagTable(db, con, "boolean_table", bag, Boolean.class); DatabaseUtil.createBagTable(db, con, "date_table", bag, Date.class); DatabaseUtil.createBagTable(db, con, "intermineobject_table", bag, InterMineObject.class); DatabaseUtil.createBagTable(db, con, "employee_table", bag, Employee.class); Statement s = con.createStatement(); ResultSet r = s.executeQuery("SELECT value FROM integer_table"); Set result = new HashSet(); while (r.next()) { result.add(r.getObject(1)); } Set expected = new HashSet(); expected.add(new Integer(-10000)); expected.add(new Integer(0)); expected.add(new Integer(10000)); assertEquals(expected, result); r = s.executeQuery("SELECT value FROM long_table"); result = new HashSet(); while (r.next()) { result.add(r.getObject(1)); } expected = new HashSet(); expected.add(new Long(-10000)); expected.add(new Long(0)); expected.add(new Long(10000)); assertEquals(expected, result); r = s.executeQuery("SELECT value FROM short_table"); result = new HashSet(); while (r.next()) { result.add(r.getObject(1)); } expected = new HashSet(); expected.add(new Short((short) -10000)); expected.add(new Short((short) 0)); expected.add(new Short((short) 10000)); assertEquals(expected, result); r = s.executeQuery("SELECT value FROM double_table"); result = new HashSet(); while (r.next()) { result.add(r.getObject(1)); } expected = new HashSet(); expected.add(new Double(-10000.0)); expected.add(new Double(0.)); expected.add(new Double(10000.0)); assertEquals(expected, result); r = s.executeQuery("SELECT value FROM float_table"); result = new HashSet(); while (r.next()) { result.add(r.getObject(1)); } expected = new HashSet(); expected.add(new Float(-10000.0)); expected.add(new Float(0.)); expected.add(new Float(10000.0)); assertEquals(expected, result); r = s.executeQuery("SELECT value FROM string_table"); result = new HashSet(); while (r.next()) { result.add(r.getObject(1)); } expected = new HashSet(); expected.add(new String()); expected.add(new String("a String with spaces")); expected.add(new String("123456")); expected.add(new String("123456.7")); assertEquals(expected, result); r = s.executeQuery("SELECT value FROM boolean_table"); result = new HashSet(); while (r.next()) { result.add(r.getObject(1)); } expected = new HashSet(); expected.add(new Boolean(true)); expected.add(new Boolean(false)); assertEquals(expected, result); r = s.executeQuery("SELECT value FROM date_table"); result = new HashSet(); while (r.next()) { result.add(r.getObject(1)); } expected = new HashSet(); expected.add(new Long(999999)); expected.add(new Long(100)); assertEquals(expected, result); r = s.executeQuery("SELECT value FROM intermineobject_table"); result = new HashSet(); while (r.next()) { result.add(r.getObject(1)); } expected = new HashSet(); expected.add(employee.getId()); expected.add(manager.getId()); expected.add(company.getId()); assertEquals(expected, result); r = s.executeQuery("SELECT value FROM employee_table"); result = new HashSet(); while (r.next()) { result.add(r.getObject(1)); } expected = new HashSet(); expected.add(employee.getId()); expected.add(manager.getId()); assertEquals(expected, result); } }
intermine/src/test/org/intermine/util/DatabaseUtilTest.java
package org.intermine.util; /* * Copyright (C) 2002-2004 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import junit.framework.TestCase; import java.sql.Connection; import java.sql.SQLException; import java.util.Arrays; import java.util.Set; import java.util.HashSet; import org.intermine.sql.DatabaseFactory; import org.intermine.metadata.Model; import org.intermine.metadata.ClassDescriptor; import org.intermine.metadata.FieldDescriptor; import org.intermine.metadata.AttributeDescriptor; import org.intermine.metadata.ReferenceDescriptor; import org.intermine.metadata.CollectionDescriptor; public class DatabaseUtilTest extends TestCase { private Connection con; private String uri = "http://www.intermine.org/model/testmodel"; public DatabaseUtilTest(String arg1) { super(arg1); } public void setUp() throws Exception { con = DatabaseFactory.getDatabase("db.unittest").getConnection(); } public void tearDown() throws Exception { con.close(); } protected void createTable() throws Exception { try { dropTable(); } catch (SQLException e) { con.rollback(); } con.createStatement().execute("CREATE TABLE table1(col1 int)"); con.commit(); } protected void dropTable() throws Exception { con.createStatement().execute("DROP TABLE table1"); con.commit(); } public void testTableExistsNullConnection() throws Exception { try { DatabaseUtil.tableExists(null, "table1"); fail("Expected: NullPointerException"); } catch (NullPointerException e) { } } public void testTableExistsNullTable() throws Exception { try { DatabaseUtil.tableExists(con, null); fail("Expected: NullPointerException"); } catch (NullPointerException e) { } } public void testTableExists() throws Exception { synchronized (con) { createTable(); assertTrue(DatabaseUtil.tableExists(con, "table1")); dropTable(); } } public void testTableNotExists() throws Exception { synchronized (con) { try { con.createStatement().execute("DROP TABLE table2"); con.commit(); } catch (SQLException e) { con.rollback(); } createTable(); assertTrue(!(DatabaseUtil.tableExists(con, "table2"))); dropTable(); } } public void testGetTableNameOne() throws Exception { ClassDescriptor cld = new ClassDescriptor("Class1", null, false, new HashSet(), new HashSet(), new HashSet()); Model model1 = new Model("test1", uri, new HashSet(Arrays.asList(new Object[] {cld}))); assertEquals("Class1", DatabaseUtil.getTableName(cld)); } public void testGetTableNameTwo() throws Exception { ClassDescriptor cld = new ClassDescriptor("Array", null, false, new HashSet(), new HashSet(), new HashSet()); Model model1 = new Model("test1", uri, new HashSet(Arrays.asList(new Object[] {cld}))); assertEquals("intermine_Array", DatabaseUtil.getTableName(cld)); } public void testGetColumnName() throws Exception { FieldDescriptor attr = new AttributeDescriptor("attr1", "int"); assertEquals(DatabaseUtil.generateSqlCompatibleName("attr1"), DatabaseUtil.getColumnName(attr)); } public void testGetIndirectionTableNameRef() throws Exception { CollectionDescriptor col1 = new CollectionDescriptor("col1", "Class2", "ref1", false); Set cols = new HashSet(Arrays.asList(new Object[] {col1})); ClassDescriptor cld1 = new ClassDescriptor("Class1", null, false, new HashSet(), new HashSet(), cols); ReferenceDescriptor ref1 = new ReferenceDescriptor("ref1", "Class1", null); Set refs = new HashSet(Arrays.asList(new Object[] {ref1})); ClassDescriptor cld2 = new ClassDescriptor("Class2", null, false, new HashSet(), refs, new HashSet()); Set clds = new HashSet(Arrays.asList(new Object[] {cld1, cld2})); Model model = new Model("test", uri, clds); try { DatabaseUtil.getIndirectionTableName(col1); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { } } public void testGetIndirectionTableNameNull() throws Exception { CollectionDescriptor col1 = new CollectionDescriptor("col1", "Class2", null, false); Set cols = new HashSet(Arrays.asList(new Object[] {col1})); ClassDescriptor cld1 = new ClassDescriptor("Class1", null, false, new HashSet(), new HashSet(), cols); ClassDescriptor cld2 = new ClassDescriptor("Class2", null, false, new HashSet(), new HashSet(), new HashSet()); Set clds = new HashSet(Arrays.asList(new Object[] {cld1, cld2})); Model model = new Model("test", uri, clds); assertEquals("Class1Col1", DatabaseUtil.getIndirectionTableName(col1)); assertEquals("Col1", DatabaseUtil.getInwardIndirectionColumnName(col1)); assertEquals("Class1", DatabaseUtil.getOutwardIndirectionColumnName(col1)); } public void testGetIndirectionTableNameCol() throws Exception { CollectionDescriptor col1 = new CollectionDescriptor("col1", "Class2", "col2", false); Set cols = new HashSet(Arrays.asList(new Object[] {col1})); ClassDescriptor cld1 = new ClassDescriptor("Class1", null, false, new HashSet(), new HashSet(), cols); CollectionDescriptor col2 = new CollectionDescriptor("col2", "Class1", "col1", false); cols = new HashSet(Arrays.asList(new Object[] {col2})); ClassDescriptor cld2 = new ClassDescriptor("Class2", null, false, new HashSet(), new HashSet(), cols); Set clds = new HashSet(Arrays.asList(new Object[] {cld1, cld2})); Model model = new Model("test", uri, clds); assertEquals("Col1Col2", DatabaseUtil.getIndirectionTableName(col1)); assertEquals("Col1", DatabaseUtil.getInwardIndirectionColumnName(col1)); assertEquals("Col2", DatabaseUtil.getOutwardIndirectionColumnName(col1)); } public void testGenerateSqlCompatibleName() throws Exception { assertEquals("intermine_end", DatabaseUtil.generateSqlCompatibleName("end")); assertEquals("intermine_intermine_end", DatabaseUtil.generateSqlCompatibleName("intermine_end")); assertEquals("id", DatabaseUtil.generateSqlCompatibleName("id")); assertEquals("index", DatabaseUtil.generateSqlCompatibleName("index")); assertEquals("intermine_order", DatabaseUtil.generateSqlCompatibleName("order")); assertEquals("intermine_full", DatabaseUtil.generateSqlCompatibleName("full")); assertEquals("intermine_offset", DatabaseUtil.generateSqlCompatibleName("offset")); assertEquals("some_string", DatabaseUtil.generateSqlCompatibleName("some_string")); try { DatabaseUtil.generateSqlCompatibleName(null); fail("Expected NullPointerException"); } catch (NullPointerException e) { } } }
Added testCreateBagTable() to test DatabaseUtil.createBagTable().
intermine/src/test/org/intermine/util/DatabaseUtilTest.java
Added testCreateBagTable() to test DatabaseUtil.createBagTable().
<ide><path>ntermine/src/test/org/intermine/util/DatabaseUtilTest.java <ide> import junit.framework.TestCase; <ide> <ide> import java.sql.Connection; <add>import java.sql.Statement; <add>import java.sql.ResultSet; <ide> import java.sql.SQLException; <ide> import java.util.Arrays; <ide> import java.util.Set; <add>import java.util.Collection; <add>import java.util.Collections; <ide> import java.util.HashSet; <add>import java.util.Date; <add>import java.math.BigDecimal; <add>import java.math.BigInteger; <ide> <ide> import org.intermine.sql.DatabaseFactory; <ide> import org.intermine.metadata.Model; <ide> import org.intermine.metadata.AttributeDescriptor; <ide> import org.intermine.metadata.ReferenceDescriptor; <ide> import org.intermine.metadata.CollectionDescriptor; <add>import org.intermine.sql.Database; <add> <add>import org.intermine.model.testmodel.*; <add>import org.intermine.model.InterMineObject; <ide> <ide> public class DatabaseUtilTest extends TestCase <ide> { <ide> private Connection con; <add> private Database db; <ide> private String uri = "http://www.intermine.org/model/testmodel"; <ide> <ide> public DatabaseUtilTest(String arg1) { <ide> } <ide> <ide> public void setUp() throws Exception { <del> con = DatabaseFactory.getDatabase("db.unittest").getConnection(); <add> db = DatabaseFactory.getDatabase("db.unittest"); <add> con = db.getConnection(); <ide> } <ide> <ide> public void tearDown() throws Exception { <ide> } catch (NullPointerException e) { <ide> } <ide> } <add> <add> public void testCreateBagTable() throws Exception { <add> Collection bag = new HashSet(); <add> <add> bag.add(new Integer(-10000)); <add> bag.add(new Integer(0)); <add> bag.add(new Integer(10000)); <add> bag.add(new Long(-10000)); <add> bag.add(new Long(0)); <add> bag.add(new Long(10000)); <add> bag.add(new Short((short) -10000)); <add> bag.add(new Short((short) 0)); <add> bag.add(new Short((short) 10000)); <add> bag.add(new BigDecimal(-10000.0)); <add> bag.add(new BigDecimal(0.0)); <add> bag.add(new BigDecimal(10000.0)); <add> bag.add(new Float(-10000.0)); <add> bag.add(new Float(0.0)); <add> bag.add(new Float(10000.0)); <add> bag.add(new Double(-10000.0)); <add> bag.add(new Double(0.0)); <add> bag.add(new Double(10000.0)); <add> bag.add(new String()); <add> bag.add(new String("a String with spaces")); <add> bag.add(new String("123456")); <add> bag.add(new String("123456.7")); <add> bag.add(new Boolean(true)); <add> bag.add(new Boolean(false)); <add> bag.add(new Date(999999)); <add> bag.add(new Date(100)); <add> Employee employee = (Employee) DynamicUtil.createObject(Collections.singleton(Employee.class)); <add> employee.setId(new Integer(5000)); <add> bag.add(employee); <add> Manager manager = (Manager) DynamicUtil.createObject(Collections.singleton(Manager.class)); <add> manager.setId(new Integer(5001)); <add> bag.add(manager); <add> Company company = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); <add> company.setId(new Integer(6000)); <add> bag.add(company); <add> <add> // this shouldn't appear in any table <add> bag.add(BigInteger.ONE); <add> <add> DatabaseUtil.createBagTable(db, con, "integer_table", bag, Integer.class); <add> DatabaseUtil.createBagTable(db, con, "long_table", bag, Long.class); <add> DatabaseUtil.createBagTable(db, con, "short_table", bag, Short.class); <add> DatabaseUtil.createBagTable(db, con, "bigdecimal_table", bag, BigDecimal.class); <add> DatabaseUtil.createBagTable(db, con, "float_table", bag, Float.class); <add> DatabaseUtil.createBagTable(db, con, "double_table", bag, Double.class); <add> DatabaseUtil.createBagTable(db, con, "string_table", bag, String.class); <add> DatabaseUtil.createBagTable(db, con, "boolean_table", bag, Boolean.class); <add> DatabaseUtil.createBagTable(db, con, "date_table", bag, Date.class); <add> DatabaseUtil.createBagTable(db, con, "intermineobject_table", bag, InterMineObject.class); <add> DatabaseUtil.createBagTable(db, con, "employee_table", bag, Employee.class); <add> <add> <add> Statement s = con.createStatement(); <add> ResultSet r = s.executeQuery("SELECT value FROM integer_table"); <add> Set result = new HashSet(); <add> while (r.next()) { <add> result.add(r.getObject(1)); <add> } <add> <add> Set expected = new HashSet(); <add> expected.add(new Integer(-10000)); <add> expected.add(new Integer(0)); <add> expected.add(new Integer(10000)); <add> <add> assertEquals(expected, result); <add> <add> r = s.executeQuery("SELECT value FROM long_table"); <add> result = new HashSet(); <add> while (r.next()) { <add> result.add(r.getObject(1)); <add> } <add> <add> expected = new HashSet(); <add> expected.add(new Long(-10000)); <add> expected.add(new Long(0)); <add> expected.add(new Long(10000)); <add> <add> assertEquals(expected, result); <add> <add> r = s.executeQuery("SELECT value FROM short_table"); <add> result = new HashSet(); <add> while (r.next()) { <add> result.add(r.getObject(1)); <add> } <add> <add> expected = new HashSet(); <add> expected.add(new Short((short) -10000)); <add> expected.add(new Short((short) 0)); <add> expected.add(new Short((short) 10000)); <add> <add> assertEquals(expected, result); <add> <add> r = s.executeQuery("SELECT value FROM double_table"); <add> result = new HashSet(); <add> while (r.next()) { <add> result.add(r.getObject(1)); <add> } <add> <add> expected = new HashSet(); <add> expected.add(new Double(-10000.0)); <add> expected.add(new Double(0.)); <add> expected.add(new Double(10000.0)); <add> <add> assertEquals(expected, result); <add> <add> r = s.executeQuery("SELECT value FROM float_table"); <add> result = new HashSet(); <add> while (r.next()) { <add> result.add(r.getObject(1)); <add> } <add> <add> expected = new HashSet(); <add> expected.add(new Float(-10000.0)); <add> expected.add(new Float(0.)); <add> expected.add(new Float(10000.0)); <add> <add> assertEquals(expected, result); <add> <add> r = s.executeQuery("SELECT value FROM string_table"); <add> result = new HashSet(); <add> while (r.next()) { <add> result.add(r.getObject(1)); <add> } <add> <add> expected = new HashSet(); <add> expected.add(new String()); <add> expected.add(new String("a String with spaces")); <add> expected.add(new String("123456")); <add> expected.add(new String("123456.7")); <add> <add> assertEquals(expected, result); <add> <add> r = s.executeQuery("SELECT value FROM boolean_table"); <add> result = new HashSet(); <add> while (r.next()) { <add> result.add(r.getObject(1)); <add> } <add> <add> expected = new HashSet(); <add> expected.add(new Boolean(true)); <add> expected.add(new Boolean(false)); <add> <add> assertEquals(expected, result); <add> <add> r = s.executeQuery("SELECT value FROM date_table"); <add> result = new HashSet(); <add> while (r.next()) { <add> result.add(r.getObject(1)); <add> } <add> <add> expected = new HashSet(); <add> expected.add(new Long(999999)); <add> expected.add(new Long(100)); <add> <add> assertEquals(expected, result); <add> <add> r = s.executeQuery("SELECT value FROM intermineobject_table"); <add> result = new HashSet(); <add> while (r.next()) { <add> result.add(r.getObject(1)); <add> } <add> <add> expected = new HashSet(); <add> expected.add(employee.getId()); <add> expected.add(manager.getId()); <add> expected.add(company.getId()); <add> <add> assertEquals(expected, result); <add> <add> r = s.executeQuery("SELECT value FROM employee_table"); <add> result = new HashSet(); <add> while (r.next()) { <add> result.add(r.getObject(1)); <add> } <add> <add> expected = new HashSet(); <add> expected.add(employee.getId()); <add> expected.add(manager.getId()); <add> <add> assertEquals(expected, result); <add> } <ide> }
JavaScript
bsd-3-clause
c692560c9814d4da0f301c739e9f8197973256b7
0
adilyalcin/Keshif
/********************************* keshif library Copyright (c) 2014-2016, University of Maryland All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Maryland 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 MICHAEL BOSTOCK 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. ************************************ */ // load google visualization library only if google scripts were included if(typeof google !== 'undefined'){ google.load('visualization', '1', {'packages': []}); } /*! * Bowser - a browser detector * https://github.com/ded/bowser * MIT License | (c) Dustin Diaz 2015 */ !function(e,t){typeof module!="undefined"&&module.exports?module.exports=t():typeof define=="function"&&define.amd?define(t):this[e]=t()}("bowser",function(){function t(t){function n(e){var n=t.match(e);return n&&n.length>1&&n[1]||""}function r(e){var n=t.match(e);return n&&n.length>1&&n[2]||""}var i=n(/(ipod|iphone|ipad)/i).toLowerCase(),s=/like android/i.test(t),o=!s&&/android/i.test(t),u=/CrOS/.test(t),a=n(/edge\/(\d+(\.\d+)?)/i),f=n(/version\/(\d+(\.\d+)?)/i),l=/tablet/i.test(t),c=!l&&/[^-]mobi/i.test(t),h;/opera|opr/i.test(t)?h={name:"Opera",opera:e,version:f||n(/(?:opera|opr)[\s\/](\d+(\.\d+)?)/i)}:/yabrowser/i.test(t)?h={name:"Yandex Browser",yandexbrowser:e,version:f||n(/(?:yabrowser)[\s\/](\d+(\.\d+)?)/i)}:/windows phone/i.test(t)?(h={name:"Windows Phone",windowsphone:e},a?(h.msedge=e,h.version=a):(h.msie=e,h.version=n(/iemobile\/(\d+(\.\d+)?)/i))):/msie|trident/i.test(t)?h={name:"Internet Explorer",msie:e,version:n(/(?:msie |rv:)(\d+(\.\d+)?)/i)}:u?h={name:"Chrome",chromeBook:e,chrome:e,version:n(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i)}:/chrome.+? edge/i.test(t)?h={name:"Microsoft Edge",msedge:e,version:a}:/chrome|crios|crmo/i.test(t)?h={name:"Chrome",chrome:e,version:n(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i)}:i?(h={name:i=="iphone"?"iPhone":i=="ipad"?"iPad":"iPod"},f&&(h.version=f)):/sailfish/i.test(t)?h={name:"Sailfish",sailfish:e,version:n(/sailfish\s?browser\/(\d+(\.\d+)?)/i)}:/seamonkey\//i.test(t)?h={name:"SeaMonkey",seamonkey:e,version:n(/seamonkey\/(\d+(\.\d+)?)/i)}:/firefox|iceweasel/i.test(t)?(h={name:"Firefox",firefox:e,version:n(/(?:firefox|iceweasel)[ \/](\d+(\.\d+)?)/i)},/\((mobile|tablet);[^\)]*rv:[\d\.]+\)/i.test(t)&&(h.firefoxos=e)):/silk/i.test(t)?h={name:"Amazon Silk",silk:e,version:n(/silk\/(\d+(\.\d+)?)/i)}:o?h={name:"Android",version:f}:/phantom/i.test(t)?h={name:"PhantomJS",phantom:e,version:n(/phantomjs\/(\d+(\.\d+)?)/i)}:/blackberry|\bbb\d+/i.test(t)||/rim\stablet/i.test(t)?h={name:"BlackBerry",blackberry:e,version:f||n(/blackberry[\d]+\/(\d+(\.\d+)?)/i)}:/(web|hpw)os/i.test(t)?(h={name:"WebOS",webos:e,version:f||n(/w(?:eb)?osbrowser\/(\d+(\.\d+)?)/i)},/touchpad\//i.test(t)&&(h.touchpad=e)):/bada/i.test(t)?h={name:"Bada",bada:e,version:n(/dolfin\/(\d+(\.\d+)?)/i)}:/tizen/i.test(t)?h={name:"Tizen",tizen:e,version:n(/(?:tizen\s?)?browser\/(\d+(\.\d+)?)/i)||f}:/safari/i.test(t)?h={name:"Safari",safari:e,version:f}:h={name:n(/^(.*)\/(.*) /),version:r(/^(.*)\/(.*) /)},!h.msedge&&/(apple)?webkit/i.test(t)?(h.name=h.name||"Webkit",h.webkit=e,!h.version&&f&&(h.version=f)):!h.opera&&/gecko\//i.test(t)&&(h.name=h.name||"Gecko",h.gecko=e,h.version=h.version||n(/gecko\/(\d+(\.\d+)?)/i)),!h.msedge&&(o||h.silk)?h.android=e:i&&(h[i]=e,h.ios=e);var p="";h.windowsphone?p=n(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i):i?(p=n(/os (\d+([_\s]\d+)*) like mac os x/i),p=p.replace(/[_\s]/g,".")):o?p=n(/android[ \/-](\d+(\.\d+)*)/i):h.webos?p=n(/(?:web|hpw)os\/(\d+(\.\d+)*)/i):h.blackberry?p=n(/rim\stablet\sos\s(\d+(\.\d+)*)/i):h.bada?p=n(/bada\/(\d+(\.\d+)*)/i):h.tizen&&(p=n(/tizen[\/\s](\d+(\.\d+)*)/i)),p&&(h.osversion=p);var d=p.split(".")[0];if(l||i=="ipad"||o&&(d==3||d==4&&!c)||h.silk)h.tablet=e;else if(c||i=="iphone"||i=="ipod"||o||h.blackberry||h.webos||h.bada)h.mobile=e;return h.msedge||h.msie&&h.version>=10||h.yandexbrowser&&h.version>=15||h.chrome&&h.version>=20||h.firefox&&h.version>=20||h.safari&&h.version>=6||h.opera&&h.version>=10||h.ios&&h.osversion&&h.osversion.split(".")[0]>=6||h.blackberry&&h.version>=10.1?h.a=e:h.msie&&h.version<10||h.chrome&&h.version<20||h.firefox&&h.version<20||h.safari&&h.version<6||h.opera&&h.version<10||h.ios&&h.osversion&&h.osversion.split(".")[0]<6?h.c=e:h.x=e,h}var e=!0,n=t(typeof navigator!="undefined"?navigator.userAgent:"");return n.test=function(e){for(var t=0;t<e.length;++t){var r=e[t];if(typeof r=="string"&&r in n)return!0}return!1},n._detect=t,n}) // kshf namespace var kshf = { surrogateCtor: function() {}, // http://stackoverflow.com/questions/4152931/javascript-inheritance-call-super-constructor-or-use-prototype-chain extendClass: function(base, sub) { // Copy the prototype from the base to setup inheritance this.surrogateCtor.prototype = base.prototype; // Tricky huh? sub.prototype = new this.surrogateCtor(); // Remember the constructor property was set wrong, let's fix it sub.prototype.constructor = sub; }, maxVisibleItems_Default: 100, scrollWidth: 19, attribPanelWidth: 220, previewTimeoutMS: 250, map: { //"http://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png", //"http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", tileTemplate: 'http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a>', }, browsers: [], dt: {}, dt_id: {}, lang: { en: { ModifyBrowser: "Modify browser", OpenDataSource: "Open data source", ShowInfoCredits: "Show info &amp; credits", ShowFullscreen: "Fullscreen", RemoveFilter: "Remove filter", RemoveAllFilters: "Remove all filters", MinimizeSummary: "Close summary", OpenSummary: "Open summary", MaximizeSummary: "Maximize summary", RemoveSummary: "Remove summary", ReverseOrder: "Reverse order", Reorder: "Reorder", ShowMoreInfo: "Show more info", Percentiles: "Percentiles", LockToCompare: "Lock to compare", Unlock: "Unlock", Search: "Search", CreatingBrowser: "Creating Keshif Browser", Rows: "Rows", More: "More", LoadingData: "Loading data sources", ShowAll: "Show All", ScrollToTop: "Top", Absolute: "Absolute", Percent: "Percent", Relative: "Relative", Width: "Length", DragToFilter: "Drag to filter", And: "And", Or: "Or", Not: "Not", EditTitle: "Rename", ResizeBrowser: "Resize browser", RemoveRecords: "Remove record view", EditFormula: "Edit formula", NoData: "(no data)", ZoomToFit: "Zoom to fit" }, tr: { ModifyBrowser: "Tarayıcıyı düzenle", OpenDataSource: "Veri kaynağını aç", ShowInfoCredits: "Bilgi", ShowFullscreen: "Tam ekran", RemoveFilter: "Filtreyi kaldır", RemoveAllFilters: "Tüm filtreleri kaldır", MinimizeSummary: "Özeti ufalt", OpenSummary: "Özeti aç", MaximizeSummary: "Özeti büyüt", RemoveSummary: "Özeti kaldır", ReverseOrder: "Ters sırala", Reorder: "Yeniden sırala", ShowMoreInfo: "Daha fazla bilgi", Percentiles: "Yüzdeler", LockToCompare: "Kilitle ve karşılaştır", Unlock: "Kilidi kaldır", Search: "Ara", LoadingData: "Veriler yükleniyor...", CreatingBrowser: "Keşif arayüzü oluşturuluyor...", Rows: "Satır", More: "Daha", ShowAll: "Hepsi", ScrollToTop: "Yukarı", Absolute: "Net", Percent: "Yüzde", Relative: "Görece", Width: "Genişlik", DragToFilter: "Sürükle ve filtre", And: "Ve", Or: "Veya", Not: "Değil", EditTitle: "Değiştir", ResizeBrowser: "Boyutlandır", RemoveRecords: "Kayıtları kaldır", EditFormula: "Formülü değiştir", NoData: "(verisiz)", ZoomToFit: "Oto-yakınlaş" }, fr: { ModifyBrowser: "Modifier le navigateur", OpenDataSource: "Ouvrir la source de données", ShowInfoCredits: "Afficher les credits", RemoveFilter: "Supprimer le filtre", RemoveAllFilters: "Supprimer tous les filtres", MinimizeSummary: "Réduire le sommaire", OpenSummary: "Ouvrir le sommaire", MaximizeSummary: "Agrandir le sommaire", RemoveSummary: "??", ReverseOrder: "Inverser l'ordre", Reorder: "Réorganiser", ShowMoreInfo: "Plus d'informations", Percentiles: "Percentiles", LockToCompare: "Bloquer pour comparer", Unlock: "Débloquer", Search: "Rechercher", CreatingBrowser: "Création du navigateur", Rows: "Lignes", More: "Plus", LoadingData: "Chargement des données", ShowAll: "Supprimer les filtres", ScrollToTop: "Début", Absolute: "Absolue", Percent: "Pourcentage", Relative: "Relative", Width: "Largeur", DragToFilter: "??", And: "??", Or: "??", Not: "??", EditFormula: "Edit Formula", NoData: "(no data)", ZoomToFit: "Zoom to fit" }, cur: null // Will be set to en if not defined before a browser is loaded }, LOG: { // Note: id parameter is integer alwats, info is string CONFIG : 1, // Filtering state // param: resultCt, selected(selected # of attribs, sep by x), filtered(filtered filter ids) FILTER_ADD : 10, FILTER_CLEAR : 11, // Filtering extra information, send in addition to filtering state messages above FILTER_CLEAR_ALL : 12, // param: - FILTER_ATTR_ADD_AND : 13, // param: id (filterID), info (attribID) FILTER_ATTR_ADD_OR : 14, // param: id (filterID), info (attribID) FILTER_ATTR_ADD_ONE : 15, FILTER_ATTR_ADD_OR_ALL : 16, // param: id (filterID) FILTER_ATTR_ADD_NOT : 17, // param: id (filterID), info (attribID) FILTER_ATTR_EXACT : 18, // param: id (filterID), info (attribID) FILTER_ATTR_UNSELECT : 19, // param: id (filterID), info (attribID) FILTER_TEXTSEARCH : 20, // param: id (filterID), info (query text) FILTER_INTRVL_HANDLE : 21, // param: id (filterID) (TODO: Include range) FILTER_INTRVL_BIN : 22, // param: id (filterID) FILTER_CLEAR_X : 23, // param: id (filterID) FILTER_CLEAR_CRUMB : 24, // param: id (filterID) FILTER_PREVIEW : 25, // param: id (filterID), info (attribID for cat, histogram range (AxB) for interval) // Facet specific non-filtering interactions FACET_COLLAPSE : 40, // param: id (facetID) FACET_SHOW : 41, // param: id (facetID) FACET_SORT : 42, // param: id (facetID), info (sortID) FACET_SCROLL_TOP : 43, // param: id (facetID) FACET_SCROLL_MORE : 44, // param: id (facetID) // List specific interactions LIST_SORT : 50, // param: info (sortID) LIST_SCROLL_TOP : 51, // param: - LIST_SHOWMORE : 52, // param: info (itemCount) LIST_SORT_INV : 53, // param: - // Item specific interactions ITEM_DETAIL_ON : 60, // param: info (itemID) ITEM_DETAIL_OFF : 61, // param: info (itemID) // Generic interactions DATASOURCE : 70, // param: - INFOBOX : 71, // param: - CLOSEPAGE : 72, // param: - BARCHARTWIDTH : 73, // param: info (width) RESIZE : 74, // param: - }, Util: { sortFunc_List_String: function(a, b){ return a.localeCompare(b); }, sortFunc_List_Date: function(a, b){ if(a===null) return -1; if(b===null) return 1; return b.getTime() - a.getTime(); // recent first }, sortFunc_List_Number: function(a, b){ return b - a; }, /** Given a list of columns which hold multiple IDs, breaks them into an array */ cellToArray: function(dt, columns, splitExpr){ if(splitExpr===undefined){ splitExpr = /\b\s+/; } var j; dt.forEach(function(p){ p = p.data; columns.forEach(function(column){ var list = p[column]; if(list===null) return; if(typeof list==="number") { p[column] = ""+list; return; } var list2 = list.split(splitExpr); list = []; // remove empty "" records for(j=0; j<list2.length; j++){ list2[j] = list2[j].trim(); if(list2[j]!=="") list.push(list2[j]); } p[column] = list; }); }); }, baseMeasureFormat: d3.format(".2s"), /** You should only display at most 3 digits + k/m/etc */ formatForItemCount: function(n){ if(n<1000) { return n; } return kshf.Util.baseMeasureFormat(n); if(n<1000000) { // 1,000-999,999 var thousands=n/1000; if(thousands<10){ return (Math.floor(n/100)/10)+"k"; } return Math.floor(thousands)+"k"; } if(n<1000000000) return Math.floor(n/1000000)+"m"; return n; }, nearestYear: function(d){ var dr = new Date(Date.UTC(d.getUTCFullYear(),0,1)); if(d.getUTCMonth()>6) dr.setUTCFullYear(dr.getUTCFullYear()+1); return dr; }, nearestMonth: function(d){ var dr = new Date(Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),1)); if(d.getUTCDate()>15) dr.setUTCMonth(dr.getUTCMonth()+1); return dr; }, nearestDay: function(d){ var dr = new Date(Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate())); if(d.getUTCHours()>12) dr.setUTCDate(dr.getUTCDate()+1); return dr; }, nearestHour: function(d){ }, nearestMinute: function(d){ }, clearArray: function(arr){ while (arr.length > 0) { arr.pop(); } }, ignoreScrollEvents: false, scrollToPos_do: function(scrollDom, targetPos){ kshf.Util.ignoreScrollEvents = true; // scroll to top var startTime = null; var scrollInit = scrollDom.scrollTop; var easeFunc = d3.ease('cubic-in-out'); var scrollTime = 500; var animateToTop = function(timestamp){ var progress; if(startTime===null) startTime = timestamp; // complete animation in 500 ms progress = (timestamp - startTime)/scrollTime; var m=easeFunc(progress); scrollDom.scrollTop = (1-m)*scrollInit+m*targetPos; if(scrollDom.scrollTop!==targetPos){ window.requestAnimationFrame(animateToTop); } else { kshf.Util.ignoreScrollEvents = false; } }; window.requestAnimationFrame(animateToTop); }, toProperCase: function(str){ return str.toLowerCase().replace(/\b[a-z]/g,function(f){return f.toUpperCase()}); }, setTransform: function(dom,transform){ dom.style.webkitTransform = transform; dom.style.MozTransform = transform; dom.style.msTransform = transform; dom.style.OTransform = transform; dom.style.transform = transform; }, // http://stackoverflow.com/questions/13627308/add-st-nd-rd-and-th-ordinal-suffix-to-a-number ordinal_suffix_of: function(i) { var j = i % 10, k = i % 100; if (j == 1 && k != 11) { return i + "st"; } if (j == 2 && k != 12) { return i + "nd"; } if (j == 3 && k != 13) { return i + "rd"; } return i + "th"; }, }, style: { color_chart_background_highlight: "rgb(194, 146, 124)" }, fontLoaded: false, loadFont: function(){ if(this.fontLoaded===true) return; WebFontConfig = { google: { families: [ 'Roboto:400,500,300,100,700:latin', 'Montserrat:400,700:latin' ] } }; var wf = document.createElement('script'); wf.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js'; wf.type = 'text/javascript'; wf.async = 'true'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(wf, s); this.fontLoaded = true; }, handleResize: function(){ this.browsers.forEach(function(browser){ browser.updateLayout(); }); }, activeTipsy: undefined, colorScale : { converge: [ d3.rgb('#ffffd9'), d3.rgb('#edf8b1'), d3.rgb('#c7e9b4'), d3.rgb('#7fcdbb'), d3.rgb('#41b6c4'), d3.rgb('#1d91c0'), d3.rgb('#225ea8'), d3.rgb('#253494'), d3.rgb('#081d58')], diverge: [ d3.rgb('#8c510a'), d3.rgb('#bf812d'), d3.rgb('#dfc27d'), d3.rgb('#f6e8c3'), d3.rgb('#f5f5f5'), d3.rgb('#c7eae5'), d3.rgb('#80cdc1'), d3.rgb('#35978f'), d3.rgb('#01665e')] }, /* -- */ intersects: function(d3bound, leafletbound){ // d3bound: [​[left, bottom], [right, top]​] // leafletBound._southWest.lat // leafletBound._southWest.long // leafletBound._northEast.lat // leafletBound._northEast.long if(d3bound[0][0]>leafletbound._northEast.lng) return false; if(d3bound[0][1]>leafletbound._northEast.lat) return false; if(d3bound[1][0]<leafletbound._southWest.lng) return false; if(d3bound[1][1]<leafletbound._southWest.lat) return false; return true; }, /** -- */ gistPublic: true, getGistLogin: function(){ if(this.githubToken===undefined) return; $.ajax( 'https://api.github.com/user', { method: "GET", async: true, dataType: "json", headers: {Authorization: "token "+kshf.githubToken}, success: function(response){ kshf.gistLogin = response.login; } } ); }, /** -- TEMP! Not a good design here! TODO change */ wrapLongitude: 170 }; // tipsy, facebook style tooltips for jquery // Modified / simplified version for internal Keshif use // version 1.0.0a // (c) 2008-2010 jason frame [[email protected]] // released under the MIT license function Tipsy(element, options) { this.jq_element = $(element); this.options = $.extend({}, { className: null, delayOut: 0, gravity: 'n', offset: 0, offset_x: 0, offset_y: 0, opacity: 1 }, options ); }; Tipsy.prototype = { show: function() { var maybeCall = function(thing, ctx) { return (typeof thing == 'function') ? (thing.call(ctx)) : thing; }; // hide active Tipsy if(kshf.activeTipsy) kshf.activeTipsy.hide(); kshf.activeTipsy = this; var title = this.getTitle(); if(!title) return; var jq_tip = this.tip(); jq_tip.find('.tipsy-inner')['html'](title); jq_tip[0].className = 'tipsy'; // reset classname in case of dynamic gravity jq_tip.remove().css({top: 0, left: 0, visibility: 'hidden', display: 'block'}).prependTo(document.body); var pos = $.extend({}, this.jq_element.offset(), { width: this.jq_element[0].offsetWidth, height: this.jq_element[0].offsetHeight }); var actualWidth = jq_tip[0].offsetWidth, actualHeight = jq_tip[0].offsetHeight, gravity = maybeCall(this.options.gravity, this.jq_element[0]); this.tipWidth = actualWidth; this.tipHeight = actualHeight; var tp; switch (gravity.charAt(0)) { case 'n': tp = {top: pos.top + pos.height + this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2}; break; case 's': tp = {top: pos.top - actualHeight - this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2}; break; case 'e': tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth - this.options.offset}; break; case 'w': tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width + this.options.offset}; break; } tp.top+=this.options.offset_y; tp.left+=this.options.offset_x; if (gravity.length == 2) { if (gravity.charAt(1) == 'w') { tp.left = pos.left + pos.width / 2 - 15; } else { tp.left = pos.left + pos.width / 2 - actualWidth + 15; } } jq_tip.css(tp).addClass('tipsy-' + gravity); jq_tip.find('.tipsy-arrow')[0].className = 'tipsy-arrow tipsy-arrow-' + gravity.charAt(0); if (this.options.className) { jq_tip.addClass(maybeCall(this.options.className, this.jq_element[0])); } jq_tip.stop().css({opacity: 0, display: 'block', visibility: 'visible'}).animate({opacity: this.options.opacity},200); }, hide: function(){ kshf.activeTipsy = undefined; this.tip().stop().fadeOut(200,function() { $(this).remove(); }); }, getTitle: function() { var title, jq_e = this.jq_element, o = this.options; var title, o = this.options; if (typeof o.title == 'string') { title = o.title; } else if (typeof o.title == 'function') { title = o.title.call(jq_e[0]); } title = ('' + title).replace(/(^\s*|\s*$)/, ""); return title; }, tip: function() { if(this.jq_tip) return this.jq_tip; this.jq_tip = $('<div class="tipsy"></div>').html('<div class="tipsy-arrow"></div><div class="tipsy-inner"></div>'); this.jq_tip.data('tipsy-pointee', this.jq_element[0]); return this.jq_tip; } }; /** * @constructor */ kshf.Record = function(d, idIndex){ this.data = d; this.idIndex = idIndex; // TODO: Items don't need to have ID index, only one per table is enough?? // By default, each item is aggregated as 1 // You can modify this with a non-negative value // Note that the aggregation currently works by summation only. this.measure_Self = 1; // Wanted item / not filtered out this.isWanted = true; this.recordRank = 0; this.recordRank_pre = -1; // The data that's used for mapping this item, used as a cache. // This is accessed by filterID // Through this, you can also reach DOM of aggregates // DOM elements that this item is mapped to // - If this is a paper, it can be paper type. If this is author, it can be author affiliation. this._valueCache = []; // caching the values this item was mapped to this._aggrCache = []; this.DOM = {}; // If item is primary type, this will be set this.DOM.record = undefined; // Internal variable // If true, filter/wanted state is dirty and needs to be updated. this._filterCacheIsDirty = true; // Cacheing filter state per each summary this._filterCache = []; this.selectCompared_str = ""; this.selectCompared = {A: false, B: false, C: false}; }; kshf.Record.prototype = { /** Returns unique ID of the item. */ id: function(){ return this.data[this.idIndex]; }, /** -- */ setFilterCache: function(index,v){ if(this._filterCache[index]===v) return; this._filterCache[index] = v; this._filterCacheIsDirty = true; }, /** Updates isWanted state, and notifies all related filter attributes of the change */ updateWanted: function(){ if(!this._filterCacheIsDirty) return false; var me = this; var oldWanted = this.isWanted; this.isWanted = this._filterCache.every(function(f){ return f; }); if(this.measure_Self && this.isWanted !== oldWanted){ // There is some change that affects computation var valToAdd = (this.isWanted && !oldWanted) ? this.measure_Self /*add*/ : -this.measure_Self /*remove*/; var cntToAdd = valToAdd>0?1:-1; this._aggrCache.forEach(function(aggr){ aggr._measure.Active += valToAdd; if(valToAdd) aggr.recCnt.Active+=cntToAdd; }); } this._filterCacheIsDirty = false; return this.isWanted !== oldWanted; }, /** -- */ setRecordDetails: function(value){ this.showDetails = value; if(this.DOM.record) this.DOM.record.setAttribute('details', this.showDetails); }, /** Called on mouse-over on a primary item type */ highlightRecord: function(){ if(this.DOM.record) this.DOM.record.setAttribute("selection","onRecord"); // summaries that this item appears in this._aggrCache.forEach(function(aggr){ if(aggr.DOM.aggrGlyph) aggr.DOM.aggrGlyph.setAttribute("selection","onRecord"); if(aggr.DOM.matrixRow) aggr.DOM.matrixRow.setAttribute("selection","onRecord"); if(aggr.summary) aggr.summary.setRecordValue(this); },this); }, /** -- */ unhighlightRecord: function(){ if(this.DOM.record) this.DOM.record.removeAttribute("selection"); // summaries that this item appears in this._aggrCache.forEach(function(aggr){ aggr.unselectAggregate(); if(aggr.summary) aggr.summary.hideRecordValue(); },this); }, /** -- */ addForHighlight: function(){ if(!this.isWanted || this.highlighted) return; if(this.DOM.record) { var x = this.DOM.record; x.setAttribute("selection","highlighted"); // SVG geo area - move it to the bottom of parent so that border can be displayed nicely. // TODO: improve the conditional check! if(x.nodeName==="path") d3.select(x.parentNode.appendChild(x)); } this._aggrCache.forEach(function(aggr){ if(this.measure_Self===null ||this.measure_Self===0) return; aggr._measure.Highlighted += this.measure_Self; aggr.recCnt.Highlighted++; }, this); this.highlighted = true; }, /** -- */ remForHighlight: function(distribute){ if(!this.isWanted || !this.highlighted) return; if(this.DOM.record) this.DOM.record.removeAttribute("selection"); if(distribute) this._aggrCache.forEach(function(aggr){ if(this.measure_Self===null || this.measure_Self===0) return; aggr._measure.Highlighted -= this.measure_Self; aggr.recCnt.Highlighted--; }, this); this.highlighted = false; }, /** -- */ setCompared: function(cT){ this.selectCompared_str+=cT+" "; this.selectCompared[cT] = true; this.domCompared(); }, /** -- */ unsetCompared: function(cT){ this.selectCompared_str = this.selectCompared_str.replace(cT+" ",""); this.selectCompared[cT] = false; this.domCompared(); }, domCompared: function(){ if(!this.DOM.record) return; if(this.selectCompared_str==="") { this.DOM.record.removeAttribute("rec_compared"); } else { this.DOM.record.setAttribute("rec_compared",this.selectCompared_str); } } }; /** * @constructor */ kshf.Aggregate = function(){}; kshf.Aggregate.prototype = { /** -- */ init: function(d,idIndex){ // Items which are mapped/related to this item this.records = []; this._measure = { Active: 0, Highlighted: 0, Total: 0, Compared_A: 0, Compared_B: 0, Compared_C: 0 } this.recCnt = { Active: 0, Highlighted: 0, Total: 0, Compared_A: 0, Compared_B: 0, Compared_C: 0 } // the main data within item this.data = d; this.idIndex = idIndex; // Selection state // 1: selected for inclusion (AND) // 2: selected for inclusion (OR) // -1: selected for removal (NOT query) // 0: not selected this.selected = 0; this.DOM = {}; // If item is used as a filter (can be primary if looking at links), this will be set this.DOM.aggrGlyph = undefined; }, /** Returns unique ID of the item. */ id: function(){ return this.data[this.idIndex]; }, /** -- */ addRecord: function(record){ this.records.push(record); record._aggrCache.push(this); if(record.measure_Self===null || record.measure_Self===0) return; this._measure.Total += record.measure_Self; this.recCnt.Total++; if(record.isWanted) { this._measure.Active += record.measure_Self; this.recCnt.Active++; } }, /** -- */ measure: function(v){ if(kshf.browser.measureFunc==="Avg"){ var r=this.recCnt[v]; return (r===0) ? 0 : this._measure[v]/r ; // avoid division by zero. } return this._measure[v]; }, /** -- */ resetAggregateMeasures: function(){ this._measure = { Active: 0, Highlighted: 0, Total: 0, Compared_A: 0, Compared_B: 0, Compared_C: 0 }; this.recCnt = { Active: 0, Highlighted: 0, Total: 0, Compared_A: 0, Compared_B: 0, Compared_C: 0 }; this.records.forEach(function(record){ if(record.measure_Self===null || record.measure_Self===0) return; this._measure.Total += record.measure_Self; this.recCnt.Total++; if(record.isWanted) { this._measure.Active += record.measure_Self; this.recCnt.Active++; } },this); }, /** -- */ ratioHighlightToTotal: function(){ return this._measure.Highlighted / this._measure.Total; }, /** -- */ ratioHighlightToActive: function(){ return this._measure.Highlighted / this._measure.Active; }, /** -- */ ratioCompareToActive: function(cT){ return this._measure["Compared_"+cT] / this._measure.Active; }, /** -- */ unselectAggregate: function(){ if(this.DOM.aggrGlyph) { this.DOM.aggrGlyph.removeAttribute("selection"); this.DOM.aggrGlyph.removeAttribute("showlock"); } if(this.DOM.matrixRow) this.DOM.matrixRow.removeAttribute("selection"); }, /** -- */ selectCompare: function(cT){ if(this.DOM.aggrGlyph) this.DOM.aggrGlyph.setAttribute("compare","true"); this.compared = cT; this.records.forEach(function(record){ record.setCompared(cT); }); }, /** -- */ clearCompare: function(cT){ if(this.DOM.aggrGlyph) this.DOM.aggrGlyph.removeAttribute("compare"); this.compared = false; this.records.forEach(function(record){ record.unsetCompared(cT); }); }, /** -- */ selectHighlight: function(){ this.records.forEach(function(record){ record.addForHighlight(); }); }, /** -- */ clearHighlight: function(){ this.records.forEach(function(record){ record.remForHighlight(false); }); }, // CATEGORICAL AGGREGATES /** -- */ f_selected: function(){ return this.selected!==0; }, f_included: function(){ return this.selected>0; }, is_NONE:function(){ return this.selected===0; }, is_NOT: function(){ return this.selected===-1; }, is_AND: function(){ return this.selected===1; }, is_OR : function(){ return this.selected===2; }, set_NONE: function(){ if(this.inList!==undefined) { this.inList.splice(this.inList.indexOf(this),1); } this.inList = undefined; this.selected = 0; this._refreshFacetDOMSelected(); }, set_NOT: function(l){ if(this.is_NOT()) return; this._insertToList(l); this.selected =-1; this._refreshFacetDOMSelected(); }, set_AND: function(l){ if(this.is_AND()) return; this._insertToList(l); this.selected = 1; this._refreshFacetDOMSelected(); }, set_OR: function(l){ if(this.is_OR()) return; this._insertToList(l); this.selected = 2; this._refreshFacetDOMSelected(); }, /** Internal */ _insertToList: function(l){ if(this.inList!==undefined) { this.inList.splice(this.inList.indexOf(this),1); } this.inList = l; l.push(this); }, /** Internal */ _refreshFacetDOMSelected: function(){ if(this.DOM.aggrGlyph) this.DOM.aggrGlyph.setAttribute("selected",this.selected); }, }; kshf.Aggregate_EmptyRecords = function(){}; kshf.Aggregate_EmptyRecords.prototype = new kshf.Aggregate(); var Aggregate_EmptyRecords_functions = { /** -- */ init: function(){ kshf.Aggregate.prototype.init.call(this,{id: null},'id'); this.isVisible = true; } } for(var index in Aggregate_EmptyRecords_functions){ kshf.Aggregate_EmptyRecords.prototype[index] = Aggregate_EmptyRecords_functions[index]; } kshf.Filter = function(filterOptions){ this.isFiltered = false; this.browser = filterOptions.browser; this.filterTitle = filterOptions.title; this.onClear = filterOptions.onClear; this.onFilter = filterOptions.onFilter; this.hideCrumb = filterOptions.hideCrumb || false; this.filterView_Detail = filterOptions.filterView_Detail; // must be a function this.filterID = this.browser.filterCount++; this.browser.records.forEach(function(record){ record.setFilterCache(this.filterID,true); },this); this.how = "All"; this.filterCrumb = null; }; kshf.Filter.prototype = { addFilter: function(){ this.isFiltered = true; if(this.onFilter) this.onFilter.call(this); var stateChanged = false; var how=0; if(this.how==="LessResults") how = -1; if(this.how==="MoreResults") how = 1; this.browser.records.forEach(function(record){ // if you will show LESS results and record is not wanted, skip // if you will show MORE results and record is wanted, skip if(!(how<0 && !record.isWanted) && !(how>0 && record.isWanted)){ stateChanged = record.updateWanted() || stateChanged; } },this); this._refreshFilterSummary(); this.browser.update_Records_Wanted_Count(); this.browser.refresh_filterClearAll(); this.browser.clearSelect_Highlight(); if(stateChanged) this.browser.updateAfterFilter(); }, /** -- */ clearFilter: function(forceUpdate, updateWanted){ if(!this.isFiltered) return; this.isFiltered = false; // clear filter cache - no other logic is necessary this.browser.records.forEach(function(record){ record.setFilterCache(this.filterID,true); },this); if(updateWanted!==false){ this.browser.records.forEach(function(record){ if(!record.isWanted) record.updateWanted(); }); } this._refreshFilterSummary(); if(this.onClear) this.onClear.call(this); if(forceUpdate!==false){ this.browser.update_Records_Wanted_Count(); this.browser.refresh_filterClearAll(); this.browser.updateAfterFilter(); } }, /** Don't call this directly */ _refreshFilterSummary: function(){ if(this.hideCrumb===true) return; if(!this.isFiltered){ var root = this.filterCrumb; if(root===null || root===undefined) return; root.attr("ready",false); setTimeout(function(){ root[0][0].parentNode.removeChild(root[0][0]); }, 350); this.filterCrumb = null; } else { // insert DOM if(this.filterCrumb===null) { this.filterCrumb = this.browser.insertDOM_crumb("Filtered",this); } this.filterCrumb.select(".crumbHeader").html(this.filterTitle()); this.filterCrumb.select(".filterDetails").html(this.filterView_Detail.call(this)); } }, }; /** -- */ kshf.RecordDisplay = function(kshf_, config){ var me = this; this.browser = kshf_; this.DOM = {}; this.config = config; this.config.sortColWidth = this.config.sortColWidth || 50; // default is 50 px this.autoExpandMore = true; if(config.autoExpandMore===false) this.autoExpandMore = false; this.maxVisibleItems_Default = config.maxVisibleItems_Default || kshf.maxVisibleItems_Default; this.maxVisibleItems = this.maxVisibleItems_Default; // This is the dynamic property this.showRank = config.showRank || false; this.mapMouseControl = "pan"; this.displayType = config.displayType || 'list'; // 'grid', 'list', 'map', 'nodelink' if(config.geo) this.displayType = 'map'; if(config.linkBy) { this.displayType = 'nodelink'; if(!Array.isArray(config.linkBy)) config.linkBy = [config.linkBy]; } else { config.linkBy = []; } this.detailsToggle = config.detailsToggle || 'zoom'; // 'one', 'zoom', 'off' (any other string counts as off practically) this.textSearchSummary = null; // no text search summary by default this.recordViewSummary = null; this.spatialAggr_Highlight = new kshf.Aggregate(); this.spatialAggr_Compare = new kshf.Aggregate(); this.spatialAggr_Highlight.init({}); this.spatialAggr_Compare .init({}); this.spatialAggr_Highlight.summary = this; this.spatialAggr_Compare .summary = this; /*********** * SORTING OPTIONS *************************************************************************/ config.sortingOpts = config.sortBy; // depracated option (sortingOpts) this.sortingOpts = config.sortingOpts || [ {title:this.browser.records[0].idIndex} ]; // Sort by id by default if(!Array.isArray(this.sortingOpts)) this.sortingOpts = [this.sortingOpts]; this.prepSortingOpts(); var firstSortOpt = this.sortingOpts[0]; // Add all interval summaries as sorting options this.browser.summaries.forEach(function(summary){ if(summary.panel===undefined) return; // Needs to be within view if(summary.type!=="interval") return; // Needs to be interval (numeric) this.addSortingOption(summary); },this); this.prepSortingOpts(); this.alphabetizeSortingOptions(); this.setSortingOpt_Active(firstSortOpt || this.sortingOpts[0]); this.DOM.root = this.browser.DOM.root.select(".recordDisplay") .attr('detailsToggle',this.detailsToggle) .attr('showRank',this.showRank) .attr('mapMouseControl',this.mapMouseControl) .attr('hasRecordView',false); var zone = this.DOM.root.append("div").attr("class","dropZone dropZone_recordView") .on("mouseenter",function(){ this.setAttribute("readyToDrop",true); }) .on("mouseleave",function(){ this.setAttribute("readyToDrop",false); }) .on("mouseup",function(event){ var movedSummary = me.browser.movedSummary; if(movedSummary===null || movedSummary===undefined) return; movedSummary.refreshNuggetDisplay(); me.setRecordViewSummary(movedSummary); if(me.textSearchSummary===null) me.setTextSearchSummary(movedSummary); me.browser.updateLayout(); }); zone.append("div").attr("class","dropIcon fa fa-list-ul"); this.DOM.recordDisplayHeader = this.DOM.root.append("div").attr("class","recordDisplayHeader"); this.initDOM_RecordViewHeader(); this.DOM.recordDisplayWrapper = this.DOM.root.append("div").attr("class","recordDisplayWrapper"); this.viewAs(this.displayType); if(config.recordView!==undefined){ if(typeof(config.recordView)==="string"){ // it may be a function definition if so, evaluate if(config.recordView.substr(0,8)==="function"){ // Evaluate string to a function!! eval("\"use strict\"; config.recordView = "+config.recordView); } } this.setRecordViewSummary( (typeof config.recordView === 'string') ? this.browser.summaries_by_name[config.recordView] : // function this.browser.createSummary('_RecordView_',config.recordView,'categorical') ); } if(config.textSearch){ // Find the summary. If it is not there, create it if(typeof(config.textSearch)==="string"){ this.setTextSearchSummary( this.browser.summaries_by_name[config.textSearch] ); } else { var name = config.textSearch.name; var value = config.textSearch.value; if(name!==undefined){ var summary = this.browser.summaries_by_name[config.textSearch]; if(!summary){ if(typeof(value)==="function"){ summary = browser.createSummary(name,value,'categorical'); } else if(typeof(value)==="string"){ summary = browser.changeSummaryName(value,name); }; } } this.setTextSearchSummary(summary); } } }; kshf.RecordDisplay.prototype = { /** -- */ setHeight: function(v){ if(this.recordViewSummary===null) return; var me=this; this.curHeight = v; this.DOM.recordDisplayWrapper.style("height",v+"px"); if(this.displayType==="map"){ setTimeout(function(){ me.leafletRecordMap.invalidateSize(); }, 1000); } }, /** -- */ refreshWidth: function(widthMiddlePanel){ this.curWidth = widthMiddlePanel; if(this.displayType==="map"){ this.leafletRecordMap.invalidateSize(); } }, /** -- */ getRecordEncoding: function(){ return (this.displayType==="map" || this.displayType==="nodelink") ? "color" : "sort"; }, /** -- */ map_refreshColorScaleBins: function(){ var me = this; this.DOM.recordColorScaleBins .style("background-color", function(d){ if(me.sortingOpt_Active.invertColorScale) d = 8-d; return kshf.colorScale[me.browser.mapColorTheme][d]; }); }, /** -- */ map_projectRecords: function(){ var me = this; var _geo_ = this.config.geo; this.DOM.kshfRecords.attr("d", function(record){ return me.recordGeoPath(record.data[_geo_]); }); }, /** -- */ map_zoomToActive: function(){ // Insert the bounds for each record path into the bs var bs = []; var _geo_ = this.config.geo; this.browser.records.forEach(function(record){ if(!record.isWanted) return; if(record._geoBounds_ === undefined) return; var b = record._geoBounds_; if(isNaN(b[0][0])) return; // Change wrapping (US World wrap issue) if(b[0][0]>kshf.wrapLongitude) b[0][0]-=360; if(b[1][0]>kshf.wrapLongitude) b[1][0]-=360; bs.push(L.latLng(b[0][1], b[0][0])); bs.push(L.latLng(b[1][1], b[1][0])); }); var bounds = new L.latLngBounds(bs); if(!this.browser.finalized){ // First time: just fit bounds this.leafletRecordMap.fitBounds( bounds ); return; } this.leafletRecordMap.flyToBounds( bounds, { padding: [0,0], pan: {animate: true, duration: 1.2}, zoom: {animate: true} } ); }, /** -- */ initDOM_MapView: function(){ var me = this; if(this.DOM.recordMap_Base) { this.DOM.recordGroup = this.DOM.recordMap_SVG.select(".recordGroup"); this.DOM.kshfRecords = this.DOM.recordGroup.selectAll(".kshfRecord"); return; // Do not initialize twice } this.setSpatialFilter(); this.DOM.recordMap_Base = this.DOM.recordDisplayWrapper.append("div").attr("class","recordMap_Base"); this.leafletRecordTileLayer = new L.TileLayer( kshf.map.tileTemplate, { attribution: kshf.map.attribution, attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a>', subdomains: 'abcd', maxZoom: 19 //nowrap: true }); this.leafletRecordMap = L.map(this.DOM.recordMap_Base[0][0], { maxBoundsViscosity: 1, /*continuousWorld: true, crs: L.CRS.EPSG3857 */ } ) .addLayer(this.leafletRecordTileLayer) .on("viewreset",function(){ me.map_projectRecords(); }) .on("movestart",function(){ me.DOM.recordGroup.style("display","none"); }) .on("move",function(){ // console.log("MapZoom: "+me.leafletRecordMap.getZoom()); // me.map_projectRecords() }) .on("moveend",function(){ me.DOM.recordGroup.style("display","block"); me.map_projectRecords(); }); this.recordGeoPath = d3.geo.path().projection( d3.geo.transform({ // Use Leaflet to implement a D3 geometric transformation. point: function(x, y) { if(x>kshf.wrapLongitude) x-=360; var point = me.leafletRecordMap.latLngToLayerPoint(new L.LatLng(y, x)); this.stream.point(point.x, point.y); } }) ); var _geo_ = this.config.geo; // Compute geo-bohts of each record this.browser.records.forEach(function(record){ var feature = record.data[_geo_]; if(typeof feature === 'undefined') return; record._geoBounds_ = d3.geo.bounds(feature); }); this.drawingFilter = false; this.DOM.recordMap_Base.select(".leaflet-tile-pane") .on("mousedown",function(){ if(me.mapMouseControl!=="draw") return; me.drawingFilter = true; me.DOM.recordMap_Base.attr("drawing",true); me.DOM.recordMap_Base.attr("drawingFilter",true); var mousePos = d3.mouse(this); var curLatLong = me.leafletRecordMap.layerPointToLatLng(L.point(mousePos[0], mousePos[1])); me.adsajasid = curLatLong; d3.event.stopPropagation(); d3.event.preventDefault(); }) .on("mouseup",function(){ if(me.mapMouseControl!=="draw") return; if(!me.drawingFilter) return; me.DOM.recordMap_Base.attr("drawing",null); me.DOM.recordMap_Base.attr("drawingFilter",null); me.drawingFilter = false; me.spatialFilter.addFilter(); d3.event.stopPropagation(); d3.event.preventDefault(); }) .on("mousemove",function(){ if(me.mapMouseControl!=="draw") return; if(me.drawingHighlight && !d3.event.shiftKey){ me.drawingHighlight = false; me.DOM.recordMap_Base.attr("drawing",null); me.DOM.recordMap_Base.attr("drawingHighlight",null); me.browser.clearSelect_Highlight(); // Disable highlight selection: TODO } var mousePos = d3.mouse(this); var curLatLong = me.leafletRecordMap.layerPointToLatLng(L.point(mousePos[0], mousePos[1])); if(d3.event.shiftKey){ if(!me.drawingFilter && !me.drawingHighlight){ // Start highlight selection me.DOM.recordMap_Base.attr("drawing",true); me.adsajasid = curLatLong; me.DOM.recordMap_Base.attr("drawingHighlight",true); me.drawingHighlight = true; } } if(!me.drawingFilter && !me.drawingHighlight) return; //console.log("X: "+mousePos[0]+", Y:"+mousePos[1]); //console.log(curLatLong); var bounds = L.latLngBounds([me.adsajasid,curLatLong]); if(me.drawingHighlight){ me.spatialQuery.highlight.setBounds(bounds); me.spatialAggr_Highlight.records = []; me.browser.records.forEach(function(record){ if(!record.isWanted) return; if(record._geoBounds_ === undefined) return; // already have "bounds" variable if(kshf.intersects(record._geoBounds_, bounds)){ me.spatialAggr_Highlight.records.push(record); } else { record.remForHighlight(true); } }); me.browser.setSelect_Highlight(null,me.spatialAggr_Highlight, "Region"); } else { me.spatialQuery.filter.setBounds(bounds); } /* me.browser.records.forEach(function(record){ if(!record.isWanted) return; if(record._geoBounds_ === undefined) return; // already have "bounds" variable if(kshf.intersects(record._geoBounds_, bounds)){ //console.log(record.data.CombinedName); } });*/ d3.event.stopPropagation(); d3.event.preventDefault(); }) ; // Add an example rectangle layer to the map var bounds = [[-54.559322, -15.767822], [56.1210604, 15.021240]]; // create an orange rectangle this.spatialQuery = { filter: L.rectangle(bounds, {color: "#5A7283", weight: 1, className: "spatialQuery_Filter"}), highlight: L.rectangle(bounds, {color: "#ff7800", weight: 1, className: "spatialQuery_Highlight"}), }; this.spatialQuery.filter.addTo(this.leafletRecordMap); this.spatialQuery.highlight.addTo(this.leafletRecordMap); this.DOM.recordMap_SVG = d3.select(this.leafletRecordMap.getPanes().overlayPane) .append("svg").attr("xmlns","http://www.w3.org/2000/svg").attr("class","recordMap_SVG"); // The fill pattern definition in SVG, used to denote geo-objects with no data. // http://stackoverflow.com/questions/17776641/fill-rect-with-pattern this.DOM.recordMap_SVG.append('defs') .append('pattern') .attr('id', 'diagonalHatch') .attr('patternUnits', 'userSpaceOnUse') .attr('width', 4) .attr('height', 4) .append('path') .attr('d', 'M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2') .attr('stroke', 'gray') .attr('stroke-width', 1); this.DOM.recordGroup = this.DOM.recordMap_SVG.append("g").attr("class", "leaflet-zoom-hide recordGroup"); // Add custom controls var DOM_control = d3.select(this.leafletRecordMap.getContainer()).select(".leaflet-control"); DOM_control.append("a") .attr("class","leaflet-control-view-map") .attr("title","Show/Hide Map") .attr("href","#") .each(function(){ this.tipsy = new Tipsy(this, {gravity: 'w', title: "Show/Hide Map"}); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout", function(){ this.tipsy.hide(); }) .html("<span class='viewMap fa fa-map-o'></span>") .on("dblclick",function(){ d3.event.preventDefault(); d3.event.stopPropagation(); }) .on("click",function(){ var x = d3.select(me.leafletRecordMap.getPanes().tilePane); x.attr("showhide", x.attr("showhide")==="hide"?"show":"hide"); d3.select(this.childNodes[0]).attr("class","fa fa-map"+((x.attr("showhide")==="hide")?"":"-o")); d3.event.preventDefault(); d3.event.stopPropagation(); }); DOM_control.append("a").attr("class","mapMouseControl fa") .each(function(){ this.tipsy = new Tipsy(this, {gravity: 'w', title: function(){ return "Drag mouse to "+(me.mapMouseControl==="pan"?"draw":"pan"); } }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout", function(){ this.tipsy.hide(); }) .on("click",function(){ me.mapMouseControl = me.mapMouseControl==="pan"?"draw":"pan"; me.DOM.root.attr("mapMouseControl",me.mapMouseControl); }); DOM_control.append("a") .attr("class","leaflet-control-viewFit").attr("title",kshf.lang.cur.ZoomToFit) .attr("href","#") .each(function(){ this.tipsy = new Tipsy(this, {gravity: 'w', title: kshf.lang.cur.ZoomToFit}); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout", function(){ this.tipsy.hide(); }) .html("<span class='viewFit fa fa-arrows-alt'></span>") .on("dblclick",function(){ d3.event.preventDefault(); d3.event.stopPropagation(); }) .on("click",function(){ me.map_zoomToActive(); d3.event.preventDefault(); d3.event.stopPropagation(); }); }, /** -- */ initDOM_NodeLinkView: function(){ var me = this; if(this.DOM.recordNodeLink_SVG) { this.DOM.recordGroup = this.DOM.recordNodeLink_SVG.select(".recordGroup"); this.DOM.kshfRecords = this.DOM.recordGroup.selectAll(".kshfRecord"); return; // Do not initialize twice } this.initDOM_NodeLinkView_Settings(); this.nodeZoomBehavior = d3.behavior.zoom() .scaleExtent([0.5, 8]) .on("zoom", function(){ gggg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")"); me.refreshNodeVis(); }); this.DOM.recordNodeLink_SVG = this.DOM.recordDisplayWrapper .append("svg").attr("xmlns","http://www.w3.org/2000/svg").attr("class","recordNodeLink_SVG") .call(this.nodeZoomBehavior); var gggg = this.DOM.recordNodeLink_SVG.append("g"); this.DOM.linkGroup = gggg.append("g").attr("class","linkGroup"); this.DOM.recordGroup = gggg.append("g").attr("class","recordGroup recordGroup_Node"); this.DOM.NodeLinkControl = this.DOM.recordDisplayWrapper.append("span").attr("class","NodeLinkControl"); var animationControl = this.DOM.NodeLinkControl.append("span").attr("class","animationControl"); animationControl.append("span").attr("class","NodeLinkAnim_Play fa fa-play") .on("click",function(){ me.nodelink_Force.start(); me.DOM.root.attr("hideLinks",true); }); animationControl.append("span").attr("class","NodeLinkAnim_Pause fa fa-pause") .on("click",function(){ me.nodelink_Force.stop(); me.DOM.root.attr("hideLinks",null); }); this.DOM.NodeLinkAnim_Refresh = this.DOM.NodeLinkControl.append("span") .attr("class","NodeLinkAnim_Refresh fa fa-refresh") .on("click",function(){ me.refreshNodeLinks(); this.style.display = null; }); }, /** -- */ initDOM_ListView: function(){ var me = this; if(this.DOM.recordGroup_List) return; this.DOM.recordGroup_List = this.DOM.recordDisplayWrapper.append("div").attr("class","recordGroup_List"); this.DOM.recordGroup = this.DOM.recordGroup_List.append("div").attr("class","recordGroup") .on("scroll",function(d){ if(this.scrollHeight-this.scrollTop-this.offsetHeight<10){ if(me.autoExpandMore===false){ me.DOM.showMore.attr("showMoreVisible",true); } else { me.showMoreRecordsOnList(); // automatically add more records } } else { me.DOM.showMore.attr("showMoreVisible",false); } me.DOM.scrollToTop.style("visibility", this.scrollTop>0?"visible":"hidden"); me.DOM.adjustSortColumnWidth.style("top",(this.scrollTop-2)+"px") }); this.DOM.adjustSortColumnWidth = this.DOM.recordGroup.append("div") .attr("class","adjustSortColumnWidth dragWidthHandle") .on("mousedown", function (d, i) { if(d3.event.which !== 1) return; // only respond to left-click me.browser.DOM.root.style('cursor','ew-resize'); var _this = this; var mouseDown_x = d3.mouse(document.body)[0]; var mouseDown_width = me.sortColWidth; me.browser.DOM.pointerBlock.attr("active",""); me.browser.DOM.root.on("mousemove", function() { _this.setAttribute("dragging",""); me.setSortColumnWidth(mouseDown_width+(d3.mouse(document.body)[0]-mouseDown_x)); }).on("mouseup", function(){ me.browser.DOM.root.style('cursor','default'); me.browser.DOM.pointerBlock.attr("active",null); me.browser.DOM.root.on("mousemove", null).on("mouseup", null); _this.removeAttribute("dragging"); }); d3.event.preventDefault(); }); this.DOM.showMore = this.DOM.root.append("div").attr("class","showMore") .attr("showMoreVisible",false) .on("mouseenter",function(){ d3.select(this).selectAll(".loading_dots").attr("anim",true); }) .on("mouseleave",function(){ d3.select(this).selectAll(".loading_dots").attr("anim",null); }) .on("click",function(){ me.showMoreRecordsOnList(); }); this.DOM.showMore.append("span").attr("class","MoreText").html("Show More"); this.DOM.showMore.append("span").attr("class","Count CountAbove"); this.DOM.showMore.append("span").attr("class","Count CountBelow"); this.DOM.showMore.append("span").attr("class","loading_dots loading_dots_1"); this.DOM.showMore.append("span").attr("class","loading_dots loading_dots_2"); this.DOM.showMore.append("span").attr("class","loading_dots loading_dots_3"); }, /** -- */ initDOM_RecordViewHeader: function(){ var me=this; this.DOM.recordColorScaleBins = this.DOM.recordDisplayHeader.append("div").attr("class","recordColorScale") .each(function(){ this.tipsy = new Tipsy(this, {gravity: 'w', title: "Change color scale"}); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .on("click",function(){ me.browser.mapColorTheme = (me.browser.mapColorTheme==="converge") ? "diverge" : "converge"; me.refreshRecordColors(); me.map_refreshColorScaleBins(); me.sortingOpt_Active.map_refreshColorScale(); }) .selectAll(".recordColorScaleBin").data([0,1,2,3,4,5,6,7,8]) .enter().append("div").attr("class","recordColorScaleBin"); this.map_refreshColorScaleBins(); this.DOM.recordDisplayHeader.append("div").attr("class","itemRank_control fa") .each(function(){ this.tipsy = new Tipsy(this, {gravity: 'n', title: function(){ return (me.showRank?"Hide":"Show")+" ranking"; }}); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .on("click",function(){ me.setShowRank(!me.showRank); }); this.initDOM_SortSelect(); this.initDOM_GlobalTextSearch(); this.DOM.recordDisplayHeader.append("div").attr("class","buttonRecordViewRemove fa fa-times") .each(function(){ this.tipsy = new Tipsy(this, {gravity: 'ne', title: kshf.lang.cur.RemoveRecords }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout", function(){ this.tipsy.hide(); }) .on("click", function(){ me.removeRecordViewSummary(); }); var x= this.DOM.recordDisplayHeader.append("span"); x.append("span").text("View: ").attr("class","recordView_HeaderSet"); x.selectAll("span.fa").data([ {v:"Map", i:"globe"}, {v:"List", i:"list-ul"}, {v:"NodeLink", i:"share-alt"} ] ).enter() .append("span").attr("class", function(d){ return "recordView_Set"+d.v+" fa fa-"+d.i; }) .each(function(d){ this.tipsy = new Tipsy(this, {gravity: 'ne', title: function(){ return "View as "+d.v; } }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout", function(){ this.tipsy.hide(); }) .on("click", function(d){ me.viewAs(d.v); }); this.DOM.scrollToTop = this.DOM.recordDisplayHeader.append("div").attr("class","scrollToTop fa fa-arrow-up") .each(function(){ this.tipsy = new Tipsy(this, {gravity: 'e', title: kshf.lang.cur.ScrollToTop }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout", function(){ this.tipsy.hide(); }) .on("click",function(){ kshf.Util.scrollToPos_do(me.DOM.recordGroup[0][0],0); }); }, /** -- */ setSpatialFilter: function(){ var me=this; this.spatialFilter = this.browser.createFilter({ title: function(){return "Region"}, onClear: function(){ me.DOM.root.select(".spatialQuery_Filter").attr("active",null); }, onFilter: function(){ me.DOM.root.select(".spatialQuery_Filter").attr("active",true); var query = []; var bounds = me.spatialQuery.filter._bounds; me.browser.records.forEach(function(record){ if(record._geoBounds_ === undefined) { record.setFilterCache(this.filterID, false); return; } // already have "bounds" variable record.setFilterCache(this.filterID, kshf.intersects(record._geoBounds_, bounds)); },this); }, filterView_Detail: function(){ return ""; } }); }, /** -- */ setTextFilter: function(){ var me=this; this.textFilter = this.browser.createFilter({ title: function(){ return me.textSearchSummary.summaryName; }, hideCrumb: true, onClear: function(){ me.DOM.recordTextSearch.select(".clearSearchText").style('display','none'); me.DOM.recordTextSearch.selectAll(".textSearchMode").style("display","none"); me.DOM.recordTextSearch.select("input")[0][0].value = ""; }, onFilter: function(){ me.DOM.recordTextSearch.select(".clearSearchText").style('display','inline-block'); var query = []; // split the input by " character var processed = this.filterStr.split('"'); processed.forEach(function(block,i){ if(i%2===0) { block.split(/\s+/).forEach(function(q){ query.push(q)}); } else { query.push(block); } }); // Remove the empty strings query = query.filter(function(v){ return v!==""}); me.DOM.recordTextSearch.selectAll(".textSearchMode").style("display",query.length>1?"inline-block":"none"); // go over all the records in the list, search each keyword separately // If some search matches, return true (any function) var summaryFunc = me.textSearchSummary.summaryFunc; me.browser.records.forEach(function(record){ var f; if(me.textFilter.multiMode==='or') f = ! query.every(function(v_i){ var v = summaryFunc.call(record.data,record); if(v===null || v===undefined) return true; return (""+v).toLowerCase().indexOf(v_i)===-1; }); if(me.textFilter.multiMode==='and') f = query.every(function(v_i){ var v = summaryFunc.call(record.data,record); return (""+v).toLowerCase().indexOf(v_i)!==-1; }); record.setFilterCache(this.filterID,f); },this); }, }); this.textFilter.multiMode = 'and'; }, /** -- */ initDOM_GlobalTextSearch: function(){ var me=this; this.DOM.recordTextSearch = this.DOM.recordDisplayHeader.append("span").attr("class","recordTextSearch"); var x= this.DOM.recordTextSearch.append("div").attr("class","dropZone_textSearch") .on("mouseenter",function(){ this.style.backgroundColor = "rgb(255, 188, 163)"; }) .on("mouseleave",function(){ this.style.backgroundColor = ""; }) .on("mouseup" ,function(){ me.setTextSearchSummary(me.movedSummary); }); x.append("div").attr("class","dropZone_textSearch_text").text("Text search"); this.DOM.recordTextSearch.append("i").attr("class","fa fa-search searchIcon"); this.DOM.recordTextSearch.append("input").attr("class","mainTextSearch_input") .on("keydown",function(){ var x = this; if(this.timer) clearTimeout(this.timer); this.timer = setTimeout( function(){ me.textFilter.filterStr = x.value.toLowerCase(); if(me.textFilter.filterStr!=="") { me.textFilter.addFilter(); } else { me.textFilter.clearFilter(); } x.timer = null; }, 750); }); this.DOM.recordTextSearch.append("span").attr("class","fa fa-times-circle clearSearchText") .attr("mode","and") .each(function(){ this.tipsy = new Tipsy(this, {gravity: 'ne', title: kshf.lang.cur.RemoveFilter }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout",function(){ this.tipsy.hide(); }) .on("click",function() { me.textFilter.clearFilter(); }); this.DOM.recordTextSearch.selectAll(".textSearchMode").data(["and","or"]).enter() .append("span") .attr("class","textSearchMode") .attr("mode",function(d){return d;}) .each(function(d){ this.tipsy = new Tipsy(this, { gravity: 'ne', title: (d==="and") ? "All words<br> must appear." : "At least one word<br> must appear." }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout",function(){ this.tipsy.hide(); }) .on("click",function(d) { me.DOM.recordTextSearch.attr("mode",d); me.textFilter.multiMode = d; me.textFilter.addFilter(); }); }, /** -- */ initDOM_NodeLinkView_Settings: function(){ var me=this; this.DOM.NodeLinkAttrib = this.DOM.recordDisplayHeader.append("span").attr("class","NodeLinkAttrib"); this.DOM.NodeLinkAttrib.append("span").attr("class","fa fa-share-alt NodeLinkAttribIcon") .each(function(d){ this.tipsy = new Tipsy(this, { gravity: 'e', title: "Show/Hide Links" }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout",function(){ this.tipsy.hide(); }) .on("click",function(){ me.DOM.root.attr("hideLinks", me.DOM.root.attr("hideLinks")?null:true ); }); var s = this.DOM.NodeLinkAttrib.append("select") .on("change",function(){ var s = this.selectedOptions[0].__data__; // TODO: change the network calculation });; s.selectAll("option").data(this.config.linkBy).enter().append("option").text(function(d){ return d; }); }, /** -- */ setRecordViewSummary: function(summary){ if(summary===undefined || summary===null) { this.removeRecordViewSummary(); return; } if(this.recordViewSummary===summary) return; if(this.recordViewSummary) this.removeRecordViewSummary(); this.DOM.root.attr('hasRecordView',true); this.recordViewSummary = summary; this.recordViewSummary.isRecordView = true; this.recordViewSummary.refreshNuggetDisplay(); if(this.displayType==="list" || this.displayType==="grid"){ this.sortRecords(); this.refreshRecordDOM(); this.setSortColumnWidth(this.config.sortColWidth); } else if(this.displayType==='map'){ this.refreshRecordDOM(); } else if(this.displayType==='nodelink'){ this.setNodeLink(); this.refreshRecordDOM(); } this.browser.DOM.root.attr("recordDisplayMapping",this.getRecordEncoding()); // "sort" or "color" }, /** -- */ removeRecordViewSummary: function(){ if(this.recordViewSummary===null) return; this.DOM.root.attr("hasRecordView",false); this.recordViewSummary.isRecordView = false; this.recordViewSummary.refreshNuggetDisplay(); this.recordViewSummary = null; this.browser.DOM.root.attr("recordDisplayMapping",null); }, /** -- */ setTextSearchSummary: function(summary){ if(summary===undefined || summary===null) return; this.textSearchSummary = summary; this.textSearchSummary.isTextSearch = true; this.DOM.recordTextSearch .attr("isActive",true) .select("input").attr("placeholder", kshf.lang.cur.Search+": "+summary.summaryName); this.setTextFilter(); }, /** -- */ addSortingOption: function(summary){ // If parameter summary is already a sorting option, nothing else to do if(this.sortingOpts.some(function(o){ return o===summary; })) return; this.sortingOpts.push(summary); summary.sortLabel = summary.summaryFunc; summary.sortInverse = false; summary.sortFunc = this.getSortFunc(summary.summaryFunc); this.prepSortingOpts(); this.refreshSortingOptions(); }, /** -- */ initDOM_SortSelect: function(){ var me=this; this.DOM.header_listSortColumn = this.DOM.recordDisplayHeader.append("div").attr("class","header_listSortColumn"); this.DOM.listSortOptionSelect = this.DOM.header_listSortColumn.append("select") .attr("class","listSortOptionSelect") .on("change", function(){ me.setSortingOpt_Active(this.selectedIndex); }); this.refreshSortingOptions(); this.DOM.removeSortOption = this.DOM.recordDisplayHeader .append("span").attr("class","removeSortOption_wrapper") .append("span").attr("class","removeSortOption fa") .each(function(){ this.tipsy = new Tipsy(this, {gravity: 'n', title: "Remove current sorting option" }); }) .style("display",(this.sortingOpts.length<2)?"none":"inline-block") .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout",function(d,i){ this.tipsy.hide(); }) .on("click",function(){ var index=-1; me.sortingOpts.forEach(function(o,i){ if(o===me.sortingOpt_Active) index=i; }) if(index!==-1){ me.sortingOpts.splice(index,1); if(index===me.sortingOpts.length) index--; me.setSortingOpt_Active(index); me.refreshSortingOptions(); me.DOM.listSortOptionSelect[0][0].selectedIndex = index; } }); this.DOM.recordDisplayHeader.append("span").attr("class","sortColumn sortButton fa") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'w', title: kshf.lang.cur.ReverseOrder }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout",function(){ this.tipsy.hide(); }) .on("click",function(d){ // NOTE: Only on list/grid views me.sortingOpt_Active.inverse = me.sortingOpt_Active.inverse?false:true; this.setAttribute("inverse",me.sortingOpt_Active.inverse); // TODO: Do not show no-value items on top, reversing needs to be a little smarter. me.browser.records.reverse(); me.updateRecordRanks(); me.refreshRecordDOM(); me.refreshRecordRanks(me.DOM.recordRanks); me.DOM.kshfRecords = me.DOM.recordGroup.selectAll(".kshfRecord") .data(me.browser.records, function(record){ return record.id(); }) .order(); kshf.Util.scrollToPos_do(me.DOM.recordGroup[0][0],0); }); }, /** -- */ refreshRecordRanks: function(d3_selection){ if(!this.showRank) return; // Do not refresh if not shown... d3_selection.text(function(record){ return (record.recordRank<0)?"":record.recordRank+1; }); }, /** -- */ setSortColumnWidth: function(v){ if(this.displayType!=='list') return; this.sortColWidth = Math.max(Math.min(v,110),30); // between 30 and 110 pixels this.DOM.recordsSortCol.style("width",this.sortColWidth+"px"); this.refreshAdjustSortColumnWidth(); }, /** -- */ refreshRecordSortLabels: function(d3_selection){ if(this.displayType!=="list") return; // Only list-view allows sorting if(d3_selection===undefined) d3_selection = this.DOM.recordsSortCol; var me=this; var labelFunc=this.sortingOpt_Active.sortLabel; var sortColformat = d3.format(".s"); if(this.sortingOpt_Active.isTimeStamp()){ sortColformat = d3.time.format("%Y"); } d3_selection.html(function(d){ var s=labelFunc.call(d.data,d); if(s===null || s===undefined) return ""; this.setAttribute("title",s); if(typeof s!=="string") s = sortColformat(s); return me.sortingOpt_Active.printWithUnitName(s); }); }, /** -- */ refreshSortingOptions: function(){ if(this.DOM.listSortOptionSelect===undefined) return; this.DOM.listSortOptionSelect.selectAll("option").remove(); var me=this; var x = this.DOM.listSortOptionSelect.selectAll("option").data(this.sortingOpts); x.enter().append("option").html(function(summary){ return summary.summaryName; }) x.exit().each(function(summary){ summary.sortingSummary = false; }); this.sortingOpts.forEach(function(summary, i){ if(summary===me.sortingOpt_Active) { var DOM = me.DOM.listSortOptionSelect[0][0]; DOM.selectedIndex = i; if(DOM.dispatchEvent && (!bowser.msie && !bowser.msedge)) DOM.dispatchEvent(new Event('change')); } }); }, /** -- */ prepSortingOpts: function(){ this.sortingOpts.forEach(function(sortOpt,i){ if(sortOpt.summaryName) return; // It already points to a summary if(typeof(sortOpt)==="string"){ sortOpt = { title: sortOpt }; } // Old API if(sortOpt.title) sortOpt.name = sortOpt.title; var summary = this.browser.summaries_by_name[sortOpt.name]; if(summary===undefined){ if(typeof(sortOpt.value)==="string"){ summary = this.browser.changeSummaryName(sortOpt.value,sortOpt.name); } else{ summary = this.browser.createSummary(sortOpt.name,sortOpt.value, "interval"); if(sortOpt.unitName){ summary.setUnitName(sortOpt.unitName); } } } summary.sortingSummary = true; summary.sortLabel = sortOpt.label || summary.summaryFunc; summary.sortInverse = sortOpt.inverse || false; summary.sortFunc = sortOpt.sortFunc || this.getSortFunc(summary.summaryFunc); this.sortingOpts[i] = summary; },this); if(this.DOM.removeSortOption) this.DOM.removeSortOption.style("display",(this.sortingOpts.length<2)?"none":"inline-block"); }, /** -- */ alphabetizeSortingOptions: function(){ this.sortingOpts.sort(function(s1,s2){ return s1.summaryName.localeCompare(s2.summaryName, { sensitivity: 'base' }); }); }, /** -- */ setSortingOpt_Active: function(index){ if(this.sortingOpt_Active){ var curHeight = this.sortingOpt_Active.getHeight(); this.sortingOpt_Active.clearAsRecordSorting(); this.sortingOpt_Active.setHeight(curHeight); } if(typeof index === "number"){ if(index<0 || index>=this.sortingOpts.length) return; this.sortingOpt_Active = this.sortingOpts[index]; } else if(index instanceof kshf.Summary_Base){ this.sortingOpt_Active = index; } { var curHeight = this.sortingOpt_Active.getHeight(); this.sortingOpt_Active.setAsRecordSorting(); this.sortingOpt_Active.setHeight(curHeight); } // If the record view summary is not set, no need to proceed with sorting or visual if(this.recordViewSummary===null) return; if(this.DOM.root===undefined) return; if(this.displayType==="map" || this.displayType==="nodelink"){ this.refreshRecordColors(); } else { this.sortRecords(); if(this.DOM.recordGroup===undefined) return; this.refreshRecordDOM(); this.refreshRecordRanks(this.DOM.recordRanks); kshf.Util.scrollToPos_do(this.DOM.recordGroup[0][0],0); this.DOM.kshfRecords = this.DOM.recordGroup.selectAll(".kshfRecord") .data(this.browser.records, function(record){ return record.id(); }) .order(); this.refreshRecordSortLabels(); } }, /** -- */ refreshAdjustSortColumnWidth: function(){ if(this.displayType!=="list") return; this.DOM.adjustSortColumnWidth.style("left", (this.sortColWidth-2)+(this.showRank?15:0)+"px") }, /** -- */ setShowRank: function(v){ this.showRank = v; this.DOM.root.attr('showRank',this.showRank); this.refreshRecordRanks(this.DOM.recordRanks); this.refreshAdjustSortColumnWidth(); }, /** -- */ refreshNodeLinks: function(){ this.generateNodeLinks(); this.nodelink_nodes = this.browser.records.filter(function(record){ return record.isWanted; }); this.nodelink_Force .nodes(this.nodelink_nodes) .links(this.nodelink_links) .start(); if(this.nodelink_links.length>1000) this.DOM.root.attr("hideLinks",true); }, /** -- */ generateNodeLinks: function(){ this.nodelink_links = []; var recordsIndexed = kshf.dt_id[browser.primaryTableName]; var linkAttribName = this.config.linkBy[0]; this.browser.records.forEach(function(recordFrom){ if(!recordFrom.isWanted) return; var links = recordFrom.data[linkAttribName]; if(links) { links.forEach(function(recordTo_id){ var recordTo = recordsIndexed[recordTo_id]; if(recordTo) { if(!recordTo.isWanted) return; this.nodelink_links.push({source:recordFrom, target: recordTo}); } },this); } },this); }, /** -- */ initializeNetwork: function(){ this.nodelink_Force.size([this.curWidth, this.curHeight]).start(); if(this.nodelink_links.length>1000) this.DOM.root.attr("hideLinks",true); this.DOM.root.attr("NodeLinkState","started"); }, refreshNodeVis: function(){ if(this.DOM.recordLinks===undefined) return; // position & direction of the line this.DOM.recordLinks.attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); // position of the record var s = 1/this.nodeZoomBehavior.scale(); this.DOM.kshfRecords.attr("transform", function(d){ return "translate("+d.x+","+d.y+") scale("+s+")"; }); }, /** -- */ setNodeLink: function(){ var me=this; this.browser.records.forEach(function(record){ record.DOM.links_To = []; record.DOM.links_From = []; record.links_To = []; record.links_From = []; }); this.nodelink_links = []; var recordsIndexed = kshf.dt_id[browser.primaryTableName]; var linkAttribName = this.config.linkBy[0]; this.browser.records.forEach(function(recordFrom){ var links = recordFrom.data[linkAttribName]; if(links) { links.forEach(function(recordTo_id){ var recordTo = recordsIndexed[recordTo_id]; if(recordTo) { recordFrom.links_To.push(recordTo); recordTo.links_From.push(recordFrom); } },this); } },this); this.generateNodeLinks(); this.DOM.recordLinks = this.DOM.linkGroup.selectAll(".recordLink").data(this.nodelink_links) .enter().append("line").attr("class", "recordLink") .each(function(link){ var recordFrom = link.source; var recordTo = link.target; recordFrom.DOM.links_To.push(this); recordTo.DOM.links_From.push(this); }); this.nodelink_Force = d3.layout.force() .charge(-60) .gravity(0.8) .alpha(0.4) .nodes(this.browser.records) .links(this.nodelink_links) .on("start",function(){ me.DOM.root.attr("NodeLinkState","started"); me.DOM.root.attr("hideLinks",true); }) .on("end", function(){ me.DOM.root.attr("NodeLinkState","stopped"); me.DOM.root.attr("hideLinks",null); }) .on("tick", function(){ me.refreshNodeVis(); }); }, /** -- */ refreshRecordColors: function(){ if(!this.recordViewSummary) return; var me=this; var s_f = this.sortingOpt_Active.summaryFunc; var s_log; if(this.sortingOpt_Active.scaleType==='log'){ this.recordColorScale = d3.scale.log(); s_log = true; } else { this.recordColorScale = d3.scale.linear(); s_log = false; } var min_v = this.sortingOpt_Active.intervalRange.min; var max_v = this.sortingOpt_Active.intervalRange.max; if(this.sortingOpt_Active.intervalRange.active){ min_v = this.sortingOpt_Active.intervalRange.active.min; max_v = this.sortingOpt_Active.intervalRange.active.max; } if(min_v===undefined) min_v = d3.min(this.browser.records, function(d){ return s_f.call(d.data); }); if(max_v===undefined) max_v = d3.max(this.browser.records, function(d){ return s_f.call(d.data); }); this.recordColorScale .range([0, 9]) .domain( [min_v, max_v] ); this.colorQuantize = d3.scale.quantize() .domain([0,9]) .range(kshf.colorScale[me.browser.mapColorTheme]); var undefinedFill = (this.displayType==="map") ? "url(#diagonalHatch)" : "white"; var fillFunc = function(d){ var v = s_f.call(d.data); if(s_log && v<=0) v=undefined; if(v===undefined) return undefinedFill; var vv = me.recordColorScale(v); if(me.sortingOpt_Active.invertColorScale) vv = 9 - vv; return me.colorQuantize(vv); }; if(this.displayType==="map") { this.DOM.kshfRecords.each(function(d){ var v = s_f.call(d.data); if(s_log && v<=0) v=undefined; if(v===undefined) { this.style.fill = undefinedFill; this.style.stroke = "gray"; return; } var vv = me.recordColorScale(v); if(me.sortingOpt_Active.invertColorScale) vv = 9 - vv; this.style.fill = me.colorQuantize(vv); this.style.stroke = me.colorQuantize(vv>=5?0:9); }); } if(this.displayType==="nodelink") { this.DOM.kshfRecords.selectAll("circle").style("fill", function(d){ var v = s_f.call(d.data); if(s_log && v<=0) v=undefined; if(v===undefined) return undefinedFill; var vv = me.recordColorScale(v); if(me.sortingOpt_Active.invertColorScale) vv = 9 - vv; return me.colorQuantize(vv); }); } }, /** -- */ highlightRelated: function(recordFrom){ recordFrom.DOM.links_To.forEach(function(dom){ dom.style.stroke = "green"; dom.style.strokeOpacity = 1; dom.style.display = "block"; }); var links = recordFrom.data[this.config.linkBy[0]]; if(!links) return; var recordsIndexed = kshf.dt_id[browser.primaryTableName]; links.forEach(function(recordTo_id){ var recordTo = recordsIndexed[recordTo_id]; if(recordTo) { if(recordTo.DOM.record){ d3.select(recordTo.DOM.record.parentNode.appendChild(recordTo.DOM.record)); recordTo.DOM.record.setAttribute("selection","related"); } } },this); }, /** -- */ unhighlightRelated: function(recordFrom){ recordFrom.DOM.links_To.forEach(function(dom){ dom.style.stroke = null; dom.style.strokeOpacity = null; dom.style.display = null; }); var links = recordFrom.data[this.config.linkBy[0]]; if(!links) return; var recordsIndexed = kshf.dt_id[browser.primaryTableName]; links.forEach(function(recordTo_id){ var recordTo = recordsIndexed[recordTo_id]; if(recordTo) { if(recordTo.DOM.record){ recordTo.DOM.record.removeAttribute("selection"); } } },this); }, /** Insert records into the UI, called once on load */ refreshRecordDOM: function(){ var me=this, x; var records = (this.displayType==="map")? this.browser.records : this.browser.records.filter(function(record){ return record.isWanted && (record.recordRank<me.maxVisibleItems); }); var newRecords = this.DOM.recordGroup.selectAll(".kshfRecord") .data(records, function(record){ return record.id(); }).enter(); var nodeType = "div"; if(this.displayType==='map'){ nodeType = 'path'; } else if(this.displayType==='nodelink'){ nodeType = 'g'; } // Shared structure per record view newRecords = newRecords .append( nodeType ) .attr('class','kshfRecord') .attr('details',false) .attr("rec_compared",function(record){ return record.selectCompared_str?record.selectCompared_str:null;}) .attr("id",function(record){ return "kshfRecord_"+record.id(); }) // can be used to apply custom CSS .each(function(record){ record.DOM.record = this; if(me.displayType==="map"){ this.tipsy = new Tipsy(this, { gravity: 'e', title: function(){ var s=""; return ""+ "<span class='mapItemName'>"+me.recordViewSummary.summaryFunc.call(record.data,record)+"</span>"+ "<span class='mapTooltipLabel'>"+me.sortingOpt_Active.summaryName+"</span>: "+ "<span class='mapTooltipValue'>"+me.sortingOpt_Active.printWithUnitName( me.sortingOpt_Active.summaryFunc.call(record.data,record))+"</span>"; } }); } }) .on("mouseenter",function(record){ if(this.tipsy) { this.tipsy.show(); this.tipsy.jq_tip[0].style.left = (d3.event.pageX-this.tipsy.tipWidth-10)+"px"; this.tipsy.jq_tip[0].style.top = (d3.event.pageY-this.tipsy.tipHeight/2)+"px"; } if(me.browser.mouseSpeed<0.2) { if(me.displayType==="nodelink") me.highlightRelated(record); record.highlightRecord(); } else { // mouse is moving fast, should wait a while... this.highlightTimeout = window.setTimeout( function(){ if(me.displayType==="nodelink") me.highlightRelated(record); record.highlightRecord(); }, me.browser.mouseSpeed*300); } if(me.displayType==="map" || me.displayType==="nodelink"){ d3.select(this.parentNode.appendChild(this)); } d3.event.stopPropagation(); d3.event.preventDefault(); }) .on("mouseleave",function(record){ if(this.highlightTimeout) window.clearTimeout(this.highlightTimeout); if(this.tipsy) this.tipsy.hide(); if(me.displayType==="nodelink") me.unhighlightRelated(record); record.unhighlightRecord(); }) .on("mousedown", function(){ this._mousemove = false; }) .on("mousemove", function(){ this._mousemove = true; if(this.tipsy){ this.tipsy.jq_tip[0].style.left = (d3.event.pageX-this.tipsy.tipWidth-10)+"px"; this.tipsy.jq_tip[0].style.top = (d3.event.pageY-this.tipsy.tipHeight/2)+"px"; } }) .on("click",function(d){ // Do not show the detail view if the mouse was used to drag the map if(this._mousemove) return; if(me.displayType==="map" || me.displayType==='nodelink'){ me.browser.updateItemZoomText(d); } }); if(this.displayType==="list" || this.displayType==="grid"){ // RANK x = newRecords.append("span").attr("class","recordRank") .each(function(d){ this.tipsy = new Tipsy(this, { gravity: 'e', title: function(){ return kshf.Util.ordinal_suffix_of((d.recordRank+1)); } }); }) .on("mouseenter",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }); this.refreshRecordRanks(x); // SORTING VALUE LABELS if(this.displayType==='list'){ x = newRecords.append("div").attr("class","recordSortCol").style("width",this.sortColWidth+"px"); this.refreshRecordSortLabels(x); } // TOGGLE DETAIL newRecords.append("div").attr("class","recordToggleDetail") .each(function(d){ this.tipsy = new Tipsy(this, { gravity:'s', title: function(){ if(me.detailsToggle==="one" && this.displayType==='list') return d.showDetails===true?"Show less":"Show more"; return kshf.lang.cur.ShowMoreInfo; } }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .append("span").attr("class","item_details_toggle fa") .on("click", function(record){ this.parentNode.tipsy.hide(); if(me.detailsToggle==="one" && me.displayType==='list'){ record.setRecordDetails(!record.showDetails); } if(me.detailsToggle==="zoom"){ me.browser.updateItemZoomText(record); } }); // Insert the custom content! // Note: the value was already evaluated and stored in the record object var recordViewID = this.recordViewSummary.summaryID; newRecords.append("div").attr("class","content") .html(function(record){ return me.recordViewSummary.summaryFunc.call(record.data, record); }); // Fixes ordering problem when new records are made visible on the list // TODO: Try to avoid this. this.DOM.recordGroup.selectAll(".kshfRecord") .data(records, function(record){ return record.id(); }) .order(); } if(this.displayType==="nodelink"){ newRecords.append("circle").attr("r",4); newRecords.append("text").attr("class","kshfRecord_label") .attr("dy",4).attr("dx",6) .html(function(record){ return me.recordViewSummary.summaryFunc.call(record.data, record); }); } // Call the domCb function for all the records that have been inserted to the page if(this.config.domCb) { newRecords.each(function(record){ me.config.domCb.call(record.data,record); }); } this.DOM.kshfRecords = this.DOM.recordGroup.selectAll(".kshfRecord"); if(this.displayType==="map") { this.map_zoomToActive(); this.map_projectRecords(); this.refreshRecordColors(); } else if(this.displayType==="nodelink"){ this.refreshRecordColors(); } else { this.DOM.recordsSortCol = this.DOM.recordGroup.selectAll(".recordSortCol"); this.DOM.recordRanks = this.DOM.recordGroup.selectAll(".recordRank"); } this.updateRecordVisibility(); }, /** -- */ showMoreRecordsOnList: function(){ if(this.displayType==="map") return; this.DOM.showMore.attr("showMoreVisible",false); this.maxVisibleItems += Math.min(this.maxVisibleItems,250); this.refreshRecordDOM(); }, /** Sort all records given the active sort option * Records are only sorted on init & when active sorting option changes. * They are not resorted on filtering. ** Filtering does not affect record sorting. */ sortRecords: function(){ var sortValueFunc = this.sortingOpt_Active.summaryFunc; var sortFunc = this.sortingOpt_Active.sortFunc; var inverse = this.sortingOpt_Active.sortInverse; this.browser.records.sort( function(record_A,record_B){ // Put filtered/remove data to later position // !! Don't do above!! Then, when you filter set, you'd need to re-order // Now, you don't need to re-order after filtering, which is record_A nice property to have. var v_a = sortValueFunc.call(record_A.data,record_A); var v_b = sortValueFunc.call(record_B.data,record_B); if(isNaN(v_a)) v_a = undefined; if(isNaN(v_b)) v_b = undefined; if(v_a===null) v_a = undefined; if(v_b===null) v_b = undefined; if(v_a===undefined && v_b!==undefined) return 1; if(v_b===undefined && v_a!==undefined) return -1; if(v_b===undefined && v_a===undefined) return 0; var dif=sortFunc(v_a,v_b); if(dif===0) dif=record_B.id()-record_A.id(); if(inverse) return -dif; return dif; // use unique IDs to add sorting order as the last option } ); this.updateRecordRanks(); }, /** Returns the sort value type for given sort Value function */ getSortFunc: function(sortValueFunc){ // 0: string, 1: date, 2: others var sortValueFunction, same; // find appropriate sortvalue type for(var k=0, same=0; true ; k++){ if(same===3 || k===this.browser.records.length) break; var item = this.browser.records[k]; var f = sortValueFunc.call(item.data,item); var sortValueType_temp2; switch(typeof f){ case 'string': sortValueType_temp2 = kshf.Util.sortFunc_List_String; break; case 'number': sortValueType_temp2 = kshf.Util.sortFunc_List_Number; break; case 'object': if(f instanceof Date) sortValueType_temp2 = kshf.Util.sortFunc_List_Date; else sortValueType_temp2 = kshf.Util.sortFunc_List_Number; break; default: sortValueType_temp2 = kshf.Util.sortFunc_List_Number; break; } if(sortValueType_temp2===sortValueFunction){ same++; } else { sortValueFunction = sortValueType_temp2; same=0; } } return sortValueFunction; }, /** Updates visibility of individual records */ updateRecordVisibility: function(){ if(this.DOM.kshfRecords===undefined) return; var me = this; var visibleItemCount=0; if(me.displayType==="map"){ this.DOM.kshfRecords.each(function(record){ this.style.opacity = record.isWanted?0.9:0.2; this.style.pointerEvents = record.isWanted?"":"none"; this.style.display = "block"; // Have this for now bc switching views can invalidate display setting }); } else if(me.displayType==="nodelink"){ this.browser.records.forEach(function(record){ if(record.DOM.record) record.DOM.record.style.display = record.isWanted?"block":"none"; }); this.DOM.recordLinks.each(function(link){ var recordFrom = link.source; var recordTo = link.target; this.style.display = (!recordFrom.isWanted || !recordTo.isWanted) ? "none" : null; }); } else { this.DOM.kshfRecords.each(function(record){ var isVisible = (record.recordRank>=0) && (record.recordRank<me.maxVisibleItems); if(isVisible) visibleItemCount++; this.style.display = isVisible?null:'none'; }); var hiddenItemCount = this.browser.recordsWantedCount-visibleItemCount; this.DOM.showMore.select(".CountAbove").html("&#x25B2;"+visibleItemCount+" shown"); this.DOM.showMore.select(".CountBelow").html(hiddenItemCount+" below&#x25BC;"); }; }, /** -- */ updateAfterFilter: function(){ if(this.recordViewSummary===null) return; if(this.displayType==="map") { this.updateRecordVisibility(); //this.map_zoomToActive(); } else if(this.displayType==="nodelink") { this.updateRecordVisibility(); this.DOM.NodeLinkAnim_Refresh.style('display','inline-block'); // this.refreshNodeLinks(); } else { var me=this; var startTime = null; var scrollDom = this.DOM.recordGroup[0][0]; var scrollInit = scrollDom.scrollTop; var easeFunc = d3.ease('cubic-in-out'); var animateToTop = function(timestamp){ var progress; if(startTime===null) startTime = timestamp; // complete animation in 500 ms progress = (timestamp - startTime)/1000; scrollDom.scrollTop = (1-easeFunc(progress))*scrollInit; if(scrollDom.scrollTop!==0){ window.requestAnimationFrame(animateToTop); return; } me.updateRecordRanks(); me.refreshRecordDOM(); me.refreshRecordRanks(me.DOM.recordRanks); }; window.requestAnimationFrame(animateToTop); } }, /** -- */ updateRecordRanks: function(){ var wantedCount = 0; var unwantedCount = 1; this.browser.records.forEach(function(record){ record.recordRank_pre = record.recordRank; if(record.isWanted){ record.recordRank = wantedCount; wantedCount++; } else { record.recordRank = -unwantedCount; unwantedCount++; } }); this.maxVisibleItems = this.maxVisibleItems_Default; }, /** -- */ viewAs: function(d){ d = d.toLowerCase(); this.displayType = d; this.DOM.root.attr("displayType",this.displayType); if(this.displayType==="map"){ this.initDOM_MapView(); this.DOM.recordDisplayHeader.select(".recordView_HeaderSet").style("display","inline-block"); this.DOM.root.select(".recordView_SetList").style("display","inline-block"); if(this.nodelink_Force) this.nodelink_Force.stop(); } else if(this.displayType==="nodelink"){ this.initDOM_NodeLinkView(); this.DOM.recordDisplayHeader.select(".recordView_HeaderSet").style("display","inline-block"); this.DOM.root.select(".recordView_SetList").style("display","inline-block"); } else { this.initDOM_ListView(); this.DOM.root.select(".recordView_SetList").style("display",null); if(this.nodelink_Force) this.nodelink_Force.stop(); } this.DOM.root.select(".recordView_SetMap").style("display", (this.config.geo && this.displayType!=="map") ? "inline-block" : null ); this.DOM.root.select(".recordView_SetNodeLink").style("display", (this.config.linkBy.length>0 && this.displayType!=="nodelink") ? "inline-block" : null ); if(this.recordViewSummary) { if(this.displayType==="list" || this.displayType==="grid"){ this.sortRecords(); this.refreshRecordDOM(); this.setSortColumnWidth(this.config.sortColWidth || 50); // default: 50px; } else if(this.displayType==='map'){ this.refreshRecordColors(); } else if(this.displayType==='nodelink'){ this.refreshRecordColors(); } this.updateRecordVisibility(); this.browser.DOM.root.attr("recordDisplayMapping",this.getRecordEncoding()); // "sort" or "color" } }, /** -- */ exportConfig: function(){ var c={}; c.displayType = this.displayType; if(this.textSearchSummary){ c.textSearch = this.textSearchSummary.summaryName; } if(typeof(this.recordViewSummary.summaryColumn)==="string"){ c.recordView = this.recordViewSummary.summaryColumn; } else { c.recordView = this.recordViewSummary.summaryFunc.toString(); } c.sortBy = []; browser.recordDisplay.sortingOpts.forEach(function(summary){ c.sortBy.push(summary.summaryName); }); if(c.sortBy.length===1) c.sortBy = c.sortBy[0]; c.sortColWidth = this.sortColWidth; c.detailsToggle = this.detailsToggle; return c; } }; kshf.Panel = function(options){ this.browser = options.browser; this.name = options.name; this.width_catLabel = options.width_catLabel; this.width_catBars = 0; // placeholder this.width_catMeasureLabel = 1; // placeholder this.summaries = []; this.DOM = {}; this.DOM.root = options.parentDOM.append("div") .attr("hasSummaries",false) .attr("class", "panel panel_"+options.name+ ((options.name==="left"||options.name==="right")?" panel_side":"")) ; this.initDOM_AdjustWidth(); this.initDOM_DropZone(); }; kshf.Panel.prototype = { /** -- */ getWidth_Total: function(){ if(this.name==="bottom") { var w = this.browser.getWidth_Total(); if(this.browser.authoringMode) w-=kshf.attribPanelWidth; return w; } return this.width_catLabel + this.width_catMeasureLabel + this.width_catBars + kshf.scrollWidth; }, /** -- */ addSummary: function(summary,index){ var curIndex=-1; this.summaries.forEach(function(s,i){ if(s===summary) curIndex=i; }); if(curIndex===-1){ // summary is new to this panel if(index===this.summaries.length) this.summaries.push(summary); else this.summaries.splice(index,0,summary); this.DOM.root.attr("hasSummaries",true); this.updateWidth_QueryPreview(); this.refreshAdjustWidth(); } else { // summary was in the panel. Change position this.summaries.splice(curIndex,1); this.summaries.splice(index,0,summary); } this.summaries.forEach(function(s,i){ s.panelOrder = i; }); this.addDOM_DropZone(summary.DOM.root[0][0]); this.refreshAdjustWidth(); }, /** -- */ removeSummary: function(summary){ var indexFrom = -1; this.summaries.forEach(function(s,i){ if(s===summary) indexFrom = i; }); if(indexFrom===-1) return; // given summary is not within this panel var toRemove=this.DOM.root.selectAll(".dropZone_between_wrapper")[0][indexFrom]; toRemove.parentNode.removeChild(toRemove); this.summaries.splice(indexFrom,1); this.summaries.forEach(function(s,i){ s.panelOrder = i; }); this.refreshDropZoneIndex(); if(this.summaries.length===0) { this.DOM.root//.attr("hasSummaries",false); .attr("hasSummaries",false); } else { this.updateWidth_QueryPreview(); } summary.panel = undefined; this.refreshAdjustWidth(); }, /** -- */ addDOM_DropZone: function(beforeDOM){ var me=this; var zone; if(beforeDOM){ zone = this.DOM.root.insert("div",function(){return beforeDOM;}); } else { zone = this.DOM.root.append("div"); } zone.attr("class","dropZone_between_wrapper") .on("mouseenter",function(){ this.setAttribute("hovered",true); this.children[0].setAttribute("readyToDrop",true); }) .on("mouseleave",function(){ this.setAttribute("hovered",false); this.children[0].setAttribute("readyToDrop",false); }) .on("mouseup",function(){ var movedSummary = me.browser.movedSummary; if(movedSummary.panel){ // if the summary was in the panels already movedSummary.DOM.root[0][0].nextSibling.style.display = ""; movedSummary.DOM.root[0][0].previousSibling.style.display = ""; } movedSummary.addToPanel(me,this.__data__); me.browser.updateLayout(); }) ; var zone2 = zone.append("div").attr("class","dropZone dropZone_summary dropZone_between"); zone2.append("div").attr("class","dropIcon fa fa-angle-double-down"); zone2.append("div").attr("class","dropText").text("Drop summary"); this.refreshDropZoneIndex(); }, /** -- */ initDOM_DropZone: function(dom){ var me=this; this.DOM.dropZone_Panel = this.DOM.root.append("div").attr("class","dropZone dropZone_summary dropZone_panel") .attr("readyToDrop",false) .on("mouseenter",function(event){ this.setAttribute("readyToDrop",true); this.style.width = me.getWidth_Total()+"px"; }) .on("mouseleave",function(event){ this.setAttribute("readyToDrop",false); this.style.width = null; }) .on("mouseup",function(event){ // If this panel has summaries within, dropping makes no difference. if(me.summaries.length!==0) return; var movedSummary = me.browser.movedSummary; if(movedSummary===undefined) return; if(movedSummary.panel){ // if the summary was in the panels already movedSummary.DOM.root[0][0].nextSibling.style.display = ""; movedSummary.DOM.root[0][0].previousSibling.style.display = ""; } movedSummary.addToPanel(me); me.browser.updateLayout(); }) ; this.DOM.dropZone_Panel.append("span").attr("class","dropIcon fa fa-angle-double-down"); this.DOM.dropZone_Panel.append("div").attr("class","dropText").text("Drop summary"); this.addDOM_DropZone(); }, /** -- */ initDOM_AdjustWidth: function(){ if(this.name==='middle' || this.name==='bottom') return; // cannot have adjust handles for now var me=this; var root = this.browser.DOM.root; this.DOM.panelAdjustWidth = this.DOM.root.append("span") .attr("class","panelAdjustWidth") .on("mousedown", function (d, i) { if(d3.event.which !== 1) return; // only respond to left-click var adjustDOM = this; adjustDOM.setAttribute("dragging",""); root.style('cursor','ew-resize'); me.browser.DOM.pointerBlock.attr("active",""); me.browser.setNoAnim(true); var mouseDown_x = d3.mouse(document.body)[0]; var mouseDown_width = me.width_catBars; d3.select("body").on("mousemove", function() { var mouseMove_x = d3.mouse(document.body)[0]; var mouseDif = mouseMove_x-mouseDown_x; if(me.name==='right') mouseDif *= -1; var oldhideBarAxis = me.hideBarAxis; me.setWidthCatBars(mouseDown_width+mouseDif); if(me.hideBarAxis!==oldhideBarAxis){ me.browser.updateLayout_Height(); } // TODO: Adjust other panel widths }).on("mouseup", function(){ adjustDOM.removeAttribute("dragging"); root.style('cursor','default'); me.browser.DOM.pointerBlock.attr("active",null); me.browser.setNoAnim(false); // unregister mouse-move callbacks d3.select("body").on("mousemove", null).on("mouseup", null); }); d3.event.preventDefault(); }) .on("click",function(){ d3.event.stopPropagation(); d3.event.preventDefault(); }); }, /** -- */ refreshDropZoneIndex: function(){ var me = this; this.DOM.root.selectAll(".dropZone_between_wrapper") .attr("panel_index",function(d,i){ this.__data__ = i; if(i===0) return "first"; if(i===me.summaries.length) return "last"; return "middle"; }) ; }, /** -- */ refreshAdjustWidth: function(){ if(this.name==='middle' || this.name==='bottom') return; // cannot have adjust handles for now this.DOM.panelAdjustWidth.style("opacity",(this.summaries.length>0)?1:0); }, /** -- */ setTotalWidth: function(_w_){ this.width_catBars = _w_-this.width_catLabel-this.width_catMeasureLabel-kshf.scrollWidth; }, /** -- */ getNumOfOpenSummaries: function(){ return this.summaries.reduce(function(prev,cur){return prev+!cur.collapsed;},0); }, /** -- */ collapseAllSummaries: function(){ this.summaries.forEach(function(summary){ summary.setCollapsed(true); }); }, /** -- */ setWidthCatLabel: function(_w_){ console.log(_w_); _w_ = Math.max(90,_w_); // use at least 90 pixels for the category label. if(_w_===this.width_catLabel) return; var widthDif = this.width_catLabel-_w_; this.width_catLabel = _w_; this.summaries.forEach(function(summary){ if(summary.refreshLabelWidth!==undefined){ summary.refreshLabelWidth(); } }); this.setWidthCatBars(this.width_catBars+widthDif); }, /** -- */ setWidthCatBars: function(_w_){ _w_ = Math.max(_w_,0); this.hideBars = _w_<=5; this.hideBarAxis = _w_<=20; if(this.hideBars===false){ this.DOM.root.attr("hidebars",false); } else { this.DOM.root.attr("hidebars",true); } if(this.hideBarAxis===false){ this.DOM.root.attr("hideBarAxis",false); } else { this.DOM.root.attr("hideBarAxis",true); } this.width_catBars = _w_; this.updateSummariesWidth(); if(this.name!=="middle") this.browser.updateMiddlePanelWidth(); }, /** --- */ updateSummariesWidth: function(){ this.summaries.forEach(function(summary){ summary.refreshWidth(); }); }, /** --- */ updateWidth_QueryPreview: function(){ var maxTotalCount = d3.max(this.summaries, function(summary){ if(summary.getMaxAggr_Total===undefined) return 0; return summary.getMaxAggr_Total(); }); var oldPreviewWidth = this.width_catMeasureLabel; this.width_catMeasureLabel = 10; var digits = 1; while(maxTotalCount>9){ digits++; maxTotalCount = Math.floor(maxTotalCount/10); } if(digits>3) { digits = 2; this.width_catMeasureLabel+=4; // "." character is used to split. It takes some space } this.width_catMeasureLabel += digits*6; if(oldPreviewWidth!==this.width_catMeasureLabel){ this.summaries.forEach(function(summary){ if(summary.refreshLabelWidth) summary.refreshLabelWidth(); }); } }, }; /** * @constructor */ kshf.Browser = function(options){ this.options = options; if(kshf.lang.cur===null) kshf.lang.cur = kshf.lang.en; // English is Default language // BASIC OPTIONS this.summaryCount = 0; this.filterCount = 0; this.summaries = []; this.summaries_by_name = {}; this.panels = {}; this.filters = []; this.authoringMode = false; this.vizActive = { Highlighted: false, Compared_A: false, Compared_B: false, Compared_C: false }; this.ratioModeActive = false; this.percentModeActive = false; this.isFullscreen = false; this.highlightSelectedSummary = null; this.highlightCrumbTimeout_Hide = undefined; this.showDropZones = false; this.mapColorTheme = "converge"; this.measureFunc = "Count"; this.mouseSpeed = 0; // includes touch-screens... this.noAnim = false; this.domID = options.domID; this.selectedAggr = { Compared_A: null, Compared_B: null, Compared_C: null, Highlighted: null } this.allAggregates = []; this.allRecordsAggr = new kshf.Aggregate(); this.allRecordsAggr.init(); this.allAggregates.push(this.allRecordsAggr); // Callbacks this.newSummaryCb = options.newSummaryCb; this.readyCb = options.readyCb; this.preview_not = false; this.itemName = options.itemName || ""; if(options.itemDisplay) options.recordDisplay = options.itemDisplay; if(typeof this.options.enableAuthoring === "undefined") this.options.enableAuthoring = false; this.DOM = {}; this.DOM.root = d3.select(this.domID) .classed("kshf",true) .attr("noanim",true) .attr("measureFunc",this.measureFunc) .style("position","relative") //.style("overflow-y","hidden") .on("mousemove",function(d,e){ // Action logging... if(typeof logIf === "object"){ logIf.setSessionID(); } // Compute mouse moving speed, to adjust repsonsiveness if(me.lastMouseMoveEvent===undefined){ me.lastMouseMoveEvent = d3.event; return; } var timeDif = d3.event.timeStamp - me.lastMouseMoveEvent.timeStamp; if(timeDif===0) return; var xDif = Math.abs(d3.event.x - me.lastMouseMoveEvent.x); var yDif = Math.abs(d3.event.y - me.lastMouseMoveEvent.y); // controls highlight selection delay me.mouseSpeed = Math.min( Math.sqrt(xDif*xDif + yDif*yDif) / timeDif , 2); me.lastMouseMoveEvent = d3.event; }); // remove any DOM elements under this domID, kshf takes complete control over what's inside var rootDomNode = this.DOM.root[0][0]; while (rootDomNode.hasChildNodes()) rootDomNode.removeChild(rootDomNode.lastChild); this.DOM.pointerBlock = this.DOM.root.append("div").attr("class","pointerBlock"); this.DOM.attribDragBox = this.DOM.root.append("div").attr("class","attribDragBox"); this.insertDOM_Infobox(); this.insertDOM_WarningBox(); this.DOM.panel_Wrapper = this.DOM.root.append("div").attr("class","panel_Wrapper"); this.insertDOM_PanelBasic(); this.DOM.panelsTop = this.DOM.panel_Wrapper.append("div").attr("class","panels_Above"); this.panels.left = new kshf.Panel({ width_catLabel : options.leftPanelLabelWidth || options.categoryTextWidth || 115, browser: this, name: 'left', parentDOM: this.DOM.panelsTop }); this.DOM.middleColumn = this.DOM.panelsTop.append("div").attr("class","middleColumn"); this.DOM.middleColumn.append("div").attr("class", "recordDisplay") this.panels.middle = new kshf.Panel({ width_catLabel : options.middlePanelLabelWidth || options.categoryTextWidth || 115, browser: this, name: 'middle', parentDOM: this.DOM.middleColumn }); this.panels.right = new kshf.Panel({ width_catLabel : options.rightPanelLabelWidth || options.categoryTextWidth || 115, browser: this, name: 'right', parentDOM: this.DOM.panelsTop }); this.panels.bottom = new kshf.Panel({ width_catLabel : options.categoryTextWidth || 115, browser: this, name: 'bottom', parentDOM: this.DOM.panel_Wrapper }); this.insertDOM_AttributePanel(); var me = this; this.DOM.root.selectAll(".panel").on("mouseleave",function(){ setTimeout( function(){ me.updateLayout_Height(); }, 1500); // update layout after 1.5 seconds }); kshf.loadFont(); kshf.browsers.push(this); kshf.browser = this; if(options.source){ window.setTimeout(function() { me.loadSource(options.source); }, 10); } else { this.panel_infobox.attr("show","source"); } }; kshf.Browser.prototype = { /** -- */ setNoAnim: function(v){ if(v===this.noAnim) return; if(this.finalized===undefined) return; this.noAnim=v; this.DOM.root.attr("noanim",this.noAnim); }, /** -- */ removeSummary: function(summary){ var indexFrom = -1; this.summaries.forEach(function(s,i){ if(s===summary) indexFrom = i; }); if(indexFrom===-1) return; // given summary is not within this panel this.summaries.splice(indexFrom,1); summary.removeFromPanel(); }, /** -- */ getAttribTypeFromFunc: function(attribFunc){ var type = null; this.records.some(function(item,i){ var item=attribFunc.call(item.data,item); if(item===null) return false; if(item===undefined) return false; if(typeof(item)==="number" || item instanceof Date) { type="interval"; return true; } // TODO": Think about boolean summaries if(typeof(item)==="string" || typeof(item)==="boolean") { type = "categorical"; return true; } if(Array.isArray(item)){ type = "categorical"; return true; } return false; },this); return type; }, /** -- */ createSummary: function(name,func,type){ if(this.summaries_by_name[name]!==undefined){ console.log("createSummary: The summary name["+name+"] is already used. Returning existing summary."); return this.summaries_by_name[name]; } if(typeof(func)==="string"){ var x=func; func = function(){ return this[x]; } } var attribFunc = func || function(){ return this[name]; } if(type===undefined){ type = this.getAttribTypeFromFunc(attribFunc); } if(type===null){ console.log("Summary data type could not be detected for summary name:"+name); return; } var summary; if(type==='categorical'){ summary = new kshf.Summary_Categorical(); } if(type==='interval'){ summary = new kshf.Summary_Interval(); } summary.initialize(this,name,func); this.summaries.push(summary); this.summaries_by_name[name] = summary; if(this.newSummaryCb) this.newSummaryCb.call(this,summary); return summary; }, /** -- */ changeSummaryName: function(curName,newName){ if(curName===newName) return; var summary = this.summaries_by_name[curName]; if(summary===undefined){ console.log("The given summary name is not there. Try again"); return; } if(this.summaries_by_name[newName]!==undefined){ if(newName!==this.summaries_by_name[newName].summaryColumn){ console.log("The new summary name is already used. It must be unique. Try again"); return; } } // remove the indexing using oldName IFF the old name was not original column name if(curName!==summary.summaryColumn){ delete this.summaries_by_name[curName]; } this.summaries_by_name[newName] = summary; summary.setSummaryName(newName); return summary; }, /** -- */ getWidth_Total: function(){ return this.divWidth; }, /** This also considers if the available attrib panel is shown */ getWidth_Browser: function(){ return this.divWidth - (this.authoringMode ? kshf.attribPanelWidth : 0); }, /** -- */ domHeight: function(){ return parseInt(this.DOM.root.style("height")); }, /** -- */ domWidth: function(){ return parseInt(this.DOM.root.style("width")); }, /** -- */ createFilter: function(filterOptions){ filterOptions.browser = this; // see if it has been created before TODO var newFilter = new kshf.Filter(filterOptions); this.filters.push(newFilter); return newFilter; }, /* -- */ insertDOM_WarningBox: function(){ this.panel_warningBox = this.DOM.root.append("div").attr("class", "warningBox_wrapper").attr("shown",false) var x = this.panel_warningBox.append("span").attr("class","warningBox"); this.DOM.warningText = x.append("span").attr("class","warningText"); x.append("span").attr("class","dismiss").html("<i class='fa fa-times-circle' style='font-size: 1.3em;'></i>") .on("click",function(){ this.parentNode.parentNode.setAttribute("shown",false); }); }, /** -- */ showWarning: function(v){ this.panel_warningBox.attr("shown",true); this.DOM.warningText.html(v); }, /** -- */ hideWarning: function(){ this.panel_warningBox.attr("shown",false); }, /** -- */ getMeasurableSummaries: function(){ return this.summaries.filter(function(summary){ return (summary.type==='interval') && summary.scaleType!=='time' // && summary.panel!==undefined && summary.intervalRange.min>=0 && summary.summaryName !== this.records[0].idIndex ; },this); }, /** -- */ insertDOM_measureSelect: function(){ var me=this; if(this.DOM.measureSelectBox) return; this.DOM.measureSelectBox = this.DOM.measureSelectBox_Wrapper.append("div").attr("class","measureSelectBox"); this.DOM.measureSelectBox.append("div").attr("class","measureSelectBox_Close fa fa-times-circle") .each(function(d){ this.tipsy = new Tipsy(this, { gravity: 'e', title: "Close" }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout", function(){ this.tipsy.hide(); }) .on("click",function(){ this.tipsy.hide(); me.closeMeasureSelectBox(); }); this.DOM.measureSelectBox.append("div").attr("class","measureSelectBox_Header").text("Choose measure"); var m = this.DOM.measureSelectBox.append("div").attr("class","measureSelectBox_Content"); m.append("span").attr("class","measureSelectBox_Content_FuncType") .selectAll(".measureFunctionType").data([ {v:"Count", l:"Count (#)"}, {v:"Sum", l:"Sum (Total)"}, {v:"Avg", l:"Average"}, ]).enter() .append("div").attr("class", function(d){ return "measureFunctionType measureFunction_"+d.v}) .html(function(d){ return d.l; }) .on("click",function(d){ if(d.v==="Count"){ me.DOM.measureSelectBox.select(".sdsso23oadsa").attr("disabled","true"); me.setMeasureFunction(); // no summary, will revert to count return; } this.setAttribute("selected",""); me.DOM.measureSelectBox.select(".sdsso23oadsa").attr("disabled",null); me.setMeasureFunction( me.DOM.sdsso23oadsa[0][0].selectedOptions[0].__data__ , d.v); }); this.DOM.sdsso23oadsa = m.append("div").attr("class","measureSelectBox_Content_Summaries") .append("select").attr("class","sdsso23oadsa") .attr("disabled",this.measureFunc==="Count"?"true":null) .on("change",function(){ var s = this.selectedOptions[0].__data__; me.setMeasureFunction(s,me.measureFunc); }); this.DOM.sdsso23oadsa .selectAll(".measureSummary").data(this.getMeasurableSummaries()).enter() .append("option") .attr("class",function(summary){ return "measureSummary measureSummary_"+summary.summaryID;; }) .attr("value",function(summary){ return summary.summaryID; }) .attr("selected", function(summary){ return summary===me.measureSummary?"true":null }) .html(function(summary){ return summary.summaryName; }) m.append("span").attr("class","measureSelectBox_Content_RecordName").html(" of "+this.itemName); }, /** -- */ closeMeasureSelectBox: function(){ this.DOM.measureSelectBox_Wrapper.attr("showMeasureBox",false); // Close box this.DOM.measureSelectBox = undefined; var d = this.DOM.measureSelectBox_Wrapper[0][0]; while (d.hasChildNodes()) d.removeChild(d.lastChild); }, /** -- */ refreshMeasureSelectAction: function(){ this.DOM.recordInfo.attr('changeMeasureBox', (this.getMeasurableSummaries().length!==0)? 'true' : null); }, /** -- */ insertDOM_PanelBasic: function(){ var me=this; this.DOM.panel_Basic = this.DOM.panel_Wrapper.append("div").attr("class","panel_Basic"); this.DOM.measureSelectBox_Wrapper = this.DOM.panel_Basic.append("span").attr("class","measureSelectBox_Wrapper") .attr("showMeasureBox",false); this.DOM.recordInfo = this.DOM.panel_Basic.append("span") .attr("class","recordInfo editableTextContainer") .attr("edittitle",false) .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'n', title: "Change measure" }); }) .on("mouseenter",function(){ if(me.authoringMode || me.getMeasurableSummaries().length===0) return; this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }) .on("click",function(){ if(me.authoringMode || me.getMeasurableSummaries().length===0) return; this.tipsy.hide(); if(me.DOM.measureSelectBox) { me.closeMeasureSelectBox(); return; } me.insertDOM_measureSelect(); me.DOM.measureSelectBox_Wrapper.attr("showMeasureBox",true); }); this.DOM.activeRecordMeasure = this.DOM.recordInfo.append("span").attr("class","activeRecordMeasure"); this.DOM.measureFuncType = this.DOM.recordInfo.append("span").attr("class","measureFuncType"); this.DOM.recordName = this.DOM.recordInfo.append("span").attr("class","recordName editableText") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'w', title: function(){ var curState=this.parentNode.getAttribute("edittitle"); return (curState===null || curState==="false") ? kshf.lang.cur.EditTitle : "OK"; } }) }) .attr("contenteditable",false) .on("mousedown", function(){ d3.event.stopPropagation(); }) .on("mouseenter",function(){ this.tipsy.show(); d3.event.stopPropagation(); d3.event.preventDefault(); }) .on("mouseleave",function(){ this.tipsy.hide(); }) .on("mousedown", function(){ d3.event.stopPropagation(); d3.event.preventDefault(); }) .on("blur",function(){ this.parentNode.setAttribute("edittitle",false); this.setAttribute("contenteditable", false); me.itemName = this.textContent; }) .on("keydown",function(){ if(event.keyCode===13){ // ENTER this.parentNode.setAttribute("edittitle",false); this.setAttribute("contenteditable", false); me.itemName = this.textContent; } }) .on("click",function(){ this.tipsy.hide(); var curState=this.parentNode.getAttribute("edittitle"); if(curState===null || curState==="false"){ this.parentNode.setAttribute("edittitle",true); var parentDOM = d3.select(this.parentNode); var v=parentDOM.select(".recordName")[0][0]; v.setAttribute("contenteditable",true); v.focus(); } else { this.parentNode.setAttribute("edittitle",false); var parentDOM = d3.select(this.parentNode); var v=parentDOM.select(".recordName")[0][0]; v.setAttribute("contenteditable",false); me.itemName = this.textContent; } }); this.DOM.breadcrumbs = this.DOM.panel_Basic.append("span").attr("class","breadcrumbs"); this.initDOM_ClearAllFilters(); var rightBoxes = this.DOM.panel_Basic.append("span").attr("class","rightBoxes"); // Attribute panel if (typeof saveAs !== 'undefined') { // FileSaver.js is included rightBoxes.append("i").attr("class","saveBrowserConfig fa fa-download") .each(function(d){ this.tipsy = new Tipsy(this, { gravity: 'ne', title: "Download Browser Configuration" }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout", function(){ this.tipsy.hide(); }) .on("click",function(){ var c = JSON.stringify(me.exportConfig(),null,' '); var blob = new Blob([c]);//, {type: "text/plain;charset=utf-8"}); saveAs(blob, "kshf_config.json"); }); } rightBoxes.append("i").attr("class","configUser fa") .each(function(d){ this.tipsy = new Tipsy(this, { gravity: 'n', title: function(){ return kshf.gistLogin? ("Welcome, <i class='fa fa-github'></i> <b>"+kshf.gistLogin+"</b>.<br><br>"+ "Click to logout.<br><br>"+"Shift-click to set gist "+(kshf.gistPublic?"secret":"public")+"."): "Sign-in using github"; } }); }) .attr("auth", false) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout", function(){ this.tipsy.hide(); }) .on("click",function(){ if(this.getAttribute("auth")==="true"){ if (d3.event.shiftKey) { kshf.gistPublic = !kshf.gistPublic; // invert public setting this.setAttribute("public",kshf.gistPublic); alert("Future uploads will be "+(kshf.gistPublic?"public":"secret")+".") return; } // de-authorize kshf.githubToken = undefined; kshf.gistLogin = undefined; this.setAttribute("auth",false) } else { kshf.githubToken = window.prompt("Your Github token (only needs access to gist)", ""); if(this.githubToken!==""){ kshf.getGistLogin(); this.setAttribute("auth",true); } } }); rightBoxes.append("i").attr("class","saveBrowserConfig fa fa-cloud-upload") .each(function(d){ this.tipsy = new Tipsy(this, { gravity: 'ne', title: "Upload Browser Config to Cloud" }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout", function(){ this.tipsy.hide(); }) .on("click",function(){ if(!confirm("The browser will be saved "+ ((kshf.gistLogin)? "to your github as "+(kshf.gistPublic?"public":"secret")+" gist.": "anonymously and public.") )){ return; } var e = me.exportConfig(); var c = JSON.stringify(e,null,' '); // Add authentication data if authentication token is set var headers = {}; if(kshf.gistLogin) headers.Authorization = "token "+kshf.githubToken; // Set description (from page title if it exists) var description = "Keshif Browser Configuration"; // In demo pages, demo_PageTitle gives more context - use it as description if(d3.select("#demo_PageTitle")[0][0]){ description = d3.select("#demo_PageTitle").html(); } var githubLoad = { description: description, public: kshf.gistPublic, files: { "kshf_config.json": { content: c }, } }; // Add style file, if custom style exists var badiStyle = d3.select("#kshfStyle"); if(badiStyle[0].length > 0 && badiStyle[0][0]!==null){ githubLoad.files["kshf_style.css"] = { content: badiStyle.text()}; } function gist_createNew(){ $.ajax( 'https://api.github.com/gists', { method: "POST", dataType: 'json', data: JSON.stringify(githubLoad), headers: headers, success: function(response){ // Keep Gist Info (you may edit/fork it next) kshf.gistInfo = response; var gistURL = response.html_url; var gistID = gistURL.replace(/.*github.*\//g,''); var keshifGist = "keshif.me/gist?"+gistID; me.showWarning( "The browser is saved to "+ "<a href='"+gistURL+"' target='_blank'>"+gistURL.replace("https://","")+"</a>.<br> "+ "To load it again, visit <a href='http://"+keshifGist+"' target='_blank'>"+keshifGist+"</a>" ) }, }, 'json' ); }; // UNAUTHORIZED / ANONYMOUS if(kshf.gistLogin===undefined){ // You cannot fork or edit a gist as anonymous user. gist_createNew(); return; } // AUTHORIZED, NEW GIST if(kshf.gistInfo===undefined){ gist_createNew(); // New gist return; } // AUTHOIZED, EXISTING GIST, FROM ANOTHER USER if(kshf.gistInfo.owner===undefined || kshf.gistInfo.owner.login !== kshf.gistLogin){ // Fork it $.ajax( 'https://api.github.com/gists/'+kshf.gistInfo.id+"/forks", { method: "POST", dataType: 'json', data: JSON.stringify(githubLoad), async: false, headers: headers, success: function(response){ kshf.gistInfo = response; // ok, now my gist }, }, 'json' ); } // AUTHORIZED, EXISTING GIST, MY GIST if(kshf.gistInfo.owner.login === kshf.gistLogin){ // edit $.ajax( 'https://api.github.com/gists/'+kshf.gistInfo.id, { method: "PATCH", dataType: 'json', data: JSON.stringify(githubLoad), headers: headers, success: function(response){ var gistURL = response.html_url; var gistID = gistURL.replace(/.*github.*\//g,''); var keshifGist = "keshif.me/gist?"+gistID; me.showWarning( "The browser is edited in "+ "<a href='"+gistURL+"' target='_blank'>"+gistURL.replace("https://","")+"</a>.<br> "+ "To load it again, visit <a href='http://"+keshifGist+"' target='_blank'>"+keshifGist+"</a>" ) }, }, 'json' ); } }); rightBoxes.append("i").attr("class","showConfigButton fa fa-cog") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'ne', title: kshf.lang.cur.ModifyBrowser }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout", function(){ this.tipsy.hide(); }) .on("click",function(){ me.enableAuthoring(); }); // Datasource this.DOM.datasource = rightBoxes.append("a").attr("class","fa fa-table datasource") .attr("target","_blank") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'ne', title: kshf.lang.cur.OpenDataSource }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout",function(d,i){ this.tipsy.hide(); }); // Info & Credits rightBoxes.append("i").attr("class","fa fa-info-circle credits") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'ne', title: kshf.lang.cur.ShowInfoCredits }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout",function(d,i){ this.tipsy.hide(); }) .on("click",function(){ me.showInfoBox();}); // Info & Credits rightBoxes.append("i").attr("class","fa fa-arrows-alt fullscreen") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'ne', title: kshf.lang.cur.ShowFullscreen }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout",function(d,i){ this.tipsy.hide(); }) .on("click",function(){ me.showFullscreen();}); var adsdasda = this.DOM.panel_Basic.append("div").attr("class","totalGlyph aggrGlyph"); this.DOM.totalGlyph = adsdasda.selectAll("[class*='measure_']") .data(["Total","Active","Highlighted","Compared_A","Compared_B","Compared_C"]) .enter() .append("span").attr("class", function(d){ return "measure_"+d;}) }, /** Inserts a summary block to the list breadcrumb DOM */ /** Don't call this directly */ insertDOM_crumb: function(_className, _filter){ var x; var me=this; // breadcrumbs must be always visible (as the basic panel) x = this.DOM.breadcrumbs.append("span") .attr("class","crumb crumbMode_"+_className) .each(function(){ if(_className!=="Highlighted"){ // Move the node to a sibling before var l=this.parentNode.childNodes.length; if(l>1){ var n=this.parentNode.childNodes[l-2]; this.parentNode.insertBefore(this,n); } } this.tipsy = new Tipsy(this, { gravity: 'n', title: function(){ switch(_className){ case "Filtered": return kshf.lang.cur.RemoveFilter; case "Highlighted": return "Remove Highlight"; case "Compared_A": case "Compared_B": case "Compared_C": return kshf.lang.cur.Unlock; } } }); }) .on("mouseenter",function(){ this.tipsy.show(); if(_className.substr(0,8)==="Compared"){ me.refreshMeasureLabels(_className); } }) .on("mouseleave",function(){ this.tipsy.hide(); if(_className.substr(0,8)==="Compared"){ me.refreshMeasureLabels(); } }) .on("click",function(){ this.tipsy.hide(); if(_className==="Filtered") { _filter.clearFilter(); // delay layout height update setTimeout( function(){ me.updateLayout_Height();}, 1000); } else if(_className==="Highlighted") { me.clearSelect_Highlight(); me.clearCrumbAggr("Highlighted"); } else { me.clearSelect_Compare(_className.substr(9)); // TODO: _className Compared_A / className, etc me.clearCrumbAggr(_className); me.refreshMeasureLabels(); } }); x.append("span").attr("class","clearCrumbButton inCrumb").append("span").attr("class","fa"); var y = x.append("span").attr("class","crumbText"); y.append("span").attr("class","crumbHeader"); y.append("span").attr("class","filterDetails"); // animate appear window.getComputedStyle(x[0][0]).opacity; // force redraw x.attr("ready",true); return x; }, /** -- */ getActiveComparedCount: function(){ return this.vizActive.Compared_A + this.vizActive.Compared_B + this.vizActive.Compared_C; }, /** -- */ refreshTotalViz: function(){ var me=this; var totalScale = d3.scale.linear() .domain([0, this.allRecordsAggr.measure(this.ratioModeActive ? 'Active' : 'Total') ]) .range([0, this.getWidth_Browser()]) .clamp(true); var totalC = this.getActiveComparedCount(); totalC++; // 1 more for highlight var VizHeight = 8; var curC = 0; var stp = VizHeight / totalC; this.DOM.totalGlyph.each(function(d){ if(d==="Total" || d==="Highlighted" || d==="Active"){ kshf.Util.setTransform(this, "scale("+totalScale(me.allRecordsAggr.measure(d))+","+VizHeight+")"); } else { kshf.Util.setTransform(this, "translateY("+(stp*curC)+"px) "+ "scale("+totalScale(me.allRecordsAggr.measure(d))+","+stp+")"); curC++; } }); }, /** --- */ initDOM_ClearAllFilters: function(){ var me=this; this.DOM.filterClearAll = this.DOM.panel_Basic.append("span").attr("class","filterClearAll") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'n', title: kshf.lang.cur.RemoveAllFilters }); }) .on("mouseenter",function(){ this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }) .on("click",function(){ this.tipsy.hide(); me.clearFilters_All(); }); this.DOM.filterClearAll.append("span").attr("class","title").text(kshf.lang.cur.ShowAll); this.DOM.filterClearAll.append("div").attr("class","clearFilterButton allFilter") .append("span").attr("class","fa fa-times"); }, /* -- */ insertDOM_Infobox: function(){ var me=this; var creditString=""; creditString += "<div align='center'>"; creditString += "<div class='header'>Data made explorable by <span class='libName'>Keshif</span>.</div>"; creditString += "<div align='center' class='boxinbox project_credits'>"; creditString += "<div>Developed by</div>"; creditString += " <a href='http://www.cs.umd.edu/hcil/' target='_blank'><img src='https://wiki.umiacs.umd.edu/hcil/images/"+ "1/10/HCIL_logo_small_no_border.gif' style='height:50px'></a>"; creditString += " <a class='myName' href='http://www.adilyalcin.me' target='_blank'>M. Adil Yalçın</a>"; creditString += " <a href='http://www.umd.edu' target='_blank'><img src='http://www.trademarks.umd.edu/marks/gr/informal.gif' "+ "style='height:50px'></a>"; creditString += "</div>"; creditString += ""; creditString += "<div align='center' class='boxinbox project_credits'>"; creditString += "<div style='float:right; text-align: right'>" creditString += "<iframe src='http://ghbtns.com/github-btn.html?user=adilyalcin&repo=Keshif&type=watch&count=true' "+ "allowtransparency='true' frameborder='0' scrolling='0' width='90px' height='20px'></iframe><br/>"; creditString += "</div>"; creditString += "<div style='float:left; padding-left: 10px'>" creditString += "<iframe src='http://ghbtns.com/github-btn.html?user=adilyalcin&repo=Keshif&type=fork&count=true' "+ "allowtransparency='true' frameborder='0' scrolling='0' width='90px' height='20px'></iframe>"; creditString += "</div>"; creditString += " 3rd party libraries used<br/>"; creditString += " <a href='http://d3js.org/' target='_blank'>D3</a> -"; creditString += " <a href='http://jquery.com' target='_blank'>JQuery</a> -"; creditString += " <a href='https://developers.google.com/chart/' target='_blank'>GoogleDocs</a>"; creditString += "</div><br/>"; creditString += ""; creditString += "<div align='center' class='project_fund'>"; creditString += "Keshif (<i>keşif</i>) means discovery / exploration in Turkish.<br/>"; creditString += ""; this.panel_infobox = this.DOM.root.append("div").attr("class", "panel panel_infobox"); this.panel_infobox.append("div").attr("class","background") .on("click",function(){ var activePanel = this.parentNode.getAttribute("show"); if(activePanel==="credit" || activePanel==="itemZoom"){ me.panel_infobox.attr("show","none"); } }) ; this.DOM.loadingBox = this.panel_infobox.append("div").attr("class","infobox_content infobox_loading"); // this.DOM.loadingBox.append("span").attr("class","fa fa-spinner fa-spin"); var ssdsd = this.DOM.loadingBox.append("span").attr("class","spinner"); ssdsd.append("span").attr("class","spinner_x spinner_1"); ssdsd.append("span").attr("class","spinner_x spinner_2"); ssdsd.append("span").attr("class","spinner_x spinner_3"); ssdsd.append("span").attr("class","spinner_x spinner_4"); ssdsd.append("span").attr("class","spinner_x spinner_5"); var hmmm=this.DOM.loadingBox.append("div").attr("class","status_text"); hmmm.append("span").attr("class","status_text_sub info").text(kshf.lang.cur.LoadingData); this.DOM.status_text_sub_dynamic = hmmm.append("span").attr("class","status_text_sub dynamic"); var infobox_credit = this.panel_infobox.append("div").attr("class","infobox_content infobox_credit"); infobox_credit.append("div").attr("class","infobox_close_button") .on("click",function(){ me.panel_infobox.attr("show","none"); }) .append("span").attr("class","fa fa-times"); infobox_credit.append("div").attr("class","all-the-credits").html(creditString); this.insertSourceBox(); this.DOM.infobox_itemZoom = this.panel_infobox.append("span").attr("class","infobox_content infobox_itemZoom"); this.DOM.infobox_itemZoom.append("div").attr("class","infobox_close_button") .on("click",function(){ me.panel_infobox.attr("show","none"); }) .append("span").attr("class","fa fa-times"); this.DOM.infobox_itemZoom_content = this.DOM.infobox_itemZoom.append("span").attr("class","content"); }, /** -- */ insertSourceBox: function(){ var me = this; var x,y,z; var source_type = "GoogleSheet"; var sourceURL = null, sourceSheet = "", localFile = undefined; var readyToLoad=function(){ if(localFile) return true; return sourceURL!==null && sourceSheet!==""; }; this.DOM.infobox_source = this.panel_infobox.append("div").attr("class","infobox_content infobox_source") .attr("selected_source_type",source_type); this.DOM.infobox_source.append("div").attr("class","sourceHeader").text("Where's your data?"); var source_wrapper = this.DOM.infobox_source.append("div").attr("class","source_wrapper"); x = source_wrapper.append("div").attr("class","sourceOptions"); x.append("span").attr("class","sourceOption").html( "<img src='https://lh3.ggpht.com/e3oZddUHSC6EcnxC80rl_6HbY94sM63dn6KrEXJ-C4GIUN-t1XM0uYA_WUwyhbIHmVMH=w300-rw' "+ " style='height: 12px;'> Google Sheet").attr("source_type","GoogleSheet"); x.append("span").attr("class","sourceOption").html( "<img src='https://developers.google.com/drive/images/drive_icon.png' style='height:12px; position: "+ "relative; top: 2px'> Google Drive Folder") .attr("source_type","GoogleDrive"); x.append("span").attr("class","sourceOption").html( "<i class='fa fa-dropbox'></i> Dropbox Folder").attr("source_type","Dropbox"); x.append("span").attr("class","sourceOption") .html("<i class='fa fa-file'></i> Local File").attr("source_type","LocalFile"); x.selectAll(".sourceOption").on("click",function(){ source_type=this.getAttribute("source_type"); me.DOM.infobox_source.attr("selected_source_type",source_type); var placeholder; switch(source_type){ case "GoogleSheet": placeholder = 'https://docs.google.com/spreadsheets/d/**************'; break; case "GoogleDrive": placeholder = 'https://******.googledrive.com/host/**************/'; break; case "Dropbox": placeholder = "https://dl.dropboxusercontent.com/u/**************/"; } gdocLink.attr("placeholder",placeholder); }); x = source_wrapper.append("div"); var gdocLink = x.append("input") .attr("type","text") .attr("class","gdocLink") .attr("placeholder",'https://docs.google.com/spreadsheets/d/**************') .on("keyup",function(){ gdocLink_ready.style("opacity",this.value===""?"0":"1"); var input = this.value; if(source_type==="GoogleSheet"){ var firstIndex = input.indexOf("docs.google.com/spreadsheets/d/"); if(firstIndex!==-1){ var input = input.substr(firstIndex+31); // focus after the base url if(input.indexOf("/")!==-1){ input = input.substr(0,input.indexOf("/")); } } if(input.length===44){ sourceURL = input; gdocLink_ready.attr("ready",true); } else { sourceURL = null; gdocLink_ready.attr("ready",false); } } if(source_type==="GoogleDrive"){ var firstIndex = input.indexOf(".googledrive.com/host/"); if(firstIndex!==-1){ // Make sure last character is "/" if(input[input.length-1]!=="/") input+="/"; sourceURL = input; gdocLink_ready.attr("ready",true); } else { sourceURL = null; gdocLink_ready.attr("ready",false); } } if(source_type==="Dropbox"){ var firstIndex = input.indexOf("dl.dropboxusercontent.com/"); if(firstIndex!==-1){ // Make sure last character is "/" if(input[input.length-1]!=="/") input+="/"; sourceURL = input; gdocLink_ready.attr("ready",true); } else { sourceURL = null; gdocLink_ready.attr("ready",false); } } actionButton.attr("disabled",!readyToLoad()); }); var fileLink = x.append("input") .attr("type","file") .attr("class","fileLink") .on("change",function(){ gdocLink_ready.style("opacity",0); var files = d3.event.target.files; // FileList object if(files.length>1){ alert("Please select only one file."); return; } if(files.length===0){ alert("Please select a file."); return; } localFile = files[0]; switch(localFile.type){ case "application/json": // json localFile.fileType = "json"; localFile.name = localFile.name.replace(".json",""); break; case "text/csv": // csv localFile.fileType = "csv"; localFile.name = localFile.name.replace(".csv",""); break; case "text/tab-separated-values": // tsv localFile.fileType = "tsv"; localFile.name = localFile.name.replace(".tsv",""); break; default: localFile = undefined; actionButton.attr("disabled",true); alert("The selected file type is not supported (csv, tsv, json)"); return; } localFile.name = localFile.name.replace("_"," "); gdocLink_ready.style("opacity",1); gdocLink_ready.attr("ready",true); actionButton.attr("disabled",false); }); x.append("span").attr("class","fa fa-info-circle") .each(function(summary){ this.tipsy = new Tipsy(this, { gravity: 's', title: function(){ if(source_type==="GoogleSheet") return "The link to your Google Sheet"; if(source_type==="GoogleDrive") return "The link to *hosted* Google Drive folder"; if(source_type==="Dropbox") return "The link to your *Public* Dropbox folder"; if(source_type==="LocalFile") return "Select your CSV/TSV/JSON file or drag-and-drop here."; } }); }) .on("mouseenter",function(){ this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }); var gdocLink_ready = x.append("span").attr("class","gdocLink_ready fa").attr("ready",false); var sheetInfo = this.DOM.infobox_source.append("div").attr("class","sheetInfo"); x = sheetInfo.append("div").attr("class","sheet_wrapper") x.append("div").attr("class","subheading tableHeader") ; x = sheetInfo.append("div").attr("class","sheet_wrapper sheetName_wrapper") x.append("span").attr("class","subheading").text("Name"); x.append("span").attr("class","fa fa-info-circle") .each(function(summary){ this.tipsy = new Tipsy(this, { gravity: 's', title: function(){ var v; if(source_type==="GoogleSheet") v="The name of the data sheet in your Google Sheet."; if(source_type==="GoogleDrive") v="The file name in the folder."; if(source_type==="Dropbox") v="The file name in the folder."; v+="<br>Also describes what each data row represents" return v; } }); }) .on("mouseenter",function(){ this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }); this.DOM.tableName = x.append("input").attr("type","text").attr("class","tableName") .on("keyup",function(){ sourceSheet = this.value; actionButton.attr("disabled",!readyToLoad()); }); z=x.append("span").attr("class","fileType_wrapper"); z.append("span").text("."); var DOMfileType = z.append("select").attr("class","fileType"); DOMfileType.append("option").attr("value","csv").text("csv"); DOMfileType.append("option").attr("value","tsv").text("tsv"); DOMfileType.append("option").attr("value","json").text("json"); x = sheetInfo.append("div").attr("class","sheet_wrapper sheetColumn_ID_wrapper") x.append("span").attr("class","subheading").text("ID column"); x.append("span").attr("class","fa fa-info-circle") .each(function(summary){ this.tipsy = new Tipsy(this, { gravity: 's', title: "The column that uniquely identifies each item.<br><br>If no such column, skip." }); }) .on("mouseenter",function(){ this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }); this.DOM.sheetColumn_ID = x.append("input").attr("class","sheetColumn_ID").attr("type","text").attr("placeholder","id"); var actionButton = this.DOM.infobox_source.append("div").attr("class","actionButton") .text("Explore it with Keshif") .attr("disabled",true) .on("click",function(){ if(!readyToLoad()){ alert("Please input your data source link and sheet name."); return; } me.options.enableAuthoring = true; // Enable authoring on data load var sheetID = me.DOM.sheetColumn_ID[0][0].value; if(sheetID==="") sheetID = "id"; switch(source_type){ case "GoogleSheet": me.loadSource({ gdocId: sourceURL, tables: {name:sourceSheet, id:sheetID} }); break; case "GoogleDrive": me.loadSource({ dirPath: sourceURL, fileType: DOMfileType[0][0].value, tables: {name:sourceSheet, id:sheetID} }); break; case "Dropbox": me.loadSource({ dirPath: sourceURL, fileType: DOMfileType[0][0].value, tables: {name:sourceSheet, id:sheetID} }); break; case "LocalFile": localFile.id = sheetID; me.loadSource({ dirPath: "", // TODO: temporary tables: localFile }); break; } }); }, /** -- */ insertDOM_AttributePanel: function(){ var me=this; this.DOM.attributePanel = this.DOM.root.append("div").attr("class","attributePanel"); var xx= this.DOM.attributePanel.append("div").attr("class","attributePanelHeader"); xx.append("span").text("Available Attributes"); xx.append("span").attr("class","hidePanel fa fa-times") .each(function(){ this.tipsy = new Tipsy(this, { gravity: "w", title: "Close panel" }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .on("click",function(){ me.enableAuthoring(); }); var attributePanelControl = this.DOM.attributePanel.append("div").attr("class","attributePanelControl"); attributePanelControl.append("span").attr("class","attribFilterIcon fa fa-filter"); // ******************************************************* // TEXT SEARCH // ******************************************************* this.DOM.attribTextSearch = attributePanelControl.append("span").attr("class","textSearchBox attribTextSearch"); this.DOM.attribTextSearchControl = this.DOM.attribTextSearch.append("span") .attr("class","textSearchControl fa") .on("click",function() { me.DOM.attribTextSearchControl.attr("showClear",false)[0][0].value=""; me.summaries.forEach(function(summary){ if(summary.DOM.nugget===undefined) return; summary.DOM.nugget.attr("filtered",false); }); }); this.DOM.attribTextSearch.append("input") .attr("class","textSearchInput") .attr("type","text") .attr("placeholder",kshf.lang.cur.Search) .on("input",function(){ if(this.timer) clearTimeout(this.timer); var x = this; var queryString = x.value.toLowerCase(); me.DOM.attribTextSearchControl.attr("showClear", (queryString!=="") ) this.timer = setTimeout( function(){ me.summaries.forEach(function(summary){ if(summary.DOM.nugget===undefined) return; summary.DOM.nugget.attr("filtered",(summary.summaryName.toLowerCase().indexOf(queryString)===-1)); }); }, 750); }); attributePanelControl.append("span").attr("class","addAllSummaries") .append("span").attr("class","fa fa-magic") // fa-caret-square-o-right .each(function(){ this.tipsy = new Tipsy(this, { gravity: "e", title: "Add all to browser" }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .on("click",function(){ me.autoCreateBrowser(); }); this.DOM.attributeList = this.DOM.attributePanel.append("div").attr("class","attributeList"); this.DOM.dropZone_AttribList = this.DOM.attributeList.append("div").attr("class","dropZone dropZone_AttribList") .attr("readyToDrop",false) .on("mouseenter",function(event){ this.setAttribute("readyToDrop",true); }) .on("mouseleave",function(event){ this.setAttribute("readyToDrop",false); }) .on("mouseup",function(event){ var movedSummary = me.movedSummary; movedSummary.removeFromPanel(); movedSummary.clearDOM(); movedSummary.browser.updateLayout(); me.movedSummary = null; }); this.DOM.dropZone_AttribList.append("span").attr("class","dropIcon fa fa-angle-double-down"); this.DOM.dropZone_AttribList.append("div").attr("class","dropText").text("Remove summary"); this.DOM.attributeList.append("div").attr("class","newAttribute").html("<i class='fa fa-plus-square'></i>") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'n', title: 'Add new attribute' }); }) .on("mouseenter",function(){ this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }) .on("click",function(){ var name = prompt("The attribute name"); if(name===null) return; // cancel var func = prompt("The attribute function"); if(func===null) return; // cancel var safeFunc = undefined; try { eval("\"use strict\"; safeFunc = function(d){"+func+"}"); } catch (e){ console.log("Eval error:"); console.log(e.message); console.log(e.name); console.log(e.fileName); console.log(e.lineNumber); console.log(e.columnNumber); console.log(e.stack); } if(typeof safeFunc !== "function"){ alert("You did not specify a function with correct format. Cannot specify new attribute."); return; } me.createSummary(name,safeFunc); }); }, /** -- */ updateItemZoomText: function(item){ var str=""; for(var column in item.data){ var v=item.data[column]; if(v===undefined || v===null) continue; str+="<b>"+column+":</b> "+ v.toString()+"<br>"; } this.DOM.infobox_itemZoom_content.html(str); this.panel_infobox.attr("show","itemZoom"); // this.DOM.infobox_itemZoom_content.html(item.data.toString()); }, /** -- deprecated */ showAttributes: function(v){ return this.enableAuthoring(); }, /** -- */ enableAuthoring: function(v){ if(v===undefined) v = !this.authoringMode; // if undefined, invert this.authoringMode = v; this.DOM.root.attr("authoringMode",this.authoringMode?"true":null); this.updateLayout(); var lastIndex = 0, me=this; var initAttib = function(){ var start = Date.now(); me.summaries[lastIndex++].initializeAggregates(); var end = Date.now(); if(lastIndex!==me.summaries.length){ setTimeout(initAttib,end-start); } else { me.reorderNuggetList(); } }; setTimeout(initAttib,150); }, /** -- */ showFullscreen: function(){ this.isFullscreen = this.isFullscreen?false:true; var elem = this.DOM.root[0][0]; if(this.isFullscreen){ if (elem.requestFullscreen) { elem.requestFullscreen(); } else if (elem.msRequestFullscreen) { elem.msRequestFullscreen(); } else if (elem.mozRequestFullScreen) { elem.mozRequestFullScreen(); } else if (elem.webkitRequestFullscreen) { elem.webkitRequestFullscreen(); } } else { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); } } }, /** -- */ showInfoBox: function(){ this.panel_infobox.attr("show","credit"); }, /** -- */ loadSource: function(v){ this.source = v; this.panel_infobox.attr("show","loading"); // Compability with older versions.. Used to specify "sheets" instead of "tables" if(this.source.sheets){ this.source.tables = this.source.sheets; } if(this.source.tables){ if(!Array.isArray(this.source.tables)) this.source.tables = [this.source.tables]; this.source.tables.forEach(function(tableDescr, i){ if(typeof tableDescr === "string") this.source.tables[i] = {name: tableDescr}; }, this); // Reset loadedTableCount this.source.loadedTableCount=0; this.DOM.status_text_sub_dynamic .text("("+this.source.loadedTableCount+"/"+this.source.tables.length+")"); this.primaryTableName = this.source.tables[0].name; if(this.source.gdocId){ this.source.url = this.source.url || ("https://docs.google.com/spreadsheets/d/"+this.source.gdocId); } this.source.tables.forEach(function(tableDescr){ if(tableDescr.id===undefined) tableDescr.id = "id"; // if this table name has been loaded, skip this one if(kshf.dt[tableDescr.name]!==undefined){ this.incrementLoadedTableCount(); return; } if(this.source.gdocId){ this.loadTable_Google(tableDescr); } else { switch(this.source.fileType || tableDescr.fileType){ case "json": this.loadTable_JSON(tableDescr); break; case "csv": case "tsv": this.loadTable_CSV(tableDescr); break; } } },this); } else { if(this.source.callback) this.source.callback(this); } }, loadTable_Google: function(sheet){ var me=this; var headers=1; if(sheet.headers){ headers = sheet.headers; } var qString='https://docs.google.com/spreadsheet/tq?key='+this.source.gdocId+'&headers='+headers; if(sheet.sheetID){ qString+='&gid='+sheet.sheetID; } else { qString+='&sheet='+sheet.name; } if(sheet.range){ qString+="&range="+sheet.range; } var googleQuery = new google.visualization.Query(qString); if(sheet.query) googleQuery.setQuery(sheet.query); googleQuery.send( function(response){ if(kshf.dt[sheet.name]!==undefined){ me.incrementLoadedTableCount(); return; } if(response.isError()) { me.panel_infobox.select("div.status_text .info") .text("Cannot load data"); me.panel_infobox.select("span.spinner").selectAll("span").remove(); me.panel_infobox.select("span.spinner").append('i').attr("class","fa fa-warning"); me.panel_infobox.select("div.status_text .dynamic") .text("("+response.getMessage()+")"); return; } var j,r,i,arr=[],idIndex=-1,itemId=0; var dataTable = response.getDataTable(); var numCols = dataTable.getNumberOfColumns(); // find the index with sheet.id (idIndex) for(i=0; true ; i++){ if(i===numCols || dataTable.getColumnLabel(i).trim()===sheet.id) { idIndex = i; break; } } var tmpTable=[]; // create the column name tables for(j=0; j<dataTable.getNumberOfColumns(); j++){ tmpTable.push(dataTable.getColumnLabel(j).trim()); } // create the item array arr.length = dataTable.getNumberOfRows(); // pre-allocate for speed for(r=0; r<dataTable.getNumberOfRows() ; r++){ var c={}; for(i=0; i<numCols ; i++) { c[tmpTable[i]] = dataTable.getValue(r,i); } // push unique id as the last column if necessary if(c[sheet.id]===undefined) c[sheet.id] = itemId++; arr[r] = new kshf.Record(c,sheet.id); } me.finishDataLoad(sheet,arr); }); }, /** -- */ loadTable_CSV: function(tableDescr){ var me=this; function processCSVText(data){ // if data is already loaded, nothing else to do... if(kshf.dt[tableDescr.name]!==undefined){ me.incrementLoadedTableCount(); return; } var arr = []; var idColumn = tableDescr.id; var config = {}; config.dynamicTyping = true; config.header = true; // header setting can be turned off if(tableDescr.header===false) config.header = false; if(tableDescr.preview!==undefined) config.preview = tableDescr.preview; if(tableDescr.fastMode!==undefined) config.fastMode = tableDescr.fastMode; if(tableDescr.dynamicTyping!==undefined) config.dynamicTyping = tableDescr.dynamicTyping; var parsedData = Papa.parse(data, config); parsedData.data.forEach(function(row,i){ if(row[idColumn]===undefined) row[idColumn] = i; arr.push(new kshf.Record(row,idColumn)); }) me.finishDataLoad(tableDescr, arr); } if(tableDescr instanceof File){ // Load using FileReader var reader = new FileReader(); reader.onload = function(e) { processCSVText(e.target.result); }; reader.readAsText(tableDescr); } else { // Load using URL var fileName=this.source.dirPath+tableDescr.name+"."+this.source.fileType; $.ajax({ url: fileName, type: "GET", async: (this.source.callback===undefined)?true:false, contentType: "text/csv", success: processCSVText }); } }, /** Note: Requires json root to be an array, and each object will be passed to keshif item. */ loadTable_JSON: function(tableDescr){ var me = this; function processJSONText(data){ // File may describe keshif config. Load from config file here! if(data.domID){ me.options = data; me.loadSource(data.source); return; }; // if data is already loaded, nothing else to do... if(kshf.dt[tableDescr.name]!==undefined){ me.incrementLoadedTableCount(); return; } var arr = []; var idColumn = tableDescr.id; data.forEach(function(dataItem,i){ if(dataItem[idColumn]===undefined) dataItem[idColumn] = i; arr.push(new kshf.Record(dataItem, idColumn)); }); me.finishDataLoad(tableDescr, arr); }; if(tableDescr instanceof File){ // Load using FileReader var reader = new FileReader(); reader.onload = function(e) { processJSONText( JSON.parse(e.target.result)); }; reader.readAsText(tableDescr); } else { var fileName = this.source.dirPath+tableDescr.name+".json"; $.ajax({ url: fileName+"?dl=0", type: "GET", async: (this.source.callback===undefined)?true:false, dataType: "json", success: processJSONText }); } }, /** -- */ finishDataLoad: function(table,arr) { kshf.dt[table.name] = arr; var id_table = {}; arr.forEach(function(record){id_table[record.id()] = record;}); kshf.dt_id[table.name] = id_table; this.incrementLoadedTableCount(); }, /** -- */ incrementLoadedTableCount: function(){ var me=this; this.source.loadedTableCount++; this.panel_infobox.select("div.status_text .dynamic") .text("("+this.source.loadedTableCount+"/"+this.source.tables.length+")"); // finish loading if(this.source.loadedTableCount===this.source.tables.length) { if(this.source.callback===undefined){ this.loadCharts(); } else { this.source.callback(this); } } }, /** -- */ loadCharts: function(){ if(this.primaryTableName===undefined){ alert("Cannot load keshif. Please define browser.primaryTableName."); return; } this.records = kshf.dt[this.primaryTableName]; this.records.forEach(function(r){ this.allRecordsAggr.addRecord(r); },this); if(this.itemName==="") { this.itemName = this.primaryTableName; } var me=this; this.panel_infobox.select("div.status_text .info").text(kshf.lang.cur.CreatingBrowser); this.panel_infobox.select("div.status_text .dynamic").text(""); window.setTimeout(function(){ me._loadCharts(); }, 50); }, /** -- */ _loadCharts: function(){ var me=this; if(this.options.loadedCb){ if(typeof this.options.loadedCb === "string" && this.options.loadedCb.substr(0,8)==="function"){ // Evaluate string to a function!! eval("\"use strict\"; this.options.loadedCb = "+this.options.loadedCb); } if(typeof this.options.loadedCb === "function") { this.options.loadedCb.call(this); } } // Create a summary for each existing column in the data for(var column in this.records[0].data){ if(typeof(column)==="string") this.createSummary(column); } // Should do this here, because bottom panel width calls for browser width, and this reads the browser width... this.divWidth = this.domWidth(); if(this.options.summaries) this.options.facets = this.options.summaries; this.options.facets = this.options.facets || []; this.options.facets.forEach(function(facetDescr){ // String -> resolve to name if(typeof facetDescr==="string"){ facetDescr = {name: facetDescr}; } // ************************************************** // API compability - process old keys if(facetDescr.title){ facetDescr.name = facetDescr.title; } if(facetDescr.sortingOpts){ facetDescr.catSortBy = facetDescr.sortingOpts } if(facetDescr.layout){ facetDescr.panel = facetDescr.layout; } if(facetDescr.intervalScale){ facetDescr.scaleType = facetDescr.intervalScale; } if(facetDescr.attribMap){ facetDescr.value = facetDescr.attribMap; } if(typeof(facetDescr.value)==="string"){ // it may be a function definition if so, evaluate if(facetDescr.value.substr(0,8)==="function"){ // Evaluate string to a function!! eval("\"use strict\"; facetDescr.value = "+facetDescr.value); } } if( facetDescr.catLabel || facetDescr.catTooltip || facetDescr.catSplit || facetDescr.catTableName || facetDescr.catSortBy || facetDescr.catMap){ facetDescr.type="categorical"; } else if(facetDescr.scaleType || facetDescr.showPercentile || facetDescr.unitName ){ facetDescr.type="interval"; } var summary = this.summaries_by_name[facetDescr.name]; if(summary===undefined){ if(typeof(facetDescr.value)==="string"){ var summary = this.summaries_by_name[facetDescr.value]; if(summary===undefined){ summary = this.createSummary(facetDescr.value); } summary = this.changeSummaryName(facetDescr.value,facetDescr.name); } else if(typeof(facetDescr.value)==="function"){ summary = this.createSummary(facetDescr.name,facetDescr.value,facetDescr.type); } else { return; } } else { if(facetDescr.value){ // Requesting a new summarywith the same name. summary.destroy(); summary = this.createSummary(facetDescr.name,facetDescr.value,facetDescr.type); } } if(facetDescr.catSplit){ summary.setCatSplit(facetDescr.catSplit); } if(facetDescr.type){ facetDescr.type = facetDescr.type.toLowerCase(); if(facetDescr.type!==summary.type){ summary.destroy(); if(facetDescr.value===undefined){ facetDescr.value = facetDescr.name; } if(typeof(facetDescr.value)==="string"){ summary = this.createSummary(facetDescr.value,null,facetDescr.type); if(facetDescr.value!==facetDescr.name) this.changeSummaryName(facetDescr.value,facetDescr.name); } else if(typeof(facetDescr.value)==="function"){ summary = this.createSummary(facetDescr.name,facetDescr.value,facetDescr.type); } } } // If summary object is not found/created, nothing else to do if(summary===undefined) return; summary.initializeAggregates(); // Common settings if(facetDescr.collapsed){ summary.setCollapsed(true); } if(facetDescr.description) { summary.setDescription(facetDescr.description); } // THESE AFFECT HOW CATEGORICAL VALUES ARE MAPPED if(summary.type==='categorical'){ if(facetDescr.catTableName){ summary.setCatTable(facetDescr.catTableName); } if(facetDescr.catLabel){ // if this is a function definition, evaluate it if(typeof facetDescr.catLabel === "string" && facetDescr.catLabel.substr(0,8)==="function"){ eval("\"use strict\"; facetDescr.catLabel = "+facetDescr.catLabel); } summary.setCatLabel(facetDescr.catLabel); } if(facetDescr.catTooltip){ summary.setCatTooltip(facetDescr.catTooltip); } if(facetDescr.catMap){ summary.setCatGeo(facetDescr.catMap); } if(facetDescr.minAggrValue) { summary.setMinAggrValue(facetDescr.minAggrValue); } if(facetDescr.catSortBy!==undefined){ summary.setSortingOptions(facetDescr.catSortBy); } if(facetDescr.panel!=="none"){ facetDescr.panel = facetDescr.panel || 'left'; summary.addToPanel(this.panels[facetDescr.panel]); } if(facetDescr.viewAs){ summary.viewAs(facetDescr.viewAs); } } if(summary.type==='interval'){ summary.unitName = facetDescr.unitName || summary.unitName; if(facetDescr.showPercentile) { summary.showPercentileChart(facetDescr.showPercentile); } summary.optimumTickWidth = facetDescr.optimumTickWidth || summary.optimumTickWidth; // add to panel before you set scale type and other options: TODO: Fix if(facetDescr.panel!=="none"){ facetDescr.panel = facetDescr.panel || 'left'; summary.addToPanel(this.panels[facetDescr.panel]); } if(facetDescr.scaleType) { summary.setScaleType(facetDescr.scaleType,true); } } },this); this.panels.left.updateWidth_QueryPreview(); this.panels.right.updateWidth_QueryPreview(); this.panels.middle.updateWidth_QueryPreview(); this.recordDisplay = new kshf.RecordDisplay(this,this.options.recordDisplay||{}); if(this.options.measure){ var summary = this.summaries_by_name[this.options.measure]; this.setMeasureFunction(summary,"Sum"); } this.DOM.recordName.html(this.itemName); if(this.source.url){ this.DOM.datasource.style("display","inline-block").attr("href",this.source.url); } this.checkBrowserZoomLevel(); this.loaded = true; var x = function(){ var totalWidth = this.divWidth; var colCount = 0; if(this.panels.left.summaries.length>0){ totalWidth-=this.panels.left.width_catLabel+kshf.scrollWidth+this.panels.left.width_catMeasureLabel; colCount++; } if(this.panels.right.summaries.length>0){ totalWidth-=this.panels.right.width_catLabel+kshf.scrollWidth+this.panels.right.width_catMeasureLabel; colCount++; } if(this.panels.middle.summaries.length>0){ totalWidth-=this.panels.middle.width_catLabel+kshf.scrollWidth+this.panels.middle.width_catMeasureLabel; colCount++; } return Math.floor((totalWidth)/8); }; var defaultBarChartWidth = x.call(this); this.panels.left.setWidthCatBars(this.options.barChartWidth || defaultBarChartWidth); this.panels.right.setWidthCatBars(this.options.barChartWidth || defaultBarChartWidth); this.panels.middle.setWidthCatBars(this.options.barChartWidth || defaultBarChartWidth); this.panels.bottom.updateSummariesWidth(this.options.barChartWidth || defaultBarChartWidth); this.updateMiddlePanelWidth(); this.refresh_filterClearAll(); this.records.forEach(function(record){ record.updateWanted(); }); this.update_Records_Wanted_Count(); this.updateAfterFilter(); this.updateLayout_Height(); // hide infobox this.panel_infobox.attr("show","none"); this.reorderNuggetList(); if(this.recordDisplay.displayType==='nodelink'){ this.recordDisplay.initializeNetwork(); } if(typeof this.readyCb === "string" && this.readyCb.substr(0,8)==="function"){ eval("\"use strict\"; this.readyCb = "+this.readyCb); } if(typeof this.readyCb === "function") { this.readyCb(this); } this.finalized = true; setTimeout(function(){ if(me.options.enableAuthoring) me.enableAuthoring(true); if(me.recordDisplay.displayType==="map"){ setTimeout(function(){ me.recordDisplay.map_zoomToActive(); }, 1000); } me.setNoAnim(false); },1000); }, /** -- */ unregisterBodyCallbacks: function(){ // TODO: Revert to previous handlers... d3.select("body").style('cursor','auto') .on("mousemove",null) .on("mouseup",null) .on("keydown",null); }, /** -- */ prepareDropZones: function(summary,source){ this.movedSummary = summary; this.showDropZones = true; this.DOM.root .attr("showdropzone",true) .attr("dropattrtype",summary.getDataType()) .attr("dropSource",source); this.DOM.attribDragBox.style("display","block").html(summary.summaryName); }, /** -- */ clearDropZones: function(){ this.showDropZones = false; this.unregisterBodyCallbacks(); this.DOM.root.attr("showdropzone",null); this.DOM.attribDragBox.style("display","none"); if(this.movedSummary && !this.movedSummary.uniqueCategories()){ // ? } this.movedSummary = undefined; }, /** -- */ reorderNuggetList: function(){ this.summaries = this.summaries.sort(function(a,b){ var a_cat = a instanceof kshf.Summary_Categorical; var b_cat = b instanceof kshf.Summary_Categorical; if(a_cat && !b_cat) return -1; if(!a_cat && b_cat) return 1; if(a_cat && b_cat && a._cats && b._cats){ return a._cats.length - b._cats.length; } return a.summaryName.localeCompare(b.summaryName, { sensitivity: 'base' }); }); var x=this.DOM.attributeList; x.selectAll(".nugget").data(this.summaries, function(summary){return summary.summaryID;}).order(); }, /** -- */ autoCreateBrowser: function(){ this.summaries.forEach(function(summary,i){ if(summary.uniqueCategories()) return; if(summary.type==="categorical" && summary._cats.length>1000) return; if(summary.panel) return; this.autoAddSummary(summary); this.updateLayout_Height(); },this); this.updateLayout(); }, /** -- */ autoAddSummary: function(summary){ if(summary.uniqueCategories()){ this.recordDisplay.setRecordViewSummary(summary); if(this.recordDisplay.textSearchSummary===null) this.recordDisplay.setTextSearchSummary(summary); return; } // If tithis, add to bottom panel var target_panel; if(summary.isTimeStamp()) { target_panel = 'bottom'; } else if(summary.type==='categorical') { target_panel = 'left'; if(this.panels.left.summaries.length>Math.floor(this.panels.left.height/150)) target_panel = 'middle'; } else if(summary.type==='interval') { target_panel = 'right'; if(this.panels.right.summaries.length>Math.floor(this.panels.right.height/150)) target_panel = 'middle'; } summary.addToPanel(this.panels[target_panel]); }, /** -- */ clearFilters_All: function(force){ var me=this; if(this.skipSortingFacet){ // you can now sort the last filtered summary, attention is no longer there. this.skipSortingFacet.dirtySort = false; this.skipSortingFacet.DOM.catSortButton.attr("resort",false); } // clear all registered filters this.filters.forEach(function(filter){ filter.clearFilter(false,false); }) if(force!==false){ this.records.forEach(function(record){ if(!record.isWanted) record.updateWanted(); // Only update records which were not wanted before. }); this.update_Records_Wanted_Count(); this.refresh_filterClearAll(); this.updateAfterFilter(); // more results } setTimeout( function(){ me.updateLayout_Height(); }, 1000); // update layout after 1.75 seconds }, /** -- */ refresh_ActiveRecordCount: function(){ if(this.allRecordsAggr.recCnt.Active===0){ this.DOM.activeRecordMeasure.html("No"); return; } var numStr = this.allRecordsAggr.measure('Active').toLocaleString(); if(this.measureSummary){ numStr = this.measureSummary.printWithUnitName(numStr); } this.DOM.activeRecordMeasure.html(numStr); }, /** -- */ update_Records_Wanted_Count: function(){ this.recordsWantedCount = 0; this.records.forEach(function(record){ if(record.isWanted) this.recordsWantedCount++; },this); this.refreshTotalViz(); this.refresh_ActiveRecordCount(); }, /** -- */ updateAfterFilter: function () { kshf.browser = this; this.clearSelect_Compare('A'); this.clearSelect_Compare('B'); this.clearSelect_Compare('C'); this.clearCrumbAggr('Compared_A'); this.summaries.forEach(function(summary){ summary.updateAfterFilter(); }); this.recordDisplay.updateAfterFilter(); }, /** -- */ refresh_filterClearAll: function(){ this.DOM.filterClearAll.attr("active", this.filters.some(function(filter){ return filter.isFiltered; }) ); }, /** Ratio mode is when glyphs scale to their max */ setMeasureAxisMode: function(how){ this.ratioModeActive = how; this.DOM.root.attr("relativeMode",how?how:null); this.setPercentLabelMode(how); this.summaries.forEach(function(summary){ summary.refreshViz_All(); }); this.refreshMeasureLabels(); this.refreshTotalViz(); }, /** -- */ refreshMeasureLabels: function(t){ this.measureLabelType = t; this.DOM.root.attr("measureLabelType",this.measureLabelType ? this.measureLabelType : null) this.summaries.forEach(function(summary){ summary.refreshMeasureLabel(); }); }, /** -- */ setPercentLabelMode: function(how){ this.percentModeActive = how; this.DOM.root.attr("percentLabelMode",how?"true":null); this.summaries.forEach(function(summary){ if(!summary.inBrowser()) return; summary.refreshMeasureLabel(); if(summary.viewType==='map'){ summary.refreshMapBounds(); } summary.refreshViz_Axis(); }); }, /** -- */ clearSelect_Compare: function(cT){ this.DOM.root.attr("selectCompared_"+cT,null); this.vizActive["Compared_"+cT] = false; if(this.selectedAggr["Compared_"+cT]){ this.selectedAggr["Compared_"+cT].clearCompare(cT); this.selectedAggr["Compared_"+cT] = null; } var ccT = "Compared_"+cT; this.allAggregates.forEach(function(aggr){ aggr._measure[ccT] = 0; aggr.recCnt[ccT] = 0; }); this.summaries.forEach(function(summary){ summary.refreshViz_Compare_All(); }); }, /** -- */ setSelect_Compare: function(selSummary, selAggregate, noReclick){ if(selAggregate.compared){ var x = "Compared_"+selAggregate.compared; this.clearSelect_Compare(selAggregate.compared); if(noReclick) { this.clearCrumbAggr(x); return; } } var cT = "A"; // Which compare type to store? A, B, C if(this.DOM.root.attr("selectCompared_A")){ cT = this.DOM.root.attr("selectCompared_B") ? "C" : "B"; } var compId = "Compared_"+cT; this.vizActive["Compared_"+cT] = true; this.DOM.root.attr("selectCompared_"+cT,true); this.selectedAggr[compId] = selAggregate; this.selectedAggr[compId].selectCompare(cT); if(!this.preview_not){ this.allAggregates.forEach(function(aggr){ aggr._measure[compId] = aggr._measure.Highlighted; aggr.recCnt[compId] = aggr.recCnt.Highlighted; },this); } else { this.allAggregates.forEach(function(aggr){ aggr._measure[compId] = aggr._measure.Active - aggr._measure.Highlighted; aggr.recCnt[compId] = aggr.recCnt.Active - aggr.recCnt.Highlighted; },this); } this.summaries.forEach(function(summary){ if(this.measureFunc==="Avg" && summary.updateChartScale_Measure){ // refreshes all visualizations automatically summary.updateChartScale_Measure(); } else { summary.refreshViz_Compare_All(); } },this); this.refreshTotalViz(); this.setCrumbAggr(compId,selSummary); }, /** -- */ clearSelect_Highlight: function(){ var me = this; this.vizActive.Highlighted = false; this.DOM.root.attr("selectHighlight",null); this.highlightSelectedSummary = null; if(this.selectedAggr.Highlighted){ this.selectedAggr.Highlighted.clearHighlight(); this.selectedAggr.Highlighted = undefined; } this.allAggregates.forEach(function(aggr){ aggr._measure.Highlighted = 0; aggr.recCnt.Highlighted = 0; }); this.summaries.forEach(function(summary){ summary.refreshViz_Highlight(); }); this.refreshTotalViz(); // if the crumb is shown, start the hide timeout if(this.highlightCrumbTimeout_Hide) clearTimeout(this.highlightCrumbTimeout_Hide); this.highlightCrumbTimeout_Hide = setTimeout(function(){ me.clearCrumbAggr("Highlighted"); this.highlightCrumbTimeout_Hide = undefined; },1000); }, /** -- */ setSelect_Highlight: function(selSummary,selAggregate, headerName){ var me=this; this.vizActive.Highlighted = true; this.DOM.root.attr("selectHighlight",true); this.highlightSelectedSummary = selSummary; this.selectedAggr.Highlighted = selAggregate; this.selectedAggr.Highlighted.selectHighlight(); this.summaries.forEach(function(summary){ summary.refreshViz_Highlight(); }); this.refreshTotalViz(); clearTimeout(this.highlightCrumbTimeout_Hide); this.highlightCrumbTimeout_Hide = undefined; this.setCrumbAggr("Highlighted",selSummary,headerName); }, /** -- */ setCrumbAggr: function(selectType, selectedSummary, headerName){ var crumb = this.DOM.breadcrumbs.select(".crumbMode_"+selectType); if(crumb[0][0]===null) crumb = this.insertDOM_crumb(selectType); if(headerName===undefined) headerName = selectedSummary.summaryName; crumb.select(".crumbHeader" ).html(headerName); if(selectedSummary) crumb.select(".filterDetails").html( (this.selectedAggr[selectType] instanceof kshf.Aggregate_EmptyRecords) ? kshf.lang.cur.NoData : selectedSummary.printAggrSelection(this.selectedAggr[selectType]) ); }, /** -- */ clearCrumbAggr: function(selectType){ var crumb = this.DOM.breadcrumbs.select(".crumbMode_"+selectType); if(crumb[0][0]===null) return; crumb.attr("ready",false); setTimeout(function(){ crumb[0][0].parentNode.removeChild(crumb[0][0]); }, 350); }, /** -- */ getMeasureFuncTypeText: function(){ return this.measureSummary ? (((this.measureFunc==="Sum")?"Total ":"Average ")+this.measureSummary.summaryName+" of ") : ""; }, /** funType: "Sum" or "Avg" */ setMeasureFunction: function(summary, funcType){ if(summary===undefined || summary.type!=='interval' || summary.scaleType==='time'){ // Clearing measure summary (defaulting to count) if(this.measureSummary===undefined) return; // No update this.measureSummary = undefined; this.records.forEach(function(record){ record.measure_Self = 1; }); this.measureFunc = "Count"; } else { if(this.measureSummary===summary && this.measureFunc===funcType) return; // No update this.measureSummary = summary; this.measureFunc = funcType; summary.initializeAggregates(); this.records.forEach(function(record){ record.measure_Self = summary.getRecordValue(record); }); } this.DOM.measureFuncType.html(this.getMeasureFuncTypeText()); this.DOM.root.attr("measureFunc",this.measureFunc); if(this.measureFunc==="Avg"){ // Remove ratio and percent modes if(this.ratioModeActive){ this.setMeasureAxisMode(false); } if(this.percentModeActive){ this.setPercentLabelMode(false); } } this.allAggregates.forEach(function(aggr){ aggr.resetAggregateMeasures(); }); this.summaries.forEach(function(summary){ summary.updateAfterFilter(); }); this.update_Records_Wanted_Count(); }, /** -- */ checkBrowserZoomLevel: function(){ // Using devicePixelRatio works in Chrome and Firefox, but not in Safari // I have not tested IE yet. if(window.devicePixelRatio!==undefined){ if(window.devicePixelRatio!==1 && window.devicePixelRatio!==2){ var me=this; setTimeout(function(){ me.showWarning("Please reset your browser zoom level for the best experience.") },1000); } else { this.hideWarning(); } } else { this.hideWarning(); } }, /** -- */ updateLayout: function(){ if(this.loaded!==true) return; this.divWidth = this.domWidth(); this.updateLayout_Height(); this.updateMiddlePanelWidth(); this.refreshTotalViz(); }, /** -- */ updateLayout_Height: function(){ var me=this; var divHeight_Total = this.domHeight(); var panel_Basic_height = Math.max(parseInt(this.DOM.panel_Basic.style("height")),24)+6; divHeight_Total-=panel_Basic_height; // initialize all summaries as not yet processed. this.summaries.forEach(function(summary){ if(summary.inBrowser()) summary.heightProcessed = false; }); var bottomPanelHeight=0; // process bottom summary if(this.panels.bottom.summaries.length>0){ var targetHeight=divHeight_Total/3; // they all share the same target height this.panels.bottom.summaries.forEach(function(summary){ targetHeight = Math.min(summary.getHeight_RangeMax(),targetHeight); summary.setHeight(targetHeight); summary.heightProcessed = true; bottomPanelHeight += summary.getHeight(); }); } var doLayout = function(sectionHeight,summaries){ sectionHeight-=1;// just use 1-pixel gap var finalPass = false; var lastRound = false; var processedFacets=0; summaries.forEach(function(summary){ if(summary.heightProcessed) processedFacets++; }); while(true){ var remainingFacetCount = summaries.length-processedFacets; if(remainingFacetCount===0) break; var processedFacets_pre = processedFacets; function finishSummary(summary){ sectionHeight-=summary.getHeight(); summary.heightProcessed = true; processedFacets++; remainingFacetCount--; }; summaries.forEach(function(summary){ if(summary.heightProcessed) return; // Empty or collapsed summaries: Fixed height, nothing to change; if(summary.isEmpty() || summary.collapsed) { finishSummary(summary); return; } // in last round, if summary can expand, expand it further if(lastRound===true && summary.heightProcessed && summary.getHeight_RangeMax()>summary.getHeight()){ sectionHeight+=summary.getHeight(); summary.setHeight(sectionHeight); sectionHeight-=summary.getHeight(); return; } if(remainingFacetCount===0) return; // Fairly distribute remaining size across all remaining summaries. var targetHeight = Math.floor(sectionHeight/remainingFacetCount); // auto-collapse summary if you do not have enough space if(finalPass && targetHeight<summary.getHeight_RangeMin()){ summary.setCollapsed(true); finishSummary(summary); return; } if(summary.getHeight_RangeMax()<=targetHeight){ summary.setHeight(summary.getHeight_RangeMax()); finishSummary(summary); } else if(finalPass){ summary.setHeight(targetHeight); finishSummary(summary); } },this); finalPass = processedFacets_pre===processedFacets; if(lastRound===true) break; if(remainingFacetCount===0) lastRound = true; } return sectionHeight; }; var topPanelsHeight = divHeight_Total; this.panels.bottom.DOM.root.style("height",bottomPanelHeight+"px"); topPanelsHeight-=bottomPanelHeight; this.DOM.panelsTop.style("height",topPanelsHeight+"px"); // Left Panel if(this.panels.left.summaries.length>0){ this.panels.left.height = topPanelsHeight; doLayout.call(this,topPanelsHeight,this.panels.left.summaries); } // Right Panel if(this.panels.right.summaries.length>0){ this.panels.right.height = topPanelsHeight; doLayout.call(this,topPanelsHeight,this.panels.right.summaries); } // Middle Panel var midPanelHeight = 0; if(this.panels.middle.summaries.length>0){ var panelHeight = topPanelsHeight; if(this.recordDisplay.recordViewSummary){ panelHeight -= 200; // give 200px fo the list display } else { panelHeight -= this.recordDisplay.DOM.root[0][0].offsetHeight; } midPanelHeight = panelHeight - doLayout.call(this,panelHeight, this.panels.middle.summaries); } this.panels.middle.DOM.root.style("height",midPanelHeight+"px"); // The part where summary DOM is updated this.summaries.forEach(function(summary){ if(summary.inBrowser()) summary.refreshHeight(); }); if(this.recordDisplay){ // get height of header var listDisplayHeight = divHeight_Total - this.recordDisplay.DOM.recordDisplayHeader[0][0].offsetHeight - midPanelHeight - bottomPanelHeight; if(this.showDropZones && this.panels.middle.summaries.length===0) listDisplayHeight*=0.5; this.recordDisplay.setHeight(listDisplayHeight); } }, /** -- */ updateMiddlePanelWidth: function(){ // for some reason, on page load, this variable may be null. urgh. var widthMiddlePanel = this.getWidth_Browser(); var marginLeft = 0; var marginRight = 0; if(this.panels.left.summaries.length>0){ marginLeft=2; widthMiddlePanel-=this.panels.left.getWidth_Total()+2; } if(this.panels.right.summaries.length>0){ marginRight=2; widthMiddlePanel-=this.panels.right.getWidth_Total()+2; } this.panels.left.DOM.root.style("margin-right",marginLeft+"px") this.panels.right.DOM.root.style("margin-left",marginRight+"px") this.panels.middle.setTotalWidth(widthMiddlePanel); this.panels.middle.updateSummariesWidth(); this.panels.bottom.setTotalWidth(this.divWidth); this.panels.bottom.updateSummariesWidth(); this.DOM.middleColumn.style("width",widthMiddlePanel+"px"); this.recordDisplay.refreshWidth(widthMiddlePanel); }, /** -- */ getMeasureLabel: function(aggr,summary){ var _val; if(!(aggr instanceof kshf.Aggregate)){ _val = aggr; } else { if(!aggr.isVisible) return ""; if(this.measureLabelType){ _val = aggr.measure(this.measureLabelType); } else { if(summary && summary === this.highlightSelectedSummary && !summary.isMultiValued){ _val = aggr.measure('Active'); } else { _val = this.vizActive.Highlighted? (this.preview_not? aggr._measure.Active - aggr._measure.Highlighted : aggr.measure('Highlighted') ) : aggr.measure('Active'); } } if(this.percentModeActive){ // Cannot be Avg-function if(aggr._measure.Active===0) return ""; if(this.ratioModeActive){ if(this.measureLabelType===undefined && !this.vizActive.Highlighted) return ""; _val = 100*_val/aggr._measure.Active; } else { _val = 100*_val/this.allRecordsAggr._measure.Active; } } } if(_val<0) _val=0; // TODO? There is it, again... Just sanity I guess if(this.measureFunc!=="Count"){ // Avg or Sum _val = Math.round(_val); } if(this.percentModeActive){ if(aggr.DOM && aggr.DOM.aggrGlyph.nodeName==="g"){ return _val.toFixed(0)+"%"; } else { return _val.toFixed(0)+"<span class='unitName'>%</span>"; } } else if(this.measureSummary){ // Print with the measure summary unit return this.measureSummary.printWithUnitName(kshf.Util.formatForItemCount( _val),(aggr.DOM && aggr.DOM.aggrGlyph.nodeName==="g") ); } else { return kshf.Util.formatForItemCount(_val); } }, /** -- */ exportConfig: function(){ var config = {}; config.domID = this.domID; config.itemName = this.itemName; config.source = this.source; delete config.source.loadedTableCount; config.summaries = []; config.leftPanelLabelWidth = this.panels.left.width_catLabel; config.rightPanelLabelWidth = this.panels.right.width_catLabel; config.middlePanelLabelWidth = this.panels.middle.width_catLabel; if(typeof this.options.loadedCb === "function"){ config.loadedCb = this.options.loadedCb.toString(); } if(typeof this.readyCb === "function"){ config.readyCb = this.readyCb.toString(); } ['left', 'right', 'middle', 'bottom'].forEach(function(p){ // Need to export summaries in-order of the panel appearance // TODO: Export summaries not within browser... this.panels[p].summaries.forEach(function(summary){ config.summaries.push(summary.exportConfig()); }); },this); if(this.recordDisplay.recordViewSummary){ config.recordDisplay = this.recordDisplay.exportConfig(); } return config; } }; // *********************************************************************************************************** // *********************************************************************************************************** kshf.Summary_Base = function(){} kshf.Summary_Base.prototype = { initialize: function(browser,name,attribFunc){ this.summaryID = browser.summaryCount++; this.browser = browser; this.summaryName = name; this.summaryColumn = attribFunc?null:name; this.summaryFunc = attribFunc || function(){ return this[name]; }; this.missingValueAggr = new kshf.Aggregate_EmptyRecords(); this.missingValueAggr.init(); this.browser.allAggregates.push(this.missingValueAggr); this.DOM = {}; this.DOM.inited = false; if(kshf.Summary_Set && this instanceof kshf.Summary_Set) return; this.chartScale_Measure = d3.scale.linear().clamp(true); this.records = this.browser.records; if(this.records===undefined||this.records===null||this.records.length===0){ alert("Error: Browser.records is not defined..."); return; } this.isRecordView = false; // Only used when summary is inserted into browser this.collapsed_pre = false; this.collapsed = false; this.aggr_initialized = false; this.createSummaryFilter(); this.insertNugget(); }, /** -- */ setSummaryName: function(name){ this.summaryName = name; if(this.DOM.summaryName_text){ this.DOM.summaryName_text.html(this.summaryName); } this.summaryFilter._refreshFilterSummary(); // This summary may be used for sorting options. Refresh the list if(this.browser.recordDisplay){ if(this.sortingSummary) this.browser.recordDisplay.refreshSortingOptions(); } if(this.isTextSearch){ this.browser.recordDisplay.DOM.recordTextSearch.select("input") .attr("placeholder",kshf.lang.cur.Search+": "+this.summaryName); } if(this.sortFunc){ this.browser.recordDisplay.refreshSortingOptions(); } if(this.DOM.nugget){ this.DOM.nugget.select(".summaryName").html(this.summaryName); this.DOM.nugget.attr("state",function(summary){ if(summary.summaryColumn===null) return "custom"; // calculated if(summary.summaryName===summary.summaryColumn) return "exact"; return "edited"; }); } }, /** -- */ setShowSetMatrix: function(v){ this.show_set_matrix = v; this.DOM.root.attr("show_set_matrix",this.show_set_matrix); if(this.setSummary===undefined){ this.setSummary = new kshf.Summary_Set(); this.setSummary.initialize(this.browser,this); this.browser.summaries.push(this.setSummary); } }, /** -- */ getDataType: function(){ if(this.type==='categorical') { var str="categorical"; if(!this.aggr_initialized) return str+=" uninitialized"; if(this.uniqueCategories()) str+=" unique"; str+=this.isMultiValued?" multivalue":" singlevalue"; return str; } if(this.type==='interval') { if(!this.aggr_initialized) return str+=" uninitialized"; if(this.isTimeStamp()) return "interval time"; return "interval numeric"; // if(this.hasFloat) return "floating"; return "integer"; } return "?"; }, /** -- */ destroy_full: function(){ this.destroy(); // TODO: Properly destroy this using nugget handlers... var nuggetDOM = this.DOM.nugget[0][0]; if(nuggetDOM && nuggetDOM.parentNode) nuggetDOM.parentNode.removeChild(nuggetDOM); }, /** -- */ destroy: function(){ delete this.browser.summaries_by_name[this.summaryName]; if(this.summaryColumn) delete this.browser.summaries_by_name[this.summaryColumn]; this.browser.removeSummary(this); if(this.DOM.root){ this.DOM.root[0][0].parentNode.removeChild(this.DOM.root[0][0]); } if(this.DOM.nugget){ this.DOM.nugget[0][0].parentNode.removeChild(this.DOM.nugget[0][0]); } }, /** -- */ inBrowser: function(){ return this.panel!==undefined; }, /** -- */ isTimeStamp: function(){ return false; // False by default }, /** -- */ clearDOM: function(){ var dom = this.DOM.root[0][0]; dom.parentNode.removeChild(dom); }, /** -- */ getWidth: function(){ return this.panel.getWidth_Total(); }, /** -- */ getHeight: function(){ if(this.isEmpty() || this.collapsed) return this.getHeight_Header(); return this.getHeight_Header() + this.getHeight_Content(); }, /** -- */ getHeight_Header: function(){ if(!this.DOM.inited) return 0; if(this._height_header==undefined) { this._height_header = this.DOM.headerGroup[0][0].offsetHeight; } return this._height_header; }, /** -- */ uniqueCategories: function(){ if(this.browser && this.browser.records[0].idIndex===this.summaryName) return true; return false; }, /** -- */ isFiltered: function(){ return this.summaryFilter.isFiltered; }, /** -- */ isEmpty: function(){ alert("Nope. Sth is wrong."); // should not be executed return true; }, /** -- */ getFuncString: function(){ var str=this.summaryFunc.toString(); // replace the beginning, and the end return str.replace(/function\s*\(\w*\)\s*{\s*/,"").replace(/}$/,""); }, /** -- */ addToPanel: function(panel, index){ if(index===undefined) index = panel.summaries.length; // add to end if(this.panel===undefined){ this.panel = panel; } else if(this.panel && this.panel!==panel){ this.panel.removeSummary(this); this.panel = panel; } else{ // this.panel === panel var curIndex; // this.panel is the same as panel... this.panel.summaries.forEach(function(s,i){ if(s===this) curIndex = i; },this); // inserting the summary to the same index as current one if(curIndex===index) return; var toRemove=this.panel.DOM.root.selectAll(".dropZone_between_wrapper")[0][curIndex]; toRemove.parentNode.removeChild(toRemove); } var beforeDOM = this.panel.DOM.root.selectAll(".dropZone_between_wrapper")[0][index]; if(this.DOM.root){ this.DOM.root.style("display",""); panel.DOM.root[0][0].insertBefore(this.DOM.root[0][0],beforeDOM); } else { this.initDOM(beforeDOM); } panel.addSummary(this,index); this.panel.refreshDropZoneIndex(); this.refreshNuggetDisplay(); if(this.type=="categorical"){ this.refreshLabelWidth(); } if(this.type==='interval'){ if(this.browser.recordDisplay) this.browser.recordDisplay.addSortingOption(this); } this.refreshWidth(); this.browser.refreshMeasureSelectAction(); }, /** -- */ removeFromPanel: function(){ if(this.panel===undefined) return; this.panel.removeSummary(this); this.refreshNuggetDisplay(); }, /** -- */ insertNugget: function(){ var me=this; if(this.DOM.nugget) return; this.attribMoved = false; this.DOM.nugget = this.browser.DOM.attributeList .append("div").attr("class","nugget editableTextContainer") .each(function(){ this.__data__ = me; }) .attr("title", (this.summaryColumn!==undefined) ? this.summaryColumn : undefined ) .attr("state",function(){ if(me.summaryColumn===null) return "custom"; // calculated if(me.summaryName===me.summaryColumn) return "exact"; return "edited"; }) .attr("datatype", this.getDataType() ) .attr("aggr_initialized", this.aggr_initialized ) .on("dblclick",function(){ me.browser.autoAddSummary(me); me.browser.updateLayout(); }) .on("mousedown",function(){ if(d3.event.which !== 1) return; // only respond to left-click var _this = this; me.attribMoved = false; d3.select("body") .on("keydown", function(){ if(event.keyCode===27){ // Escape key _this.removeAttribute("moved"); me.browser.clearDropZones(); } }) .on("mousemove", function(){ if(!me.attribMoved){ _this.setAttribute("moved",""); me.browser.prepareDropZones(me,"attributePanel"); me.attribMoved = true; } var mousePos = d3.mouse(me.browser.DOM.root[0][0]); kshf.Util.setTransform(me.browser.DOM.attribDragBox[0][0], "translate("+(mousePos[0]-20)+"px,"+(mousePos[1]+5)+"px)"); d3.event.stopPropagation(); d3.event.preventDefault(); }) .on("mouseup", function(){ if(!me.attribMoved) return; _this.removeAttribute("moved"); me.browser.DOM.root.attr("drag_cursor",null); me.browser.clearDropZones(); d3.event.preventDefault(); }); d3.event.preventDefault(); }) .on("mouseup",function(){ if(me.attribMoved===false) me.browser.unregisterBodyCallbacks(); }); this.DOM.nuggetViz = this.DOM.nugget.append("span").attr("class","nuggetViz") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'e', title: function(){ return (!me.aggr_initialized) ? "Initialize" : me.getDataType(); } }); }) .on("mousedown",function(){ if(!me.aggr_initialized){ d3.event.stopPropagation(); d3.event.preventDefault(); } }) .on("click",function(){ if(!me.aggr_initialized) me.initializeAggregates(); }); this.DOM.nuggetViz.append("span").attr("class","nuggetInfo fa"); this.DOM.nuggetViz.append("span").attr("class","nuggetChart"); this.DOM.nugget.append("span").attr("class","summaryName editableText") .attr("contenteditable",false) .html(this.summaryName) .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'w', title: kshf.lang.cur.EditTitle }); }) .on("mouseenter",function(){ this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }) .on("mousedown",function(){ this.tipsy.hide(); var parentDOM = d3.select(this.parentNode); var summaryName = parentDOM.select(".summaryName"); var summaryName_DOM = parentDOM.select(".summaryName")[0][0]; var curState=this.parentNode.getAttribute("edittitle"); if(curState===null || curState==="false"){ this.parentNode.setAttribute("edittitle",true); summaryName_DOM.setAttribute("contenteditable",true); summaryName_DOM.focus(); } else { /* this.parentNode.setAttribute("edittitle",false); summaryName_DOM.setAttribute("contenteditable",false); me.browser.changeSummaryName(me.summaryName,summaryName_DOM.textContent); */ } // stop dragging event start d3.event.stopPropagation(); d3.event.preventDefault(); }) .on("blur",function(){ this.parentNode.setAttribute("edittitle",false); this.setAttribute("contenteditable",false); me.browser.changeSummaryName(me.summaryName,this.textContent); d3.event.preventDefault(); d3.event.stopPropagation(); }) .on("keydown",function(){ if(d3.event.keyCode===13){ // ENTER this.parentNode.setAttribute("edittitle",false); this.setAttribute("contenteditable",false); me.browser.changeSummaryName(me.summaryName,this.textContent); d3.event.preventDefault(); d3.event.stopPropagation(); } }); this.DOM.nugget.append("div").attr("class","fa fa-code editCodeButton") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'w', title: kshf.lang.cur.EditFormula }); }) .on("mouseenter",function(){ this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }) .on("mousedown",function(){ d3.event.stopPropagation(); d3.event.preventDefault(); }) .on("click",function(){ var safeFunc, func = window.prompt("Specify the function:", me.getFuncString()); if(func!==null){ var safeFunc; eval("\"use strict\"; safeFunc = function(d){"+func+"}"); me.browser.createSummary(me.summaryName,safeFunc); } // stop dragging event start d3.event.stopPropagation(); d3.event.preventDefault(); }); this.DOM.nugget.append("div").attr("class","splitCatAttribute_Button fa fa-scissors") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'w', title: "Split" }); }) .on("mouseenter",function(){ this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }) .on("click",function(){ d3.event.stopPropagation(); d3.event.preventDefault(); var catSplit = window.prompt('Split by text: (Ex: Splitting "A;B;C" by ";" will create 3 separate values: A,B,C', ""); if(catSplit!==null){ me.setCatSplit(catSplit); } // stop dragging event start d3.event.stopPropagation(); d3.event.preventDefault(); }); this.DOM.nugget.append("div").attr("class","addFromAttribute_Button fa fa-plus-square") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'w', title: function(){ if(me.isMultiValued) return "Extract \"# of"+me.summaryName+"\""; if(me.isTimeStamp() ) { if(me.timeTyped.month && me.summary_sub_month===undefined){ return "Extract Month of "+me.summaryName; } if(me.timeTyped.day && me.summary_sub_day===undefined){ return "Extract WeekDay of "+me.summaryName; } if(me.timeTyped.hour && me.summary_sub_hour===undefined){ return "Extract Hour of "+me.summaryName; } } return "?"; } }); }) .on("mouseenter",function(){ this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }) .on("click",function(){ d3.event.stopPropagation(); d3.event.preventDefault(); if(me.isMultiValued && !me.hasDegreeSummary){ var summary = me.browser.createSummary( "# of "+me.summaryName, function(d){ var arr=d._valueCache[me.summaryID]; return (arr===null) ? null : arr.length; }, 'interval' ); summary.initializeAggregates(); me.hasDegreeSummary = true; this.style.display = "none"; return; } if(me.isTimeStamp()){ if(me.timeTyped.month && me.summary_sub_month===undefined){ me.createMonthSummary(); } else if(me.timeTyped.day && me.summary_sub_day===undefined){ me.createDaySummary(); } else if(me.timeTyped.hour && me.summary_sub_hour===undefined){ me.createHourSummary(); } } }); this.refreshNuggetDisplay(); if(this.aggr_initialized) this.refreshViz_Nugget(); }, /** -- */ refreshNuggetDisplay: function(){ if(this.DOM.nugget===undefined) return; var me=this; var nuggetHidden = (this.panel||this.isRecordView); if(nuggetHidden){ this.DOM.nugget.attr('anim','disappear'); setTimeout(function(){ me.DOM.nugget.attr('hidden','true'); },700); } else { this.DOM.nugget.attr("hidden",false); setTimeout(function(){ me.DOM.nugget.attr('anim','appear'); },300); } }, /** -- */ insertRoot: function(beforeDOM){ this.DOM.root = this.panel.DOM.root.insert("div", function(){ return beforeDOM; }); this.DOM.root .attr("class","kshfSummary") .attr("summary_id",this.summaryID) .attr("collapsed",this.collapsed) .attr("filtered",false) .attr("showConfig",false); }, /** -- */ insertHeader: function(){ var me = this; this.DOM.headerGroup = this.DOM.root.append("div").attr("class","headerGroup") .on("mousedown", function(){ if(d3.event.which !== 1) return; // only respond to left-click if(!me.browser.authoringMode) { d3.event.preventDefault(); return; } var _this = this; var _this_nextSibling = _this.parentNode.nextSibling; var _this_previousSibling = _this.parentNode.previousSibling; var moved = false; d3.select("body") .style('cursor','move') .on("keydown", function(){ if(event.keyCode===27){ // ESP key _this.style.opacity = null; me.browser.clearDropZones(); } }) .on("mousemove", function(){ if(!moved){ _this_nextSibling.style.display = "none"; _this_previousSibling.style.display = "none"; _this.parentNode.style.opacity = 0.5; me.browser.prepareDropZones(me,"browser"); moved = true; } var mousePos = d3.mouse(me.browser.DOM.root[0][0]); kshf.Util.setTransform(me.browser.DOM.attribDragBox[0][0], "translate("+(mousePos[0]-20)+"px,"+(mousePos[1]+5)+"px)"); d3.event.stopPropagation(); d3.event.preventDefault(); }) .on("mouseup", function(){ // Mouse up on the body me.browser.clearDropZones(); if(me.panel!==undefined || true) { _this.parentNode.style.opacity = null; _this_nextSibling.style.display = ""; _this_previousSibling.style.display = ""; } d3.event.preventDefault(); }); d3.event.preventDefault(); }) ; var header_display_control = this.DOM.headerGroup.append("span").attr("class","header_display_control"); header_display_control.append("span").attr("class","buttonSummaryCollapse fa fa-collapse") .each(function(){ this.tipsy = new Tipsy(this, { gravity: function(){ return me.panelOrder!==0?'sw':'nw'; }, title: function(){ return me.collapsed?kshf.lang.cur.OpenSummary:kshf.lang.cur.MinimizeSummary; } }) }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .on("mousedown", function(){ d3.event.preventDefault(); d3.event.stopPropagation(); }) .on("click",function(){ this.tipsy.hide(); if(me instanceof kshf.Summary_Set){ me.setListSummary.setShowSetMatrix(false); } else { me.setCollapsedAndLayout(!me.collapsed); } }) ; header_display_control.append("span").attr("class","buttonSummaryExpand fa fa-arrows-alt") .each(function(){ this.tipsy = new Tipsy(this, { gravity: function(){ return me.panelOrder!==0?'sw':'nw'; }, title: kshf.lang.cur.MaximizeSummary }) }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .on("mousedown", function(){ d3.event.preventDefault(); d3.event.stopPropagation(); }) .on("click",function(){ me.panel.collapseAllSummaries(); me.setCollapsedAndLayout(false); // uncollapse this one }) ; header_display_control.append("span").attr("class","buttonSummaryRemove fa fa-remove") .each(function(){ this.tipsy = new Tipsy(this, { gravity: function(){ return me.panelOrder!==0?'sw':'nw'; }, title: kshf.lang.cur.RemoveSummary }) }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .on("mousedown", function(){ d3.event.preventDefault(); d3.event.stopPropagation(); }) .on("click",function(){ this.tipsy.hide(); me.removeFromPanel(); me.clearDOM(); me.browser.updateLayout(); }) ; this.DOM.summaryName = this.DOM.headerGroup.append("span") .attr("class","summaryName editableTextContainer") .attr("edittitle",false) .on("click",function(){ if(me.collapsed) me.setCollapsedAndLayout(false); }); this.DOM.summaryName.append("span").attr("class","chartFilterButtonParent").append("div") .attr("class","clearFilterButton rowFilter inSummary") .each(function(d){ this.tipsy = new Tipsy(this, { gravity: function(){ return me.panelOrder!==0?'s':'n'; }, title: kshf.lang.cur.RemoveFilter }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .on("mousedown", function(){ d3.event.preventDefault(); d3.event.stopPropagation(); }) .on("click", function(d,i){ this.tipsy.hide(); me.summaryFilter.clearFilter(); }) .append("span").attr("class","fa fa-times"); this.DOM.summaryName_text = this.DOM.summaryName.append("span").attr("class","summaryName_text editableText") .attr("contenteditable",false) .each(function(summary){ this.tipsy = new Tipsy(this, { gravity: 'w', title: kshf.lang.cur.EditTitle }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .on("mousedown", function(){ // stop dragging event start d3.event.stopPropagation(); d3.event.preventDefault(); }) .on("click", function(){ var curState=this.parentNode.getAttribute("edittitle"); if(curState===null || curState==="false"){ this.parentNode.setAttribute("edittitle",true); var parentDOM = d3.select(this.parentNode); var v=parentDOM.select(".summaryName_text")[0][0]; v.setAttribute("contenteditable",true); v.focus(); } else { this.parentNode.setAttribute("edittitle",false); var parentDOM = d3.select(this.parentNode); var v=parentDOM.select(".summaryName_text")[0][0]; v.setAttribute("contenteditable",false); me.browser.changeSummaryName(me.summaryName,v.textContent); } }) .on("blur",function(){ this.parentNode.setAttribute("edittitle",false); this.setAttribute("contenteditable", false); me.browser.changeSummaryName(me.summaryName,this.textContent); }) .on("keydown",function(){ if(event.keyCode===13){ // ENTER this.parentNode.setAttribute("edittitle",false); this.setAttribute("contenteditable", false); me.browser.changeSummaryName(me.summaryName,this.textContent); } }) .html(this.summaryName); this.DOM.summaryIcons = this.DOM.headerGroup.append("span").attr("class","summaryIcons"); this.DOM.summaryIcons.append("span").attr("class", "hasMultiMappings fa fa-tags") .each(function(d){ this.tipsy = new Tipsy(this, { gravity: 'ne', title: "Show relations within "+me.summaryName+"" }); }) .style("display", (this.isMultiValued && this._cats.length>5) ? "inline-block" : "none") .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .on("click",function(){ me.setShowSetMatrix(!me.show_set_matrix); }); this.DOM.summaryConfigControl = this.DOM.summaryIcons.append("span") .attr("class","summaryConfigControl fa fa-gear") .each(function(d){ this.tipsy = new Tipsy(this, { gravity:'ne', title: "Configure" }); }) .on("mouseover",function(d){ this.tipsy.show(); }) .on("mouseout" ,function(d){ this.tipsy.hide(); }) .on("click",function(d){ this.tipsy.hide(); me.DOM.root.attr("showConfig",me.DOM.root.attr("showConfig")==="false"); }); this.DOM.summaryForRecordDisplay = this.DOM.summaryIcons.append("span") .attr("class", "useForRecordDisplay fa") .each(function(d){ this.tipsy = new Tipsy(this, { gravity: 'ne', title: function(){ return "Use to "+me.browser.recordDisplay.getRecordEncoding()+" "+me.browser.itemName; } }); }) .on("mouseover",function(d){ this.tipsy.show(); }) .on("mouseout" ,function(d){ this.tipsy.hide(); }) .on("click",function(d){ if(me.browser.recordDisplay.recordViewSummary===null) return; me.browser.recordDisplay.setSortingOpt_Active(me); me.browser.recordDisplay.refreshSortingOptions(); }); this.DOM.summaryViewAs = this.DOM.summaryIcons.append("span") .attr("class","summaryViewAs fa") .attr("viewAs","map") .each(function(d){ this.tipsy = new Tipsy(this, { gravity: 'ne', title: function(){ return "View as "+(me.viewType==='list'?'Map':'List'); } }); }) .on("mouseover",function(d){ this.tipsy.show(); }) .on("mouseout" ,function(d){ this.tipsy.hide(); }) .on("click",function(d){ this.tipsy.hide(); this.setAttribute("viewAs",me.viewType); me.viewAs( (me.viewType==='list') ? 'map' : 'list' ); }); this.DOM.summaryDescription = this.DOM.summaryIcons.append("span") .attr("class","summaryDescription fa fa-info-circle") .each(function(d){ this.tipsy = new Tipsy(this, { gravity:'ne', title:function(){return me.description;} }); }) .on("mouseover",function(d){ this.tipsy.show(); }) .on("mouseout" ,function(d){ this.tipsy.hide(); }); this.setDescription(this.description); this.DOM.summaryConfig = this.DOM.root.append("div").attr("class","summaryConfig"); this.DOM.wrapper = this.DOM.root.append("div").attr("class","wrapper"); this.insertDOM_EmptyAggr(); }, /** -- */ setDescription: function(description){ this.description = description; if(this.DOM.summaryDescription===undefined) return; this.DOM.summaryDescription.style("display",this.description===undefined?null:"inline"); }, /** -- */ insertChartAxis_Measure: function(dom, pos1, pos2){ var me=this; this.DOM.chartAxis_Measure = dom.append("div").attr("class","chartAxis_Measure"); this.DOM.chartAxis_Measure.append("span").attr("class","measurePercentControl") .each(function(){ this.tipsy = new Tipsy(this, { gravity: pos1, title: function(){ return "<span class='fa fa-eye'></span> "+kshf.lang.cur[(me.browser.percentModeActive?'Absolute':'Percent')]; }, }) }) .on("click",function(){ this.tipsy.hide(); me.browser.setPercentLabelMode(!me.browser.percentModeActive); }) .on("mouseover",function(){ me.browser.DOM.root.selectAll(".measurePercentControl").attr("highlight",true); this.tipsy.show(); }) .on("mouseout",function(){ me.browser.DOM.root.selectAll(".measurePercentControl").attr("highlight",false); this.tipsy.hide(); }); // Two controls, one for each side of the scale this.DOM.chartAxis_Measure.selectAll(".relativeModeControl").data(["left","right"]) .enter().append("span") .attr("class",function(d){ return "relativeModeControl measureAxis_"+d+" relativeModeControl_"+d; }) .each(function(d){ var pos = pos2; if(pos2==='nw' && d==="right") pos = 'ne'; this.tipsy = new Tipsy(this, { gravity: pos, title: function(){ return (me.browser.ratioModeActive?kshf.lang.cur.Absolute:kshf.lang.cur.Relative)+" "+ kshf.lang.cur.Width+ " <span class='fa fa-arrows-h'></span>"; }, }); }) .on("click",function(){ this.tipsy.hide(); me.browser.setMeasureAxisMode(!me.browser.ratioModeActive); }) .on("mouseover",function(){ me.browser.DOM.root.selectAll(".relativeModeControl").attr("highlight",true); this.tipsy.show(); }) .on("mouseout",function(){ me.browser.DOM.root.selectAll(".relativeModeControl").attr("highlight",false); this.tipsy.hide(); }); this.DOM.chartAxis_Measure_TickGroup = this.DOM.chartAxis_Measure.append("div").attr("class","tickGroup"); this.DOM.highlightedMeasureValue = this.DOM.chartAxis_Measure.append("div").attr("class","highlightedMeasureValue longRefLine"); this.DOM.highlightedMeasureValue.append("div").attr('class','fa fa-mouse-pointer highlightedAggrValuePointer'); }, /** -- */ setCollapsedAndLayout: function(hide){ this.setCollapsed(hide); this.browser.updateLayout_Height(); }, /** -- */ setCollapsed: function(v){ this.collapsed_pre = this.collapsed; this.collapsed = v; if(this.DOM.root){ this.DOM.root .attr("collapsed",this.collapsed) .attr("showConfig",false); if(!this.collapsed) { this.refreshViz_All(); this.refreshMeasureLabel(); } else { this.DOM.headerGroup.select(".buttonSummaryExpand").style("display","none"); } } }, /** -- */ refreshViz_All: function(){ if(this.isEmpty() || this.collapsed || !this.inBrowser()) return; this.refreshViz_Total(); this.refreshViz_Active(); this.refreshViz_Highlight(); this.refreshViz_Compare_All(); this.refreshViz_Axis(); }, /** -- */ insertDOM_EmptyAggr: function(){ var me = this; this.DOM.missingValueAggr = this.DOM.wrapper.append("span").attr("class","missingValueAggr fa fa-ban") .each(function(){ me.missingValueAggr.DOM.aggrGlyph = this; this.tipsy = new Tipsy(this, {gravity: 'w', title: function(){ var x = me.browser.getMeasureLabel(me.missingValueAggr, me); // TODO: Number should depend on filtering state, and also reflect percentage-mode return "<b>"+x+"</b> "+me.browser.getMeasureFuncTypeText()+me.browser.itemName+" "+kshf.lang.cur.NoData; }}); }) .on("mouseover",function(){ this.tipsy.show(); // TODO: Disable mouse-over action if aggregate has no active item me.browser.setSelect_Highlight(me,me.missingValueAggr); }) .on("mouseout" ,function(){ this.tipsy.hide(); me.browser.clearSelect_Highlight(); }) .on("click", function(){ if(d3.event.shiftKey){ me.browser.setSelect_Compare(me,me.missingValueAggr,true); return; } me.summaryFilter.clearFilter(); if(me.missingValueAggr.filtered){ me.missingValueAggr.filtered = false; this.removeAttribute("filtered"); return; } else { me.missingValueAggr.filtered = true; this.setAttribute("filtered",true); me.summaryFilter.how = "All"; me.summaryFilter.addFilter(); } }); }, /** -- */ refreshViz_EmptyRecords: function(){ if(!this.DOM.missingValueAggr) return; var me=this; var interp = d3.interpolateHsl(d3.rgb(211,211,211)/*lightgray*/, d3.rgb(255,69,0)); this.DOM.missingValueAggr .style("display",this.missingValueAggr.recCnt.Active>0?"block":"none") .style("color", function(){ if(me.missingValueAggr.recCnt.Active===0) return; return interp(me.missingValueAggr.ratioHighlightToActive()); }); }, refreshViz_Compare_All: function(){ var totalC = this.browser.getActiveComparedCount(); if(totalC===0) return; totalC++; // 1 more for highlight if(this.browser.measureFunc==="Avg") totalC++; var activeNum = totalC-2; if(this.browser.vizActive.Compared_A) { this.refreshViz_Compare("A", activeNum, totalC); activeNum--; } if(this.browser.vizActive.Compared_B) { this.refreshViz_Compare("B", activeNum, totalC); activeNum--; } if(this.browser.vizActive.Compared_C) { this.refreshViz_Compare("C", activeNum, totalC); activeNum--; } }, /** -- */ exportConfig: function(){ var config = { name: this.summaryName, panel: this.panel.name, }; // config.value if(this.summaryColumn!==this.summaryName){ config.value = this.summaryColumn; if(config.value===null){ // custom function config.value = this.summaryFunc.toString(); // if it is function, converts it to string representation } } if(this.collapsed) config.collapsed = true; if(this.description) config.description = this.description; if(this.catLabel_attr){ // Indexed string if(this.catLabel_attr!=="id") config.catLabel = this.catLabel_attr; } else if(this.catLabel_table){ // Lookup table config.catLabel = this.catLabel_table; } else if(this.catLabel_Func){ config.catLabel = this.catLabel_Func.toString(); // Function to string } if(this.minAggrValue>1) config.minAggrValue = this.minAggrValue; if(this.unitName) config.unitName = this.unitName; if(this.scaleType_forced) config.intervalScale = this.scaleType_forced; if(this.percentileChartVisible) config.showPercentile = this.percentileChartVisible; // catSortBy if(this.catSortBy){ var _sortBy = this.catSortBy[0]; if(_sortBy.sortKey){ config.catSortBy = _sortBy.sortKey; // string or lookup table } else if(_sortBy.value) { config.catSortBy = _sortBy.value.toString(); } // TODO: support 'inverse' option }; if(this.catTableName_custom){ config.catTableName = this.catTableName; } if(this.catSplit){ config.catSplit = this.catSplit; } if(this.viewType){ if(this.viewType==="map") config.viewAs = this.viewType; } return config; }, /** -- */ refreshMeasureLabel: function(){ if(this.isEmpty() || this.collapsed || !this.inBrowser() || this.DOM.measureLabel===undefined) return; var me=this; this.DOM.measureLabel.html(function(aggr){ return me.browser.getMeasureLabel(aggr,me); }); }, }; kshf.Summary_Categorical = function(){}; kshf.Summary_Categorical.prototype = new kshf.Summary_Base(); var Summary_Categorical_functions = { /** -- */ initialize: function(browser,name,attribFunc){ kshf.Summary_Base.prototype.initialize.call(this,browser,name,attribFunc); this.type='categorical'; this.heightRow_category = 18; this.show_set_matrix = false; this.scrollTop_cache = 0; this.firstCatIndexInView = 0; this.configRowCount = 0; this.minAggrValue = 1; this.catSortBy = []; this.viewType = 'list'; this.setCatLabel("id"); if(this.records.length<=1000) this.initializeAggregates(); }, /** -- */ initializeAggregates: function(){ if(this.aggr_initialized) return; if(this.catTableName===undefined){ // Create new table this.catTableName = this.summaryName+"_h_"+this.summaryID; } this.mapToAggregates(); if(this.catSortBy.length===0) this.setSortingOptions(); this.aggr_initialized = true; this.refreshViz_Nugget(); }, /** -- */ refreshViz_Nugget: function(){ if(this.DOM.nugget===undefined) return; var nuggetChart = this.DOM.nugget.select(".nuggetChart"); this.DOM.nugget .attr("aggr_initialized",this.aggr_initialized) .attr("datatype",this.getDataType()); if(!this.aggr_initialized) return; if(this.uniqueCategories()){ this.DOM.nugget.select(".nuggetInfo").html("<span class='fa fa-tag'></span><br>Unique"); nuggetChart.style("display",'none'); return; } nuggetChart.selectAll(".nuggetBar").data([]).exit().remove(); var totalWidth= 25; var maxAggregate_Total = this.getMaxAggr_Total(); nuggetChart.selectAll(".nuggetBar").data(this._cats).enter() .append("span") .attr("class","nuggetBar") .style("width",function(cat){ return totalWidth*(cat.records.length/maxAggregate_Total)+"px"; }); this.DOM.nugget.select(".nuggetInfo").html( "<span class='fa fa-tag"+(this.isMultiValued?"s":"")+"'></span><br>"+ this._cats.length+"<br>rows<br>"); }, /*********************************** * SIZE (HEIGH/WIDTH) QUERY FUNCTIONS *************************************/ /** -- */ getHeight_RangeMax: function(){ if(this.viewType==="map") { return this.getWidth()*1.5; } if(this.isEmpty()) return this.getHeight_Header(); // minimum 2 categories return this.getHeight_WithoutCats() + this._cats.length*this.heightRow_category; }, /** -- */ getHeight_RangeMin: function(){ if(this.isEmpty()) return this.getHeight_Header(); return this.getHeight_WithoutCats() + Math.min(this.catCount_Visible,2)*this.heightRow_category; }, getHeight_WithoutCats: function(){ return this.getHeight_Header() + this.getHeight_Config() + this.getHeight_Bottom(); }, /** -- */ getHeight_Config: function(){ return (this.showTextSearch?18:0)+(this.catSortBy.length>1?18:0); }, /** -- */ getHeight_Bottom: function(){ if(!this.areAllCatsInDisplay() || !this.panel.hideBarAxis || this._cats.length>4) return 18; return 0; }, /** -- */ getHeight_Content: function(){ return this.categoriesHeight + this.getHeight_Config() + this.getHeight_Bottom(); }, /** -- */ getHeight_VisibleAttrib: function(){ return this.catCount_Visible*this.heightRow_category; }, /** -- */ getWidth_Label: function(){ return this.panel.width_catLabel; }, /** -- */ getWidth_CatChart: function(){ // This will make the bar width extend over to the scroll area. // Doesn't look better, the amount of space saved makes chart harder to read and breaks the regularly spaced flow. /*if(!this.scrollBarShown()){ return this.panel.width_catBars+kshf.scrollWidth-5; }*/ return this.panel.width_catBars; }, /** -- */ areAllCatsInDisplay: function(){ return this.catCount_Visible===this.catCount_InDisplay; }, /** -- */ isEmpty: function(){ if(this._cats && this._cats.length===0) return true; return this.summaryFunc===undefined; }, /** -- */ hasCategories: function(){ if(this._cats && this._cats.length===0) return false; return this.summaryFunc!==undefined; }, /** -- */ uniqueCategories: function(){ if(this._cats===undefined) return true; if(this._cats.length===0) return true; return 1 === d3.max(this._cats, function(aggr){ return aggr.records.length; }); }, /*********************************** * SORTING FUNCTIONS *************************************/ /** -- */ insertSortingOption: function(opt){ this.catSortBy.push( this.prepareSortingOption(opt) ); }, /** -- */ prepareSortingOption: function(opt){ if(Array.isArray(opt)){ var _lookup = {}; opt.forEach(function(s,i){ _lookup[s] = i; }); return { inverse : false, no_resort : true, sortKey : opt, name : 'Custom Order', value : function(){ var v=_lookup[this.id]; if(v!==undefined) return v; return 99999; // unknown is 99999th item } }; } opt.inverse = opt.inverse || false; // Default is false if(opt.value){ if(typeof(opt.value)==="string"){ var x = opt.value; opt.name = opt.name || x; opt.sortKey = x; opt.value = function(){ return this[x]; } } else if(typeof(opt.value)==="function"){ if(opt.name===undefined) opt.name = "custom" } opt.no_resort = true; } else { opt.name = opt.name || "# of Active"; } if(opt.no_resort===undefined) opt.no_resort = (this._cats.length<=4); return opt; }, /** -- */ setSortingOptions: function(opts){ this.catSortBy = opts || {}; if(!Array.isArray(this.catSortBy)) { this.catSortBy = [this.catSortBy]; } else { // if it is an array, it might still be defining a sorting order for the categories if(this.catSortBy.every(function(v){ return (typeof v==="string"); })){ this.catSortBy = [this.catSortBy]; } } this.catSortBy.forEach(function(opt,i){ if(typeof opt==="string" || typeof opt==="function") this.catSortBy[i] = {value: opt}; this.catSortBy[i] = this.prepareSortingOption(this.catSortBy[i]); },this); this.catSortBy_Active = this.catSortBy[0]; this.updateCatSorting(0,true,true); this.refreshSortOptions(); this.refreshSortButton(); }, /** -- */ refreshSortButton: function(){ if(this.DOM.catSortButton===undefined) return; this.DOM.catSortButton .style("display",(this.catSortBy_Active.no_resort?"none":"inline-block")) .attr("inverse",this.catSortBy_Active.inverse); }, /** -- */ refreshSortOptions: function(){ if(this.DOM.optionSelect===undefined) return; this.refreshConfigRowCount(); this.DOM.optionSelect.style("display", (this.catSortBy.length>1)?"block":"none" ); this.DOM.optionSelect.selectAll(".sort_label").data([]).exit().remove(); // remove all existing options this.DOM.optionSelect.selectAll(".sort_label").data(this.catSortBy) .enter().append("option").attr("class", "sort_label").text(function(d){ return d.name; }); }, /** -- */ sortCategories: function(){ var me = this; var inverse = this.catSortBy_Active.inverse; if(this.catSortBy_Active.prep) this.catSortBy_Active.prep.call(this); // idCompareFunc can be based on integer or string comparison var idCompareFunc = function(a,b){return b.id()-a.id();}; if(typeof(this._cats[0].id())==="string") idCompareFunc = function(a,b){return b.id().localeCompare(a.id());}; var theSortFunc; var sortV = this.catSortBy_Active.value; // sortV can only be function. Just having the check for sanity if(sortV && typeof sortV==="function"){ // valueCompareFunc can be based on integer or string comparison var valueCompareFunc = function(a,b){return a-b;}; if(typeof(sortV.call(this._cats[0].data, this._cats[0]))==="string") valueCompareFunc = function(a,b){return a.localeCompare(b);}; // Of the given function takes 2 parameters, assume it defines a nice sorting order. if(sortV.length===2){ theSortFunc = sortV; } else { // The value is a custom value that returns an integer theSortFunc = function(a,b){ var x = valueCompareFunc(sortV.call(a.data,a),sortV.call(b.data,b)); if(x===0) x=idCompareFunc(a,b); if(inverse) x=-x; return x; }; } } else { theSortFunc = function(a,b){ // selected on top of the list if(!a.f_selected() && b.f_selected()) return 1; if( a.f_selected() && !b.f_selected()) return -1; // Rest var x = b.measure('Active') - a.measure('Active'); if(x===0) x = b.measure('Total') - a.measure('Total'); if(x===0) x = idCompareFunc(a,b); // stable sorting. ID's would be string most probably. if(inverse) x=-x; return x; }; } this._cats.sort(theSortFunc); this._cats.forEach(function(cat,i){ cat.orderIndex=i; }); }, /** -- */ setCatLabel: function( accessor ){ // Clear all assignments this.catLabel_attr = null; this.catLabel_table = null; this.catLabel_Func = null; if(typeof(accessor)==="function"){ this.catLabel_Func = accessor; } else if(typeof(accessor)==="string"){ this.catLabel_attr = accessor; this.catLabel_Func = function(){ return this[accessor]; }; } else if(typeof(accessor)==="object"){ // specifies key->value this.catLabel_table = accessor; this.catLabel_Func = function(){ var x = accessor[this.id]; return x?x:this.id; } } else { alert("Bad parameter"); return; } var me=this; if(this.DOM.theLabel) this.DOM.theLabel.html(function(cat){ return me.catLabel_Func.call(cat.data); }); }, /** -- */ setCatTooltip: function( catTooltip ){ if(typeof(catTooltip)==="function"){ this.catTooltip = catTooltip; } else if(typeof(catTooltip)==="string"){ var x = catTooltip; this.catTooltip = function(){ return this[x]; }; } else { this.setCatTooltip = undefined; this.DOM.aggrGlyphs.attr("title",undefined); return; } if(this.DOM.aggrGlyphs) this.DOM.aggrGlyphs.attr("title",function(cat){ return me.catTooltip.call(cat.data); }); }, /** -- */ setCatGeo: function( accessor){ if(typeof(accessor)==="function"){ this.catMap = accessor; } else if(typeof(accessor)==="string" || typeof(accessor)=="number"){ var x = accessor; this.catMap = function(){ return this[x]; }; } else { this.catMap = undefined; return; } if(this.DOM.root) this.DOM.root.attr("hasMap",true); }, /** -- */ setCatTable: function(tableName){ this.catTableName = tableName; this.catTableName_custom = true; if(this.aggr_initialized){ this.mapToAggregates(); this.updateCats(); } }, /** -- */ setCatSplit: function(catSplit){ this.catSplit = catSplit; if(this.aggr_initialized){ // Remove existing aggregations { var aggrs=this.browser.allAggregates; this._cats.forEach(function(aggr){ aggrs.splice(aggrs.indexOf(aggr),1); },this); if(this.DOM.aggrGroup) this.DOM.aggrGroup.selectAll(".aggrGlyph").data([]).exit().remove(); } this.mapToAggregates(); this.updateCats(); this.insertCategories(); this.updateCatSorting(0,true,true); this.refreshViz_Nugget(); } }, /** -- */ createSummaryFilter: function(){ var me=this; this.summaryFilter = this.browser.createFilter( { title: function(){ return me.summaryName }, onClear: function(){ me.clearCatTextSearch(); me.unselectAllCategories(); me._update_Selected(); }, onFilter: function(){ // at least one category is selected in some modality (and/ or/ not) me._update_Selected(); me.records.forEach(function(record){ var recordVal_s = record._valueCache[me.summaryID]; if(me.missingValueAggr.filtered===true){ record.setFilterCache(this.filterID, recordVal_s===null); return; } if(recordVal_s===null){ // survives if AND and OR is not selected record.setFilterCache(this.filterID, this.selected_AND.length===0 && this.selected_OR.length===0 ); return; } // Check NOT selections - If any mapped record is NOT, return false // Note: no other filtering depends on NOT state. // This is for ,multi-level filtering using not query /* if(this.selected_NOT.length>0){ if(!recordVal_s.every(function(record){ return !record.is_NOT() && record.isWanted; })){ record.setFilterCache(this.filterID,false); return; } }*/ function getAggr(v){ return me.catTable_id[v]; }; // If any of the record values are selected with NOT, the record will be removed if(this.selected_NOT.length>0){ if(!recordVal_s.every(function(v){ return !getAggr(v).is_NOT(); })){ record.setFilterCache(this.filterID,false); return; } } // All AND selections must be among the record values if(this.selected_AND.length>0){ var t=0; // Compute the number of record values selected with AND. recordVal_s.forEach(function(v){ if(getAggr(v).is_AND()) t++; }) if(t!==this.selected_AND.length){ record.setFilterCache(this.filterID,false); return; } } // One of the OR selections must be among the record values // Check OR selections - If any mapped record is OR, return true if(this.selected_OR.length>0){ record.setFilterCache(this.filterID, recordVal_s.some(function(v){return (getAggr(v).is_OR());}) ); return; } // only NOT selection record.setFilterCache(this.filterID,true); }, this); }, filterView_Detail: function(){ if(me.missingValueAggr.filtered===true) return kshf.lang.cur.NoData; // 'this' is the Filter // go over all records and prepare the list var selectedItemsText=""; var catTooltip = me.catTooltip; var totalSelectionCount = this.selectedCount_Total(); var query_and = " <span class='AndOrNot AndOrNot_And'>"+kshf.lang.cur.And+"</span> "; var query_or = " <span class='AndOrNot AndOrNot_Or'>"+kshf.lang.cur.Or+"</span> "; var query_not = " <span class='AndOrNot AndOrNot_Not'>"+kshf.lang.cur.Not+"</span> "; if(totalSelectionCount>4){ selectedItemsText = "<b>"+totalSelectionCount+"</b> selected"; // Note: Using selected because selections can include not, or,and etc (a variety of things) } else { var selectedItemsCount=0; // OR selections if(this.selected_OR.length>0){ var useBracket_or = this.selected_AND.length>0 || this.selected_NOT.length>0; if(useBracket_or) selectedItemsText+="["; // X or Y or .... this.selected_OR.forEach(function(category,i){ selectedItemsText+=((i!==0 || selectedItemsCount>0)?query_or:"")+"<span class='attribName'>" +me.catLabel_Func.call(category.data)+"</span>"; selectedItemsCount++; }); if(useBracket_or) selectedItemsText+="]"; } // AND selections this.selected_AND.forEach(function(category,i){ selectedItemsText+=((selectedItemsText!=="")?query_and:"") +"<span class='attribName'>"+me.catLabel_Func.call(category.data)+"</span>"; selectedItemsCount++; }); // NOT selections this.selected_NOT.forEach(function(category,i){ selectedItemsText+=query_not+"<span class='attribName'>"+me.catLabel_Func.call(category.data)+"</span>"; selectedItemsCount++; }); } return selectedItemsText; } }); this.summaryFilter.selected_AND = []; this.summaryFilter.selected_OR = []; this.summaryFilter.selected_NOT = []; this.summaryFilter.selectedCount_Total = function(){ return this.selected_AND.length + this.selected_OR.length + this.selected_NOT.length; }; this.summaryFilter.selected_Any = function(){ return this.selected_AND.length>0 || this.selected_OR.length>0 || this.selected_NOT.length>0; }; this.summaryFilter.selected_All_clear = function(){ kshf.Util.clearArray(this.selected_AND); kshf.Util.clearArray(this.selected_OR); kshf.Util.clearArray(this.selected_NOT); }; }, /** -- * Note: accesses summaryFilter, summaryFunc */ mapToAggregates: function(){ var aggrTable_id = {}; var aggrTable = []; var mmmm=false; // Converting from kshf.Record to kshf.Aggregate if(kshf.dt[this.catTableName] && kshf.dt[this.catTableName][0] instanceof kshf.Record ){ kshf.dt[this.catTableName].forEach(function(record){ var aggr = new kshf.Aggregate(); aggr.init(record.data,record.idIndex); aggrTable_id[aggr.id()] = aggr; aggrTable.push(aggr); this.browser.allAggregates.push(aggr); },this); } else { mmmm = true; } this.catTable_id = aggrTable_id; this._cats = aggrTable; var maxDegree = 0; var hasString = false; this.records.forEach(function(record){ var mapping = this.summaryFunc.call(record.data,record); // Split if(this.catSplit && typeof mapping === "string"){ mapping = mapping.split(this.catSplit); } // make mapping an array if it is not if(!(mapping instanceof Array)) mapping = [mapping]; // Filter invalid / duplicate values var found = {}; mapping = mapping.filter(function(e){ if(e===undefined || e==="" || e===null || found[e]!==undefined) return false; return (found[e] = true); }); // Record is not mapped to any value (missing value) if(mapping.length===0) { record._valueCache[this.summaryID] = null; if(record._aggrCache[this.summaryID]!==this.missingValueAggr) this.missingValueAggr.addRecord(record); return; } record._valueCache[this.summaryID] = []; maxDegree = Math.max(maxDegree, mapping.length); mapping.forEach(function(v){ if(typeof(v)==="string") hasString=true; var aggr = aggrTable_id[v]; if(aggr==undefined) { aggr = new kshf.Aggregate(); aggr.init({id:v},'id'); aggrTable_id[v] = aggr; this._cats.push(aggr); this.browser.allAggregates.push(aggr); } record._valueCache[this.summaryID].push(v); aggr.addRecord(record); },this); }, this); if(mmmm && hasString){ this._cats.forEach(function(aggr){ aggr.data.id = ""+aggr.data.id; }); } this.isMultiValued = maxDegree>1; // add degree summary if attrib has multi-value records and set-vis is enabled if(this.isMultiValued && this.enableSetVis){ this.browser.addSummary( { name:"<i class='fa fa-hand-o-up'></i> # of "+this.summaryName, value: function(record){ var arr=record._valueCache[me.summaryID]; if(arr===null) return null; // maps to no items return arr.length; }, collapsed: true, type: 'interval', panel: this.panel }, this.browser.primaryTableName ); } this.updateCats(); this.unselectAllCategories(); this.refreshViz_EmptyRecords(); }, // Modified internal dataMap function - Skip rows with 0 active item count setMinAggrValue: function(v){ this.minAggrValue = Math.max(1,v); this._cats = this._cats.filter(function(cat){ return cat.records.length>=this.minAggrValue; },this); this.updateCats(); }, /** -- */ updateCats: function(){ // Few categories. Disable resorting after filtering if(this._cats.length<=4) { this.catSortBy.forEach(function(sortOpt){ sortOpt.no_resort=true; }); } this.showTextSearch = this._cats.length>=20; this.updateCatCount_Active(); }, /** -- */ updateCatCount_Active: function(){ this.catCount_Visible = 0; this.catCount_NowVisible = 0; this.catCount_NowInvisible = 0; this._cats.forEach(function(cat){ v = this.isCatActive(cat); cat.isActiveBefore = cat.isActive; cat.isActive = v; if(!cat.isActive && cat.isActiveBefore) this.catCount_NowInvisible++; if(cat.isActive && !cat.isActiveBefore) this.catCount_NowVisible++; if(cat.isActive) this.catCount_Visible++; },this); }, /** -- */ refreshConfigRowCount: function(){ this.configRowCount = 0; if(this.showTextSearch) this.configRowCount++; if(this.catSortBy.length>1) this.configRowCount++; if(this.configRowCount>0) this.DOM.summaryControls.style("display","block"); }, /** -- */ initDOM: function(beforeDOM){ this.initializeAggregates(); var me=this; if(this.DOM.inited===true) return; this.insertRoot(beforeDOM); this.DOM.root .attr("filtered_or",0) .attr("filtered_and",0) .attr("filtered_not",0) .attr("filtered_total",0) .attr("isMultiValued",this.isMultiValued) .attr("summary_type","categorical") .attr("hasMap",this.catMap!==undefined) .attr("viewType",this.viewType); this.insertHeader(); if(!this.isEmpty()) this.init_DOM_Cat(); this.setCollapsed(this.collapsed); this.DOM.summaryConfig_CatHeight = this.DOM.summaryConfig.append("div") .attr("class","summaryConfig_CatHeight summaryConfig_Option"); this.DOM.summaryConfig_CatHeight.append("span").html("<i class='fa fa-arrows-v'></i> Category Height: "); x = this.DOM.summaryConfig_CatHeight.append("span").attr("class","optionGroup"); x.selectAll(".configOption").data( [ {l:"Short",v:18}, {l:"Long", v:35} ]) .enter() .append("span").attr("class",function(d){ return "configOption pos_"+d.v;}) .attr("active",function(d){ return d.v===me.heightRow_category; }) .html(function(d){ return d.l; }) .on("click", function(d){ me.setHeight_Category(d.v); }) this.DOM.inited = true; }, /** -- */ init_DOM_Cat: function(){ var me=this; this.DOM.summaryCategorical = this.DOM.wrapper.append("div").attr("class","summaryCategorical"); this.DOM.summaryControls = this.DOM.summaryCategorical.append("div").attr("class","summaryControls"); this.initDOM_CatTextSearch(); this.initDOM_CatSortButton(); this.initDOM_CatSortOpts(); if(this.showTextSearch) this.DOM.catTextSearch.style("display","block"); this.refreshConfigRowCount(); this.DOM.scrollToTop = this.DOM.summaryCategorical.append("div").attr("class","scrollToTop fa fa-arrow-up") .each(function(){ this.tipsy = new Tipsy(this, {gravity: 'e', title: kshf.lang.cur.ScrollToTop }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .on("click",function(d){ this.tipsy.hide(); kshf.Util.scrollToPos_do(me.DOM.aggrGroup[0][0],0); }); this.DOM.aggrGroup = this.DOM.summaryCategorical.append("div").attr("class","aggrGroup") .on("mousedown",function(){ d3.event.stopPropagation(); d3.event.preventDefault(); }) .on("scroll",function(d){ if(kshf.Util.ignoreScrollEvents===true) return; me.scrollTop_cache = me.DOM.aggrGroup[0][0].scrollTop; me.DOM.scrollToTop.style("visibility", me.scrollTop_cache>0?"visible":"hidden"); me.firstCatIndexInView = Math.floor(me.scrollTop_cache/me.heightRow_category); me.refreshScrollDisplayMore(me.firstCatIndexInView+me.catCount_InDisplay); me.updateCatIsInView(); me.cullAttribs(); me.refreshMeasureLabel(); }); this.DOM.aggrGroup_list = this.DOM.aggrGroup; this.DOM.catMap_Base = this.DOM.summaryCategorical.append("div").attr("class","catMap_Base"); // with this, I make sure that the (scrollable) div height is correctly set to visible number of categories this.DOM.chartBackground = this.DOM.aggrGroup.append("span").attr("class","chartBackground"); this.DOM.chartCatLabelResize = this.DOM.chartBackground.append("span").attr("class","chartCatLabelResize dragWidthHandle") .on("mousedown", function (d, i) { var resizeDOM = this; me.panel.DOM.root.attr("catLabelDragging",true); me.browser.DOM.pointerBlock.attr("active",""); me.browser.DOM.root.style('cursor','col-resize'); me.browser.setNoAnim(true); var mouseDown_x = d3.mouse(d3.select("body")[0][0])[0]; var initWidth = me.panel.width_catLabel; d3.select("body").on("mousemove", function() { var mouseDown_x_diff = d3.mouse(d3.select("body")[0][0])[0]-mouseDown_x; me.panel.setWidthCatLabel(initWidth+mouseDown_x_diff); }).on("mouseup", function(){ me.panel.DOM.root.attr("catLabelDragging",false); me.browser.DOM.pointerBlock.attr("active",null); me.browser.DOM.root.style('cursor','default'); me.browser.setNoAnim(false); d3.select("body").on("mousemove", null).on("mouseup", null); }); d3.event.preventDefault(); }); this.DOM.belowCatChart = this.DOM.summaryCategorical.append("div").attr("class","belowCatChart"); this.insertChartAxis_Measure(this.DOM.belowCatChart,'e','e'); this.DOM.scroll_display_more = this.DOM.belowCatChart.append("div") .attr("class","hasLabelWidth scroll_display_more") .on("click",function(){ kshf.Util.scrollToPos_do( me.DOM.aggrGroup[0][0],me.DOM.aggrGroup[0][0].scrollTop+me.heightRow_category); }); this.insertCategories(); this.refreshLabelWidth(); this.updateCatSorting(0,true,true); }, /** -- */ initDOM_CatSortButton: function(){ var me=this; // Context dependent this.DOM.catSortButton = this.DOM.summaryControls.append("span").attr("class","catSortButton sortButton fa") .on("click",function(d){ if(me.dirtySort){ me.dirtySort = false; me.DOM.catSortButton.attr("resort",true); } else{ me.catSortBy_Active.inverse = me.catSortBy_Active.inverse?false:true; me.refreshSortButton(); } me.updateCatSorting(0,true); }) .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'w', title: function(){ return kshf.lang.cur[me.dirtySort?'Reorder':'ReverseOrder']; } }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }); this.refreshSortButton(); }, /** -- */ initDOM_CatSortOpts: function(){ var me=this; var x = this.DOM.summaryControls.append("span").attr("class","sortOptionSelectGroup hasLabelWidth"); this.DOM.optionSelect = x.append("select").attr("class","optionSelect") .on("change", function(){ me.catSortBy_Active = me.catSortBy[this.selectedIndex]; me.refreshSortButton(); me.updateCatSorting(0,true); }) this.refreshSortOptions(); }, /** -- */ initDOM_CatTextSearch: function(){ var me=this; this.DOM.catTextSearch = this.DOM.summaryControls.append("div").attr("class","textSearchBox catTextSearch hasLabelWidth"); this.DOM.catTextSearchControl = this.DOM.catTextSearch.append("span") .attr("class","textSearchControl fa") .on("click",function() { me.DOM.catTextSearchControl.attr("showClear",false); me.summaryFilter.clearFilter(); }); this.DOM.catTextSearchInput = this.DOM.catTextSearch.append("input") .attr("class","textSearchInput") .attr("type","text") .attr("placeholder",kshf.lang.cur.Search) // .on("mousedown",function(){alert('sdsdd');}) .on("input",function(){ if(this.timer) clearTimeout(this.timer); var x = this; this.timer = setTimeout( function(){ me.unselectAllCategories(); var query = []; // split the query by " character var processed = x.value.toLowerCase().split('"'); processed.forEach(function(block,i){ if(i%2===0) { block.split(/\s+/).forEach(function(q){ query.push(q)}); } else { query.push(block); } }); // Remove the empty strings query = query.filter(function(v){ return v!==""}); if(query.length>0){ me.DOM.catTextSearchControl.attr("showClear",true); var labelFunc = me.catLabel_Func; var tooltipFunc = me.catTooltip; me._cats.forEach(function(_category){ var catLabel = labelFunc.call(_category.data).toString().toLowerCase(); var f = query.every(function(query_str){ if(catLabel.indexOf(query_str)!==-1){ return true; } if(tooltipFunc) { var tooltipText = tooltipFunc.call(_category.data); return (tooltipText && tooltipText.toLowerCase().indexOf(query_str)!==-1); } return false; }); if(f){ _category.set_OR(me.summaryFilter.selected_OR); } else { _category.set_NONE(me.summaryFilter.selected_OR); } }); // All categories are process, and the filtering state is set. Now, process the summary as a whole if(me.summaryFilter.selectedCount_Total()===0){ me.skipTextSearchClear = true; me.summaryFilter.clearFilter(); me.skipTextSearchClear = false; } else { me.summaryFilter.how = "All"; me.missingValueAggr.filtered = false; me.summaryFilter.addFilter(); } } }, 750); }); }, /** returns the maximum active aggregate value per row in chart data */ getMaxAggr_Active: function(){ return d3.max(this._cats, function(aggr){ return aggr.measure('Active'); }); }, /** returns the maximum total aggregate value stored per row in chart data */ getMaxAggr_Total: function(){ if(this._cats===undefined) return 0; if(this.isEmpty()) return 0; return d3.max(this._cats, function(aggr){ return aggr.measure('Total'); }); }, /** -- */ _update_Selected: function(){ if(this.DOM.root) { this.DOM.root .attr("filtered",this.isFiltered()) .attr("filtered_or",this.summaryFilter.selected_OR.length) .attr("filtered_and",this.summaryFilter.selected_AND.length) .attr("filtered_not",this.summaryFilter.selected_NOT.length) .attr("filtered_total",this.summaryFilter.selectedCount_Total()); } var show_box = (this.summaryFilter.selected_OR.length+this.summaryFilter.selected_AND.length)>1; this.summaryFilter.selected_OR.forEach(function(category){ category.DOM.aggrGlyph.setAttribute("show-box",show_box); },this); this.summaryFilter.selected_AND.forEach(function(category){ category.DOM.aggrGlyph.setAttribute("show-box",show_box); },this); this.summaryFilter.selected_NOT.forEach(function(category){ category.DOM.aggrGlyph.setAttribute("show-box","true"); },this); }, /** -- */ unselectAllCategories: function(){ this._cats.forEach(function(aggr){ if(aggr.f_selected() && aggr.DOM.aggrGlyph) aggr.DOM.aggrGlyph.removeAttribute("selection"); aggr.set_NONE(); }); this.summaryFilter.selected_All_clear(); if(this.DOM.inited) this.DOM.missingValueAggr.attr("filtered",null); }, /** -- */ clearCatTextSearch: function(){ if(!this.showTextSearch) return; if(this.skipTextSearchClear) return; this.DOM.catTextSearchControl.attr("showClear",false); this.DOM.catTextSearchInput[0][0].value = ''; }, /** -- */ scrollBarShown: function(){ return this.categoriesHeight<this._cats.length*this.heightRow_category; }, /** -- */ updateChartScale_Measure: function(){ if(!this.aggr_initialized || this.isEmpty()) return; // nothing to do var maxMeasureValue = this.getMaxAggr_Active(); if(this.browser.measureFunc==="Avg"){ ["Highlighted","Compared_A","Compared_B","Compared_C"].forEach(function(distr){ if(!this.browser.vizActive[distr]) return; maxMeasureValue = Math.max(maxMeasureValue, d3.max(this._cats, function(aggr){return aggr.measure(distr);} ) ); },this); } this.chartScale_Measure .rangeRound([0, this.getWidth_CatChart()]) .nice(this.chartAxis_Measure_TickSkip()) .domain([ 0,(maxMeasureValue===0)?1:maxMeasureValue ]); this.refreshViz_All(); }, /** -- */ setHeight: function(newHeight){ var me = this; if(this.isEmpty()) return; // take into consideration the other components in the summary var attribHeight_old = this.categoriesHeight; newHeight -= this.getHeight_Header()+this.getHeight_Config()+this.getHeight_Bottom(); if(this.viewType==='map'){ this.categoriesHeight = newHeight; if(this.categoriesHeight!==attribHeight_old) setTimeout(function(){ me.map_zoomToActive();}, 1000); return; } this.categoriesHeight = Math.min( newHeight, this.heightRow_category*this.catCount_Visible); if(this.cbSetHeight && attribHeight_old!==this.categoriesHeight) this.cbSetHeight(this); }, /** -- */ setHeight_Category: function(h){ var me=this; this.heightRow_category = h; if(this.viewType==='list') { this.refreshHeight_Category(); } else { this.heightRow_category_dirty = true; } }, /** -- */ refreshHeight_Category: function(){ var me=this; this.heightRow_category_dirty = false; this.browser.setNoAnim(true); this.browser.updateLayout(); this.DOM.aggrGlyphs .each(function(aggr){ kshf.Util.setTransform(this, "translate("+aggr.posX+"px,"+(me.heightRow_category*aggr.orderIndex)+"px)"); }) .style("height",this.heightRow_category+"px"); this.DOM.aggrGlyphs.selectAll(".categoryLabel").style("padding-top",(this.heightRow_category/2-8)+"px"); this.DOM.chartBackground.style("height",this.getHeight_VisibleAttrib()+"px"); this.DOM.chartCatLabelResize.style("height",this.getHeight_VisibleAttrib()+"px"); this.DOM.summaryConfig_CatHeight.selectAll(".configOption").attr("active",false); this.DOM.summaryConfig_CatHeight.selectAll(".pos_"+this.heightRow_category).attr("active",true); if(this.cbSetHeight) this.cbSetHeight(this); setTimeout(function(){ me.browser.setNoAnim(false); },100); }, /** -- */ updateAfterFilter: function(){ if(this.isEmpty() || this.collapsed || !this.inBrowser()) return; var me=this; if(this.viewType==='map'){ this.updateCatCount_Active(); //this.map_refreshBounds_Active(); //setTimeout(function(){ me.map_zoomToActive(); }, 1000); this.refreshMeasureLabel(); this.refreshViz_Active(); return; } this.updateChartScale_Measure(); this.refreshMeasureLabel(); this.refreshViz_EmptyRecords(); if(this.show_set_matrix) { this.dirtySort = true; this.DOM.catSortButton.attr('resort',true); } if(!this.dirtySort) { this.updateCatSorting(); } else { this.refreshViz_All(); this.refreshMeasureLabel(); } }, /** -- */ refreshWidth: function(){ if(this.DOM.summaryCategorical===undefined) return; this.updateChartScale_Measure(); this.DOM.summaryCategorical.style("width",this.getWidth()+"px"); this.DOM.summaryName.style("max-width",(this.getWidth()-40)+"px"); this.DOM.chartAxis_Measure.selectAll(".relativeModeControl") .style("width",(this.getWidth()-this.panel.width_catMeasureLabel-this.getWidth_Label()-kshf.scrollWidth)+"px"); this.refreshViz_Axis(); }, /** -- */ refreshViz_Total: function(){ if(this.isEmpty() || this.collapsed) return; if(this.viewType==='map') return; // Maps do not display total distribution. if(this.browser.ratioModeActive){ // Do not need to update total. Total value is invisible. Percent view is based on active count. this.DOM.measureTotalTip.style("opacity",0); } else { var me = this; var width_Text = this.getWidth_Label()+this.panel.width_catMeasureLabel; this.DOM.measure_Total.each(function(_cat){ kshf.Util.setTransform(this, "translateX("+width_Text+"px) scaleX("+me.chartScale_Measure(_cat.measure('Total'))+")"); }); this.DOM.measureTotalTip .each(function(_cat){ kshf.Util.setTransform(this, "translateX("+(me.chartScale_Measure.range()[1]+width_Text)+"px)"); }) .style("opacity",function(_cat){ return (_cat.measure('Total')>me.chartScale_Measure.domain()[1])?1:0; }); } }, /** -- */ refreshMapBounds: function(){ var maxAggr_Active = this.getMaxAggr_Active(); var boundMin, boundMax; if(this.browser.percentModeActive){ boundMin = 0; boundMax = 100*maxAggr_Active/this.browser.allRecordsAggr.measure('Active'); } else { boundMin = 1; //d3.min(this._cats, function(_cat){ return _cat.measure.Active; }), boundMax = maxAggr_Active; } this.mapColorScale = d3.scale.linear().range([0, 9]).domain([boundMin, boundMax]); this.DOM.catMapColorScale.select(".boundMin").html( this.browser.getMeasureLabel(boundMin,this) ); this.DOM.catMapColorScale.select(".boundMax").html( this.browser.getMeasureLabel(boundMax,this) ); }, /** -- */ refreshViz_Active: function(){ if(this.isEmpty() || this.collapsed) return; var me=this; var ratioMode = this.browser.ratioModeActive; if(this.viewType==='map') { this.refreshMapBounds(); var allRecordsAggr_measure_Active = me.browser.allRecordsAggr.measure('Active'); this.DOM.measure_Active .attr("fill", function(_cat){ var v = _cat.measure('Active'); if(v<=0 || v===undefined ) return "url(#diagonalHatch)"; if(me.browser.percentModeActive){ v = 100*v/allRecordsAggr_measure_Active; } var vv = me.mapColorScale(v); if(ratioMode) vv=0; //if(me.sortingOpt_Active.invertColorScale) vv = 9 - vv; return me.mapColorQuantize(vv); }) .attr("stroke", function(_cat){ var v = _cat.measure('Active'); if(me.browser.percentModeActive){ v = 100*v/allRecordsAggr_measure_Active; } var vv = 9-me.mapColorScale(v); if(ratioMode) vv=8; //if(me.sortingOpt_Active.invertColorScale) vv = 9 - vv; return me.mapColorQuantize(vv); }); return; } var maxWidth = this.chartScale_Measure.range()[1]; var width_Text = this.getWidth_Label()+this.panel.width_catMeasureLabel; this.DOM.measure_Active.each(function(_cat){ kshf.Util.setTransform(this,"translateX("+width_Text+"px) scaleX("+(ratioMode? ((_cat.measure_Active===0)?0:maxWidth): me.chartScale_Measure(_cat.measure('Active')) )+")"); }); this.DOM.attribClickArea.style("width",function(_cat){ return width_Text+(ratioMode? ((_cat.recCnt.Active===0)?0:maxWidth): Math.min((me.chartScale_Measure(_cat.measure('Active'))+10),maxWidth) )+"px"; }); this.DOM.lockButton .attr("inside",function(_cat){ if(ratioMode) return ""; if(maxWidth-me.chartScale_Measure(_cat.measure('Active'))<10) return ""; return null; // nope, not inside }); }, /** -- */ refreshViz_Highlight: function(){ if(this.isEmpty() || this.collapsed || !this.DOM.inited || !this.inBrowser()) return; var me=this; this.refreshViz_EmptyRecords(); this.refreshMeasureLabel(); var ratioMode = this.browser.ratioModeActive; var isThisIt = this===this.browser.highlightSelectedSummary; var maxWidth = this.chartScale_Measure.range()[1]; var width_Text = this.getWidth_Label()+this.panel.width_catMeasureLabel; if(this.browser.vizActive.Highlighted){ if(this.browser.ratioModeActive) { if(this.viewType==="map"){ //this.DOM.highlightedMeasureValue.style("left",(100*(this.mapColorScale(aggr.measure.Highlighted)/9))+"%"); } else { this.DOM.highlightedMeasureValue .style("opacity",1) .style("left",(this.browser.allRecordsAggr.ratioHighlightToTotal()*maxWidth)+"px"); } } } else { this.DOM.highlightedMeasureValue.style("opacity",0); } if(this.viewType=='map'){ if(!this.browser.vizActive.Highlighted){ this.refreshViz_Active(); return; } if(!isThisIt || this.isMultiValued) { var boundMin = ratioMode ? d3.min(this._cats, function(aggr){ if(aggr.recCnt.Active===0 || aggr.recCnt.Highlighted===0) return null; return 100*aggr.ratioHighlightToActive(); }) : 1; //d3.min(this._cats, function(_cat){ return _cat.measure.Active; }), var boundMax = ratioMode ? d3.max(this._cats, function(_cat){ return (_cat._measure.Active===0) ? null : 100*_cat.ratioHighlightToActive(); }) : d3.max(this._cats, function(_cat){ return _cat.measure('Highlighted'); }); this.DOM.catMapColorScale.select(".boundMin").text(Math.round(boundMin)); this.DOM.catMapColorScale.select(".boundMax").text(Math.round(boundMax)); this.mapColorScale = d3.scale.linear() .range([0, 9]) .domain([boundMin,boundMax]); } var allRecordsAggr_measure_Active = me.browser.allRecordsAggr.measure('Active'); this.DOM.measure_Active .attr("fill", function(_cat){ //if(_cat === me.browser.selectedAggr.Highlighted) return ""; var _v; if(me.isMultiValued || me.browser.highlightSelectedSummary!==me){ v = _cat.measure('Highlighted'); if(ratioMode) v = 100*v/_cat.measure('Active'); } else { v = _cat.measure('Active'); if(me.browser.percentModeActive){ v = 100*v/allRecordsAggr_measure_Active; } } if(v<=0 || v===undefined ) return "url(#diagonalHatch)"; return me.mapColorQuantize(me.mapColorScale(v)); }) return; } if(this.viewType==='list'){ var totalC = this.browser.getActiveComparedCount(); if(this.browser.measureFunc==="Avg") totalC++; var barHeight = (this.heightRow_category-8)/(totalC+1); this.DOM.measure_Highlighted.each(function(aggr){ var p = aggr.measure('Highlighted'); if(me.browser.preview_not) p = aggr._measure.Active - aggr._measure.Highlighted; kshf.Util.setTransform(this, "translateX("+width_Text+"px) "+ "scale("+(ratioMode ? ((p/aggr._measure.Active)*maxWidth ) : me.chartScale_Measure(p))+","+barHeight+")"); }); } }, /** -- */ refreshViz_Compare: function(cT, curGroup, totalGroups){ if(this.isEmpty() || this.collapsed || !this.inBrowser()) return; var me=this, ratioMode=this.browser.ratioModeActive, maxWidth = this.chartScale_Measure.range()[1]; var width_Text = this.getWidth_Label()+this.panel.width_catMeasureLabel; var _translateX = "translateX("+width_Text+"px) "; var barHeight = (this.heightRow_category-8)/totalGroups; var _translateY = "translateY("+(barHeight*(curGroup+1))+"px)"; var compId = "Compared_"+cT; this.DOM["measure_Compared_"+cT].each(function(aggr){ var sx = (me.browser.vizActive[compId])? ( ratioMode ? (aggr.ratioCompareToActive(cT)*maxWidth) : me.chartScale_Measure(aggr.measure(compId)) ) : 0; kshf.Util.setTransform(this,_translateX+_translateY+"scale("+sx+","+barHeight+")"); }); }, /** -- */ refreshViz_Axis: function(){ if(this.isEmpty()) return; var me=this; var tickValues, posFunc, transformFunc, maxValue, chartWidth = this.getWidth_CatChart(); var axis_Scale = this.chartScale_Measure; function setCustomAxis(){ axis_Scale = d3.scale.linear() .rangeRound([0, chartWidth]) .nice(me.chartAxis_Measure_TickSkip()) .clamp(true) .domain([0,maxValue]); }; if(this.browser.ratioModeActive) { maxValue = 100; setCustomAxis(); } else if(this.browser.percentModeActive) { maxValue = Math.round(100*me.getMaxAggr_Active()/me.browser.allRecordsAggr.measure('Active')); setCustomAxis(); } // GET TICK VALUES *********************************************************** tickValues = axis_Scale.ticks(this.chartAxis_Measure_TickSkip()); // remove 0-tick tickValues = tickValues.filter(function(d){return d!==0;}); // Remove non-integer values from count if((this.browser.measureFunc==="Count") || (this.browser.measureFunc==="Sum" && !this.browser.measureSummary.hasFloat)){ tickValues = tickValues.filter(function(d){return d%1===0;}); } var tickDoms = this.DOM.chartAxis_Measure_TickGroup.selectAll("span.tick").data(tickValues,function(i){return i;}); transformFunc = function(d){ kshf.Util.setTransform(this,"translateX("+(axis_Scale(d)-0.5)+"px)"); } var x=this.browser.noAnim; if(x===false) this.browser.setNoAnim(true); var tickData_new=tickDoms.enter().append("span").attr("class","tick").each(transformFunc); if(x===false) this.browser.setNoAnim(false); // translate the ticks horizontally on scale tickData_new.append("span").attr("class","line longRefLine") .style("top","-"+(this.categoriesHeight+3)+"px") .style("height",(this.categoriesHeight-1)+"px"); tickData_new.append("span").attr("class","text"); if(this.configRowCount>0){ var h=this.categoriesHeight; var hm=tickData_new.append("span").attr("class","text text_upper").style("top",(-h-21)+"px"); this.DOM.chartAxis_Measure.selectAll(".relativeModeControl_right").style("top",(-h-14)+"px") .style("display","block"); this.DOM.chartAxis_Measure.select(".chartAxis_Measure_background_2").style("display","block"); } this.DOM.chartAxis_Measure_TickGroup.selectAll(".text").html(function(d){ return me.browser.getMeasureLabel(d); }); setTimeout(function(){ me.DOM.chartAxis_Measure.selectAll("span.tick").style("opacity",1).each(transformFunc); }); tickDoms.exit().remove(); }, /** -- */ refreshLabelWidth: function(){ if(this.isEmpty()) return; if(this.DOM.summaryCategorical===undefined) return; var labelWidth = this.getWidth_Label(); var barChartMinX = labelWidth + this.panel.width_catMeasureLabel; this.DOM.chartCatLabelResize.style("left",(labelWidth+1)+"px"); this.DOM.summaryCategorical.selectAll(".hasLabelWidth").style("width",labelWidth+"px"); this.DOM.measureLabel .style("left",labelWidth+"px") .style("width",this.panel.width_catMeasureLabel+"px"); this.DOM.chartAxis_Measure.each(function(){ kshf.Util.setTransform(this,"translateX("+barChartMinX+"px)"); }); this.DOM.catSortButton .style("left",labelWidth+"px") .style("width",this.panel.width_catMeasureLabel+"px"); }, /** -- */ refreshScrollDisplayMore: function(bottomItem){ if(this._cats.length<=4) { this.DOM.scroll_display_more.style("display","none"); return; } var moreTxt = ""+this.catCount_Visible+" "+kshf.lang.cur.Rows; var below = this.catCount_Visible-bottomItem; if(below>0) moreTxt+=" <span class='fa fa-angle-down'></span>"+below+" "+kshf.lang.cur.More; this.DOM.scroll_display_more.html(moreTxt); }, /** -- */ refreshHeight: function(){ if(this.isEmpty()) return; // update catCount_InDisplay var c = Math.floor(this.categoriesHeight / this.heightRow_category); var c = Math.floor(this.categoriesHeight / this.heightRow_category); if(c<0) c=1; if(c>this.catCount_Visible) c=this.catCount_Visible; if(this.catCount_Visible<=2){ c = this.catCount_Visible; } else { c = Math.max(c,2); } this.catCount_InDisplay = c+1; this.catCount_InDisplay = Math.min(this.catCount_InDisplay,this.catCount_Visible); this.refreshScrollDisplayMore(this.firstCatIndexInView+this.catCount_InDisplay); this.updateCatIsInView(); this.cullAttribs(); this.DOM.headerGroup.select(".buttonSummaryExpand").style("display", (this.panel.getNumOfOpenSummaries()<=1||this.areAllCatsInDisplay())? "none": "inline-block" ); this.updateChartScale_Measure(); var h=this.categoriesHeight; this.DOM.wrapper.style("height",(this.collapsed?"0":this.getHeight_Content())+"px"); this.DOM.aggrGroup.style("height",h+"px"); this.DOM.root.style("max-height",(this.getHeight()+1)+"px"); this.DOM.chartAxis_Measure.selectAll(".longRefLine").style("top",(-h+1)+"px").style("height",(h-2)+"px"); this.DOM.chartAxis_Measure.selectAll(".text_upper").style("top",(-h-21)+"px"); this.DOM.chartAxis_Measure.selectAll(".chartAxis_Measure_background_2").style("top",(-h-12)+"px"); if(this.viewType==='map'){ this.DOM.catMap_Base.style("height",h+"px"); if(this.DOM.catMap_SVG) this.DOM.catMap_SVG.style("height",h+"px"); if(this.leafletAttrMap) this.leafletAttrMap.invalidateSize(); } }, /** -- */ isCatActive: function(category){ if(category.f_selected()) return true; if(category.recCnt.Active!==0) return true; // summary is not filtered yet, don't show categories with no records if(!this.isFiltered()) return category.recCnt.Active!==0; if(this.viewType==='map') return category.recCnt.Active!==0; // Hide if multiple options are selected and selection is and // if(this.summaryFilter.selecttype==="SelectAnd") return false; // TODO: Figuring out non-selected, zero-active-item attribs under "SelectOr" is tricky! return true; }, /** -- */ isCatSelectable: function(category){ if(category.f_selected()) return true; if(category.recCnt.Active!==0) return true; // Show if multiple attributes are selected and the summary does not include multi value records if(this.isFiltered() && !this.isMultiValued) return true; // Hide return false; }, /** When clicked on an attribute ... what: AND / OR / NOT / NONE how: MoreResults / LessResults */ filterCategory: function(ctgry, what, how){ if(this.browser.skipSortingFacet){ // you can now sort the last filtered summary, attention is no longer there. this.browser.skipSortingFacet.dirtySort = false; this.browser.skipSortingFacet.DOM.catSortButton.attr("resort",false); } this.browser.skipSortingFacet=this; this.browser.skipSortingFacet.dirtySort = true; this.browser.skipSortingFacet.DOM.catSortButton.attr("resort",true); var i=0; var preTest = (this.summaryFilter.selected_OR.length>0 && (this.summaryFilter.selected_AND.length>0 || this.summaryFilter.selected_NOT.length>0)); // if selection is in same mode, "undo" to NONE. if(what==="NOT" && ctgry.is_NOT()) what = "NONE"; if(what==="AND" && ctgry.is_AND()) what = "NONE"; if(what==="OR" && ctgry.is_OR() ) what = "NONE"; if(what==="NONE"){ if(ctgry.is_AND() || ctgry.is_NOT()){ this.summaryFilter.how = "MoreResults"; } if(ctgry.is_OR()){ this.summaryFilter.how = this.summaryFilter.selected_OR.length===0?"MoreResults":"LessResults"; } ctgry.set_NONE(); if(this.summaryFilter.selected_OR.length===1 && this.summaryFilter.selected_AND.length===0){ this.summaryFilter.selected_OR.forEach(function(a){ a.set_NONE(); a.set_AND(this.summaryFilter.selected_AND); },this); } if(!this.summaryFilter.selected_Any()){ this.dirtySort = false; this.DOM.catSortButton.attr("resort",false); } } if(what==="NOT"){ if(ctgry.is_NONE()){ if(ctgry.recCnt.Active===this.browser.allRecordsAggr.recCnt.Active){ alert("Removing this category will create an empty result list, so it is not allowed."); return; } this.summaryFilter.how = "LessResults"; } else { this.summaryFilter.how = "All"; } ctgry.set_NOT(this.summaryFilter.selected_NOT); } if(what==="AND"){ ctgry.set_AND(this.summaryFilter.selected_AND); this.summaryFilter.how = "LessResults"; } if(what==="OR"){ if(!this.isMultiValued && this.summaryFilter.selected_NOT.length>0){ var temp = []; this.summaryFilter.selected_NOT.forEach(function(a){ temp.push(a); }); temp.forEach(function(a){ a.set_NONE(); }); } if(this.summaryFilter.selected_OR.length===0 && this.summaryFilter.selected_AND.length===1){ this.summaryFilter.selected_AND.forEach(function(a){ a.set_NONE(); a.set_OR(this.summaryFilter.selected_OR); },this); } ctgry.set_OR(this.summaryFilter.selected_OR); this.summaryFilter.how = "MoreResults"; } if(how) this.summaryFilter.how = how; if(preTest){ this.summaryFilter.how = "All"; } if(this.summaryFilter.selected_OR.length>0 && (this.summaryFilter.selected_AND.length>0 || this.summaryFilter.selected_NOT.length>0)){ this.summaryFilter.how = "All"; } if(this.missingValueAggr.filtered===true){ this.summaryFilter.how = "All"; } if(this.summaryFilter.selectedCount_Total()===0){ this.summaryFilter.clearFilter(); return; } this.clearCatTextSearch(); this.missingValueAggr.filtered = false; this.summaryFilter.addFilter(); }, /** -- */ onCatClick: function(ctgry){ if(!this.isCatSelectable(ctgry)) return; if(d3.event.shiftKey){ this.browser.setSelect_Compare(this,ctgry,true); return; } if(this.dblClickTimer){ // double click if(!this.isMultiValued) return; this.unselectAllCategories(); this.filterCategory("AND","All"); return; } if(ctgry.is_NOT()){ this.filterCategory(ctgry,"NOT"); } else if(ctgry.is_AND()){ this.filterCategory(ctgry,"AND"); } else if(ctgry.is_OR()){ this.filterCategory(ctgry,"OR"); } else { // remove the single selection if it is defined with OR if(!this.isMultiValued && this.summaryFilter.selected_Any()){ if(this.summaryFilter.selected_OR.indexOf(ctgry)<0){ var temp = []; this.summaryFilter.selected_OR.forEach(function(a){ temp.push(a); }); temp.forEach(function(a){ a.set_NONE(); }); } if(this.summaryFilter.selected_AND.indexOf(ctgry)<0){ var temp = []; this.summaryFilter.selected_AND.forEach(function(a){ temp.push(a); }); temp.forEach(function(a){ a.set_NONE(); }); } if(this.summaryFilter.selected_NOT.indexOf(ctgry)<0){ var temp = []; this.summaryFilter.selected_NOT.forEach(function(a){ temp.push(a); }); temp.forEach(function(a){ a.set_NONE(); }); } this.filterCategory(ctgry,"AND","All"); } else { this.filterCategory(ctgry,"AND"); } } if(this.isMultiValued){ var x = this; this.dblClickTimer = setTimeout(function() { x.dblClickTimer = null; }, 500); } }, /** -- */ onCatEnter: function(aggr){ if(!this.isCatSelectable(aggr)) return; if(aggr.DOM.matrixRow) aggr.DOM.matrixRow.setAttribute("selection","selected"); aggr.DOM.aggrGlyph.setAttribute("selecttype","and"); aggr.DOM.aggrGlyph.setAttribute("selection","selected"); // Comes after setting select type of the category - visual feedback on selection... if(!this.isMultiValued && this.summaryFilter.selected_AND.length!==0) return; // Show the highlight (preview) if(aggr.is_NOT()) return; if(this.isMultiValued || this.summaryFilter.selected_AND.length===0){ aggr.DOM.aggrGlyph.setAttribute("showlock",true); this.browser.setSelect_Highlight(this,aggr); if(!this.browser.ratioModeActive) { if(this.viewType==="map"){ this.DOM.highlightedMeasureValue.style("left",(100*(this.mapColorScale(aggr.measure('Highlighted'))/9))+"%"); } else { this.DOM.highlightedMeasureValue.style("left",this.chartScale_Measure(aggr.measure('Active'))+"px"); } this.DOM.highlightedMeasureValue.style("opacity",1); } } }, /** -- */ onCatLeave: function(ctgry){ ctgry.unselectAggregate(); if(!this.isCatSelectable(ctgry)) return; this.browser.clearSelect_Highlight(); if(this.viewType==='map') this.DOM.highlightedMeasureValue.style("opacity",0); }, /** -- */ onCatEnter_OR: function(ctgry){ this.browser.clearSelect_Highlight(); ctgry.DOM.aggrGlyph.setAttribute("selecttype","or"); ctgry.DOM.aggrGlyph.setAttribute("selection","selected"); if(this.summaryFilter.selected_OR.length>0){ this.browser.clearSelect_Highlight(); if(this.viewType==='map') this.DOM.highlightedMeasureValue.style("opacity",0); } d3.event.stopPropagation(); }, /** -- */ onCatLeave_OR: function(ctgry){ ctgry.DOM.aggrGlyph.setAttribute("selecttype","and"); }, /** -- */ onCatClick_OR: function(ctgry){ this.filterCategory(ctgry,"OR"); d3.event.stopPropagation(); d3.event.preventDefault(); }, /** -- */ onCatEnter_NOT: function(ctgry){ ctgry.DOM.aggrGlyph.setAttribute("selecttype","not"); ctgry.DOM.aggrGlyph.setAttribute("selection","selected"); this.browser.preview_not = true; this.browser.setSelect_Highlight(this,ctgry); d3.event.stopPropagation(); }, /** -- */ onCatLeave_NOT: function(ctgry){ ctgry.DOM.aggrGlyph.setAttribute("selecttype","and"); this.browser.preview_not = false; this.browser.clearSelect_Highlight(); if(this.viewType==='map') this.DOM.highlightedMeasureValue.style("opacity",0); }, /** -- */ onCatClick_NOT: function(ctgry){ var me=this; this.browser.preview_not = true; this.filterCategory(ctgry,"NOT"); setTimeout(function(){ me.browser.preview_not = false; }, 1000); d3.event.stopPropagation(); d3.event.preventDefault(); }, /** - */ insertCategories: function(){ var me = this; if(typeof this.DOM.aggrGroup === "undefined") return; var aggrGlyphSelection = this.DOM.aggrGroup.selectAll(".aggrGlyph") .data(this._cats, function(aggr){ return aggr.id(); }); var DOM_cats_new = aggrGlyphSelection.enter() .append(this.viewType=='list' ? 'span' : 'g') .attr("class","aggrGlyph "+(this.viewType=='list'?'cat':'map')+"Glyph") .attr("selected",0) .on("mousedown", function(){ this._mousemove = false; }) .on("mousemove", function(){ this._mousemove = true; if(this.tipsy){ this.tipsy.jq_tip[0].style.left = (d3.event.pageX-this.tipsy.tipWidth-10)+"px"; this.tipsy.jq_tip[0].style.top = (d3.event.pageY-this.tipsy.tipHeight/2)+"px"; } }) .attr("title",me.catTooltip?function(_cat){ return me.catTooltip.call(_cat.data); }:null); this.updateCatIsInView(); if(this.viewType==='list'){ DOM_cats_new .style("height",this.heightRow_category+"px") .each(function(_cat){ kshf.Util.setTransform(this,"translateY(0px)"); }) var clickArea = DOM_cats_new.append("span").attr("class", "clickArea") .on("mouseenter",function(_cat){ if(me.browser.mouseSpeed<0.2) { me.onCatEnter(_cat); } else { this.highlightTimeout = window.setTimeout( function(){ me.onCatEnter(_cat) }, me.browser.mouseSpeed*500); } }) .on("mouseleave",function(_cat){ if(this.highlightTimeout) window.clearTimeout(this.highlightTimeout); me.onCatLeave(_cat); }) .on("click", function(aggr){ me.onCatClick(aggr); }); clickArea.append("span").attr("class","lockButton fa") .on("mouseenter",function(aggr){ this.tipsy = new Tipsy(this, { gravity: me.panel.name==='right'?'se':'w', title: function(){ return kshf.lang.cur[ me.browser.selectedAggr["Compared_A"]!==aggr ? 'LockToCompare' : 'Unlock']; } }); this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }) .on("click",function(_cat){ this.tipsy.hide(); me.browser.setSelect_Compare(me,_cat,true); d3.event.preventDefault(); d3.event.stopPropagation(); }); var domAttrLabel = DOM_cats_new.append("span").attr("class", "categoryLabel hasLabelWidth") .style("padding-top",(this.heightRow_category/2-8)+"px"); var filterButtons = domAttrLabel.append("span").attr("class", "filterButtons"); filterButtons.append("span").attr("class","filterButton notButton") .text(kshf.lang.cur.Not) .on("mouseover", function(_cat){ me.onCatEnter_NOT(_cat); }) .on("mouseout", function(_cat){ me.onCatLeave_NOT(_cat); }) .on("click", function(_cat){ me.onCatClick_NOT(_cat); }); filterButtons.append("span").attr("class","filterButton orButton") .text(kshf.lang.cur.Or) .on("mouseover",function(_cat){ me.onCatEnter_OR(_cat); }) .on("mouseout", function(_cat){ me.onCatLeave_OR(_cat); }) .on("click", function(_cat){ me.onCatClick_OR(_cat); }); this.DOM.theLabel = domAttrLabel.append("span").attr("class","theLabel").html(function(_cat){ return me.catLabel_Func.call(_cat.data); }); DOM_cats_new.append("span").attr("class", "measureLabel"); ["Total","Active","Highlighted","Compared_A","Compared_B","Compared_C"].forEach(function(m){ DOM_cats_new.append("span").attr("class", "measure_"+m); }); DOM_cats_new.selectAll("[class^='measure_Compared_']") .on("mouseover" ,function(){ me.browser.refreshMeasureLabels(this.classList[0].substr(8)); d3.event.preventDefault(); d3.event.stopPropagation(); }) .on("mouseleave",function(){ me.browser.refreshMeasureLabels(); d3.event.preventDefault(); d3.event.stopPropagation(); }); DOM_cats_new.append("span").attr("class", "total_tip"); } else { DOM_cats_new .each(function(_cat){ this.tipsy = new Tipsy(this, { gravity: 'e', title: function(){ return "<span class='mapItemName'>"+me.catLabel_Func.call(_cat.data)+"</span>"+ me.browser.getMeasureLabel(_cat)+" "+me.browser.itemName; } }); }) .on("mouseenter",function(_cat){ if(this.tipsy) { this.tipsy.show(); this.tipsy.jq_tip[0].style.left = (d3.event.pageX-this.tipsy.tipWidth-10)+"px"; this.tipsy.jq_tip[0].style.top = (d3.event.pageY-this.tipsy.tipHeight/2)+"px"; } if(me.browser.mouseSpeed<0.2) { me.onCatEnter(_cat); } else { this.highlightTimeout = window.setTimeout( function(){ me.onCatEnter(_cat) }, me.browser.mouseSpeed*500); } }) .on("mouseleave",function(_cat){ if(this.tipsy) this.tipsy.hide(); if(this.highlightTimeout) window.clearTimeout(this.highlightTimeout); me.onCatLeave(_cat); }); DOM_cats_new.append("path").attr("class", "measure_Active"); DOM_cats_new.select(".measure_Active").on("click", function(aggr){ me.onCatClick(aggr); }); DOM_cats_new.append("text").attr("class", "measureLabel"); // label on top of (after) all the rest } this.refreshDOMcats(); }, /** -- */ refreshDOMcats: function(){ this.DOM.aggrGlyphs = this.DOM.aggrGroup.selectAll(".aggrGlyph").each(function(aggr){ aggr.DOM.aggrGlyph = this; }); this.DOM.measureLabel = this.DOM.aggrGlyphs.selectAll(".measureLabel"); this.DOM.measureTotalTip = this.DOM.aggrGlyphs.selectAll(".total_tip"); ["Total","Active","Highlighted","Compared_A","Compared_B","Compared_C"].forEach(function(m){ this.DOM["measure_"+m] = this.DOM.aggrGlyphs.selectAll(".measure_"+m); },this); if(this.viewType==='list'){ this.DOM.attribClickArea = this.DOM.aggrGlyphs.selectAll(".clickArea"); this.DOM.lockButton = this.DOM.aggrGlyphs.selectAll(".lockButton"); } }, /** -- */ updateCatIsInView: function(){ var me=this; if(this.viewType==='map'){ this._cats.forEach(function(_cat){ _cat.isVisible = true; }); return; } this._cats.forEach(function(_cat){ _cat.isVisibleBefore = _cat.isVisible; if(!_cat.isActive){ _cat.isVisible = false; } else if(_cat.orderIndex<me.firstCatIndexInView) { _cat.isVisible = false; } else if(_cat.orderIndex>me.firstCatIndexInView+me.catCount_InDisplay) { _cat.isVisible = false; } else { _cat.isVisible = true; } }); }, /** -- */ cullAttribs: function(){ if(this.viewType==='map') return; // no culling on maps, for now. this.DOM.aggrGlyphs .style("visibility",function(_cat){ return _cat.isVisible?"visible":"hidden"; }) .style("display",function(_cat){ return _cat.isVisible?"block":"none"; }); if(this.onCategoryCull) this.onCategoryCull.call(this); }, /** -- */ updateCatSorting: function(sortDelay,force,noAnim){ if(this.viewType==='map') return; if(this._cats===undefined) return; if(this._cats.length===0) return; if(this.uniqueCategories() && this.panel===undefined) return; // Nothing to sort... if(this.catSortBy_Active.no_resort===true && force!==true) return; var me = this; this.updateCatCount_Active(); this.sortCategories(); if(this.panel===undefined) return; // The rest deals with updating UI if(this.DOM.aggrGlyphs===undefined) return; this.updateCatIsInView(); var xRemoveOffset = (this.panel.name==='right')?-1:-100; // disappear direction, depends on the panel location if(this.cbFacetSort) this.cbFacetSort.call(this); // Items outside the view are not visible, chartBackground expand the box and makes the scroll bar visible if necessary. this.DOM.chartBackground.style("height",this.getHeight_VisibleAttrib()+"px"); var attribGroupScroll = me.DOM.aggrGroup[0][0]; // always scrolls to top row automatically when re-sorted if(this.scrollTop_cache!==0) kshf.Util.scrollToPos_do(attribGroupScroll,0); this.refreshScrollDisplayMore(this.firstCatIndexInView+this.catCount_InDisplay); this.refreshMeasureLabel(); if(noAnim){ this.DOM.aggrGlyphs.each(function(ctgry){ this.style.opacity = 1; this.style.visibility = "visible"; this.style.display = "block"; var x = 0; var y = me.heightRow_category*ctgry.orderIndex; ctgry.posX = x; ctgry.posY = y; kshf.Util.setTransform(this,"translate("+x+"px,"+y+"px)"); }); return; } setTimeout(function(){ // 1. Make items disappear // Note: do not cull with number of items made visible. // We are applying visible and block to ALL attributes as we animate the change me.DOM.aggrGlyphs.each(function(ctgry){ if(ctgry.isActiveBefore && !ctgry.isActive){ // disappear into left panel... this.style.opacity = 0; ctgry.posX = xRemoveOffset; ctgry.posY = ctgry.posY; kshf.Util.setTransform(this,"translate("+ctgry.posX+"px,"+ctgry.posY+"px)"); } if(!ctgry.isActiveBefore && ctgry.isActive){ // will be made visible... ctgry.posY = me.heightRow_category*ctgry.orderIndex; kshf.Util.setTransform(this,"translate("+xRemoveOffset+"px,"+ctgry.posY+"px)"); } if(ctgry.isActive || ctgry.isActiveBefore){ this.style.opacity = 0; this.style.visibility = "visible"; this.style.display = "block"; } }); // 2. Re-sort setTimeout(function(){ me.DOM.aggrGlyphs.each(function(ctgry){ if(ctgry.isActive && ctgry.isActiveBefore){ this.style.opacity = 1; ctgry.posX = 0; ctgry.posY = me.heightRow_category*ctgry.orderIndex; kshf.Util.setTransform(this,"translate("+ctgry.posX+"px,"+ctgry.posY+"px)"); } }); // 3. Make items appear setTimeout(function(){ me.DOM.aggrGlyphs.each(function(ctgry){ if(!ctgry.isActiveBefore && ctgry.isActive){ this.style.opacity = 1; ctgry.posX = 0; ctgry.posY = me.heightRow_category*ctgry.orderIndex; kshf.Util.setTransform(this, "translate("+ctgry.posX+"px,"+ctgry.posY+"px)"); } }); // 4. Apply culling setTimeout(function(){ me.cullAttribs();} , 700); },(me.catCount_NowVisible>0)?300:0); },(me.catCount_NowInvisible>0)?300:0); }, (sortDelay===undefined) ? 1000 : sortDelay ); }, /** -- */ chartAxis_Measure_TickSkip: function(){ var width = this.chartScale_Measure.range()[1]; var ticksSkip = width/25; if(this.getMaxAggr_Active()>100000){ ticksSkip = width/30; } if(this.browser.percentModeActive){ ticksSkip /= 1.1; } return ticksSkip; }, /** -- */ map_projectCategories: function(){ var me = this; this.DOM.measure_Active.attr("d", function(_cat){ _cat._d_ = me.catMap.call(_cat.data,_cat); if(_cat._d_===undefined) return; return me.geoPath(_cat._d_); }); this.DOM.measure_Highlighted.attr("d", function(_cat){ return me.geoPath(_cat._d_); }); this.DOM.measureLabel .attr("transform", function(_cat){ var centroid = me.geoPath.centroid(_cat._d_); return "translate("+centroid[0]+","+centroid[1]+")"; }) .style("display",function(aggr){ var bounds = me.geoPath.bounds(aggr._d_); var width = Math.abs(bounds[0][0]-bounds[1][0]); return (width<me.panel.width_catMeasureLabel)?"none":"block"; }) ; }, /** -- */ map_refreshBounds_Active: function(){ // Insert the bounds for each record path into the bs var bs = []; var me = this; this._cats.forEach(function(_cat){ if(!_cat.isActive) return; var feature = me.catMap.call(_cat.data,_cat); if(typeof feature === 'undefined') return; var b = d3.geo.bounds(feature); if(isNaN(b[0][0])) return; // Change wrapping if(b[0][0]>kshf.wrapLongitude) b[0][0]-=360; if(b[1][0]>kshf.wrapLongitude) b[1][0]-=360; bs.push(L.latLng(b[0][1], b[0][0])); bs.push(L.latLng(b[1][1], b[1][0])); }); this.mapBounds_Active = new L.latLngBounds(bs); }, /** -- */ map_zoomToActive: function(){ if(this.asdsds===undefined){ // First time: just fit bounds this.asdsds = true; this.leafletAttrMap.fitBounds(this.mapBounds_Active); return; } this.leafletAttrMap.flyToBounds( this.mapBounds_Active, { padding: [0,0], pan: {animate: true, duration: 1.2}, zoom: {animate: true} } ); }, /** -- */ map_refreshColorScale: function(){ var me=this; this.DOM.mapColorBlocks .style("background-color", function(d){ if(me.invertColorScale) d = 8-d; return kshf.colorScale[me.browser.mapColorTheme][d]; }); }, /** -- */ viewAs: function(_type){ var me = this; this.viewType = _type; this.DOM.root.attr("viewType",this.viewType); if(this.viewType==='list'){ this.DOM.aggrGroup = this.DOM.aggrGroup_list; if(this.heightRow_category_dirty) this.refreshHeight_Category(); this.refreshDOMcats(); this.updateCatSorting(0,true,true); return; } // 'map' // The map view is already initialized if(this.leafletAttrMap) { this.DOM.aggrGroup = this.DOM.summaryCategorical.select(".catMap_SVG > .aggrGroup"); this.refreshDOMcats(); this.map_refreshBounds_Active(); this.map_zoomToActive(); this.map_projectCategories(); this.refreshViz_Active(); return; } // See http://leaflet-extras.github.io/leaflet-providers/preview/ for alternative layers this.leafletAttrMap = L.map(this.DOM.catMap_Base[0][0] ) .addLayer(new L.TileLayer( kshf.map.tileTemplate, { attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a>', subdomains: 'abcd', maxZoom: 19 })) .on("viewreset",function(){ me.map_projectCategories() }) .on("movestart",function(){ me.DOM.aggrGlyphs.style("display","none"); }) .on("move",function(){ // console.log("MapZoom: "+me.leafletAttrMap.getZoom()); // me.map_projectCategories() }) .on("moveend",function(){ me.DOM.aggrGlyphs.style("display","block"); me.map_projectCategories() }) ; //var width = 500, height = 500; //var projection = d3.geo.albersUsa().scale(900).translate([width / 2, height / 2]); this.geoPath = d3.geo.path().projection( d3.geo.transform({ // Use Leaflet to implement a D3 geometric transformation. point: function(x, y) { if(x>kshf.wrapLongitude) x-=360; var point = me.leafletAttrMap.latLngToLayerPoint(new L.LatLng(y, x)); this.stream.point(point.x, point.y); } }) ); this.mapColorQuantize = d3.scale.quantize() .domain([0,9]) .range(kshf.colorScale.converge); this.DOM.catMap_SVG = d3.select(this.leafletAttrMap.getPanes().overlayPane) .append("svg").attr("xmlns","http://www.w3.org/2000/svg") .attr("class","catMap_SVG"); // The fill pattern definition in SVG, used to denote geo-objects with no data. // http://stackoverflow.com/questions/17776641/fill-rect-with-pattern this.DOM.catMap_SVG.append('defs') .append('pattern') .attr('id', 'diagonalHatch') .attr('patternUnits', 'userSpaceOnUse') .attr('width', 4) .attr('height', 4) .append('path') .attr('d', 'M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2') .attr('stroke', 'gray') .attr('stroke-width', 1); // Add custom controls var DOM_control = d3.select(this.leafletAttrMap.getContainer()).select(".leaflet-control"); DOM_control.append("a") .attr("class","leaflet-control-viewFit").attr("title",kshf.lang.cur.ZoomToFit) .attr("href","#") .html("<span class='viewFit fa fa-arrows-alt'></span>") .on("dblclick",function(){ d3.event.preventDefault(); d3.event.stopPropagation(); }) .on("click",function(){ me.map_refreshBounds_Active(); me.map_zoomToActive(); d3.event.preventDefault(); d3.event.stopPropagation(); }); this.DOM.aggrGroup = this.DOM.catMap_SVG.append("g").attr("class", "leaflet-zoom-hide aggrGroup"); // Now this will insert map svg component this.insertCategories(); this.DOM.catMapColorScale = this.DOM.belowCatChart.append("div").attr("class","catMapColorScale"); this.DOM.catMapColorScale.append("span").attr("class","scaleBound boundMin"); this.DOM.catMapColorScale.append("span").attr("class","scaleBound boundMax"); this.DOM.catMapColorScale.append("span") .attr("class","relativeModeControl fa fa-arrows-h") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'e', title: function(){ return kshf.lang.cur[me.browser.ratioModeActive?'Absolute':'Relative']+" "+kshf.lang.cur.Width; } }); }) .on("click",function(){ this.tipsy.hide(); me.browser.setMeasureAxisMode(!me.browser.ratioModeActive); }) .on("mouseover",function(){ me.browser.DOM.root.selectAll(".relativeModeControl").attr("highlight",true); this.tipsy.show(); }) .on("mouseout",function(){ me.browser.DOM.root.selectAll(".relativeModeControl").attr("highlight",false); this.tipsy.hide(); }); this.DOM.catMapColorScale.append("span").attr("class","measurePercentControl") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'w', title: function(){ return "<span class='fa fa-eye'></span> "+kshf.lang.cur[(me.browser.percentModeActive?'Absolute':'Percent')]; }, }) }) .on("click",function(){ this.tipsy.hide(); me.browser.setPercentLabelMode(!me.browser.percentModeActive); }) .on("mouseover",function(){ me.browser.DOM.root.selectAll(".measurePercentControl").attr("highlight",true); this.tipsy.show(); }) .on("mouseout",function(){ me.browser.DOM.root.selectAll(".measurePercentControl").attr("highlight",false); this.tipsy.hide(); }); this.DOM.highlightedMeasureValue = this.DOM.catMapColorScale.append("span").attr("class","highlightedMeasureValue"); this.DOM.highlightedMeasureValue.append("div").attr('class','fa fa-mouse-pointer highlightedAggrValuePointer'); this.DOM.mapColorBlocks = this.DOM.catMapColorScale.selectAll(".mapColorBlock") .data([0,1,2,3,4,5,6,7,8]).enter() .append("div").attr("class","mapColorBlock") .each(function(d){ this.tipsy = new Tipsy(this, { gravity: 's', title: function(){ var _minValue = Math.round(me.mapColorScale.invert(d)); var _maxValue = Math.round(me.mapColorScale.invert(d+1)); return Math.round(_minValue)+" to "+Math.round(_maxValue); } }); }) .on("mouseenter",function(d){ this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }); // Set height var h = this.categoriesHeight; this.DOM.catMap_Base.style("height",h+"px"); if(this.DOM.catMap_SVG) this.DOM.catMap_SVG.style("height",h+"px"); if(this.leafletAttrMap) this.leafletAttrMap.invalidateSize(); this.DOM.aggrGroup.style("height",h+"px"); this.map_refreshColorScale(); this.map_refreshBounds_Active(); this.map_zoomToActive(); this.map_projectCategories(); this.refreshMeasureLabel(); this.refreshViz_Active(); }, /** -- */ printAggrSelection: function(aggr){ return this.catLabel_Func.call(aggr.data); } }; for(var index in Summary_Categorical_functions){ kshf.Summary_Categorical.prototype[index] = Summary_Categorical_functions[index]; } /** * Keshif Interval Summary * @constructor */ kshf.Summary_Interval = function(){}; kshf.Summary_Interval.prototype = new kshf.Summary_Base(); var Summary_Interval_functions = { initialize: function(browser,name,attribFunc){ kshf.Summary_Base.prototype.initialize.call(this,browser,name,attribFunc); this.type='interval'; // Call the parent's constructor var me = this; // pixel width settings... this.height_hist = 1; // Initial width (will be updated later...) this.height_hist_min = 10; // Minimum possible histogram height this.height_hist_max = 100; // Maximim possible histogram height this.height_slider = 12; // Slider height this.height_labels = 13; // Height for labels this.height_hist_topGap = 12; // Height for histogram gap on top. this.width_barGap = 2; // The width between neighboring histgoram bars this.width_measureAxisLabel = 30; // .. this.optimumTickWidth = 45; this.hasFloat = false; this.timeTyped = { base: false }; this.unitName = undefined; // the text appended to the numeric value (TODO: should not apply to time) this.percentileChartVisible = false; // Percentile chart is a 1-line chart which shows %10-%20-%30-%40-%50 percentiles this.zoomed = false; this.usedForSorting = false; this.invertColorScale = false; this.highlightRangeLimits_Active = false; // Used for flexible range selection. // TODO: Support multiple compare selections. this.flexAggr_Highlight = new kshf.Aggregate(); this.flexAggr_Compare = new kshf.Aggregate(); this.flexAggr_Highlight.init({}); this.flexAggr_Compare .init({}); this.flexAggr_Highlight.summary = this; this.flexAggr_Compare .summary = this; this.quantile_val = {}; this.quantile_pos = {}; this.histBins = []; this.intervalTicks = []; this.intervalRange = {}; this.intervalTickFormat = function(v){ return (me.hasFloat) ? d3.format("s")(v) : d3.format(".2f")(v); }; if(this.records.length<=1000) this.initializeAggregates(); }, /** -- */ isTimeStamp: function(){ return this.timeTyped.base; }, /** TODO: Only relevant is timeStamp-- */ createMonthSummary: function(){ if(!this.isTimeStamp()) return; if(this.summary_sub_month) return this.summary_sub_month; var summaryID = this.summaryID; this.summary_sub_month = this.browser.createSummary( "Month of "+this.summaryName, function(d){ var arr=d._valueCache[summaryID]; return (arr===null) ? null : arr.getUTCMonth(); }, 'categorical' ); this.summary_sub_month.setSortingOptions("id"); this.summary_sub_month.setCatLabel(_demo.Month); this.summary_sub_month.initializeAggregates(); return this.summary_sub_month; }, /** TODO: Only relevant is timeStamp-- */ createDaySummary: function(){ if(!this.isTimeStamp()) return; if(this.summary_sub_day) return this.summary_sub_day; var summaryID = this.summaryID; this.summary_sub_day = this.browser.createSummary( "WeekDay of "+this.summaryName, function(d){ var arr=d._valueCache[summaryID]; return (arr===null) ? null : arr.getUTCDay(); }, 'categorical' ); this.summary_sub_day.setSortingOptions("id"); this.summary_sub_day.setCatLabel(_demo.DayOfWeek); this.summary_sub_day.initializeAggregates(); return this.summary_sub_day; }, /** TODO: Only relevant is timeStamp-- */ createHourSummary: function(){ if(!this.isTimeStamp()) return; if(this.summary_sub_hour) return this.summary_sub_hour; var summaryID = this.summaryID; this.summary_sub_hour = this.browser.createSummary( "Hour of "+this.summaryName, function(d){ var arr=d._valueCache[summaryID]; return (arr===null) ? null : arr.getUTCHours(); }, 'interval' ); this.summary_sub_hour.initializeAggregates(); this.summary_sub_hour.setUnitName(":00"); return this.summary_sub_hour; }, /** -- */ initializeAggregates: function(){ if(this.aggr_initialized) return; var me = this; this.getRecordValue = function(record){ return record._valueCache[me.summaryID]; }; this.records.forEach(function(record){ var v=this.summaryFunc.call(record.data,record); if(isNaN(v)) v=null; if(v===undefined) v=null; if(v!==null){ if(v instanceof Date){ this.timeTyped.base = true; } else { if(typeof v!=='number'){ v = null; } else{ this.hasFloat = this.hasFloat || v%1!==0; } } } record._valueCache[this.summaryID] = v; if(v===null) this.missingValueAggr.addRecord(record); },this); if(this.timeTyped.base===true){ // Check time resolutions this.timeTyped.month = false; this.timeTyped.hour = false; this.timeTyped.day = false; var tempDay = null; this.records.forEach(function(record){ v = record._valueCache[this.summaryID]; if(v) { if(v.getUTCMonth()!==0) this.timeTyped.month = true; if(v.getUTCHours()!==0) this.timeTyped.hour = true; // Day if(!this.timeTyped.day){ if(tempDay===null) { tempDay = v.getUTCDay(); } else { if(v.getUTCDay()!==tempDay) this.timeTyped.day = true; tempDay = v.getUTCDay(); } } } },this); } // remove records that map to null / undefined this.filteredItems = this.records.filter(function(record){ var v = me.getRecordValue(record); return (v!==undefined && v!==null); }); // Sort the items by their attribute value var sortValue = this.isTimeStamp()? function(a){ return me.getRecordValue(a).getTime(); }: function(a){ return me.getRecordValue(a); }; this.filteredItems.sort(function(a,b){ return sortValue(a)-sortValue(b);}); this.updateIntervalRangeMinMax(); this.detectScaleType(); this.aggr_initialized = true; this.refreshViz_Nugget(); this.refreshViz_EmptyRecords(); }, /** -- */ isEmpty: function(){ return this._isEmpty; }, /** -- */ detectScaleType: function(){ if(this.isEmpty()) return; var me = this; this.stepTicks = false; // TIME SCALE if(this.isTimeStamp()) { this.setScaleType('time',true); return; } // decide scale type based on the filtered records var activeItemV = function(record){ var v = record._valueCache[me.summaryID]; if(v>=me.intervalRange.active.min && v <= me.intervalRange.active.max) return v; // value is within filtered range }; var deviation = d3.deviation(this.filteredItems, activeItemV); var activeRange = this.intervalRange.active.max-this.intervalRange.active.min; var _width_ = this.getWidth_Chart(); var stepRange = (this.intervalRange.active.max-this.intervalRange.active.min)+1; // Apply step range before you check for log - it has higher precedence if(!this.hasFloat){ if( (_width_ / this.getWidth_OptimumTick()) >= stepRange){ this.stepTicks = true; this.setScaleType('linear',false); // converted to step on display return; } } // LOG SCALE if(deviation/activeRange<0.12 && this.intervalRange.active.min>=0){ this.setScaleType('log',false); return; } // The scale can be linear or step after this stage // STEP SCALE if number are floating if(this.hasFloat){ this.setScaleType('linear',false); return; } if( (_width_ / this.getWidth_OptimumTick()) >= stepRange){ this.stepTicks = true; } this.setScaleType('linear',false); }, /** -- */ createSummaryFilter: function(){ var me=this; this.summaryFilter = this.browser.createFilter({ title: function(){ return me.summaryName; }, onClear: function(){ if(this.filteredBin){ this.filteredBin.setAttribute("filtered",false); this.filteredBin = undefined; } me.DOM.root.attr("filtered",false); if(me.zoomed){ me.setZoomed(false); } me.resetIntervalFilterActive(); me.refreshIntervalSlider(); if(me.DOM.missingValueAggr) me.DOM.missingValueAggr.attr("filtered",null); }, onFilter: function(){ me.DOM.root.attr("filtered",true); var valueID = me.summaryID; if(me.missingValueAggr.filtered){ me.records.forEach(function(record){ record.setFilterCache(this.filterID, record._valueCache[valueID]===null); },this); return; } var i_min = this.active.min; var i_max = this.active.max; var isFilteredCb; if(me.isFiltered_min() && me.isFiltered_max()){ if(this.max_inclusive) isFilteredCb = function(v){ return v>=i_min && v<=i_max; }; else isFilteredCb = function(v){ return v>=i_min && v<i_max; }; } else if(me.isFiltered_min()){ isFilteredCb = function(v){ return v>=i_min; }; } else { if(this.max_inclusive) isFilteredCb = function(v){ return v<=i_max; }; else isFilteredCb = function(v){ return v<i_max; }; } if(me.stepTicks){ if(i_min+1===i_max){ isFilteredCb = function(v){ return v===i_min; }; } } // TODO: Optimize: Check if the interval scale is extending/shrinking or completely updated... me.records.forEach(function(record){ var v = record._valueCache[valueID]; record.setFilterCache(this.filterID, (v!==null)?isFilteredCb(v):false); },this); me.DOM.zoomControl.attr("sign", (me.stepTicks && me.scaleType==="linear") ? (this.zoomed ? "minus" : "") : "plus" ); me.refreshIntervalSlider(); }, filterView_Detail: function(){ return (me.missingValueAggr.filtered) ? kshf.lang.cur.NoData : me.printAggrSelection(); }, }); }, /** -- */ printAggrSelection: function(aggr){ var minValue, maxValue; if(aggr){ minValue = aggr.minV; maxValue = aggr.maxV; } else { minValue = this.summaryFilter.active.min; maxValue = this.summaryFilter.active.max; } if(this.stepTicks){ if(minValue+1===maxValue || aggr) { return "<b>"+this.printWithUnitName(minValue)+"</b>"; } } if(this.scaleType==='time'){ return "<b>"+this.intervalTickFormat(minValue)+ "</b> to <b>"+this.intervalTickFormat(maxValue)+"</b>"; } if(this.hasFloat){ minValue = minValue.toFixed(2); maxValue = maxValue.toFixed(2); } var minIsLarger = minValue > this.intervalRange.min; var maxIsSmaller = maxValue < this.intervalRange.max; if(minIsLarger && maxIsSmaller){ return "<b>"+this.printWithUnitName(minValue)+"</b> to <b>"+this.printWithUnitName(maxValue)+"</b>"; } else if(minIsLarger){ return "<b>at least "+this.printWithUnitName(minValue)+"</b>"; } else { return "<b>at most "+this.printWithUnitName(maxValue)+"</b>"; } }, /** -- */ refreshViz_Nugget: function(){ if(this.DOM.nugget===undefined) return; var nuggetChart = this.DOM.nugget.select(".nuggetChart"); this.DOM.nugget .attr("aggr_initialized",this.aggr_initialized) .attr("datatype",this.getDataType()); if(!this.aggr_initialized) return; if(this.uniqueCategories()){ this.DOM.nugget.select(".nuggetInfo").html("<span class='fa fa-tag'></span><br>Unique"); nuggetChart.style("display",'none'); return; } var maxAggregate_Total = this.getMaxAggr_Total(); if(this.intervalRange.min===this.intervalRange.max){ this.DOM.nugget.select(".nuggetInfo").html("only<br>"+this.intervalRange.min); nuggetChart.style("display",'none'); return; } var totalHeight = 17; nuggetChart.selectAll(".nuggetBar").data(this.histBins).enter() .append("span").attr("class","nuggetBar") .style("height",function(aggr){ return totalHeight*(aggr.records.length/maxAggregate_Total)+"px"; }); this.DOM.nugget.select(".nuggetInfo").html( "<span class='num_left'>"+this.intervalTickFormat(this.intervalRange.min)+"</span>"+ "<span class='num_right'>"+this.intervalTickFormat(this.intervalRange.max)+"</span>"); }, /** -- */ updateIntervalRangeMinMax: function(){ this.intervalRange.min = d3.min(this.filteredItems,this.getRecordValue); this.intervalRange.max = d3.max(this.filteredItems,this.getRecordValue); this.intervalRange.active = { min: this.intervalRange.min, max: this.intervalRange.max }; this.resetIntervalFilterActive(); this._isEmpty = this.intervalRange.min===undefined; if(this._isEmpty) this.setCollapsed(true); }, /** -- */ resetIntervalFilterActive: function(){ this.summaryFilter.active = { min: this.intervalRange.min, max: this.intervalRange.max }; }, /** -- */ setScaleType: function(t,force){ if(this.scaleType===t) return; var me=this; this.viewType = t==='time'?'line':'bar'; if(this.DOM.inited) { this.DOM.root.attr("viewType",this.viewType); } if(force===false && this.scaleType_forced) return; this.scaleType = t; if(force) this.scaleType_forced = this.scaleType; if(this.DOM.inited){ this.DOM.summaryConfig.selectAll(".summaryConfig_ScaleType .configOption").attr("active",false); this.DOM.summaryConfig.selectAll(".summaryConfig_ScaleType .pos_"+this.scaleType).attr("active",true); this.DOM.summaryInterval.attr("scaleType",this.scaleType); } if(this.filteredItems === undefined) return; // remove records with value:0 (because log(0) is invalid) if(this.scaleType==='log'){ if(this.intervalRange.min<=0){ var x=this.filteredItems.length; this.filteredItems = this.filteredItems.filter(function(record){ var v=this.getRecordValue(record)!==0; if(v===false) { record._valueCache[this.summaryID] = null; // TODO: Remove from existing aggregate for this summary this.missingValueAggr.addRecord(record); } return v; },this); if(x!==this.filteredItems.length){ // Some records are filtered bc they are 0. this.updateIntervalRangeMinMax(); } } // cannot be zero. var minnn = d3.min(this.filteredItems,function(record){ var v=me.getRecordValue(record); if(v>0) return v; } ); this.intervalRange.active.min = Math.max(minnn, this.intervalRange.active.min); this.summaryFilter.active.min = Math.max(minnn, this.summaryFilter.active.min); } if(this.scaleType==="linear"){ // round the maximum to an integer. If it is an integer already, has no effect. this.intervalRange.active.max = Math.ceil(this.intervalRange.active.max); } this.updateScaleAndBins(true); if(this.usedForSorting) this.browser.recordDisplay.refreshRecordColors(); }, /** -- */ getHeight_RecordEncoding: function(){ if(this.usedForSorting===false) return 0; if(this.browser.recordDisplay===undefined) return 0; if(this.browser.recordDisplay.displayType==="map") return 20; if(this.browser.recordDisplay.displayType==="nodelink") return 20; return 0; }, /** -- */ getHeight_Content: function(){ return this.height_hist + this.getHeight_Extra(); }, /** -- */ getHeight_Percentile: function(){ if(this.percentileChartVisible===false) return 0; if(this.percentileChartVisible==="Basic") return 15; if(this.percentileChartVisible==="Extended") return 32; }, /** -- */ getHeight_Extra: function(){ return 7+ this.height_hist_topGap+ this.height_labels+ this.height_slider+ this.getHeight_Percentile()+ this.getHeight_RecordEncoding(); }, /** -- */ getHeight_Extra_max: function(){ return 7+ this.height_hist_topGap+ this.height_labels+ this.height_slider+ 35; }, /** -- */ getHeight_RangeMax: function(){ return this.height_hist_max + this.getHeight_Header() + this.getHeight_Extra_max(); }, /** -- */ getHeight_RangeMin: function(){ return this.height_hist_min + this.getHeight_Header() + this.getHeight_Extra_max(); }, /** -- */ getWidth_Chart: function(){ if(this.panel===undefined) return 30; return this.getWidth() - this.width_measureAxisLabel - ( this.getWidth()>400 ? this.width_measureAxisLabel : 11 ); }, /** -- */ getWidth_OptimumTick: function(){ if(this.panel===undefined) return 10; return this.optimumTickWidth; }, /** -- */ getWidth_Bin: function(){ return this.aggrWidth-this.width_barGap*2; }, /** -- */ isFiltered_min: function(){ // the active min is different from intervalRange min. if(this.summaryFilter.active.min!==this.intervalRange.min) return true; // if using log scale, assume min is also filtered when max is filtered. if(this.scaleType==='log') return this.isFiltered_max(); return false; }, /** -- */ isFiltered_max: function(){ return this.summaryFilter.active.max!==this.intervalRange.max; }, /** -- */ getMaxAggr_Total: function(){ return d3.max(this.histBins,function(aggr){ return aggr.measure('Total'); }); }, /** -- */ getMaxAggr_Active: function(){ return d3.max(this.histBins,function(aggr){ return aggr.measure('Active'); }); }, /** -- */ refreshPercentileChart: function(){ this.DOM.percentileGroup .style("opacity",this.percentileChartVisible?1:0) .attr("percentileChartVisible",this.percentileChartVisible); if(this.percentileChartVisible){ this.DOM.percentileGroup.style("height",(this.percentileChartVisible==="Basic"?13:30)+"px"); } this.DOM.summaryConfig.selectAll(".summaryConfig_Percentile .configOption").attr("active",false); this.DOM.summaryConfig.selectAll(".summaryConfig_Percentile .pos_"+this.percentileChartVisible).attr("active",true); }, /** -- */ showPercentileChart: function(v){ if(v===true) v="Basic"; this.percentileChartVisible = v; if(this.DOM.inited) { var curHeight = this.getHeight(); this.refreshPercentileChart(); if(this.percentileChartVisible) this.updatePercentiles("Active"); this.setHeight(curHeight); this.browser.updateLayout_Height(); } }, /** -- */ initDOM: function(beforeDOM){ this.initializeAggregates(); if(this.isEmpty()) return; if(this.DOM.inited===true) return; var me = this; this.insertRoot(beforeDOM); this.DOM.root .attr("summary_type","interval") .attr("usedForSorting",this.usedForSorting) .attr("viewType",this.viewType); this.insertHeader(); this.initDOM_IntervalConfig(); this.DOM.summaryInterval = this.DOM.wrapper.append("div").attr("class","summaryInterval") .attr("scaleType",this.scaleType) .attr("zoomed",this.zoomed) .on("mousedown",function(){ d3.event.stopPropagation(); d3.event.preventDefault(); }); this.DOM.histogram = this.DOM.summaryInterval.append("div").attr("class","histogram"); this.DOM.histogram_bins = this.DOM.histogram.append("div").attr("class","aggrGroup") .on("mousemove", function(){ if(d3.event.shiftKey){ var pointerPosition = me.valueScale.invert(d3.mouse(this)[0]); if(this.initPos===undefined){ this.initPos = pointerPosition; } var maxPos = d3.max([this.initPos, pointerPosition]); var minPos = d3.min([this.initPos, pointerPosition]); me.highlightRangeLimits_Active = true; // Set preview selection me.flexAggr_Highlight.records = []; me.filteredItems.forEach(function(record){ var v = me.getRecordValue(record); if(v>=minPos && v<=maxPos) me.flexAggr_Highlight.records.push(record); else record.remForHighlight(true); }); me.flexAggr_Highlight.minV = minPos; me.flexAggr_Highlight.maxV = maxPos; me.browser.setSelect_Highlight(me,me.flexAggr_Highlight); d3.event.preventDefault(); d3.event.stopPropagation(); } else { if(me.highlightRangeLimits_Active){ this.initPos = undefined; me.browser.clearSelect_Highlight(); d3.event.preventDefault(); d3.event.stopPropagation(); } } }) .on("click", function(){ if(d3.event.shiftKey && me.highlightRangeLimits_Active){ // Lock for comparison me.flexAggr_Compare.minV = me.flexAggr_Highlight.minV; me.flexAggr_Compare.maxV = me.flexAggr_Highlight.maxV; me.browser.setSelect_Compare(me,me.flexAggr_Compare,false); this.initPos = undefined; d3.event.preventDefault(); d3.event.stopPropagation(); } }); this.DOM.highlightRangeLimits = this.DOM.histogram_bins.selectAll(".highlightRangeLimits") .data([0,1]).enter() .append("div").attr("class","highlightRangeLimits"); if(this.scaleType==='time'){ this.DOM.timeSVG = this.DOM.histogram.append("svg").attr("class","timeSVG") .attr("xmlns","http://www.w3.org/2000/svg") .style("margin-left",(this.width_barGap)+"px"); } this.insertChartAxis_Measure(this.DOM.histogram, 'w', 'nw'); this.initDOM_Slider(); this.initDOM_RecordMapColor(); this.initDOM_Percentile(); this.updateScaleAndBins(); this.setCollapsed(this.collapsed); this.setUnitName(this.unitName); this.DOM.inited = true; }, /** -- */ setZoomed: function(v){ this.zoomed = v; this.DOM.summaryInterval.attr("zoomed",this.zoomed); if(this.zoomed){ this.intervalRange.active.min = this.summaryFilter.active.min; this.intervalRange.active.max = this.summaryFilter.active.max; this.DOM.zoomControl.attr("sign","minus"); } else { this.intervalRange.active.min = this.intervalRange.min; this.intervalRange.active.max = this.intervalRange.max; this.DOM.zoomControl.attr("sign","plus"); } this.detectScaleType(); this.updateScaleAndBins(); }, /** -- */ setUnitName: function(v){ this.unitName = v; if(this.unitName) this.DOM.unitNameInput[0][0].value = this.unitName; this.refreshTickLabels(); if(this.usedForSorting && this.browser.recordDisplay.recordViewSummary){ this.browser.recordDisplay.refreshRecordSortLabels(); } }, /** -- */ printWithUnitName: function(v,noDiv){ if(v instanceof Date) return this.intervalTickFormat(v); if(this.unitName){ var s; if(noDiv){ s=this.unitName; } else { s = "<span class='unitName'>"+this.unitName+"</span>"; } return (this.unitName==='$' || this.unitName==='€') ? (s+v) : (v+s); } return v; }, /** -- */ setAsRecordSorting: function(){ this.usedForSorting = true; if(this.DOM.root) this.DOM.root.attr("usedForSorting","true"); }, /** -- */ clearAsRecordSorting: function(){ this.usedForSorting = false; if(this.DOM.root) this.DOM.root.attr("usedForSorting","false"); }, /** -- */ initDOM_IntervalConfig: function(){ var me=this, x; var summaryConfig_UnitName = this.DOM.summaryConfig.append("div") .attr("class","summaryConfig_UnitName summaryConfig_Option"); summaryConfig_UnitName.append("span").text("Value Unit: "); this.DOM.unitNameInput = summaryConfig_UnitName.append("input").attr("type","text") .attr("class","unitNameInput") .attr("placeholder",kshf.unitName) .attr("maxlength",5) .on("input",function(){ if(this.timer) clearTimeout(this.timer); var x = this; var queryString = x.value.toLowerCase(); this.timer = setTimeout( function(){ me.setUnitName(queryString); }, 750); });; // Show the linear/log scale transformation only if... if(this.scaleType!=='time' && !this.stepTicks && this.intervalRange.min>=0){ this.DOM.summaryConfig_ScaleType = this.DOM.summaryConfig.append("div") .attr("class","summaryConfig_ScaleType summaryConfig_Option"); this.DOM.summaryConfig_ScaleType.append("span").html("<i class='fa fa-arrows-h'></i> Scale: "); x = this.DOM.summaryConfig_ScaleType.append("span").attr("class","optionGroup"); x.selectAll(".configOption").data( [ {l:"Linear <span style='font-size:0.8em; color: gray'>(1,2,3,4,5)</span>",v:"Linear"}, {l:"Log <span style='font-size:0.8em; color: gray'>(1,2,4,8,16)</span>", v:"Log"} ]) .enter() .append("span").attr("class",function(d){ return "configOption pos_"+d.v.toLowerCase();}) .attr("active",function(d){ return d.v.toLowerCase()===me.scaleType; }) .html(function(d){ return d.l; }) .on("click", function(d){ me.setScaleType(d.v.toLowerCase(),true); }) } var summaryConfig_Percentile = this.DOM.summaryConfig.append("div") .attr("class","summaryConfig_Percentile summaryConfig_Option"); summaryConfig_Percentile.append("span").text("Percentile Charts: ") x = summaryConfig_Percentile.append("span").attr("class","optionGroup"); x.selectAll(".configOption").data( [ {l:"<i class='bl_Active'></i><i class='bl_Highlighted'></i>"+ "<i class='bl_Compared_A'></i><i class='bl_Compared_B'></i><i class='bl_Compared_C'></i> Full",v:"Extended"}, {l:"<i class='bl_Active'></i><i class='bl_Highlighted'></i> Basic",v:"Basic"}, {l:"<i class='fa fa-eye-slash'></i> Hide",v:false} ]).enter() .append("span") .attr("class",function(d){ return "configOption pos_"+d.v;}) .attr("active",function(d){ return d.v===me.percentileChartVisible; }) .html(function(d){ return d.l; }) .on("click", function(d){ me.showPercentileChart(d.v); }); }, /** -- */ initDOM_Percentile: function(){ if(this.DOM.summaryInterval===undefined) return; var me=this; this.DOM.percentileGroup = this.DOM.summaryInterval.append("div").attr("class","percentileGroup"); this.DOM.percentileGroup.append("span").attr("class","percentileTitle").html(kshf.lang.cur.Percentiles); this.DOM.quantile = {}; function addPercentileDOM(parent, distr){ [[10,90],[20,80],[30,70],[40,60]].forEach(function(qb){ this.DOM.quantile[distr+qb[0]+"_"+qb[1]] = parent.append("span") .attr("class","quantile q_range q_"+qb[0]+"_"+qb[1]) .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'sw', title: function(){ return "<span style='font-weight:300'>"+qb[0]+"% - "+qb[1]+"% percentile: </span>"+ "<span style='font-weight:500'>"+me.quantile_val[distr+qb[0]]+"</span> - "+ "<span style='font-weight:500'>"+me.quantile_val[distr+qb[1]]+"</span>"; } }) }) .on("mouseover",function(){ this.tipsy.show(); me.flexAggr_Highlight.records = []; me.filteredItems.forEach(function(record){ var v = me.getRecordValue(record); if(v>=me.quantile_val[distr+qb[0]] && v<=me.quantile_val[distr+qb[1]]) me.flexAggr_Highlight.records.push(record); }); me.flexAggr_Highlight.minV = me.quantile_val[distr+qb[0]]; me.flexAggr_Highlight.maxV = me.quantile_val[distr+qb[1]]; me.highlightRangeLimits_Active = true; me.browser.setSelect_Highlight(me,me.flexAggr_Highlight); }) .on("mouseout" ,function(){ this.tipsy.hide(); me.browser.clearSelect_Highlight(); }) .on("click", function(){ if(d3.event.shiftKey){ me.flexAggr_Compare.minV = me.quantile_val[distr+qb[0]]; me.flexAggr_Compare.maxV = me.quantile_val[distr+qb[1]]; me.browser.setSelect_Compare(me,me.flexAggr_Compare, false); return; } me.summaryFilter.active = { min: me.quantile_val[distr+qb[0]], max: me.quantile_val[distr+qb[1]] }; me.summaryFilter.filteredBin = undefined; me.summaryFilter.addFilter(); }) ; },this); [10,20,30,40,50,60,70,80,90].forEach(function(q){ this.DOM.quantile[distr+q] = parent.append("span") .attr("class","quantile q_pos q_"+q) .each(function(){ this.tipsy = new Tipsy(this, { gravity: 's', title: function(){ return "Median: "+ me.quantile_val[distr+q]; } }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }); },this); }; addPercentileDOM.call(this, this.DOM.percentileGroup.append("div").attr("class","percentileChart_Active"), "Active"); addPercentileDOM.call(this, this.DOM.percentileGroup.append("div").attr("class","percentileChart_Highlighted"), "Highlighted"); // Adding blocks in reverse order (C,B,A) so when they are inserted, they are linked to visually next to highlight selection addPercentileDOM.call(this, this.DOM.percentileGroup.append("div").attr("class","percentileChart_Compared_C"), "Compared_C"); addPercentileDOM.call(this, this.DOM.percentileGroup.append("div").attr("class","percentileChart_Compared_B"), "Compared_B"); addPercentileDOM.call(this, this.DOM.percentileGroup.append("div").attr("class","percentileChart_Compared_A"), "Compared_A"); this.refreshPercentileChart(); }, /** -- Uses - this.scaleType - this.intervalRange min & max Updates - this.intervalTickFormat - this.valueScale.nice() Return - the tick values in an array */ getValueTicks: function(optimalTickCount){ var me=this; var ticks; // HANDLE TIME CAREFULLY if(this.scaleType==='time') { // 1. Find the appropriate aggregation interval (day, month, etc) var timeRange_ms = this.intervalRange.active.max-this.intervalRange.active.min; // in milliseconds var timeInterval; var timeIntervalStep = 1; optimalTickCount *= 1.3; if((timeRange_ms/1000) < optimalTickCount){ timeInterval = d3.time.second.utc; this.intervalTickFormat = d3.time.format.utc("%S"); } else if((timeRange_ms/(1000*5)) < optimalTickCount){ timeInterval = d3.time.second.utc; timeIntervalStep = 5; this.intervalTickFormat = d3.time.format.utc("%-S"); } else if((timeRange_ms/(1000*15)) < optimalTickCount){ timeInterval = d3.time.second.utc; timeIntervalStep = 15; this.intervalTickFormat = d3.time.format.utc("%-S"); } else if((timeRange_ms/(1000*60)) < optimalTickCount){ timeInterval = d3.time.minute.utc; timeIntervalStep = 1; this.intervalTickFormat = d3.time.format.utc("%-M"); } else if((timeRange_ms/(1000*60*5)) < optimalTickCount){ timeInterval = d3.time.minute.utc; timeIntervalStep = 5; this.intervalTickFormat = d3.time.format.utc("%-M"); } else if((timeRange_ms/(1000*60*15)) < optimalTickCount){ timeInterval = d3.time.minute.utc; timeIntervalStep = 15; this.intervalTickFormat = d3.time.format.utc("%-M"); } else if((timeRange_ms/(1000*60*60)) < optimalTickCount){ timeInterval = d3.time.hour.utc; timeIntervalStep = 1; this.intervalTickFormat = d3.time.format.utc("%-H"); } else if((timeRange_ms/(1000*60*60*6)) < optimalTickCount){ timeInterval = d3.time.hour.utc; timeIntervalStep = 6; this.intervalTickFormat = d3.time.format.utc("%-H"); } else if((timeRange_ms/(1000*60*60*24)) < optimalTickCount){ timeInterval = d3.time.day.utc; timeIntervalStep = 1; this.intervalTickFormat = d3.time.format.utc("%-e"); } else if((timeRange_ms/(1000*60*60*24*7)) < optimalTickCount){ timeInterval = d3.time.week.utc; this.intervalTickFormat = function(v){ var suffix = kshf.Util.ordinal_suffix_of(v.getUTCDate()); var first=d3.time.format.utc("%-b")(v); return suffix+"<br>"+first; }; this.height_labels = 28; } else if((timeRange_ms/(1000*60*60*24*30)) < optimalTickCount){ timeInterval = d3.time.month.utc; timeIntervalStep = 1; this.intervalTickFormat = function(v){ var threeMonthsLater = timeInterval.offset(v, 3); var first=d3.time.format.utc("%-b")(v); var s=first; if(first==="Jan") s+="<br>"+(d3.time.format("%Y")(threeMonthsLater)); return s; }; this.height_labels = 28; } else if((timeRange_ms/(1000*60*60*24*30*3)) < optimalTickCount){ timeInterval = d3.time.month.utc; timeIntervalStep = 3; this.intervalTickFormat = function(v){ var threeMonthsLater = timeInterval.offset(v, 3); var first=d3.time.format.utc("%-b")(v); var s=first; if(first==="Jan") s+="<br>"+(d3.time.format("%Y")(threeMonthsLater)); return s; }; this.height_labels = 28; } else if((timeRange_ms/(1000*60*60*24*30*6)) < optimalTickCount){ timeInterval = d3.time.month.utc; timeIntervalStep = 6; this.intervalTickFormat = function(v){ var threeMonthsLater = timeInterval.offset(v, 6); var first=d3.time.format.utc("%-b")(v); var s=first; if(first==="Jan") s+="<br>"+(d3.time.format("%Y")(threeMonthsLater)); return s; }; this.height_labels = 28; } else if((timeRange_ms/(1000*60*60*24*365)) < optimalTickCount){ timeInterval = d3.time.year.utc; timeIntervalStep = 1; this.intervalTickFormat = d3.time.format.utc("%Y"); } else if((timeRange_ms/(1000*60*60*24*365*2)) < optimalTickCount){ timeInterval = d3.time.year.utc; timeIntervalStep = 2; this.intervalTickFormat = d3.time.format.utc("%Y"); } else if((timeRange_ms/(1000*60*60*24*365*3)) < optimalTickCount){ timeInterval = d3.time.year.utc; timeIntervalStep = 3; this.intervalTickFormat = d3.time.format.utc("%Y"); } else if((timeRange_ms/(1000*60*60*24*365*5)) < optimalTickCount){ timeInterval = d3.time.year.utc; timeIntervalStep = 5; this.intervalTickFormat = function(v){ var later = timeInterval.offset(v, 4); return d3.time.format.utc("%Y")(v); }; this.height_labels = 28; } else if((timeRange_ms/(1000*60*60*24*365*25)) < optimalTickCount){ timeInterval = d3.time.year.utc; timeIntervalStep = 25; this.intervalTickFormat = d3.time.format.utc("%Y"); } else if((timeRange_ms/(1000*60*60*24*365*100)) < optimalTickCount){ timeInterval = d3.time.year.utc; timeIntervalStep = 100; this.intervalTickFormat = d3.time.format.utc("%Y"); } else { timeInterval = d3.time.year.utc; timeIntervalStep = 500; this.intervalTickFormat = d3.time.format.utc("%Y"); } this.stepTicks = timeIntervalStep===1; this.valueScale.nice(timeInterval, timeIntervalStep); ticks = this.valueScale.ticks(timeInterval, timeIntervalStep); if(this.stepTicks){ ticks.pop(); // remove last tick } } else if(this.stepTicks){ ticks = []; for(var i=this.intervalRange.active.min ; i<=this.intervalRange.active.max; i++){ ticks.push(i); } this.intervalTickFormat = d3.format("d"); } else if(this.scaleType==='log'){ this.valueScale.nice(); // Generate ticks ticks = this.valueScale.ticks(); // ticks cannot be customized directly while(ticks.length > optimalTickCount*1.6){ ticks = ticks.filter(function(d,i){return i%2===0;}); } if(!this.hasFloat) ticks = ticks.filter(function(d){return d%1===0;}); this.intervalTickFormat = d3.format(".1s"); } else { this.valueScale.nice(optimalTickCount); this.valueScale.nice(optimalTickCount); ticks = this.valueScale.ticks(optimalTickCount); this.valueScale.nice(optimalTickCount); ticks = this.valueScale.ticks(optimalTickCount); if(!this.hasFloat) ticks = ticks.filter(function(tick){return tick===0||tick%1===0;}); // Does TICKS have a floating number var ticksFloat = ticks.some(function(tick){ return tick%1!==0; }); var d3Formating = d3.format(ticksFloat?".2f":".2s"); this.intervalTickFormat = function(d){ if(!me.hasFloat && d<10) return d; if(!me.hasFloat && Math.abs(ticks[1]-ticks[0])<1000) return d; var x= d3Formating(d); if(x.indexOf(".00")!==-1) x = x.replace(".00",""); if(x.indexOf(".0")!==-1) x = x.replace(".0",""); return x; } } // Make sure the non-extreme ticks are between intervalRange.active.min and intervalRange.active.max for(var tickNo=1; tickNo<ticks.length-1; ){ var tick = ticks[tickNo]; if(tick<this.intervalRange.active.min){ ticks.splice(tickNo-1,1); // remove the tick } else if(tick > this.intervalRange.active.max){ ticks.splice(tickNo+1,1); // remove the tick } else { tickNo++ } } this.valueScale.domain([ticks[0], ticks[ticks.length-1]]); return ticks; }, /** -- */ getStepWidth: function(){ var _width_ = this.getWidth_Chart(); var stepRange = (this.intervalRange.active.max-this.intervalRange.active.min)+1; return _width_/stepRange; }, /** Uses - optimumTickWidth - this.intervalRang Updates: - scaleType (step vs linear) - valueScale - intervalTickFormat */ updateScaleAndBins: function(force){ var me=this; if(this.isEmpty()) return; switch(this.scaleType){ case 'linear': this.valueScale = d3.scale.linear(); break; case 'log': this.valueScale = d3.scale.log().base(2); break; case 'time': this.valueScale = d3.time.scale.utc(); break; } var _width_ = this.getWidth_Chart(); var stepWidth = this.getStepWidth(); this.valueScale .domain([this.intervalRange.active.min, this.intervalRange.active.max]) .range( this.stepTicks ? [0, _width_-stepWidth] : [0, _width_] ); var ticks = this.getValueTicks( _width_/this.getWidth_OptimumTick() ); // Maybe the ticks still follow step-function ([3,4,5] or [12,13,14,15,16,17] or [2010,2011,2012,2013,2014]) if(!this.stepTicks && !this.hasFloat && this.scaleType==='linear' && ticks.length>2){ // Second: First+1, Last=BeforeLast+1 if( (ticks[1]===ticks[0]+1) && (ticks[ticks.length-1]===ticks[ticks.length-2]+1)) { this.stepTicks = true; if(this.intervalRange.max<ticks[ticks.length-1]){ ticks.pop(); // remove last tick this.intervalRange.active.max = this.intervalRange.max; } this.valueScale .domain([this.intervalRange.active.min, this.intervalRange.active.max]) .range([0, _width_-stepWidth]); } } this.aggrWidth = this.valueScale(ticks[1])-this.valueScale(ticks[0]); if(this.stepTicks && this.scaleType==='time'){ this.valueScale .range([-this.aggrWidth/2+3, _width_-(this.aggrWidth/2)]); } var ticksChanged = (this.intervalTicks.length!==ticks.length) || this.intervalTicks[0]!==ticks[0] || this.intervalTicks[this.intervalTicks.length-1] !== ticks[ticks.length-1] ; if(ticksChanged || force){ this.intervalTicks = ticks; var getRecordValue = this.getRecordValue; // Remove existing aggregates from browser if(this.histBins){ var aggrs=this.browser.allAggregates; this.histBins.forEach(function(aggr){ aggrs.splice(aggrs.indexOf(aggr),1); },this); } this.histBins = []; // Create histBins as kshf.Aggregate this.intervalTicks.forEach(function(tick,i){ var d = new kshf.Aggregate(); d.init(); d.minV = tick; d.maxV = this.intervalTicks[i+1]; d.summary = this; this.histBins.push(d); me.browser.allAggregates.push(d); }, this); if(!this.stepTicks){ this.histBins.pop(); // remove last bin } // distribute records across bins this.filteredItems.forEach(function(record){ var v = getRecordValue(record); if(v===null || v===undefined) return; if(v<this.intervalRange.active.min) return; if(v>this.intervalRange.active.max) return; var binI = null; this.intervalTicks.every(function(tick,i){ if(v>=tick) { binI = i; return true; // keep going } return false; // stop iteration }); if(this.stepTicks) binI = Math.min(binI, this.intervalTicks.length-1); else binI = Math.min(binI, this.intervalTicks.length-2); var bin = this.histBins[binI]; // If the record already had a bin for this summary, remove that bin var existingBinIndex = null; record._aggrCache.some(function(aggr,i){ if(aggr.summary && aggr.summary === this) { existingBinIndex = i; return true; } return false; },this); if(existingBinIndex!==null){ record._aggrCache.splice(existingBinIndex,1); } // ****************************************************************** bin.addRecord(record); },this); this.updateBarScale2Active(); if(this.DOM.root) this.insertVizDOM(); this.updatePercentiles("Active"); } if(this.DOM.root){ if(this.DOM.aggrGlyphs===undefined) this.insertVizDOM(); this.refreshBins_Translate(); this.refreshViz_Scale(); var offset=this.getTickOffset(); this.DOM.labelGroup.selectAll(".tick").style("left",function(d){ return (me.valueScale(d)+offset)+"px"; }); this.refreshIntervalSlider(); } }, /** -- */ getTickOffset: function(){ return (!this.stepTicks) ? 0 : (this.aggrWidth/2); }, /** -- */ insertVizDOM: function(){ if(this.scaleType==='time' && this.DOM.root) { // delete existing DOM: // TODO: Find a way to avoid this? this.DOM.timeSVG.selectAll("*").remove(); this.DOM.measure_Total_Area = this.DOM.timeSVG .append("path").attr("class","measure_Total_Area").datum(this.histBins); this.DOM.measure_Active_Area = this.DOM.timeSVG .append("path").attr("class","measure_Active_Area").datum(this.histBins); this.DOM.lineTrend_ActiveLine = this.DOM.timeSVG.selectAll(".measure_Active_Line") .data(this.histBins, function(d,i){ return i; }) .enter().append("line").attr("class","measure_Active_Line"); this.DOM.measure_Highlighted_Area = this.DOM.timeSVG .append("path").attr("class","measure_Highlighted_Area").datum(this.histBins); this.DOM.measure_Highlighted_Line = this.DOM.timeSVG.selectAll(".measure_Highlighted_Line") .data(this.histBins, function(d,i){ return i; }) .enter().append("line").attr("class","measure_Highlighted_Line"); this.DOM.measure_Compared_Area_A = this.DOM.timeSVG .append("path").attr("class","measure_Compared_Area_A measure_Compared_A").datum(this.histBins); this.DOM.measure_Compared_Line_A = this.DOM.timeSVG.selectAll(".measure_Compared_Line_A") .data(this.histBins, function(d,i){ return i; }) .enter().append("line").attr("class","measure_Compared_Line_A measure_Compared_A"); this.DOM.measure_Compared_Area_B = this.DOM.timeSVG .append("path").attr("class","measure_Compared_Area_B measure_Compared_B").datum(this.histBins); this.DOM.measure_Compared_Line_B = this.DOM.timeSVG.selectAll(".measure_Compared_Line_B") .data(this.histBins, function(d,i){ return i; }) .enter().append("line").attr("class","measure_Compared_Line_B measure_Compared_B"); this.DOM.measure_Compared_Area_C = this.DOM.timeSVG .append("path").attr("class","measure_Compared_Area_C measure_Compared_C").datum(this.histBins); this.DOM.measure_Compared_Line_C = this.DOM.timeSVG.selectAll(".measure_Compared_Line_C") .data(this.histBins, function(d,i){ return i; }) .enter().append("line").attr("class","measure_Compared_Line_C measure_Compared_C"); } this.insertBins(); this.refreshViz_Axis(); this.refreshMeasureLabel(); this.updateTicks(); }, /** -- */ updateTicks: function(){ this.DOM.labelGroup.selectAll(".tick").data([]).exit().remove(); // remove all existing ticks var ddd = this.DOM.labelGroup.selectAll(".tick").data(this.intervalTicks); var ddd_enter = ddd.enter().append("span").attr("class","tick"); ddd_enter.append("span").attr("class","line"); ddd_enter.append("span").attr("class","text"); this.refreshTickLabels(); }, /** -- */ refreshTickLabels: function(){ var me=this; if(this.DOM.labelGroup===undefined) return; this.DOM.labelGroup.selectAll(".tick .text").html(function(d){ if(me.scaleType==='time') return me.intervalTickFormat(d); if(d<1 && d!==0) return me.printWithUnitName( d.toFixed(1) ); else return me.printWithUnitName( me.intervalTickFormat(d) ); }); }, /** -- */ onBinMouseOver: function(aggr){ aggr.DOM.aggrGlyph.setAttribute("showlock",true); aggr.DOM.aggrGlyph.setAttribute("selection","selected"); if(!this.browser.ratioModeActive){ this.DOM.highlightedMeasureValue .style("top",(this.height_hist - this.chartScale_Measure(aggr.measure('Active')))+"px") .style("opacity",1); } this.browser.setSelect_Highlight(this,aggr); }, /** -- */ insertBins: function(){ var me=this; // just remove all aggrGlyphs that existed before. this.DOM.histogram_bins.selectAll(".aggrGlyph").data([]).exit().remove(); var activeBins = this.DOM.histogram_bins.selectAll(".aggrGlyph").data(this.histBins, function(d,i){return i;}); var newBins=activeBins.enter().append("span").attr("class","aggrGlyph rangeGlyph") .each(function(aggr){ aggr.isVisible = true; aggr.DOM.aggrGlyph = this; }) .on("mouseenter",function(aggr){ if(me.highlightRangeLimits_Active) return; var thiss=this; // mouse is moving slow, just do it. if(me.browser.mouseSpeed<0.2) { me.onBinMouseOver(aggr); return; } // mouse is moving fast, should wait a while... this.highlightTimeout = window.setTimeout( function(){ me.onBinMouseOver(aggr) }, me.browser.mouseSpeed*300); }) .on("mouseleave",function(aggr){ if(me.highlightRangeLimits_Active) return; if(this.highlightTimeout) window.clearTimeout(this.highlightTimeout); aggr.unselectAggregate(); me.browser.clearSelect_Highlight(); }) .on("click",function(aggr){ if(me.highlightRangeLimits_Active) return; if(d3.event.shiftKey){ me.browser.setSelect_Compare(me,aggr,true); return; } if(me.summaryFilter.filteredBin===this){ me.summaryFilter.clearFilter(); return; } this.setAttribute("filtered","true"); // store histogram state if(me.scaleType==='time'){ me.summaryFilter.active = { min: aggr.minV, max: aggr.maxV }; } else { me.summaryFilter.active = { min: aggr.minV, max: aggr.maxV }; } me.summaryFilter.filteredBin = null; me.summaryFilter.addFilter(); }); ["Total","Active","Highlighted","Compared_A","Compared_B","Compared_C"].forEach(function(m){ newBins.append("span").attr("class","measure_"+m); }); newBins.selectAll("[class^='measure_Compared_']") .on("mouseover" ,function(){ me.browser.refreshMeasureLabels(this.classList[0].substr(8)); }) .on("mouseleave",function(){ me.browser.refreshMeasureLabels(); }); newBins.append("span").attr("class","total_tip"); newBins.append("span").attr("class","lockButton fa") .each(function(aggr){ this.tipsy = new Tipsy(this, { gravity: 's', title: function(){ return kshf.lang.cur[ me.browser.selectedAggr["Compared_A"]!==aggr ? 'LockToCompare' : 'Unlock']; } }); }) .on("click",function(aggr){ this.tipsy.hide(); me.browser.setSelect_Compare(me,aggr,true); d3.event.stopPropagation(); }) .on("mouseenter",function(aggr){ this.tipsy.options.className = "tipsyFilterLock"; this.tipsy.hide(); this.tipsy.show(); d3.event.stopPropagation(); }) .on("mouseleave",function(aggr){ this.tipsy_title = undefined; this.tipsy.hide(); d3.event.stopPropagation(); }); newBins.append("span").attr("class","measureLabel").each(function(bar){ kshf.Util.setTransform(this,"translateY("+me.height_hist+"px)"); }); this.DOM.aggrGlyphs = this.DOM.histogram_bins.selectAll(".aggrGlyph"); this.DOM.measureLabel = this.DOM.aggrGlyphs.selectAll(".measureLabel"); this.DOM.measureTotalTip = this.DOM.aggrGlyphs.selectAll(".total_tip"); ["Total","Active","Highlighted","Compared_A","Compared_B","Compared_C"].forEach(function(m){ this.DOM["measure_"+m] = this.DOM.aggrGlyphs.selectAll(".measure_"+m); },this); this.DOM.lockButton = this.DOM.aggrGlyphs.selectAll(".lockButton"); }, /** --- */ roundFilterRange: function(){ if(this.scaleType==='time'){ // TODO: Round to meaningful dates return; } // Make sure the range is within the visible limits: this.summaryFilter.active.min = Math.max( this.intervalTicks[0], this.summaryFilter.active.min); this.summaryFilter.active.max = Math.min( this.intervalTicks[this.intervalTicks.length-1], this.summaryFilter.active.max); if(this.stepTicks || !this.hasFloat){ this.summaryFilter.active.min=Math.round(this.summaryFilter.active.min); this.summaryFilter.active.max=Math.round(this.summaryFilter.active.max); } }, /** -- */ map_refreshColorScale: function(){ var me=this; this.DOM.mapColorBlocks .style("background-color", function(d){ if(me.invertColorScale) d = 8-d; return kshf.colorScale[me.browser.mapColorTheme][d]; }); }, /** -- */ initDOM_RecordMapColor: function(){ var me=this; this.DOM.mapColorBar = this.DOM.summaryInterval.append("div").attr("class","mapColorBar"); this.DOM.mapColorBar.append("span").attr("class","invertColorScale fa fa-adjust") .each(function(d){ this.tipsy = new Tipsy(this, { gravity: 'sw', title: "Invert Color Scale" }); }) .on("mouseenter",function(){ this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }) .on("click", function(){ me.invertColorScale = !me.invertColorScale; me.browser.recordDisplay.refreshRecordColors(); me.browser.recordDisplay.map_refreshColorScaleBins(); me.map_refreshColorScale(); }); this.DOM.mapColorBlocks = this.DOM.mapColorBar.selectAll("mapColorBlock") .data([0,1,2,3,4,5,6,7,8]).enter() .append("div").attr("class","mapColorBlock") .each(function(d){ var r = me.valueScale.range()[1]/9; this._minValue = me.valueScale.invert(d*r); this._maxValue = me.valueScale.invert((d+1)*r); this.tipsy = new Tipsy(this, { gravity: 's', title: function(){ return Math.round(this._minValue)+" to "+Math.round(this._maxValue); } }); }) .on("mouseenter",function(d,i){ this.tipsy.show(); this.style.borderColor = (i<4)?"black":"white"; var r = me.valueScale.range()[1]/9; var _minValue = me.valueScale.invert(d*r); var _maxValue = me.valueScale.invert((d+1)*r); me.flexAggr_Highlight.records = []; me.filteredItems.forEach(function(record){ var v = me.getRecordValue(record); if(v>=_minValue && v<=_maxValue) me.flexAggr_Highlight.records.push(record); }); me.flexAggr_Highlight.minV = _minValue; me.flexAggr_Highlight.maxV = _maxValue; me.highlightRangeLimits_Active = true; me.browser.setSelect_Highlight(me,me.flexAggr_Highlight); }) .on("mouseleave",function(){ this.tipsy.hide(); me.browser.clearSelect_Highlight(); }) .on("click",function(){ me.summaryFilter.active = { min: this._minValue, max: this._maxValue }; me.summaryFilter.addFilter(); }); this.map_refreshColorScale(); }, /** -- */ initDOM_Slider: function(){ var me=this; this.DOM.intervalSlider = this.DOM.summaryInterval.append("div").attr("class","intervalSlider"); this.DOM.zoomControl = this.DOM.intervalSlider.append("span").attr("class","zoomControl fa") .attr("sign","plus") .each(function(d){ this.tipsy = new Tipsy(this, { gravity: 'w', title: function(){ return (this.getAttribute("sign")==="plus")?"Zoom into range":"Zoom out"; } }); }) .on("mouseenter",function(){ this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }) .on("click",function(){ this.tipsy.hide(); me.setZoomed(this.getAttribute("sign")==="plus"); }); var controlLine = this.DOM.intervalSlider.append("div").attr("class","controlLine") .on("mousedown", function(){ if(d3.event.which !== 1) return; // only respond to left-click me.browser.setNoAnim(true); var e=this.parentNode; var initPos = me.valueScale.invert(d3.mouse(e)[0]); d3.select("body").style('cursor','ew-resize') .on("mousemove", function() { var targetPos = me.valueScale.invert(d3.mouse(e)[0]); me.summaryFilter.active.min=d3.min([initPos,targetPos]); me.summaryFilter.active.max=d3.max([initPos,targetPos]); me.roundFilterRange(); me.refreshIntervalSlider(); // wait half second to update if(this.timer) clearTimeout(this.timer); me.summaryFilter.filteredBin = this; this.timer = setTimeout(function(){ if(me.isFiltered_min() || me.isFiltered_max()){ me.summaryFilter.addFilter(); } else { me.summaryFilter.clearFilter(); } },250); }).on("mouseup", function(){ me.browser.setNoAnim(false); d3.select("body").style('cursor','auto').on("mousemove",null).on("mouseup",null); }); d3.event.preventDefault(); }); controlLine.append("span").attr("class","base total"); controlLine.append("span").attr("class","base active") .each(function(){ this.tipsy = new Tipsy(this, { gravity: "s", title: kshf.lang.cur.DragToFilter }); }) // TODO: The problem is, the x-position (left-right) of the tooltip is not correctly calculated // because the size of the bar is set by scaling, not through width.... //.on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .on("mousedown", function(){ this.tipsy.hide(); if(d3.event.which !== 1) return; // only respond to left-click if(me.scaleType==='time') return; // time is not supported for now. var e=this.parentNode; var initMin = me.summaryFilter.active.min; var initMax = me.summaryFilter.active.max; var initRange= initMax - initMin; var initPos = d3.mouse(e)[0]; d3.select("body").style('cursor','ew-resize') .on("mousemove", function() { if(me.scaleType==='log'){ var targetDif = d3.mouse(e)[0]-initPos; me.summaryFilter.active.min = me.valueScale.invert(me.valueScale(initMin)+targetDif); me.summaryFilter.active.max = me.valueScale.invert(me.valueScale(initMax)+targetDif); } else if(me.scaleType==='time'){ // TODO return; } else { var targetPos = me.valueScale.invert(d3.mouse(e)[0]); var targetDif = targetPos-me.valueScale.invert(initPos); me.summaryFilter.active.min = initMin+targetDif; me.summaryFilter.active.max = initMax+targetDif; if(me.summaryFilter.active.min<me.intervalRange.active.min){ me.summaryFilter.active.min=me.intervalRange.active.min; me.summaryFilter.active.max=me.intervalRange.active.min+initRange; } if(me.summaryFilter.active.max>me.intervalRange.active.max){ me.summaryFilter.active.max=me.intervalRange.active.max; me.summaryFilter.active.min=me.intervalRange.active.max-initRange; } } me.roundFilterRange(); me.refreshIntervalSlider(); // wait half second to update if(this.timer) clearTimeout(this.timer); me.summaryFilter.filteredBin = this; this.timer = setTimeout(function(){ if(me.isFiltered_min() || me.isFiltered_max()){ me.summaryFilter.addFilter(); } else{ me.summaryFilter.clearFilter(); } },200); }).on("mouseup", function(){ d3.select("body").style('cursor','auto').on("mousemove",null).on("mouseup",null); }); d3.event.preventDefault(); d3.event.stopPropagation(); }); controlLine.selectAll(".handle").data(['min','max']).enter() .append("span").attr("class",function(d){ return "handle "+d; }) .each(function(d,i){ this.tipsy = new Tipsy(this, { gravity: i==0?"w":"e", title: kshf.lang.cur.DragToFilter }); }) .on("mouseover",function(){ if(this.dragging!==true) this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .on("mousedown", function(d,i){ this.tipsy.hide(); if(d3.event.which !== 1) return; // only respond to left-click var mee = this; var e=this.parentNode; d3.select("body").style('cursor','ew-resize') .on("mousemove", function() { mee.dragging = true; var targetPos = me.valueScale.invert(d3.mouse(e)[0]); me.summaryFilter.active[d] = targetPos; // Swap is min > max if(me.summaryFilter.active.min>me.summaryFilter.active.max){ var t=me.summaryFilter.active.min; me.summaryFilter.active.min = me.summaryFilter.active.max; me.summaryFilter.active.max = t; if(d==='min') d='max'; else d='min'; } me.roundFilterRange(); me.refreshIntervalSlider(); // wait half second to update if(this.timer) clearTimeout(this.timer); me.summaryFilter.filteredBin = this; this.timer = setTimeout( function(){ if(me.isFiltered_min() || me.isFiltered_max()){ me.summaryFilter.addFilter(); } else { me.summaryFilter.clearFilter(); } },200); }).on("mouseup", function(){ mee.dragging = false; d3.select("body").style('cursor','auto').on("mousemove",null).on("mouseup",null); }); d3.event.preventDefault(); d3.event.stopPropagation(); }) .append("span").attr("class","rangeLimitOnChart"); this.DOM.recordValue = controlLine.append("div").attr("class","recordValue"); this.DOM.recordValue.append("span").attr("class","recordValueScaleMark"); this.DOM.recordValueText = this.DOM.recordValue .append("span").attr("class","recordValueText") .append("span").attr("class","recordValueText-v"); this.DOM.labelGroup = this.DOM.intervalSlider.append("div").attr("class","labelGroup"); }, /** -- */ updateBarScale2Active: function(){ this.chartScale_Measure .domain([0, this.getMaxAggr_Active() || 1]) .range ([0, this.height_hist]); }, /** -- */ refreshBins_Translate: function(){ var me=this; var offset = (this.stepTicks)? this.width_barGap : 0; this.DOM.aggrGlyphs .style("width",this.getWidth_Bin()+"px") .each(function(aggr){ kshf.Util.setTransform(this,"translateX("+(me.valueScale(aggr.minV)+offset)+"px)"); }); }, /** -- */ refreshViz_Scale: function(){ this.refreshViz_Total(); this.refreshViz_Active(); }, /** -- */ refreshViz_Total: function(){ if(this.isEmpty() || this.collapsed) return; var me=this; var width=this.getWidth_Bin(); var heightTotal = function(aggr){ if(aggr._measure.Total===0) return 0; if(me.browser.ratioModeActive) return me.height_hist; return me.chartScale_Measure(aggr.measure('Total')); }; if(this.scaleType==='time'){ var durationTime=this.browser.noAnim?0:700; this.timeSVGLine = d3.svg.area().interpolate("cardinal") .x(function(aggr){ return me.valueScale(aggr.minV)+width/2; }) .y0(me.height_hist) .y1(function(aggr){ return (aggr._measure.Total===0) ? (me.height_hist+3) : (me.height_hist-heightTotal(aggr)); }); this.DOM.measure_Total_Area.transition().duration(durationTime).attr("d", this.timeSVGLine); } else { this.DOM.measure_Total.each(function(aggr){ kshf.Util.setTransform(this, "translateY("+me.height_hist+"px) scale("+width+","+heightTotal(aggr)+")"); }); if(!this.browser.ratioModeActive){ this.DOM.measureTotalTip .style("opacity",function(aggr){ return (aggr.measure('Total')>me.chartScale_Measure.domain()[1])?1:0; }) .style("width",width+"px"); } else { this.DOM.measureTotalTip.style("opacity",0); } } }, /** -- */ refreshViz_Active: function(){ if(this.isEmpty() || this.collapsed) return; var me=this; var width = this.getWidth_Bin(); var heightActive = function(aggr){ if(aggr._measure.Active===0) return 0; if(me.browser.ratioModeActive) return me.height_hist; return me.chartScale_Measure(aggr.measure('Active')); }; // Position the lock button this.DOM.lockButton .each(function(aggr){ kshf.Util.setTransform(this,"translateY("+(me.height_hist-heightActive(aggr)-10)+"px)"); }) .attr("inside",function(aggr){ if(me.browser.ratioModeActive) return ""; if(me.height_hist-heightActive(aggr)<6) return ""; }); // Time (line chart) update if(this.scaleType==='time'){ var durationTime = this.browser.noAnim ? 0 : 700; var xFunc = function(aggr){ return me.valueScale(aggr.minV)+width/2; }; this.timeSVGLine = d3.svg.area().interpolate("cardinal") .x(xFunc).y0(me.height_hist+2) .y1(function(aggr){ return (aggr._measure.Active===0) ? me.height_hist+3 : (me.height_hist-heightActive(aggr)+1); }); this.DOM.measure_Active_Area.transition().duration(durationTime).attr("d", this.timeSVGLine); this.DOM.lineTrend_ActiveLine.transition().duration(durationTime) .attr("x1",xFunc) .attr("x2",xFunc) .attr("y1",function(aggr){ return me.height_hist+3; }) .attr("y2",function(aggr){ return (aggr._measure.Active===0) ? (me.height_hist+3) : (me.height_hist - heightActive(aggr)+1); }); } if(!this.isFiltered() || this.scaleType==='time' || this.stepTicks){ // No partial rendering this.DOM.measure_Active.each(function(aggr){ kshf.Util.setTransform(this, "translateY("+me.height_hist+"px) scale("+width+","+heightActive(aggr)+")"); }); } else { // Partial rendering // is filtered & not step scale var filter_min = this.summaryFilter.active.min; var filter_max = this.summaryFilter.active.max; var minPos = this.valueScale(filter_min); var maxPos = this.valueScale(filter_max); this.DOM.measure_Active.each(function(aggr){ var translateX = ""; var width_self=width; var aggr_min = aggr.minV; var aggr_max = aggr.maxV; if(aggr._measure.Active>0){ // it is within the filtered range if(aggr_min<filter_min){ var lostWidth = minPos-me.valueScale(aggr_min); translateX = "translateX("+lostWidth+"px) "; width_self -= lostWidth; } if(aggr_max>filter_max){ width_self -= me.valueScale(aggr_max)-maxPos-me.width_barGap*2; } } kshf.Util.setTransform(this, "translateY("+me.height_hist+"px) "+translateX+"scale("+width_self+","+heightActive(aggr)+")"); }); } }, /** -- */ refreshViz_Compare: function(cT, curGroup, totalGroups){ if(this.isEmpty() || this.collapsed || !this.inBrowser()) return; var me=this; var width = this.getWidth_Bin(); var binWidth = width / totalGroups; var ratioModeActive = this.browser.ratioModeActive; var compId = "Compared_"+cT; if(this.percentileChartVisible==="Extended"){ if(this.browser.vizActive[compId]){ this.DOM.percentileGroup.select(".compared_percentileChart").style("display","block"); if(this.browser.vizActive["Compared_"+cT]) this.updatePercentiles("Compared_"+cT); } else { this.DOM.percentileGroup.select(".compared_percentileChart").style("display","none"); } } var heightCompare = function(aggr){ if(aggr._measure[compId]===0) return 0; return ratioModeActive ? aggr.ratioCompareToActive(cT)*me.height_hist : me.chartScale_Measure(aggr.measure(compId)); }; // Time (line chart) update if(this.scaleType==='time'){ var yFunc = function(aggr){ return (aggr._measure[compId]===0) ? (me.height_hist+3) : (me.height_hist-heightCompare(aggr)); }; var xFunc = function(aggr){ return me.valueScale(aggr.minV)+width/2; }; var dTime = 200; this.timeSVGLine = d3.svg.area().interpolate("cardinal").x(xFunc).y(yFunc); this.DOM["measure_Compared_Area_"+cT].transition().duration(dTime).attr("d", this.timeSVGLine); this.DOM["measure_Compared_Line_"+cT].transition().duration(dTime) .attr("y1",me.height_hist+3 ).attr("y2",yFunc) .attr("x1",xFunc).attr("x2",xFunc); return; } var _translateY = "translateY("+me.height_hist+"px) "; var _translateX = "translateX("+((curGroup+1)*binWidth)+"px) "; if(!this.isFiltered() || this.scaleType==='time' || this.stepTicks){ // No partial rendering this.DOM["measure_Compared_"+cT].each(function(aggr){ kshf.Util.setTransform(this, _translateY+_translateX+"scale("+binWidth+","+heightCompare(aggr)+")"); }); } else { // partial rendering var filter_min = this.summaryFilter.active.min; var filter_max = this.summaryFilter.active.max; var minPos = this.valueScale(filter_min); var maxPos = this.valueScale(filter_max); this.DOM["measure_Compared_"+cT].each(function(aggr){ var translateX = ""; var width_self=(curGroup*binWidth); var aggr_min = aggr.minV; var aggr_max = aggr.maxV; if(aggr._measure.Active>0){ // it is within the filtered range if(aggr_min<filter_min){ var lostWidth = minPos-me.valueScale(aggr_min); translateX = "translateX("+lostWidth+"px) "; width_self -= lostWidth; } if(aggr_max>filter_max){ width_self -= me.valueScale(aggr_max)-maxPos-me.width_barGap*2; } } kshf.Util.setTransform(this, _translateY+translateX+"scale("+(width_self/2)+","+heightCompare(aggr)+")"); }); } }, /** -- */ refreshViz_Highlight: function(){ if(this.isEmpty() || this.collapsed || !this.DOM.inited || !this.inBrowser()) return; var me=this; var width = this.getWidth_Bin(); this.refreshViz_EmptyRecords(); this.refreshMeasureLabel(); var totalC = this.browser.getActiveComparedCount(); if(this.browser.measureFunc==="Avg") totalC++; if(this.browser.vizActive.Highlighted){ this.updatePercentiles("Highlighted"); this.DOM.highlightedMeasureValue .style("top",( this.height_hist * (1-this.browser.allRecordsAggr.ratioHighlightToTotal() ))+"px") .style("opacity",(this.browser.ratioModeActive?1:0)); } else { // Highlight not active this.DOM.percentileGroup.select(".percentileChart_Highlighted").style("opacity",0); this.DOM.highlightedMeasureValue.style("opacity",0); this.refreshMeasureLabel(); this.highlightRangeLimits_Active = false; } this.DOM.highlightRangeLimits .style("opacity",(this.highlightRangeLimits_Active&&this.browser.vizActive.Highlighted)?1:0) .style("left", function(d){ return me.valueScale(me.flexAggr_Highlight[(d===0)?'minV':'maxV'])+"px"; }); var getAggrHeight_Preview = function(aggr){ var p=aggr.measure('Highlighted'); if(me.browser.preview_not) p = aggr.measure('Active')-p; if(me.browser.ratioModeActive){ if(aggr._measure.Active===0) return 0; return (p / aggr.measure('Active'))*me.height_hist; } else { return me.chartScale_Measure(p); } }; if(this.scaleType==='time'){ var yFunc = function(aggr){ return (aggr._measure.Highlighted===0) ? (me.height_hist+3) : (me.height_hist-getAggrHeight_Preview(aggr)); }; var xFunc = function(aggr){ return me.valueScale(aggr.minV)+width/2; }; var dTime=200; this.timeSVGLine = d3.svg.area().interpolate("cardinal") .x(xFunc) .y0(me.height_hist+2) .y1(yFunc); this.DOM.measure_Highlighted_Area.transition().duration(dTime).attr("d", this.timeSVGLine); this.DOM.measure_Highlighted_Line.transition().duration(dTime) .attr("y1",me.height_hist+3) .attr("y2",yFunc) .attr("x1",xFunc) .attr("x2",xFunc); } else { if(!this.browser.vizActive.Highlighted){ var xx = (width / (totalC+1)); var transform = "translateY("+this.height_hist+"px) scale("+xx+",0)"; this.DOM.measure_Highlighted.each(function(){ kshf.Util.setTransform(this,transform); }); return; } var _translateY = "translateY("+me.height_hist+"px) "; var range_min = this.valueScale.domain()[0]; var range_max = this.valueScale.domain()[1]; var rangeFill = false; if(this.isFiltered()){ range_min = Math.max(range_min, this.summaryFilter.active.min); range_max = Math.max(range_min, this.summaryFilter.active.max); rangeFill = true; } if(this.highlightRangeLimits_Active){ range_min = Math.max(range_min, this.flexAggr_Highlight.minV); range_max = Math.max(range_min, this.flexAggr_Highlight.maxV); rangeFill = true; } var minPos = this.valueScale(range_min); var maxPos = this.valueScale(range_max); this.DOM.measure_Highlighted.each(function(aggr){ var _translateX = ""; var barWidth = width; if(aggr._measure.Active>0 && rangeFill){ var aggr_min = aggr.minV; var aggr_max = aggr.maxV; // it is within the filtered range if(aggr_min<range_min){ var lostWidth = minPos-me.valueScale(aggr_min); _translateX = "translateX("+lostWidth+"px) "; barWidth -= lostWidth; } if(aggr_max>range_max){ barWidth -= me.valueScale(aggr_max)-maxPos-me.width_barGap*2; } } if(!rangeFill){ barWidth = barWidth / (totalC+1); //_translateX = "translateX("+barWidth*totalC+"px) "; } var _scale = "scale("+barWidth+","+getAggrHeight_Preview(aggr)+")"; kshf.Util.setTransform(this,_translateY+_translateX+_scale); }); } }, /** -- */ refreshViz_Axis: function(){ if(this.isEmpty() || this.collapsed) return; var me = this, tickValues, maxValue; var chartAxis_Measure_TickSkip = me.height_hist/17; if(this.browser.ratioModeActive || this.browser.percentModeActive) { maxValue = (this.browser.ratioModeActive) ? 100 : Math.round(100*me.getMaxAggr_Active()/me.browser.allRecordsAggr.measure('Active')); tickValues = d3.scale.linear() .rangeRound([0, this.height_hist]) .domain([0,maxValue]) .clamp(true) .ticks(chartAxis_Measure_TickSkip); } else { tickValues = this.chartScale_Measure.ticks(chartAxis_Measure_TickSkip); } // remove non-integer values & 0... tickValues = tickValues.filter(function(d){return d%1===0&&d!==0;}); var tickDoms = this.DOM.chartAxis_Measure_TickGroup.selectAll("span.tick") .data(tickValues,function(i){return i;}); tickDoms.exit().remove(); var tickData_new=tickDoms.enter().append("span").attr("class","tick"); // translate the ticks horizontally on scale tickData_new.append("span").attr("class","line"); tickData_new.append("span").attr("class","text text_left measureAxis_left"); tickData_new.append("span").attr("class","text text_right measureAxis_right"); // Place the doms at the bottom of the histogram, so their position is animated? tickData_new.each(function(){ kshf.Util.setTransform(this,"translateY("+me.height_hist+"px)"); }); this.DOM.chartAxis_Measure_TickGroup.selectAll("span.tick > span.text") .html(function(d){ return me.browser.getMeasureLabel(d); }); setTimeout(function(){ var transformFunc; if(me.browser.ratioModeActive){ transformFunc=function(d){ kshf.Util.setTransform(this,"translateY("+ (me.height_hist-d*me.height_hist/100)+"px)"); }; } else { if(me.browser.percentModeActive){ transformFunc=function(d){ kshf.Util.setTransform(this,"translateY("+(me.height_hist-(d/maxValue)*me.height_hist)+"px)"); }; } else { transformFunc=function(d){ kshf.Util.setTransform(this,"translateY("+(me.height_hist-me.chartScale_Measure(d))+"px)"); }; } } var x = me.browser.noAnim; if(x===false) me.browser.setNoAnim(true); me.DOM.chartAxis_Measure.selectAll(".tick").style("opacity",1).each(transformFunc); if(x===false) me.browser.setNoAnim(false); }); }, /** -- */ refreshIntervalSlider: function(){ var minPos = this.valueScale(this.summaryFilter.active.min); var maxPos = this.valueScale(this.summaryFilter.active.max); // Adjusting min/max position is important because if it is not adjusted, the // tips of the filtering range may not appear at the bar limits, which looks distracting. if(this.summaryFilter.active.min===this.intervalRange.min){ minPos = this.valueScale.range()[0]; } if(this.summaryFilter.active.max===this.intervalRange.max){ maxPos = this.valueScale.range()[1]; if(this.stepTicks){ maxPos += this.getWidth_Bin(); } } this.DOM.intervalSlider.select(".base.active") .attr("filtered",this.isFiltered()) .each(function(d){ this.style.left = minPos+"px"; this.style.width = (maxPos-minPos)+"px"; //kshf.Util.setTransform(this,"translateX("+minPos+"px) scaleX("+(maxPos-minPos)+")"); }); this.DOM.intervalSlider.selectAll(".handle") .each(function(d){ kshf.Util.setTransform(this,"translateX("+((d==="min")?minPos:maxPos)+"px)"); }); }, /** -- */ refreshHeight: function(){ this.DOM.histogram.style("height",(this.height_hist+this.height_hist_topGap)+"px") this.DOM.wrapper.style("height",(this.collapsed?"0":this.getHeight_Content())+"px"); this.DOM.root.style("max-height",(this.getHeight()+1)+"px"); var labelTranslate ="translateY("+this.height_hist+"px)"; if(this.DOM.measureLabel) this.DOM.measureLabel.each(function(bar){ kshf.Util.setTransform(this,labelTranslate); }); if(this.DOM.timeSVG) this.DOM.timeSVG.style("height",(this.height_hist+2)+"px"); }, /** -- */ refreshWidth: function(){ this.detectScaleType(); this.updateScaleAndBins(); if(this.DOM.inited===false) return; var chartWidth = this.getWidth_Chart(); var wideChart = this.getWidth()>400; this.DOM.summaryInterval .attr("measureAxis_right",wideChart?"true":null) .style("width",this.getWidth()+"px") .style("padding-left", this.width_measureAxisLabel+"px") .style("padding-right", ( wideChart ? this.width_measureAxisLabel : 11)+"px"); this.DOM.summaryInterval.selectAll(".measureAxis_right").style("display",wideChart?"block":"none"); this.DOM.summaryName.style("max-width",(this.getWidth()-40)+"px"); if(this.DOM.timeSVG) this.DOM.timeSVG.style("width",(chartWidth+2)+"px") }, /** -- */ setHeight: function(targetHeight){ if(this.histBins===undefined) return; var c = targetHeight - this.getHeight_Header() - this.getHeight_Extra(); if(this.height_hist===c) return; this.height_hist = c; this.updateBarScale2Active(); if(!this.DOM.inited) return; this.refreshBins_Translate(); this.refreshViz_Scale(); this.refreshViz_Highlight(); this.refreshViz_Compare_All(); this.refreshViz_Axis(); this.refreshHeight(); this.DOM.labelGroup.style("height",this.height_labels+"px"); this.DOM.intervalSlider.selectAll(".rangeLimitOnChart") .style("height",(this.height_hist+13)+"px") .style("top",(-this.height_hist-13)+"px"); this.DOM.highlightRangeLimits.style("height",this.height_hist+"px"); }, /** -- */ updateAfterFilter: function(){ if(this.isEmpty() || this.collapsed || !this.inBrowser()) return; this.updateChartScale_Measure(); this.refreshMeasureLabel(); this.refreshViz_EmptyRecords(); this.updatePercentiles("Active"); }, /** -- */ updateChartScale_Measure: function(){ if(!this.aggr_initialized || this.isEmpty()) return; // nothing to do var me=this; this.updateBarScale2Active(); this.refreshBins_Translate(); this.refreshViz_Scale(); this.refreshViz_Highlight(); this.refreshViz_Compare_All(); this.refreshViz_Axis(); }, /** -- */ setRecordValue: function(record){ if(!this.inBrowser()) return; if(this.DOM.inited===false) return; var v = this.getRecordValue(record); if(v===null) return; if(this.valueScale===undefined) return; if(this.scaleType==='log' && v<=0) return; // do not map zero/negative values var me=this; var offset=this.getTickOffset(); this.DOM.recordValue .each(function(){ kshf.Util.setTransform(this,"translateX("+(me.valueScale(v)+offset)+"px)"); }) .style("display","block"); this.DOM.recordValueText.html( this.printWithUnitName(this.intervalTickFormat(v)) ); }, /** -- */ hideRecordValue: function(){ if(!this.DOM.inited) return; this.DOM.recordValue.style("display",null); }, /** -- */ updateQuantiles: function(distr){ var me=this; // get active values into an array // the items are already sorted by their numeric value, it's just a linear pass. var values = []; if(distr==="Active"){ this.filteredItems.forEach(function(record){ if(record.isWanted) values.push(me.getRecordValue(record)); }); } else if(distr==="Highlighted"){ this.filteredItems.forEach(function(record){ if(record.highlighted) values.push(me.getRecordValue(record)); }); } else { var cT = distr.substr(9); // Compared_A / Compared_B / Compared_C this.filteredItems.forEach(function(record){ if(record.selectCompared[cT]) values.push(me.getRecordValue(record)); }); // Below doesn't work: The values will not be in sorted order!! /* this.browser.selectedAggr[distr].records.forEach(function(record){ val v = me.getRecordValue(record); if(v!==null) values.push(v); }); */ } [10,20,30,40,50,60,70,80,90].forEach(function(q){ var x =d3.quantile(values,q/100); this.quantile_val[distr+q] = x; this.quantile_pos[distr+q] = this.valueScale(x); },this); }, /** -- */ updatePercentiles: function(distr){ if(this.percentileChartVisible===false) return; this.updateQuantiles(distr); this.DOM.percentileGroup.select(".percentileChart_"+distr).style("opacity",1); this._updatePercentiles(distr); }, /** -- */ _updatePercentiles: function(distr){ [10,20,30,40,50,60,70,80,90].forEach(function(q){ kshf.Util.setTransform(this.DOM.quantile[distr+q][0][0],"translateX("+this.quantile_pos[distr+q]+"px)"); },this); [[10,90],[20,80],[30,70],[40,60]].forEach(function(qb){ kshf.Util.setTransform(this.DOM.quantile[distr+qb[0]+"_"+qb[1]][0][0], "translateX("+(this.quantile_pos[distr+qb[0]])+"px) "+ "scaleX("+(this.quantile_pos[distr+qb[1]]-this.quantile_pos[distr+qb[0]])+") "); },this); } }; for(var index in Summary_Interval_functions){ kshf.Summary_Interval.prototype[index] = Summary_Interval_functions[index]; } kshf.Summary_Set = function(){}; kshf.Summary_Set.prototype = new kshf.Summary_Base(); var Summary_Clique_functions = { initialize: function(browser,setListSummary,side){ kshf.Summary_Base.prototype.initialize.call(this,browser,"Relations in "+setListSummary.summaryName); var me = this; this.setListSummary = setListSummary; this.panel = this.setListSummary.panel; if(side) this.position = side; else{ this.position = (this.panel.name==="left") ? "right" : "left"; } this.pausePanning=false; this.gridPan_x=0; // Update sorting options of setListSummary (adding relatednesness metric...) this.setListSummary.catSortBy[0].name = this.browser.itemName+" #"; this.setListSummary.insertSortingOption({ name: "Relatedness", value: function(category){ return -category.MST.index; }, prep: function(){ me.updatePerceptualOrder(); } }); this.setListSummary.refreshSortOptions(); this.setListSummary.DOM.optionSelect.attr("dir","rtl"); // quick hack: right-align the sorting label this.setListSummary.cbFacetSort = function(){ me.refreshWindowSize(); me.refreshRow(); me.DOM.setPairGroup.attr("animate_position",false); me.refreshSetPair_Position(); setTimeout(function(){ me.DOM.setPairGroup.attr("animate_position",true); },1000); }; this.setListSummary.onCategoryCull = function(){ if(me.pausePanning) return; me.checkPan(); me.refreshSVGViewBox(); }; this.setListSummary.cbSetHeight = function(){ // update self me.updateWidthFromHeight(); me.updateSetPairScale(); // do not show number labels if the row height is small me.DOM.chartRoot.attr("showNumberLabels",me.getRowHeight()>=30); me.DOM.chartRoot.attr("show_gridlines",(me.getRowHeight()>15)); me.DOM.setPairGroup.attr("animate_position",false); me.refreshRow(); me.refreshSetPair_Background(); me.refreshSetPair_Position(); me.refreshViz_All(); me.refreshWindowSize(); me.refreshSetPair_Strength(); setTimeout(function(){ me.DOM.setPairGroup.attr("animate_position",true); },1000); }; this._setPairs = []; this._setPairs_ID = {}; this._sets = this.setListSummary._cats; // sorted already this._sets.forEach(function(set){ set.setPairs = []; }); this.createSetPairs(); // Inserts the DOM root under the setListSummary so that the matrix view is attached... this.DOM.root = this.setListSummary.DOM.root.insert("div",":first-child") .attr("class","kshfSummary setPairSummary") .attr("filtered",false) .attr("position",this.position); // Use keshif's standard header this.insertHeader(); this.DOM.headerGroup.style("height",(this.setListSummary.getHeight_Header())+"px"); this.DOM.chartRoot = this.DOM.wrapper.append("span") .attr("class","Summary_Set") .attr("noanim",false) .attr("show_gridlines",true); var body=d3.select("body"); this.DOM.chartRoot.append("span").attr("class","setMatrixWidthAdjust") .attr("title","Drag to adjust panel width") .on("mousedown", function (d, i) { if(d3.event.which !== 1) return; // only respond to left-click browser.DOM.root.style('cursor','ew-resize'); me.DOM.root.attr('noanim',true); me.DOM.setPairGroup.attr("animate_position",false); var mouseInit_x = d3.mouse(body[0][0])[0]; console.log("mouseInit_x: "+mouseInit_x); var initWidth = me.getWidth(); var myHeight = me.getHeight(); body.on("mousemove", function() { var mouseDif = d3.mouse(body[0][0])[0]-mouseInit_x; console.log("mouseNew_x: "+d3.mouse(body[0][0])[0]); var targetWidth = initWidth-mouseDif; var targetAngle_Rad = Math.atan(myHeight/targetWidth); var targetAngle_Deg = 90-(targetAngle_Rad*180)/Math.PI; targetAngle_Deg = Math.min(Math.max(targetAngle_Deg,30),60); me.noanim = true; me.summaryWidth = (me.position==="left") ? initWidth-mouseDif : initWidth+mouseDif; me.checkWidth(); me.refreshWindowSize(); me.refreshRow_LineWidths(); me.refreshSetPair_Position(); }).on("mouseup", function(){ browser.DOM.root.style('cursor','default'); me.DOM.setPairGroup.attr("animate_position",true); me.DOM.root.attr('noanim',false); me.noanim = false; // unregister mouse-move callbacks body.on("mousemove", null).on("mouseup", null); }); d3.event.preventDefault(); }) .on("click",function(){ d3.event.stopPropagation(); d3.event.preventDefault(); }); this.insertControls(); this.DOM.setMatrixSVG = this.DOM.chartRoot.append("svg").attr("xmlns","http://www.w3.org/2000/svg").attr("class","setMatrix"); /** BELOW THE MATRIX **/ this.DOM.belowMatrix = this.DOM.chartRoot.append("div").attr("class","belowMatrix"); this.DOM.belowMatrix.append("div").attr("class","border_line"); this.DOM.pairCount = this.DOM.belowMatrix.append("span").attr("class","pairCount matrixInfo"); this.DOM.pairCount.append("span").attr("class","circleeee"); this.DOM.pairCount_Text = this.DOM.pairCount.append("span").attr("class","pairCount_Text") .text(""+this._setPairs.length+" pairs ("+Math.round(100*this._setPairs.length/this.getSetPairCount_Total())+"%)"); this.DOM.subsetCount = this.DOM.belowMatrix.append("span").attr("class","subsetCount matrixInfo"); this.DOM.subsetCount.append("span").attr("class","circleeee borrderr"); this.DOM.subsetCount_Text = this.DOM.subsetCount.append("span").attr("class","subsetCount_Text"); // invisible background - Used for panning this.DOM.setMatrixBackground = this.DOM.setMatrixSVG.append("rect") .attr("x",0).attr("y",0) .style("fill-opacity","0") .on("mousedown",function(){ var background_dom = this.parentNode.parentNode.parentNode.parentNode; background_dom.style.cursor = "all-scroll"; me.browser.DOM.pointerBlock.attr("active",""); var mouseInitPos = d3.mouse(background_dom); var gridPan_x_init = me.gridPan_x; // scroll the setlist summary too... var scrollDom = me.setListSummary.DOM.aggrGroup[0][0]; var initScrollPos = scrollDom.scrollTop; var w=me.getWidth(); var h=me.getHeight(); var initT = me.setListSummary.scrollTop_cache; var initR = Math.min(-initT-me.gridPan_x,0); me.pausePanning = true; me.browser.DOM.root.on("mousemove", function() { var mouseMovePos = d3.mouse(background_dom); var difX = mouseMovePos[0]-mouseInitPos[0]; var difY = mouseMovePos[1]-mouseInitPos[1]; if(me.position==="right") { difX *= -1; } me.gridPan_x = Math.min(0,gridPan_x_init+difX+difY); me.checkPan(); var maxHeight = me.setListSummary.heightRow_category*me.setListSummary._cats.length - h; var t = initT-difY; t = Math.min(maxHeight,Math.max(0,t)); var r = initR-difX; r = Math.min(0,Math.max(r,-t)); if(me.position==="right") r = -r; me.DOM.setMatrixSVG.attr("viewBox",r+" "+t+" "+w+" "+h); scrollDom.scrollTop = Math.max(0,initScrollPos-difY); d3.event.preventDefault(); d3.event.stopPropagation(); }).on("mouseup", function(){ me.pausePanning = false; background_dom.style.cursor = "default"; me.browser.DOM.root.on("mousemove", null).on("mouseup", null); me.browser.DOM.pointerBlock.attr("active",null); me.refreshLabel_Vert_Show(); d3.event.preventDefault(); d3.event.stopPropagation(); }); d3.event.preventDefault(); d3.event.stopPropagation(); }) ; this.DOM.setMatrixSVG.append("g").attr("class","rows"); this.DOM.setPairGroup = this.DOM.setMatrixSVG.append("g").attr("class","aggrGroup setPairGroup").attr("animate_position",true); this.insertRows(); this.insertSetPairs(); this.updateWidthFromHeight(); this.updateSetPairScale(); this.refreshRow(); this.refreshSetPair_Background(); this.refreshSetPair_Position(); this.refreshSetPair_Containment(); this.refreshViz_Axis(); this.refreshViz_Active(); this.refreshWindowSize(); }, /** -- */ refreshHeight: function(){ // TODO: Added just because the browser calls this automatically }, /** -- */ isEmpty: function(){ return false; // TODO Temp? }, /** -- */ getHeight: function(){ return this.setListSummary.categoriesHeight; }, /** -- */ getWidth: function(){ return this.summaryWidth; }, /** -- */ getRowHeight: function(){ return this.setListSummary.heightRow_category; }, /** -- */ getSetPairCount_Total: function(){ return this._sets.length*(this._sets.length-1)/2; }, /** -- */ getSetPairCount_Empty: function(){ return this.getSetPairCount_Total()-this._setPairs.length; }, /** -- */ updateWidthFromHeight: function(){ this.summaryWidth = this.getHeight()+25; this.checkWidth(); }, /** -- */ updateSetPairScale: function(){ this.setPairDiameter = this.setListSummary.heightRow_category; this.setPairRadius = this.setPairDiameter/2; }, /** -- */ updateMaxAggr_Active: function(){ this._maxSetPairAggr_Active = d3.max(this._setPairs, function(aggr){ return aggr.measure('Active'); }); }, /** -- */ checkWidth: function(){ var minv=210; var maxv=Math.max(minv,this.getHeight())+40; this.summaryWidth = Math.min(maxv,Math.max(minv,this.summaryWidth)); }, /** -- */ checkPan: function(){ var maxV, minV; maxV = 0; minV = -this.setListSummary.scrollTop_cache; this.gridPan_x = Math.round(Math.min(maxV,Math.max(minV,this.gridPan_x))); }, /** -- */ insertControls: function(){ var me=this; this.DOM.summaryControls = this.DOM.chartRoot.append("div").attr("class","summaryControls") .style("height",(this.setListSummary.getHeight_Config())+"px"); // TODO: remove var buttonTop = (this.setListSummary.getHeight_Config()-18)/2; this.DOM.strengthControl = this.DOM.summaryControls.append("span").attr("class","strengthControl") .on("click",function(){ me.browser.setMeasureAxisMode(me.browser.ratioModeActive!==true); }) .style("margin-top",buttonTop+"px"); // ******************* STRENGTH CONFIG this.DOM.strengthControl.append("span").attr("class","strengthLabel").text("Weak"); this.DOM.strengthControl.append("span").attr("class","strengthText").text("Strength"); this.DOM.strengthControl.append("span").attr("class","strengthLabel").text("Strong"); this.DOM.scaleLegend_SVG = this.DOM.summaryControls.append("svg").attr("xmlns","http://www.w3.org/2000/svg") .attr("class","sizeLegend"); this.DOM.legendHeader = this.DOM.scaleLegend_SVG.append("text").attr("class","legendHeader").text("#"); this.DOM.legend_Group = this.DOM.scaleLegend_SVG.append("g"); // ******************* ROW HEIGHT CONFIG var domRowHeightControl = this.DOM.summaryControls.append("span").attr("class","configRowHeight configOpt"); var sdad = domRowHeightControl.append("span").attr("class","configOpt_label") domRowHeightControl.append("span").attr("class","configOpt_icon") .append("span").attr("class","fa fa-search-plus"); sdad.append("span").attr("class","sdsdssds").text("Zoom"); sdad.append("span").attr("class","fa fa-plus").on("mousedown",function(){ // TODO: Keep calling as long as the mouse is clicked - to a certain limit me.setListSummary.setHeight_Category(me.getRowHeight()+1); d3.event.stopPropagation(); }); sdad.append("span").attr("class","fa fa-minus").on("mousedown",function(){ // TODO: Keep calling as long as the mouse is clicked - to a certain limit me.setListSummary.setHeight_Category(me.getRowHeight()-1); d3.event.stopPropagation(); }); sdad.append("span").attr("class","fa fa-arrows-alt").on("mousedown",function(){ // TODO: Keep calling as long as the mouse is clicked - to a certain limit me.setListSummary.setHeight_Category(10); d3.event.stopPropagation(); }); }, /** -- */ insertRows: function(){ var me=this; var newRows = this.DOM.setMatrixSVG.select("g.rows").selectAll("g.row") .data(this._sets, function(d,i){ return d.id(); }) .enter().append("g").attr("class","row") .each(function(d){ d.DOM.matrixRow = this; }) .on("mouseenter",function(d){ me.setListSummary.onCatEnter(d); }) .on("mouseleave",function(d){ me.setListSummary.onCatLeave(d); }); // tmp is used to parse html text. TODO: delete the temporary DOM var tmp = document.createElement("div"); newRows.append("line").attr("class","line line_vert") .attr("x1",0).attr("y1",0).attr("y1",0).attr("y2",0); newRows.append("text").attr("class","label label_horz") .text(function(d){ tmp.innerHTML = me.setListSummary.catLabel_Func.call(d.data); return tmp.textContent || tmp.innerText || ""; }); newRows.append("line").attr("class","line line_horz") .attr("x1",0).attr("y1",0).attr("y2",0); newRows.append("text").attr("class","label label_vert") .text(function(d){ tmp.innerHTML = me.setListSummary.catLabel_Func.call(d.data); return tmp.textContent || tmp.innerText || ""; }) .attr("y",-4); this.DOM.setRows = this.DOM.setMatrixSVG.selectAll("g.rows > g.row"); this.DOM.line_vert = this.DOM.setMatrixSVG.selectAll("g.rows > g.row > line.line_vert"); this.DOM.line_horz = this.DOM.setMatrixSVG.selectAll("g.rows > g.row > line.line_horz"); this.DOM.line_horz_label = this.DOM.setMatrixSVG.selectAll("g.rows > g.row > text.label_horz"); this.DOM.line_vert_label = this.DOM.setMatrixSVG.selectAll("g.rows > g.row > text.label_vert"); }, /** -- */ onSetPairEnter: function(aggr){ aggr.set_1.DOM.matrixRow.setAttribute("selection","selected"); aggr.set_2.DOM.matrixRow.setAttribute("selection","selected"); aggr.set_1.DOM.aggrGlyph.setAttribute("selectType","and"); aggr.set_2.DOM.aggrGlyph.setAttribute("selectType","and"); aggr.set_1.DOM.aggrGlyph.setAttribute("selection","selected"); aggr.set_2.DOM.aggrGlyph.setAttribute("selection","selected"); this.browser.setSelect_Highlight(this,aggr); }, /** -- */ onSetPairLeave: function(aggr){ aggr.set_1.DOM.matrixRow.removeAttribute("selection"); aggr.set_2.DOM.matrixRow.removeAttribute("selection"); aggr.set_1.DOM.aggrGlyph.removeAttribute("selection"); aggr.set_2.DOM.aggrGlyph.removeAttribute("selection"); this.browser.clearSelect_Highlight(); }, /** -- */ insertSetPairs: function(){ var me=this; var newCliques = this.DOM.setMatrixSVG.select("g.setPairGroup").selectAll("g.setPairGlyph") .data(this._setPairs,function(d,i){ return i; }) .enter().append("g").attr("class","aggrGlyph setPairGlyph") .each(function(d){ d.DOM.aggrGlyph = this; }) .on("mouseenter",function(aggr){ if(me.browser.mouseSpeed<0.2) { me.onSetPairEnter(aggr); return; } this.highlightTimeout = window.setTimeout( function(){ me.onSetPairEnter(aggr) }, me.browser.mouseSpeed*500); }) .on("mouseleave",function(aggr){ if(this.highlightTimeout) window.clearTimeout(this.highlightTimeout); me.onSetPairLeave(aggr); }) .on("click",function(aggr){ if(d3.event.shiftKey){ me.browser.setSelect_Compare(me,aggr,false); return; } me.setListSummary.filterCategory(aggr.set_1,"AND"); me.setListSummary.filterCategory(aggr.set_2,"AND"); }); newCliques.append("rect").attr("class","setPairBackground").attr("rx",3).attr("ry",3); newCliques.append("circle").attr("class","measure_Active").attr("cx",0).attr("cy",0).attr("r",0); newCliques.append("path").attr("class","measure_Highlighted").each(function(aggr){ aggr.currentPreviewAngle=-Math.PI/2; }); newCliques.append("path").attr("class","measure_Compared_A"); newCliques.append("path").attr("class","measure_Compared_B"); newCliques.append("path").attr("class","measure_Compared_C"); this.DOM.aggrGlyphs = this.DOM.setPairGroup.selectAll("g.setPairGlyph"); this.DOM.setPairBackground = this.DOM.aggrGlyphs.selectAll(".setPairBackground"); this.DOM.measure_Active = this.DOM.aggrGlyphs.selectAll(".measure_Active"); this.DOM.measure_Highlighted = this.DOM.aggrGlyphs.selectAll(".measure_Highlighted"); this.DOM.measure_Compared_A = this.DOM.aggrGlyphs.selectAll(".measure_Compared_A"); this.DOM.measure_Compared_B = this.DOM.aggrGlyphs.selectAll(".measure_Compared_B"); this.DOM.measure_Compared_C = this.DOM.aggrGlyphs.selectAll(".measure_Compared_C"); }, /** -- */ printAggrSelection: function(aggr){ return this.setListSummary.printAggrSelection(aggr.set_1)+ " and "+ this.setListSummary.printAggrSelection(aggr.set_2); }, /** -- */ refreshLabel_Vert_Show: function(){ var me=this; var setListSummary=this.setListSummary; var totalWidth=this.getWidth(); var totalHeight = this.getHeight(); var w=this.getWidth(); var h=this.getHeight(); var t=this.setListSummary.scrollTop_cache; var r=(t)*-1; this.DOM.line_vert_label // points up/right .attr("show",function(d){ return !d.isVisible; }) .attr("transform",function(d){ var i=d.orderIndex; var x=totalWidth-((i+0.5)*me.setPairDiameter)-2; if(me.position==="right") x = totalWidth-x-4; var y=((me.setListSummary.catCount_Visible-i-1)*me.setPairDiameter); y-=setListSummary.getHeight_VisibleAttrib()-setListSummary.scrollTop_cache-totalHeight; return "translate("+x+" "+y+") rotate(-90)";//" rotate(45) "; }); }, /** --*/ updatePerceptualOrder: function(){ var me=this; // Edges are set-pairs with at least one element inside (based on the filtering state) var edges = this._setPairs.filter(function(setPair){ return setPair._measure.Active>0; }); // Nodes are the set-categories var nodes = this.setListSummary._cats; // Initialize per-node (per-set) data structures nodes.forEach(function(node){ node.MST = { tree: new Object(), // Some unqiue identifier, to check if two nodes are in the same tree. childNodes: [], parentNode: null }; }); // Compute the perceptual similarity metric (mst_distance) edges.forEach(function(edge){ var set_1 = edge.set_1; var set_2 = edge.set_2; edge.mst_distance = 0; // For every intersection of set_1 set_1.setPairs.forEach(function(setPair_1){ if(setPair_1===edge) return; var set_other = (setPair_1.set_1===set_1)?setPair_1.set_2:setPair_1.set_1; // find the set-pair of set_2 and set_other; var setPair_2 = undefined; if(set_2.id()>set_other.id()){ if(me._setPairs_ID[set_other.id()]) setPair_2 = me._setPairs_ID[set_other.id()][set_2.id()]; } else { if(me._setPairs_ID[set_2.id()]) setPair_2 = me._setPairs_ID[set_2.id()][set_other.id()]; } if(setPair_2===undefined){ // the other intersection size is zero, there is no link edge.mst_distance+=setPair_1._measure.Active; return; } edge.mst_distance += Math.abs(setPair_1._measure.Active-setPair_2._measure.Active); }); // For every intersection of set_2 set_2.setPairs.forEach(function(setPair_1){ if(setPair_1===edge) return; var set_other = (setPair_1.set_1===set_2)?setPair_1.set_2:setPair_1.set_1; // find the set-pair of set_1 and set_other; var setPair_2 = undefined; if(set_1.id()>set_other.id()){ if(me._setPairs_ID[set_other.id()]) setPair_2 = me._setPairs_ID[set_other.id()][set_1.id()]; } else { if(me._setPairs_ID[set_1.id()]) setPair_2 = me._setPairs_ID[set_1.id()][set_other.id()]; } if(setPair_2===undefined){ // the other intersection size is zero, there is no link edge.mst_distance+=setPair_1._measure.Active; return; } // If ther is setPair_2, it was already processed in the main loop above }); }); // Order the edges (setPairs) by their distance (lower score is better) edges.sort(function(e1, e2){ return e1.mst_distance-e2.mst_distance; }); // Run Kruskal's algorithm... edges.forEach(function(setPair){ var node_1 = setPair.set_1; var node_2 = setPair.set_2; // set_1 and set_2 are in the same tree if(node_1.MST.tree===node_2.MST.tree) return; // set_1 and set_2 are not in the same tree, connect set_2 under set_1 var set_above, set_below; if(node_1.setPairs.length<node_2.setPairs.length){ set_above = node_1; set_below = node_2; } else { set_above = node_2; set_below = node_1; } set_below.MST.tree = set_above.MST.tree; set_below.MST.parentNode = set_above; set_above.MST.childNodes.push(set_below); }); // Identify the root-nodes of resulting MSTs var treeRootNodes = nodes.filter(function(node){ return node.MST.parentNode===null; }); // We can have multiple trees (there can be sub-groups disconnected from each other) // Update tree size recursively by starting at the root nodes var updateTreeSize = function(node){ node.MST.treeSize=1; node.MST.childNodes.forEach(function(childNode){ node.MST.treeSize+=updateTreeSize(childNode); }); return node.MST.treeSize; }; treeRootNodes.forEach(function(rootNode){ updateTreeSize(rootNode); }); // Sort the root nodes by largest tree first treeRootNodes.sort(function(node1, node2){ return node1.MST.treeSize - node2.MST.treeSize; }); // For each MST, traverse the nodes and add the MST (perceptual) node index incrementally var mst_index = 0; var updateNodeIndex = function(node){ node.MST.childNodes.forEach(function(chileNode){ chileNode.MST.index = mst_index++; }); node.MST.childNodes.forEach(function(chileNode){ updateNodeIndex(chileNode); }); }; treeRootNodes.forEach(function(node){ node.MST.index = mst_index++; updateNodeIndex(node); }); }, /** -- */ refreshViz_Axis: function(){ var me=this; this.refreshSetPair_Strength(); if(this.browser.ratioModeActive){ this.DOM.scaleLegend_SVG.style("display","none"); return; } this.DOM.scaleLegend_SVG.style("display","block"); this.DOM.scaleLegend_SVG .attr("width",this.setPairDiameter+50) .attr("height",this.setPairDiameter+10) .attr("viewBox","0 0 "+(this.setPairDiameter+50)+" "+(this.setPairDiameter+10)); this.DOM.legend_Group.attr("transform", "translate("+(this.setPairRadius)+","+(this.setPairRadius+18)+")"); this.DOM.legendHeader.attr("transform", "translate("+(2*this.setPairRadius+3)+",6)"); var maxVal = this._maxSetPairAggr_Active; tickValues = [maxVal]; if(this.setPairRadius>8) tickValues.push(Math.round(maxVal/4)); this.DOM.legend_Group.selectAll("g.legendMark").remove(); var tickDoms = this.DOM.legend_Group.selectAll("g.legendMark").data(tickValues,function(i){return i;}); this.DOM.legendCircleMarks = tickDoms.enter().append("g").attr("class","legendMark"); this.DOM.legendCircleMarks.append("circle").attr("class","legendCircle") .attr("cx",0).attr("cy",0) .attr("r",function(d,i){ return me.setPairRadius*Math.sqrt(d/maxVal); }); this.DOM.legendCircleMarks.append("line").attr("class","legendLine") .each(function(d,i){ var rx=me.setPairRadius+3; var ry=me.setPairRadius*Math.sqrt(d/maxVal); var x2,y1; switch(i%4){ case 0: x2 = rx; y1 = -ry; break; case 1: x2 = rx; // -rx; y1 = ry; // -ry; break; case 2: x2 = rx; y1 = ry; break; case 3: x2 = -rx; y1 = ry; break; } this.setAttribute("x1",0); this.setAttribute("x2",x2); this.setAttribute("y1",y1); this.setAttribute("y2",y1); }); this.DOM.legendText = this.DOM.legendCircleMarks .append("text").attr("class","legendLabel"); this.DOM.legendText.each(function(d,i){ var rx=me.setPairRadius+3; var ry=me.setPairRadius*Math.sqrt(d/maxVal); var x2,y1; switch(i%4){ case 0: x2 = rx; y1 = -ry; break; case 1: x2 = rx; // -rx; y1 = ry; // -ry; break; case 2: x2 = rx; y1 = ry; break; case 3: x2 = -rx; y1 = ry; break; } this.setAttribute("transform","translate("+x2+","+y1+")"); this.style.textAnchor = (i%2===0||true)?"start":"end"; }); this.DOM.legendText.text(function(d){ return d3.format("s")(d); }); }, /** -- */ refreshWindowSize: function(){ var w=this.getWidth(); var h=this.getHeight(); this.DOM.wrapper.style("height",( this.setListSummary.getHeight()-this.setListSummary.getHeight_Header())+"px"); this.DOM.setMatrixBackground .attr("x",-w*24) .attr("y",-h*24) .attr("width",w*50) .attr("height",h*50); this.DOM.root .style(this.position,(-w)+"px") .style(this.position==="left"?"right":"left","initial"); ; if(!this.pausePanning) this.refreshSVGViewBox(); }, /** -- */ setPosition: function(p){ if(p===this.position) return; this.position = p; this.DOM.root.attr("position",this.position); this.refreshWindowSize(); this.refreshRow_LineWidths(); this.refreshSetPair_Position(); }, /** -- */ refreshSVGViewBox: function(){ var w=this.getWidth(); var h=this.getHeight(); var t=this.setListSummary.scrollTop_cache; var r; if(this.position==="left"){ r=Math.min(-t-this.gridPan_x,0); // r cannot be positive } if(this.position==="right"){ r=Math.max(t+this.gridPan_x,0); } this.DOM.setMatrixSVG.attr("width",w).attr("height",h).attr("viewBox",r+" "+t+" "+w+" "+h); this.refreshLabel_Vert_Show(); }, /** -- */ refreshSetPair_Background: function(){ this.DOM.setPairBackground .attr("x",-this.setPairRadius) .attr("y",-this.setPairRadius) .attr("width",this.setPairDiameter) .attr("height",this.setPairDiameter); }, /** - Call when measure.Active is updated - Does not work with Average aggregate */ updateSetPairSimilarity: function(){ this._setPairs.forEach(function(setPair){ var size_A = setPair.set_1._measure.Active; var size_B = setPair.set_2._measure.Active; var size_and = setPair._measure.Active; setPair.Similarity = (size_and===0 || (size_A===0&&size_B===0)) ? 0 : size_and/Math.min(size_A,size_B); }); this._maxSimilarity = d3.max(this._setPairs, function(d){ return d.Similarity; }); }, /** For each element in the given list, checks the set membership and adds setPairs */ createSetPairs: function(){ var me=this; var insertToClique = function(set_1,set_2,record){ // avoid self reference and adding the same data item twice (insert only A-B, not B-A or A-A/B-B) if(set_2.id()<=set_1.id()) return; if(me._setPairs_ID[set_1.id()]===undefined) me._setPairs_ID[set_1.id()] = {}; var targetClique = me._setPairs_ID[set_1.id()][set_2.id()]; if(targetClique===undefined){ targetClique = new kshf.Aggregate(); targetClique.init([me._setPairs.length],0); me.browser.allAggregates.push(targetClique); targetClique.set_1 = set_1; targetClique.set_2 = set_2; set_1.setPairs.push(targetClique); set_2.setPairs.push(targetClique); me._setPairs.push(targetClique); me._setPairs_ID[set_1.id()][set_2.id()] = targetClique; } targetClique.addRecord(record); }; // AND var filterID = this.setListSummary.summaryID; function getAggr(v){ return me.setListSummary.catTable_id[v]; }; this.setListSummary.records.forEach(function(record){ var values = record._valueCache[filterID]; if(values===null) return; // maps to no value values.forEach(function(v_1){ set_1 = getAggr(v_1); // make sure set_1 has an attrib on c display if(set_1.setPairs===undefined) return; values.forEach(function(v_2){ set_2 = getAggr(v_2); if(set_2.setPairs===undefined) return; insertToClique(set_1,set_2,record); }); }); }); this.updateMaxAggr_Active(); this.updateSetPairSimilarity(); }, /** -- */ refreshRow_LineWidths: function(){ var me=this; var setPairDiameter=this.setPairDiameter; var totalWidth=this.getWidth(); var totalHeight = this.getHeight(); // vertical this.DOM.line_vert.each(function(d){ var i=d.orderIndex; var height=((me.setListSummary.catCount_Visible-i-1)*setPairDiameter); var right=((i+0.5)*setPairDiameter); var m=totalWidth-right; if(me.position==="right") m = right; this.setAttribute("x1",m); this.setAttribute("x2",m); this.setAttribute("y2",height); }); // horizontal this.DOM.line_horz .attr("x2",(this.position==="left")?totalWidth : 0) .attr("x1",function(d){ var m = ((d.orderIndex+0.5)*setPairDiameter); return (me.position==="left") ? (totalWidth-m) : m; }); this.DOM.line_horz_label.attr("transform",function(d){ var m=((d.orderIndex+0.5)*setPairDiameter)+2; if(me.position==="left") m = totalWidth-m; return "translate("+m+" 0)"; }); }, /** -- */ refreshRow_Position: function(){ var rowHeight = this.setPairDiameter; this.DOM.setRows.attr("transform",function(set){ return "translate(0,"+((set.orderIndex+0.5)*rowHeight)+")"; }); }, /** -- */ refreshRow: function(){ this.refreshRow_Position(); this.refreshRow_LineWidths(); }, /** -- */ refreshSetPair_Position: function(){ var me=this; var w=this.getWidth(); this.DOM.aggrGlyphs.each(function(setPair){ var i1 = setPair.set_1.orderIndex; var i2 = setPair.set_2.orderIndex; var left = (Math.min(i1,i2)+0.5)*me.setPairDiameter; if(me.position==="left") left = w-left; var top = (Math.max(i1,i2)+0.5)*me.setPairDiameter; kshf.Util.setTransform(this,"translate("+left+"px,"+top+"px)"); }); }, /** -- */ getCliqueSizeRatio: function(setPair){ return Math.sqrt(setPair.measure('Active')/this._maxSetPairAggr_Active); }, /** Given a setPair, return the angle for preview Does not work with "Avg" measure **/ getAngleToActive_rad: function(setPair,m){ if(setPair._measure.Active===0) return 0; var ratio = setPair._measure[m] / setPair._measure.Active; if(this.browser.preview_not) ratio = 1-ratio; if(ratio===1) ratio=0.999; return ((360*ratio-90) * Math.PI) / 180; }, /** -- */ // http://stackoverflow.com/questions/5737975/circle-drawing-with-svgs-arc-path // http://stackoverflow.com/questions/15591614/svg-radial-wipe-animation-using-css3-js // http://jsfiddle.net/Matt_Coughlin/j3Bhz/5/ getPiePath: function(endAngleRad,sub,ratio){ var r = ratio*this.setPairRadius-sub; var endX = Math.cos(endAngleRad) * r; var endY = Math.sin(endAngleRad) * r; var largeArcFlag = (endAngleRad>Math.PI/2)?1:0; return "M 0,"+(-r)+" A "+r+","+r+" "+largeArcFlag+" "+largeArcFlag+" 1 "+endX+","+endY+" L0,0"; }, /** setPairGlyph do not have a total component */ refreshViz_Total: function(){ }, /** -- */ refreshViz_Active: function(){ var me=this; this.DOM.aggrGlyphs.attr("activesize",function(aggr){ return aggr.measure('Active'); }); this.DOM.measure_Active.transition().duration(this.noanim?0:700) .attr("r",this.browser.ratioModeActive ? function(setPair){ return (setPair.subset!=='') ? me.setPairRadius-1 : me.setPairRadius; } : function(setPair){ return me.getCliqueSizeRatio(setPair)*me.setPairRadius; } ); }, /** -- */ refreshViz_Highlight: function(){ var me=this; this.DOM.measure_Highlighted .transition().duration(500).attrTween("d",function(aggr) { var angleInterp = d3.interpolate(aggr.currentPreviewAngle, me.getAngleToActive_rad(aggr,"Highlighted")); var ratio=(me.browser.ratioModeActive)?1:me.getCliqueSizeRatio(aggr); return function(t) { var newAngle=angleInterp(t); aggr.currentPreviewAngle = newAngle; return me.getPiePath(newAngle,(aggr.subset!=='' && me.browser.ratioModeActive)?2:0,ratio); }; }); }, /** -- */ refreshViz_Compare: function(cT, curGroup, totalGroups){ var me=this; var strokeWidth = 1; if(this.browser.ratioModeActive){ strokeWidth = Math.ceil(this.getRowHeight()/18); } this.DOM["measure_Compared_"+cT].attr("d",function(setPair){ var ratio=(me.browser.ratioModeActive)?1:me.getCliqueSizeRatio(setPair); this.style.display = setPair.measure("Compared_"+cT)===0 ? "none" : "block"; this.style.strokeWidth = strokeWidth; return me.getPiePath( me.getAngleToActive_rad(setPair,"Compared_"+cT), curGroup*strokeWidth, ratio ); }); }, /** Does not work with Avg pair */ refreshSetPair_Containment: function(){ var me=this; var numOfSubsets = 0; this.DOM.measure_Active .each(function(setPair){ var setPair_itemCount = setPair._measure.Active; var set_1_itemCount = setPair.set_1._measure.Active; var set_2_itemCount = setPair.set_2._measure.Active; if(setPair_itemCount===set_1_itemCount || setPair_itemCount===set_2_itemCount){ numOfSubsets++; setPair.subset = (set_1_itemCount===set_2_itemCount)?'equal':'proper'; } else { setPair.subset = ''; } }) .attr("subset",function(setPair){ return (setPair.subset!=='')?true:null; }); this.DOM.subsetCount.style("display",(numOfSubsets===0)?"none":null); this.DOM.subsetCount_Text.text(numOfSubsets); this.refreshSetPair_Strength(); }, /** -- */ refreshSetPair_Strength: function(){ var me=this; var strengthColor = d3.interpolateHsl(d3.rgb(230, 230, 247),d3.rgb(159, 159, 223)); this.DOM.measure_Active.style("fill",function(setPair){ if(!me.browser.ratioModeActive) return null; return strengthColor(setPair.Similarity/me._maxSimilarity); }); if(this.browser.ratioModeActive){ this.DOM.measure_Active.each(function(setPair){ // border if(setPair.subset==='') return; if(setPair.subset==='equal'){ this.style.strokeDasharray = ""; this.style.strokeDashoffset = ""; return; } var halfCircle = (me.setPairRadius-1)*Math.PI; this.style.strokeDasharray = halfCircle+"px"; // rotate halfway var i1 = setPair.set_1.orderIndex; var i2 = setPair.set_2.orderIndex; var c1 = setPair.set_1._measure.Active; var c2 = setPair.set_2._measure.Active; if((i1<i2 && c1<c2) || (i1>i2 && c1>c2)) halfCircle = halfCircle/2; this.style.strokeDashoffset = halfCircle+"px"; }); } }, /** -- */ updateAfterFilter: function () { if(this.isEmpty() || this.collapsed || !this.inBrowser()) return; this.updateMaxAggr_Active(); this.refreshViz_All(); this.refreshViz_EmptyRecords(); this.DOM.setRows.style("opacity",function(setRow){ return (setRow._measure.Active>0)?1:0.3; }); this.updateSetPairSimilarity(); this.refreshSetPair_Containment(); }, }; for(var index in Summary_Clique_functions){ kshf.Summary_Set.prototype[index] = Summary_Clique_functions[index]; }
keshif.js
/********************************* keshif library Copyright (c) 2014-2016, University of Maryland All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Maryland 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 MICHAEL BOSTOCK 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. ************************************ */ // load google visualization library only if google scripts were included if(typeof google !== 'undefined'){ google.load('visualization', '1', {'packages': []}); } /*! * Bowser - a browser detector * https://github.com/ded/bowser * MIT License | (c) Dustin Diaz 2015 */ !function(e,t){typeof module!="undefined"&&module.exports?module.exports=t():typeof define=="function"&&define.amd?define(t):this[e]=t()}("bowser",function(){function t(t){function n(e){var n=t.match(e);return n&&n.length>1&&n[1]||""}function r(e){var n=t.match(e);return n&&n.length>1&&n[2]||""}var i=n(/(ipod|iphone|ipad)/i).toLowerCase(),s=/like android/i.test(t),o=!s&&/android/i.test(t),u=/CrOS/.test(t),a=n(/edge\/(\d+(\.\d+)?)/i),f=n(/version\/(\d+(\.\d+)?)/i),l=/tablet/i.test(t),c=!l&&/[^-]mobi/i.test(t),h;/opera|opr/i.test(t)?h={name:"Opera",opera:e,version:f||n(/(?:opera|opr)[\s\/](\d+(\.\d+)?)/i)}:/yabrowser/i.test(t)?h={name:"Yandex Browser",yandexbrowser:e,version:f||n(/(?:yabrowser)[\s\/](\d+(\.\d+)?)/i)}:/windows phone/i.test(t)?(h={name:"Windows Phone",windowsphone:e},a?(h.msedge=e,h.version=a):(h.msie=e,h.version=n(/iemobile\/(\d+(\.\d+)?)/i))):/msie|trident/i.test(t)?h={name:"Internet Explorer",msie:e,version:n(/(?:msie |rv:)(\d+(\.\d+)?)/i)}:u?h={name:"Chrome",chromeBook:e,chrome:e,version:n(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i)}:/chrome.+? edge/i.test(t)?h={name:"Microsoft Edge",msedge:e,version:a}:/chrome|crios|crmo/i.test(t)?h={name:"Chrome",chrome:e,version:n(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i)}:i?(h={name:i=="iphone"?"iPhone":i=="ipad"?"iPad":"iPod"},f&&(h.version=f)):/sailfish/i.test(t)?h={name:"Sailfish",sailfish:e,version:n(/sailfish\s?browser\/(\d+(\.\d+)?)/i)}:/seamonkey\//i.test(t)?h={name:"SeaMonkey",seamonkey:e,version:n(/seamonkey\/(\d+(\.\d+)?)/i)}:/firefox|iceweasel/i.test(t)?(h={name:"Firefox",firefox:e,version:n(/(?:firefox|iceweasel)[ \/](\d+(\.\d+)?)/i)},/\((mobile|tablet);[^\)]*rv:[\d\.]+\)/i.test(t)&&(h.firefoxos=e)):/silk/i.test(t)?h={name:"Amazon Silk",silk:e,version:n(/silk\/(\d+(\.\d+)?)/i)}:o?h={name:"Android",version:f}:/phantom/i.test(t)?h={name:"PhantomJS",phantom:e,version:n(/phantomjs\/(\d+(\.\d+)?)/i)}:/blackberry|\bbb\d+/i.test(t)||/rim\stablet/i.test(t)?h={name:"BlackBerry",blackberry:e,version:f||n(/blackberry[\d]+\/(\d+(\.\d+)?)/i)}:/(web|hpw)os/i.test(t)?(h={name:"WebOS",webos:e,version:f||n(/w(?:eb)?osbrowser\/(\d+(\.\d+)?)/i)},/touchpad\//i.test(t)&&(h.touchpad=e)):/bada/i.test(t)?h={name:"Bada",bada:e,version:n(/dolfin\/(\d+(\.\d+)?)/i)}:/tizen/i.test(t)?h={name:"Tizen",tizen:e,version:n(/(?:tizen\s?)?browser\/(\d+(\.\d+)?)/i)||f}:/safari/i.test(t)?h={name:"Safari",safari:e,version:f}:h={name:n(/^(.*)\/(.*) /),version:r(/^(.*)\/(.*) /)},!h.msedge&&/(apple)?webkit/i.test(t)?(h.name=h.name||"Webkit",h.webkit=e,!h.version&&f&&(h.version=f)):!h.opera&&/gecko\//i.test(t)&&(h.name=h.name||"Gecko",h.gecko=e,h.version=h.version||n(/gecko\/(\d+(\.\d+)?)/i)),!h.msedge&&(o||h.silk)?h.android=e:i&&(h[i]=e,h.ios=e);var p="";h.windowsphone?p=n(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i):i?(p=n(/os (\d+([_\s]\d+)*) like mac os x/i),p=p.replace(/[_\s]/g,".")):o?p=n(/android[ \/-](\d+(\.\d+)*)/i):h.webos?p=n(/(?:web|hpw)os\/(\d+(\.\d+)*)/i):h.blackberry?p=n(/rim\stablet\sos\s(\d+(\.\d+)*)/i):h.bada?p=n(/bada\/(\d+(\.\d+)*)/i):h.tizen&&(p=n(/tizen[\/\s](\d+(\.\d+)*)/i)),p&&(h.osversion=p);var d=p.split(".")[0];if(l||i=="ipad"||o&&(d==3||d==4&&!c)||h.silk)h.tablet=e;else if(c||i=="iphone"||i=="ipod"||o||h.blackberry||h.webos||h.bada)h.mobile=e;return h.msedge||h.msie&&h.version>=10||h.yandexbrowser&&h.version>=15||h.chrome&&h.version>=20||h.firefox&&h.version>=20||h.safari&&h.version>=6||h.opera&&h.version>=10||h.ios&&h.osversion&&h.osversion.split(".")[0]>=6||h.blackberry&&h.version>=10.1?h.a=e:h.msie&&h.version<10||h.chrome&&h.version<20||h.firefox&&h.version<20||h.safari&&h.version<6||h.opera&&h.version<10||h.ios&&h.osversion&&h.osversion.split(".")[0]<6?h.c=e:h.x=e,h}var e=!0,n=t(typeof navigator!="undefined"?navigator.userAgent:"");return n.test=function(e){for(var t=0;t<e.length;++t){var r=e[t];if(typeof r=="string"&&r in n)return!0}return!1},n._detect=t,n}) // kshf namespace var kshf = { surrogateCtor: function() {}, // http://stackoverflow.com/questions/4152931/javascript-inheritance-call-super-constructor-or-use-prototype-chain extendClass: function(base, sub) { // Copy the prototype from the base to setup inheritance this.surrogateCtor.prototype = base.prototype; // Tricky huh? sub.prototype = new this.surrogateCtor(); // Remember the constructor property was set wrong, let's fix it sub.prototype.constructor = sub; }, maxVisibleItems_Default: 100, scrollWidth: 19, attribPanelWidth: 220, previewTimeoutMS: 250, map: { //"http://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png", //"http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", tileTemplate: 'http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a>', }, browsers: [], dt: {}, dt_id: {}, lang: { en: { ModifyBrowser: "Modify browser", OpenDataSource: "Open data source", ShowInfoCredits: "Show info &amp; credits", ShowFullscreen: "Fullscreen", RemoveFilter: "Remove filter", RemoveAllFilters: "Remove all filters", MinimizeSummary: "Close summary", OpenSummary: "Open summary", MaximizeSummary: "Maximize summary", RemoveSummary: "Remove summary", ReverseOrder: "Reverse order", Reorder: "Reorder", ShowMoreInfo: "Show more info", Percentiles: "Percentiles", LockToCompare: "Lock to compare", Unlock: "Unlock", Search: "Search", CreatingBrowser: "Creating Keshif Browser", Rows: "Rows", More: "More", LoadingData: "Loading data sources", ShowAll: "Show All", ScrollToTop: "Top", Absolute: "Absolute", Percent: "Percent", Relative: "Relative", Width: "Length", DragToFilter: "Drag to filter", And: "And", Or: "Or", Not: "Not", EditTitle: "Rename", ResizeBrowser: "Resize browser", RemoveRecords: "Remove record view", EditFormula: "Edit formula", NoData: "(no data)", ZoomToFit: "Zoom to fit" }, tr: { ModifyBrowser: "Tarayıcıyı düzenle", OpenDataSource: "Veri kaynağını aç", ShowInfoCredits: "Bilgi", ShowFullscreen: "Tam ekran", RemoveFilter: "Filtreyi kaldır", RemoveAllFilters: "Tüm filtreleri kaldır", MinimizeSummary: "Özeti ufalt", OpenSummary: "Özeti aç", MaximizeSummary: "Özeti büyüt", RemoveSummary: "Özeti kaldır", ReverseOrder: "Ters sırala", Reorder: "Yeniden sırala", ShowMoreInfo: "Daha fazla bilgi", Percentiles: "Yüzdeler", LockToCompare: "Kilitle ve karşılaştır", Unlock: "Kilidi kaldır", Search: "Ara", LoadingData: "Veriler yükleniyor...", CreatingBrowser: "Keşif arayüzü oluşturuluyor...", Rows: "Satır", More: "Daha", ShowAll: "Hepsi", ScrollToTop: "Yukarı", Absolute: "Net", Percent: "Yüzde", Relative: "Görece", Width: "Genişlik", DragToFilter: "Sürükle ve filtre", And: "Ve", Or: "Veya", Not: "Değil", EditTitle: "Değiştir", ResizeBrowser: "Boyutlandır", RemoveRecords: "Kayıtları kaldır", EditFormula: "Formülü değiştir", NoData: "(verisiz)", ZoomToFit: "Oto-yakınlaş" }, fr: { ModifyBrowser: "Modifier le navigateur", OpenDataSource: "Ouvrir la source de données", ShowInfoCredits: "Afficher les credits", RemoveFilter: "Supprimer le filtre", RemoveAllFilters: "Supprimer tous les filtres", MinimizeSummary: "Réduire le sommaire", OpenSummary: "Ouvrir le sommaire", MaximizeSummary: "Agrandir le sommaire", RemoveSummary: "??", ReverseOrder: "Inverser l'ordre", Reorder: "Réorganiser", ShowMoreInfo: "Plus d'informations", Percentiles: "Percentiles", LockToCompare: "Bloquer pour comparer", Unlock: "Débloquer", Search: "Rechercher", CreatingBrowser: "Création du navigateur", Rows: "Lignes", More: "Plus", LoadingData: "Chargement des données", ShowAll: "Supprimer les filtres", ScrollToTop: "Début", Absolute: "Absolue", Percent: "Pourcentage", Relative: "Relative", Width: "Largeur", DragToFilter: "??", And: "??", Or: "??", Not: "??", EditFormula: "Edit Formula", NoData: "(no data)", ZoomToFit: "Zoom to fit" }, cur: null // Will be set to en if not defined before a browser is loaded }, LOG: { // Note: id parameter is integer alwats, info is string CONFIG : 1, // Filtering state // param: resultCt, selected(selected # of attribs, sep by x), filtered(filtered filter ids) FILTER_ADD : 10, FILTER_CLEAR : 11, // Filtering extra information, send in addition to filtering state messages above FILTER_CLEAR_ALL : 12, // param: - FILTER_ATTR_ADD_AND : 13, // param: id (filterID), info (attribID) FILTER_ATTR_ADD_OR : 14, // param: id (filterID), info (attribID) FILTER_ATTR_ADD_ONE : 15, FILTER_ATTR_ADD_OR_ALL : 16, // param: id (filterID) FILTER_ATTR_ADD_NOT : 17, // param: id (filterID), info (attribID) FILTER_ATTR_EXACT : 18, // param: id (filterID), info (attribID) FILTER_ATTR_UNSELECT : 19, // param: id (filterID), info (attribID) FILTER_TEXTSEARCH : 20, // param: id (filterID), info (query text) FILTER_INTRVL_HANDLE : 21, // param: id (filterID) (TODO: Include range) FILTER_INTRVL_BIN : 22, // param: id (filterID) FILTER_CLEAR_X : 23, // param: id (filterID) FILTER_CLEAR_CRUMB : 24, // param: id (filterID) FILTER_PREVIEW : 25, // param: id (filterID), info (attribID for cat, histogram range (AxB) for interval) // Facet specific non-filtering interactions FACET_COLLAPSE : 40, // param: id (facetID) FACET_SHOW : 41, // param: id (facetID) FACET_SORT : 42, // param: id (facetID), info (sortID) FACET_SCROLL_TOP : 43, // param: id (facetID) FACET_SCROLL_MORE : 44, // param: id (facetID) // List specific interactions LIST_SORT : 50, // param: info (sortID) LIST_SCROLL_TOP : 51, // param: - LIST_SHOWMORE : 52, // param: info (itemCount) LIST_SORT_INV : 53, // param: - // Item specific interactions ITEM_DETAIL_ON : 60, // param: info (itemID) ITEM_DETAIL_OFF : 61, // param: info (itemID) // Generic interactions DATASOURCE : 70, // param: - INFOBOX : 71, // param: - CLOSEPAGE : 72, // param: - BARCHARTWIDTH : 73, // param: info (width) RESIZE : 74, // param: - }, Util: { sortFunc_List_String: function(a, b){ return a.localeCompare(b); }, sortFunc_List_Date: function(a, b){ if(a===null) return -1; if(b===null) return 1; return b.getTime() - a.getTime(); // recent first }, sortFunc_List_Number: function(a, b){ return b - a; }, /** Given a list of columns which hold multiple IDs, breaks them into an array */ cellToArray: function(dt, columns, splitExpr){ if(splitExpr===undefined){ splitExpr = /\b\s+/; } var j; dt.forEach(function(p){ p = p.data; columns.forEach(function(column){ var list = p[column]; if(list===null) return; if(typeof list==="number") { p[column] = ""+list; return; } var list2 = list.split(splitExpr); list = []; // remove empty "" records for(j=0; j<list2.length; j++){ list2[j] = list2[j].trim(); if(list2[j]!=="") list.push(list2[j]); } p[column] = list; }); }); }, baseMeasureFormat: d3.format(".2s"), /** You should only display at most 3 digits + k/m/etc */ formatForItemCount: function(n){ if(n<1000) { return n; } return kshf.Util.baseMeasureFormat(n); if(n<1000000) { // 1,000-999,999 var thousands=n/1000; if(thousands<10){ return (Math.floor(n/100)/10)+"k"; } return Math.floor(thousands)+"k"; } if(n<1000000000) return Math.floor(n/1000000)+"m"; return n; }, nearestYear: function(d){ var dr = new Date(Date.UTC(d.getUTCFullYear(),0,1)); if(d.getUTCMonth()>6) dr.setUTCFullYear(dr.getUTCFullYear()+1); return dr; }, nearestMonth: function(d){ var dr = new Date(Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),1)); if(d.getUTCDate()>15) dr.setUTCMonth(dr.getUTCMonth()+1); return dr; }, nearestDay: function(d){ var dr = new Date(Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate())); if(d.getUTCHours()>12) dr.setUTCDate(dr.getUTCDate()+1); return dr; }, nearestHour: function(d){ }, nearestMinute: function(d){ }, clearArray: function(arr){ while (arr.length > 0) { arr.pop(); } }, ignoreScrollEvents: false, scrollToPos_do: function(scrollDom, targetPos){ kshf.Util.ignoreScrollEvents = true; // scroll to top var startTime = null; var scrollInit = scrollDom.scrollTop; var easeFunc = d3.ease('cubic-in-out'); var scrollTime = 500; var animateToTop = function(timestamp){ var progress; if(startTime===null) startTime = timestamp; // complete animation in 500 ms progress = (timestamp - startTime)/scrollTime; var m=easeFunc(progress); scrollDom.scrollTop = (1-m)*scrollInit+m*targetPos; if(scrollDom.scrollTop!==targetPos){ window.requestAnimationFrame(animateToTop); } else { kshf.Util.ignoreScrollEvents = false; } }; window.requestAnimationFrame(animateToTop); }, toProperCase: function(str){ return str.toLowerCase().replace(/\b[a-z]/g,function(f){return f.toUpperCase()}); }, setTransform: function(dom,transform){ dom.style.webkitTransform = transform; dom.style.MozTransform = transform; dom.style.msTransform = transform; dom.style.OTransform = transform; dom.style.transform = transform; }, // http://stackoverflow.com/questions/13627308/add-st-nd-rd-and-th-ordinal-suffix-to-a-number ordinal_suffix_of: function(i) { var j = i % 10, k = i % 100; if (j == 1 && k != 11) { return i + "st"; } if (j == 2 && k != 12) { return i + "nd"; } if (j == 3 && k != 13) { return i + "rd"; } return i + "th"; }, }, style: { color_chart_background_highlight: "rgb(194, 146, 124)" }, fontLoaded: false, loadFont: function(){ if(this.fontLoaded===true) return; WebFontConfig = { google: { families: [ 'Roboto:400,500,300,100,700:latin', 'Montserrat:400,700:latin' ] } }; var wf = document.createElement('script'); wf.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js'; wf.type = 'text/javascript'; wf.async = 'true'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(wf, s); this.fontLoaded = true; }, handleResize: function(){ this.browsers.forEach(function(browser){ browser.updateLayout(); }); }, activeTipsy: undefined, colorScale : { converge: [ d3.rgb('#ffffd9'), d3.rgb('#edf8b1'), d3.rgb('#c7e9b4'), d3.rgb('#7fcdbb'), d3.rgb('#41b6c4'), d3.rgb('#1d91c0'), d3.rgb('#225ea8'), d3.rgb('#253494'), d3.rgb('#081d58')], diverge: [ d3.rgb('#8c510a'), d3.rgb('#bf812d'), d3.rgb('#dfc27d'), d3.rgb('#f6e8c3'), d3.rgb('#f5f5f5'), d3.rgb('#c7eae5'), d3.rgb('#80cdc1'), d3.rgb('#35978f'), d3.rgb('#01665e')] }, /* -- */ intersects: function(d3bound, leafletbound){ // d3bound: [​[left, bottom], [right, top]​] // leafletBound._southWest.lat // leafletBound._southWest.long // leafletBound._northEast.lat // leafletBound._northEast.long if(d3bound[0][0]>leafletbound._northEast.lng) return false; if(d3bound[0][1]>leafletbound._northEast.lat) return false; if(d3bound[1][0]<leafletbound._southWest.lng) return false; if(d3bound[1][1]<leafletbound._southWest.lat) return false; return true; }, /** -- */ gistPublic: true, getGistLogin: function(){ if(this.githubToken===undefined) return; $.ajax( 'https://api.github.com/user', { method: "GET", async: true, dataType: "json", headers: {Authorization: "token "+kshf.githubToken}, success: function(response){ kshf.gistLogin = response.login; } } ); }, /** -- TEMP! Not a good design here! TODO change */ wrapLongitude: 170 }; // tipsy, facebook style tooltips for jquery // Modified / simplified version for internal Keshif use // version 1.0.0a // (c) 2008-2010 jason frame [[email protected]] // released under the MIT license function Tipsy(element, options) { this.jq_element = $(element); this.options = $.extend({}, { className: null, delayOut: 0, gravity: 'n', offset: 0, offset_x: 0, offset_y: 0, opacity: 1 }, options ); }; Tipsy.prototype = { show: function() { var maybeCall = function(thing, ctx) { return (typeof thing == 'function') ? (thing.call(ctx)) : thing; }; // hide active Tipsy if(kshf.activeTipsy) kshf.activeTipsy.hide(); kshf.activeTipsy = this; var title = this.getTitle(); if(!title) return; var jq_tip = this.tip(); jq_tip.find('.tipsy-inner')['html'](title); jq_tip[0].className = 'tipsy'; // reset classname in case of dynamic gravity jq_tip.remove().css({top: 0, left: 0, visibility: 'hidden', display: 'block'}).prependTo(document.body); var pos = $.extend({}, this.jq_element.offset(), { width: this.jq_element[0].offsetWidth, height: this.jq_element[0].offsetHeight }); var actualWidth = jq_tip[0].offsetWidth, actualHeight = jq_tip[0].offsetHeight, gravity = maybeCall(this.options.gravity, this.jq_element[0]); this.tipWidth = actualWidth; this.tipHeight = actualHeight; var tp; switch (gravity.charAt(0)) { case 'n': tp = {top: pos.top + pos.height + this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2}; break; case 's': tp = {top: pos.top - actualHeight - this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2}; break; case 'e': tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth - this.options.offset}; break; case 'w': tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width + this.options.offset}; break; } tp.top+=this.options.offset_y; tp.left+=this.options.offset_x; if (gravity.length == 2) { if (gravity.charAt(1) == 'w') { tp.left = pos.left + pos.width / 2 - 15; } else { tp.left = pos.left + pos.width / 2 - actualWidth + 15; } } jq_tip.css(tp).addClass('tipsy-' + gravity); jq_tip.find('.tipsy-arrow')[0].className = 'tipsy-arrow tipsy-arrow-' + gravity.charAt(0); if (this.options.className) { jq_tip.addClass(maybeCall(this.options.className, this.jq_element[0])); } jq_tip.stop().css({opacity: 0, display: 'block', visibility: 'visible'}).animate({opacity: this.options.opacity},200); }, hide: function(){ kshf.activeTipsy = undefined; this.tip().stop().fadeOut(200,function() { $(this).remove(); }); }, getTitle: function() { var title, jq_e = this.jq_element, o = this.options; var title, o = this.options; if (typeof o.title == 'string') { title = o.title; } else if (typeof o.title == 'function') { title = o.title.call(jq_e[0]); } title = ('' + title).replace(/(^\s*|\s*$)/, ""); return title; }, tip: function() { if(this.jq_tip) return this.jq_tip; this.jq_tip = $('<div class="tipsy"></div>').html('<div class="tipsy-arrow"></div><div class="tipsy-inner"></div>'); this.jq_tip.data('tipsy-pointee', this.jq_element[0]); return this.jq_tip; } }; /** * @constructor */ kshf.Record = function(d, idIndex){ this.data = d; this.idIndex = idIndex; // TODO: Items don't need to have ID index, only one per table is enough?? // By default, each item is aggregated as 1 // You can modify this with a non-negative value // Note that the aggregation currently works by summation only. this.measure_Self = 1; // Wanted item / not filtered out this.isWanted = true; this.recordRank = 0; this.recordRank_pre = -1; // The data that's used for mapping this item, used as a cache. // This is accessed by filterID // Through this, you can also reach DOM of aggregates // DOM elements that this item is mapped to // - If this is a paper, it can be paper type. If this is author, it can be author affiliation. this._valueCache = []; // caching the values this item was mapped to this._aggrCache = []; this.DOM = {}; // If item is primary type, this will be set this.DOM.record = undefined; // Internal variable // If true, filter/wanted state is dirty and needs to be updated. this._filterCacheIsDirty = true; // Cacheing filter state per each summary this._filterCache = []; this.selectCompared_str = ""; this.selectCompared = {A: false, B: false, C: false}; }; kshf.Record.prototype = { /** Returns unique ID of the item. */ id: function(){ return this.data[this.idIndex]; }, /** -- */ setFilterCache: function(index,v){ if(this._filterCache[index]===v) return; this._filterCache[index] = v; this._filterCacheIsDirty = true; }, /** Updates isWanted state, and notifies all related filter attributes of the change */ updateWanted: function(){ if(!this._filterCacheIsDirty) return false; var me = this; var oldWanted = this.isWanted; this.isWanted = this._filterCache.every(function(f){ return f; }); if(this.measure_Self && this.isWanted !== oldWanted){ // There is some change that affects computation var valToAdd = (this.isWanted && !oldWanted) ? this.measure_Self /*add*/ : -this.measure_Self /*remove*/; var cntToAdd = valToAdd>0?1:-1; this._aggrCache.forEach(function(aggr){ aggr._measure.Active += valToAdd; if(valToAdd) aggr.recCnt.Active+=cntToAdd; }); } this._filterCacheIsDirty = false; return this.isWanted !== oldWanted; }, /** -- */ setRecordDetails: function(value){ this.showDetails = value; if(this.DOM.record) this.DOM.record.setAttribute('details', this.showDetails); }, /** Called on mouse-over on a primary item type */ highlightRecord: function(){ if(this.DOM.record) this.DOM.record.setAttribute("selection","onRecord"); // summaries that this item appears in this._aggrCache.forEach(function(aggr){ if(aggr.DOM.aggrGlyph) aggr.DOM.aggrGlyph.setAttribute("selection","onRecord"); if(aggr.DOM.matrixRow) aggr.DOM.matrixRow.setAttribute("selection","onRecord"); if(aggr.summary) aggr.summary.setRecordValue(this); },this); }, /** -- */ unhighlightRecord: function(){ if(this.DOM.record) this.DOM.record.removeAttribute("selection"); // summaries that this item appears in this._aggrCache.forEach(function(aggr){ aggr.unselectAggregate(); if(aggr.summary) aggr.summary.hideRecordValue(); },this); }, /** -- */ addForHighlight: function(){ if(!this.isWanted || this.highlighted) return; if(this.DOM.record) { var x = this.DOM.record; x.setAttribute("selection","highlighted"); // SVG geo area - move it to the bottom of parent so that border can be displayed nicely. // TODO: improve the conditional check! if(x.nodeName==="path") d3.select(x.parentNode.appendChild(x)); } this._aggrCache.forEach(function(aggr){ if(this.measure_Self===null ||this.measure_Self===0) return; aggr._measure.Highlighted += this.measure_Self; aggr.recCnt.Highlighted++; }, this); this.highlighted = true; }, /** -- */ remForHighlight: function(distribute){ if(!this.isWanted || !this.highlighted) return; if(this.DOM.record) this.DOM.record.removeAttribute("selection"); if(distribute) this._aggrCache.forEach(function(aggr){ if(this.measure_Self===null || this.measure_Self===0) return; aggr._measure.Highlighted -= this.measure_Self; aggr.recCnt.Highlighted--; }, this); this.highlighted = false; }, /** -- */ setCompared: function(cT){ this.selectCompared_str+=cT+" "; this.selectCompared[cT] = true; this.domCompared(); }, /** -- */ unsetCompared: function(cT){ this.selectCompared_str = this.selectCompared_str.replace(cT+" ",""); this.selectCompared[cT] = false; this.domCompared(); }, domCompared: function(){ if(!this.DOM.record) return; if(this.selectCompared_str==="") { this.DOM.record.removeAttribute("rec_compared"); } else { this.DOM.record.setAttribute("rec_compared",this.selectCompared_str); } } }; /** * @constructor */ kshf.Aggregate = function(){}; kshf.Aggregate.prototype = { /** -- */ init: function(d,idIndex){ // Items which are mapped/related to this item this.records = []; this._measure = { Active: 0, Highlighted: 0, Total: 0, Compared_A: 0, Compared_B: 0, Compared_C: 0 } this.recCnt = { Active: 0, Highlighted: 0, Total: 0, Compared_A: 0, Compared_B: 0, Compared_C: 0 } // the main data within item this.data = d; this.idIndex = idIndex; // Selection state // 1: selected for inclusion (AND) // 2: selected for inclusion (OR) // -1: selected for removal (NOT query) // 0: not selected this.selected = 0; this.DOM = {}; // If item is used as a filter (can be primary if looking at links), this will be set this.DOM.aggrGlyph = undefined; }, /** Returns unique ID of the item. */ id: function(){ return this.data[this.idIndex]; }, /** -- */ addRecord: function(record){ this.records.push(record); record._aggrCache.push(this); if(record.measure_Self===null || record.measure_Self===0) return; this._measure.Total += record.measure_Self; this.recCnt.Total++; if(record.isWanted) { this._measure.Active += record.measure_Self; this.recCnt.Active++; } }, /** -- */ measure: function(v){ if(kshf.browser.measureFunc==="Avg"){ var r=this.recCnt[v]; return (r===0) ? 0 : this._measure[v]/r ; // avoid division by zero. } return this._measure[v]; }, /** -- */ resetAggregateMeasures: function(){ this._measure = { Active: 0, Highlighted: 0, Total: 0, Compared_A: 0, Compared_B: 0, Compared_C: 0 }; this.recCnt = { Active: 0, Highlighted: 0, Total: 0, Compared_A: 0, Compared_B: 0, Compared_C: 0 }; this.records.forEach(function(record){ if(record.measure_Self===null || record.measure_Self===0) return; this._measure.Total += record.measure_Self; this.recCnt.Total++; if(record.isWanted) { this._measure.Active += record.measure_Self; this.recCnt.Active++; } },this); }, /** -- */ ratioHighlightToTotal: function(){ return this._measure.Highlighted / this._measure.Total; }, /** -- */ ratioHighlightToActive: function(){ return this._measure.Highlighted / this._measure.Active; }, /** -- */ ratioCompareToActive: function(cT){ return this._measure["Compared_"+cT] / this._measure.Active; }, /** -- */ unselectAggregate: function(){ if(this.DOM.aggrGlyph) { this.DOM.aggrGlyph.removeAttribute("selection"); this.DOM.aggrGlyph.removeAttribute("showlock"); } if(this.DOM.matrixRow) this.DOM.matrixRow.removeAttribute("selection"); }, /** -- */ selectCompare: function(cT){ if(this.DOM.aggrGlyph) this.DOM.aggrGlyph.setAttribute("compare","true"); this.compared = cT; this.records.forEach(function(record){ record.setCompared(cT); }); }, /** -- */ clearCompare: function(cT){ if(this.DOM.aggrGlyph) this.DOM.aggrGlyph.removeAttribute("compare"); this.compared = false; this.records.forEach(function(record){ record.unsetCompared(cT); }); }, /** -- */ selectHighlight: function(){ this.records.forEach(function(record){ record.addForHighlight(); }); }, /** -- */ clearHighlight: function(){ this.records.forEach(function(record){ record.remForHighlight(false); }); }, // CATEGORICAL AGGREGATES /** -- */ f_selected: function(){ return this.selected!==0; }, f_included: function(){ return this.selected>0; }, is_NONE:function(){ return this.selected===0; }, is_NOT: function(){ return this.selected===-1; }, is_AND: function(){ return this.selected===1; }, is_OR : function(){ return this.selected===2; }, set_NONE: function(){ if(this.inList!==undefined) { this.inList.splice(this.inList.indexOf(this),1); } this.inList = undefined; this.selected = 0; this._refreshFacetDOMSelected(); }, set_NOT: function(l){ if(this.is_NOT()) return; this._insertToList(l); this.selected =-1; this._refreshFacetDOMSelected(); }, set_AND: function(l){ if(this.is_AND()) return; this._insertToList(l); this.selected = 1; this._refreshFacetDOMSelected(); }, set_OR: function(l){ if(this.is_OR()) return; this._insertToList(l); this.selected = 2; this._refreshFacetDOMSelected(); }, /** Internal */ _insertToList: function(l){ if(this.inList!==undefined) { this.inList.splice(this.inList.indexOf(this),1); } this.inList = l; l.push(this); }, /** Internal */ _refreshFacetDOMSelected: function(){ if(this.DOM.aggrGlyph) this.DOM.aggrGlyph.setAttribute("selected",this.selected); }, }; kshf.Aggregate_EmptyRecords = function(){}; kshf.Aggregate_EmptyRecords.prototype = new kshf.Aggregate(); var Aggregate_EmptyRecords_functions = { /** -- */ init: function(){ kshf.Aggregate.prototype.init.call(this,{id: null},'id'); this.isVisible = true; } } for(var index in Aggregate_EmptyRecords_functions){ kshf.Aggregate_EmptyRecords.prototype[index] = Aggregate_EmptyRecords_functions[index]; } kshf.Filter = function(filterOptions){ this.isFiltered = false; this.browser = filterOptions.browser; this.filterTitle = filterOptions.title; this.onClear = filterOptions.onClear; this.onFilter = filterOptions.onFilter; this.hideCrumb = filterOptions.hideCrumb || false; this.filterView_Detail = filterOptions.filterView_Detail; // must be a function this.filterID = this.browser.filterCount++; this.browser.records.forEach(function(record){ record.setFilterCache(this.filterID,true); },this); this.how = "All"; this.filterCrumb = null; }; kshf.Filter.prototype = { addFilter: function(){ this.isFiltered = true; if(this.onFilter) this.onFilter.call(this); var stateChanged = false; var how=0; if(this.how==="LessResults") how = -1; if(this.how==="MoreResults") how = 1; this.browser.records.forEach(function(record){ // if you will show LESS results and record is not wanted, skip // if you will show MORE results and record is wanted, skip if(!(how<0 && !record.isWanted) && !(how>0 && record.isWanted)){ stateChanged = record.updateWanted() || stateChanged; } },this); this._refreshFilterSummary(); this.browser.update_Records_Wanted_Count(); this.browser.refresh_filterClearAll(); this.browser.clearSelect_Highlight(); if(stateChanged) this.browser.updateAfterFilter(); }, /** -- */ clearFilter: function(forceUpdate, updateWanted){ if(!this.isFiltered) return; this.isFiltered = false; // clear filter cache - no other logic is necessary this.browser.records.forEach(function(record){ record.setFilterCache(this.filterID,true); },this); if(updateWanted!==false){ this.browser.records.forEach(function(record){ if(!record.isWanted) record.updateWanted(); }); } this._refreshFilterSummary(); if(this.onClear) this.onClear.call(this); if(forceUpdate!==false){ this.browser.update_Records_Wanted_Count(); this.browser.refresh_filterClearAll(); this.browser.updateAfterFilter(); } }, /** Don't call this directly */ _refreshFilterSummary: function(){ if(this.hideCrumb===true) return; if(!this.isFiltered){ var root = this.filterCrumb; if(root===null || root===undefined) return; root.attr("ready",false); setTimeout(function(){ root[0][0].parentNode.removeChild(root[0][0]); }, 350); this.filterCrumb = null; } else { // insert DOM if(this.filterCrumb===null) { this.filterCrumb = this.browser.insertDOM_crumb("Filtered",this); } this.filterCrumb.select(".crumbHeader").html(this.filterTitle()); this.filterCrumb.select(".filterDetails").html(this.filterView_Detail.call(this)); } }, }; /** -- */ kshf.RecordDisplay = function(kshf_, config){ var me = this; this.browser = kshf_; this.DOM = {}; this.config = config; this.config.sortColWidth = this.config.sortColWidth || 50; // default is 50 px this.autoExpandMore = true; if(config.autoExpandMore===false) this.autoExpandMore = false; this.maxVisibleItems_Default = config.maxVisibleItems_Default || kshf.maxVisibleItems_Default; this.maxVisibleItems = this.maxVisibleItems_Default; // This is the dynamic property this.showRank = config.showRank || false; this.mapMouseControl = "pan"; this.displayType = config.displayType || 'list'; // 'grid', 'list', 'map', 'nodelink' if(config.geo) this.displayType = 'map'; if(config.linkBy) { this.displayType = 'nodelink'; if(!Array.isArray(config.linkBy)) config.linkBy = [config.linkBy]; } else { config.linkBy = []; } this.detailsToggle = config.detailsToggle || 'zoom'; // 'one', 'zoom', 'off' (any other string counts as off practically) this.textSearchSummary = null; // no text search summary by default this.recordViewSummary = null; this.spatialAggr_Highlight = new kshf.Aggregate(); this.spatialAggr_Compare = new kshf.Aggregate(); this.spatialAggr_Highlight.init({}); this.spatialAggr_Compare .init({}); this.spatialAggr_Highlight.summary = this; this.spatialAggr_Compare .summary = this; /*********** * SORTING OPTIONS *************************************************************************/ config.sortingOpts = config.sortBy; // depracated option (sortingOpts) this.sortingOpts = config.sortingOpts || [ {title:this.browser.records[0].idIndex} ]; // Sort by id by default if(!Array.isArray(this.sortingOpts)) this.sortingOpts = [this.sortingOpts]; this.prepSortingOpts(); var firstSortOpt = this.sortingOpts[0]; // Add all interval summaries as sorting options this.browser.summaries.forEach(function(summary){ if(summary.panel===undefined) return; // Needs to be within view if(summary.type!=="interval") return; // Needs to be interval (numeric) this.addSortingOption(summary); },this); this.prepSortingOpts(); this.alphabetizeSortingOptions(); this.setSortingOpt_Active(firstSortOpt || this.sortingOpts[0]); this.DOM.root = this.browser.DOM.root.select(".recordDisplay") .attr('detailsToggle',this.detailsToggle) .attr('showRank',this.showRank) .attr('mapMouseControl',this.mapMouseControl) .attr('hasRecordView',false); var zone = this.DOM.root.append("div").attr("class","dropZone dropZone_recordView") .on("mouseenter",function(){ this.setAttribute("readyToDrop",true); }) .on("mouseleave",function(){ this.setAttribute("readyToDrop",false); }) .on("mouseup",function(event){ var movedSummary = me.browser.movedSummary; if(movedSummary===null || movedSummary===undefined) return; movedSummary.refreshNuggetDisplay(); me.setRecordViewSummary(movedSummary); if(me.textSearchSummary===null) me.setTextSearchSummary(movedSummary); me.browser.updateLayout(); }); zone.append("div").attr("class","dropIcon fa fa-list-ul"); this.DOM.recordDisplayHeader = this.DOM.root.append("div").attr("class","recordDisplayHeader"); this.initDOM_RecordViewHeader(); this.DOM.recordDisplayWrapper = this.DOM.root.append("div").attr("class","recordDisplayWrapper"); this.viewAs(this.displayType); if(config.recordView!==undefined){ if(typeof(config.recordView)==="string"){ // it may be a function definition if so, evaluate if(config.recordView.substr(0,8)==="function"){ // Evaluate string to a function!! eval("\"use strict\"; config.recordView = "+config.recordView); } } this.setRecordViewSummary( (typeof config.recordView === 'string') ? this.browser.summaries_by_name[config.recordView] : // function this.browser.createSummary('_RecordView_',config.recordView,'categorical') ); } if(config.textSearch){ // Find the summary. If it is not there, create it if(typeof(config.textSearch)==="string"){ this.setTextSearchSummary( this.browser.summaries_by_name[config.textSearch] ); } else { var name = config.textSearch.name; var value = config.textSearch.value; if(name!==undefined){ var summary = this.browser.summaries_by_name[config.textSearch]; if(!summary){ if(typeof(value)==="function"){ summary = browser.createSummary(name,value,'categorical'); } else if(typeof(value)==="string"){ summary = browser.changeSummaryName(value,name); }; } } this.setTextSearchSummary(summary); } } }; kshf.RecordDisplay.prototype = { /** -- */ setHeight: function(v){ if(this.recordViewSummary===null) return; var me=this; this.curHeight = v; this.DOM.recordDisplayWrapper.style("height",v+"px"); if(this.displayType==="map"){ setTimeout(function(){ me.leafletRecordMap.invalidateSize(); }, 1000); } }, /** -- */ refreshWidth: function(widthMiddlePanel){ this.curWidth = widthMiddlePanel; if(this.displayType==="map"){ this.leafletRecordMap.invalidateSize(); } }, /** -- */ getRecordEncoding: function(){ return (this.displayType==="map" || this.displayType==="nodelink") ? "color" : "sort"; }, /** -- */ map_refreshColorScaleBins: function(){ var me = this; this.DOM.recordColorScaleBins .style("background-color", function(d){ if(me.sortingOpt_Active.invertColorScale) d = 8-d; return kshf.colorScale[me.browser.mapColorTheme][d]; }); }, /** -- */ map_projectRecords: function(){ var me = this; var _geo_ = this.config.geo; this.DOM.kshfRecords.attr("d", function(record){ return me.recordGeoPath(record.data[_geo_]); }); }, /** -- */ map_zoomToActive: function(){ // Insert the bounds for each record path into the bs var bs = []; var _geo_ = this.config.geo; this.browser.records.forEach(function(record){ if(!record.isWanted) return; if(record._geoBounds_ === undefined) return; var b = record._geoBounds_; if(isNaN(b[0][0])) return; // Change wrapping (US World wrap issue) if(b[0][0]>kshf.wrapLongitude) b[0][0]-=360; if(b[1][0]>kshf.wrapLongitude) b[1][0]-=360; bs.push(L.latLng(b[0][1], b[0][0])); bs.push(L.latLng(b[1][1], b[1][0])); }); var bounds = new L.latLngBounds(bs); if(!this.browser.finalized){ // First time: just fit bounds this.leafletRecordMap.fitBounds( bounds ); return; } this.leafletRecordMap.flyToBounds( bounds, { padding: [0,0], pan: {animate: true, duration: 1.2}, zoom: {animate: true} } ); }, /** -- */ initDOM_MapView: function(){ var me = this; if(this.DOM.recordMap_Base) { this.DOM.recordGroup = this.DOM.recordMap_SVG.select(".recordGroup"); this.DOM.kshfRecords = this.DOM.recordGroup.selectAll(".kshfRecord"); return; // Do not initialize twice } this.setSpatialFilter(); this.DOM.recordMap_Base = this.DOM.recordDisplayWrapper.append("div").attr("class","recordMap_Base"); this.leafletRecordTileLayer = new L.TileLayer( kshf.map.tileTemplate, { attribution: kshf.map.attribution, attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a>', subdomains: 'abcd', maxZoom: 19 //nowrap: true }); this.leafletRecordMap = L.map(this.DOM.recordMap_Base[0][0], { maxBoundsViscosity: 1, /*continuousWorld: true, crs: L.CRS.EPSG3857 */ } ) .addLayer(this.leafletRecordTileLayer) .on("viewreset",function(){ me.map_projectRecords(); }) .on("movestart",function(){ me.DOM.recordGroup.style("display","none"); }) .on("move",function(){ // console.log("MapZoom: "+me.leafletRecordMap.getZoom()); // me.map_projectRecords() }) .on("moveend",function(){ me.DOM.recordGroup.style("display","block"); me.map_projectRecords(); }); this.recordGeoPath = d3.geo.path().projection( d3.geo.transform({ // Use Leaflet to implement a D3 geometric transformation. point: function(x, y) { if(x>kshf.wrapLongitude) x-=360; var point = me.leafletRecordMap.latLngToLayerPoint(new L.LatLng(y, x)); this.stream.point(point.x, point.y); } }) ); var _geo_ = this.config.geo; // Compute geo-bohts of each record this.browser.records.forEach(function(record){ var feature = record.data[_geo_]; if(typeof feature === 'undefined') return; record._geoBounds_ = d3.geo.bounds(feature); }); this.drawingFilter = false; this.DOM.recordMap_Base.select(".leaflet-tile-pane") .on("mousedown",function(){ if(me.mapMouseControl!=="draw") return; me.drawingFilter = true; me.DOM.recordMap_Base.attr("drawing",true); me.DOM.recordMap_Base.attr("drawingFilter",true); var mousePos = d3.mouse(this); var curLatLong = me.leafletRecordMap.layerPointToLatLng(L.point(mousePos[0], mousePos[1])); me.adsajasid = curLatLong; d3.event.stopPropagation(); d3.event.preventDefault(); }) .on("mouseup",function(){ if(me.mapMouseControl!=="draw") return; if(!me.drawingFilter) return; me.DOM.recordMap_Base.attr("drawing",null); me.DOM.recordMap_Base.attr("drawingFilter",null); me.drawingFilter = false; me.spatialFilter.addFilter(); d3.event.stopPropagation(); d3.event.preventDefault(); }) .on("mousemove",function(){ if(me.mapMouseControl!=="draw") return; if(me.drawingHighlight && !d3.event.shiftKey){ me.drawingHighlight = false; me.DOM.recordMap_Base.attr("drawing",null); me.DOM.recordMap_Base.attr("drawingHighlight",null); me.browser.clearSelect_Highlight(); // Disable highlight selection: TODO } var mousePos = d3.mouse(this); var curLatLong = me.leafletRecordMap.layerPointToLatLng(L.point(mousePos[0], mousePos[1])); if(d3.event.shiftKey){ if(!me.drawingFilter && !me.drawingHighlight){ // Start highlight selection me.DOM.recordMap_Base.attr("drawing",true); me.adsajasid = curLatLong; me.DOM.recordMap_Base.attr("drawingHighlight",true); me.drawingHighlight = true; } } if(!me.drawingFilter && !me.drawingHighlight) return; //console.log("X: "+mousePos[0]+", Y:"+mousePos[1]); //console.log(curLatLong); var bounds = L.latLngBounds([me.adsajasid,curLatLong]); if(me.drawingHighlight){ me.spatialQuery.highlight.setBounds(bounds); me.spatialAggr_Highlight.records = []; me.browser.records.forEach(function(record){ if(!record.isWanted) return; if(record._geoBounds_ === undefined) return; // already have "bounds" variable if(kshf.intersects(record._geoBounds_, bounds)){ me.spatialAggr_Highlight.records.push(record); } else { record.remForHighlight(true); } }); me.browser.setSelect_Highlight(null,me.spatialAggr_Highlight, "Region"); } else { me.spatialQuery.filter.setBounds(bounds); } /* me.browser.records.forEach(function(record){ if(!record.isWanted) return; if(record._geoBounds_ === undefined) return; // already have "bounds" variable if(kshf.intersects(record._geoBounds_, bounds)){ //console.log(record.data.CombinedName); } });*/ d3.event.stopPropagation(); d3.event.preventDefault(); }) ; // Add an example rectangle layer to the map var bounds = [[-54.559322, -15.767822], [56.1210604, 15.021240]]; // create an orange rectangle this.spatialQuery = { filter: L.rectangle(bounds, {color: "#5A7283", weight: 1, className: "spatialQuery_Filter"}), highlight: L.rectangle(bounds, {color: "#ff7800", weight: 1, className: "spatialQuery_Highlight"}), }; this.spatialQuery.filter.addTo(this.leafletRecordMap); this.spatialQuery.highlight.addTo(this.leafletRecordMap); this.DOM.recordMap_SVG = d3.select(this.leafletRecordMap.getPanes().overlayPane) .append("svg").attr("xmlns","http://www.w3.org/2000/svg").attr("class","recordMap_SVG"); // The fill pattern definition in SVG, used to denote geo-objects with no data. // http://stackoverflow.com/questions/17776641/fill-rect-with-pattern this.DOM.recordMap_SVG.append('defs') .append('pattern') .attr('id', 'diagonalHatch') .attr('patternUnits', 'userSpaceOnUse') .attr('width', 4) .attr('height', 4) .append('path') .attr('d', 'M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2') .attr('stroke', 'gray') .attr('stroke-width', 1); this.DOM.recordGroup = this.DOM.recordMap_SVG.append("g").attr("class", "leaflet-zoom-hide recordGroup"); // Add custom controls var DOM_control = d3.select(this.leafletRecordMap.getContainer()).select(".leaflet-control"); DOM_control.append("a") .attr("class","leaflet-control-view-map") .attr("title","Show/Hide Map") .attr("href","#") .each(function(){ this.tipsy = new Tipsy(this, {gravity: 'w', title: "Show/Hide Map"}); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout", function(){ this.tipsy.hide(); }) .html("<span class='viewMap fa fa-map-o'></span>") .on("dblclick",function(){ d3.event.preventDefault(); d3.event.stopPropagation(); }) .on("click",function(){ var x = d3.select(me.leafletRecordMap.getPanes().tilePane); x.attr("showhide", x.attr("showhide")==="hide"?"show":"hide"); d3.select(this.childNodes[0]).attr("class","fa fa-map"+((x.attr("showhide")==="hide")?"":"-o")); d3.event.preventDefault(); d3.event.stopPropagation(); }); DOM_control.append("a").attr("class","mapMouseControl fa") .each(function(){ this.tipsy = new Tipsy(this, {gravity: 'w', title: function(){ return "Drag mouse to "+(me.mapMouseControl==="pan"?"draw":"pan"); } }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout", function(){ this.tipsy.hide(); }) .on("click",function(){ me.mapMouseControl = me.mapMouseControl==="pan"?"draw":"pan"; me.DOM.root.attr("mapMouseControl",me.mapMouseControl); }); DOM_control.append("a") .attr("class","leaflet-control-viewFit").attr("title",kshf.lang.cur.ZoomToFit) .attr("href","#") .each(function(){ this.tipsy = new Tipsy(this, {gravity: 'w', title: kshf.lang.cur.ZoomToFit}); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout", function(){ this.tipsy.hide(); }) .html("<span class='viewFit fa fa-arrows-alt'></span>") .on("dblclick",function(){ d3.event.preventDefault(); d3.event.stopPropagation(); }) .on("click",function(){ me.map_zoomToActive(); d3.event.preventDefault(); d3.event.stopPropagation(); }); }, /** -- */ initDOM_NodeLinkView: function(){ var me = this; if(this.DOM.recordNodeLink_SVG) { this.DOM.recordGroup = this.DOM.recordNodeLink_SVG.select(".recordGroup"); this.DOM.kshfRecords = this.DOM.recordGroup.selectAll(".kshfRecord"); return; // Do not initialize twice } this.initDOM_NodeLinkView_Settings(); this.nodeZoomBehavior = d3.behavior.zoom() .scaleExtent([0.5, 8]) .on("zoom", function(){ gggg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")"); me.refreshNodeVis(); }); this.DOM.recordNodeLink_SVG = this.DOM.recordDisplayWrapper .append("svg").attr("xmlns","http://www.w3.org/2000/svg").attr("class","recordNodeLink_SVG") .call(this.nodeZoomBehavior); var gggg = this.DOM.recordNodeLink_SVG.append("g"); this.DOM.linkGroup = gggg.append("g").attr("class","linkGroup"); this.DOM.recordGroup = gggg.append("g").attr("class","recordGroup recordGroup_Node"); this.DOM.NodeLinkControl = this.DOM.recordDisplayWrapper.append("span").attr("class","NodeLinkControl"); var animationControl = this.DOM.NodeLinkControl.append("span").attr("class","animationControl"); animationControl.append("span").attr("class","NodeLinkAnim_Play fa fa-play") .on("click",function(){ me.nodelink_Force.start(); me.DOM.root.attr("hideLinks",true); }); animationControl.append("span").attr("class","NodeLinkAnim_Pause fa fa-pause") .on("click",function(){ me.nodelink_Force.stop(); me.DOM.root.attr("hideLinks",null); }); this.DOM.NodeLinkAnim_Refresh = this.DOM.NodeLinkControl.append("span") .attr("class","NodeLinkAnim_Refresh fa fa-refresh") .on("click",function(){ me.refreshNodeLinks(); this.style.display = null; }); }, /** -- */ initDOM_ListView: function(){ var me = this; if(this.DOM.recordGroup_List) return; this.DOM.recordGroup_List = this.DOM.recordDisplayWrapper.append("div").attr("class","recordGroup_List"); this.DOM.recordGroup = this.DOM.recordGroup_List.append("div").attr("class","recordGroup") .on("scroll",function(d){ if(this.scrollHeight-this.scrollTop-this.offsetHeight<10){ if(me.autoExpandMore===false){ me.DOM.showMore.attr("showMoreVisible",true); } else { me.showMoreRecordsOnList(); // automatically add more records } } else { me.DOM.showMore.attr("showMoreVisible",false); } me.DOM.scrollToTop.style("visibility", this.scrollTop>0?"visible":"hidden"); me.DOM.adjustSortColumnWidth.style("top",(this.scrollTop-2)+"px") }); this.DOM.adjustSortColumnWidth = this.DOM.recordGroup.append("div") .attr("class","adjustSortColumnWidth dragWidthHandle") .on("mousedown", function (d, i) { if(d3.event.which !== 1) return; // only respond to left-click me.browser.DOM.root.style('cursor','ew-resize'); var _this = this; var mouseDown_x = d3.mouse(document.body)[0]; var mouseDown_width = me.sortColWidth; me.browser.DOM.pointerBlock.attr("active",""); me.browser.DOM.root.on("mousemove", function() { _this.setAttribute("dragging",""); me.setSortColumnWidth(mouseDown_width+(d3.mouse(document.body)[0]-mouseDown_x)); }).on("mouseup", function(){ me.browser.DOM.root.style('cursor','default'); me.browser.DOM.pointerBlock.attr("active",null); me.browser.DOM.root.on("mousemove", null).on("mouseup", null); _this.removeAttribute("dragging"); }); d3.event.preventDefault(); }); this.DOM.showMore = this.DOM.root.append("div").attr("class","showMore") .attr("showMoreVisible",false) .on("mouseenter",function(){ d3.select(this).selectAll(".loading_dots").attr("anim",true); }) .on("mouseleave",function(){ d3.select(this).selectAll(".loading_dots").attr("anim",null); }) .on("click",function(){ me.showMoreRecordsOnList(); }); this.DOM.showMore.append("span").attr("class","MoreText").html("Show More"); this.DOM.showMore.append("span").attr("class","Count CountAbove"); this.DOM.showMore.append("span").attr("class","Count CountBelow"); this.DOM.showMore.append("span").attr("class","loading_dots loading_dots_1"); this.DOM.showMore.append("span").attr("class","loading_dots loading_dots_2"); this.DOM.showMore.append("span").attr("class","loading_dots loading_dots_3"); }, /** -- */ initDOM_RecordViewHeader: function(){ var me=this; this.DOM.recordColorScaleBins = this.DOM.recordDisplayHeader.append("div").attr("class","recordColorScale") .each(function(){ this.tipsy = new Tipsy(this, {gravity: 'w', title: "Change color scale"}); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .on("click",function(){ me.browser.mapColorTheme = (me.browser.mapColorTheme==="converge") ? "diverge" : "converge"; me.refreshRecordColors(); me.map_refreshColorScaleBins(); me.sortingOpt_Active.map_refreshColorScale(); }) .selectAll(".recordColorScaleBin").data([0,1,2,3,4,5,6,7,8]) .enter().append("div").attr("class","recordColorScaleBin"); this.map_refreshColorScaleBins(); this.DOM.recordDisplayHeader.append("div").attr("class","itemRank_control fa") .each(function(){ this.tipsy = new Tipsy(this, {gravity: 'n', title: function(){ return (me.showRank?"Hide":"Show")+" ranking"; }}); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .on("click",function(){ me.setShowRank(!me.showRank); }); this.initDOM_SortSelect(); this.initDOM_GlobalTextSearch(); this.DOM.recordDisplayHeader.append("div").attr("class","buttonRecordViewRemove fa fa-times") .each(function(){ this.tipsy = new Tipsy(this, {gravity: 'ne', title: kshf.lang.cur.RemoveRecords }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout", function(){ this.tipsy.hide(); }) .on("click", function(){ me.removeRecordViewSummary(); }); var x= this.DOM.recordDisplayHeader.append("span"); x.append("span").text("View: ").attr("class","recordView_HeaderSet"); x.selectAll("span.fa").data([ {v:"Map", i:"globe"}, {v:"List", i:"list-ul"}, {v:"NodeLink", i:"share-alt"} ] ).enter() .append("span").attr("class", function(d){ return "recordView_Set"+d.v+" fa fa-"+d.i; }) .each(function(d){ this.tipsy = new Tipsy(this, {gravity: 'ne', title: function(){ return "View as "+d.v; } }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout", function(){ this.tipsy.hide(); }) .on("click", function(d){ me.viewAs(d.v); }); this.DOM.scrollToTop = this.DOM.recordDisplayHeader.append("div").attr("class","scrollToTop fa fa-arrow-up") .each(function(){ this.tipsy = new Tipsy(this, {gravity: 'e', title: kshf.lang.cur.ScrollToTop }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout", function(){ this.tipsy.hide(); }) .on("click",function(){ kshf.Util.scrollToPos_do(me.DOM.recordGroup[0][0],0); }); }, /** -- */ setSpatialFilter: function(){ var me=this; this.spatialFilter = this.browser.createFilter({ title: function(){return "Region"}, onClear: function(){ me.DOM.root.select(".spatialQuery_Filter").attr("active",null); }, onFilter: function(){ me.DOM.root.select(".spatialQuery_Filter").attr("active",true); var query = []; var bounds = me.spatialQuery.filter._bounds; me.browser.records.forEach(function(record){ if(record._geoBounds_ === undefined) { record.setFilterCache(this.filterID, false); return; } // already have "bounds" variable record.setFilterCache(this.filterID, kshf.intersects(record._geoBounds_, bounds)); },this); }, filterView_Detail: function(){ return ""; } }); }, /** -- */ setTextFilter: function(){ var me=this; this.textFilter = this.browser.createFilter({ title: function(){ return me.textSearchSummary.summaryName; }, hideCrumb: true, onClear: function(){ me.DOM.recordTextSearch.select(".clearSearchText").style('display','none'); me.DOM.recordTextSearch.selectAll(".textSearchMode").style("display","none"); me.DOM.recordTextSearch.select("input")[0][0].value = ""; }, onFilter: function(){ me.DOM.recordTextSearch.select(".clearSearchText").style('display','inline-block'); var query = []; // split the input by " character var processed = this.filterStr.split('"'); processed.forEach(function(block,i){ if(i%2===0) { block.split(/\s+/).forEach(function(q){ query.push(q)}); } else { query.push(block); } }); // Remove the empty strings query = query.filter(function(v){ return v!==""}); me.DOM.recordTextSearch.selectAll(".textSearchMode").style("display",query.length>1?"inline-block":"none"); // go over all the records in the list, search each keyword separately // If some search matches, return true (any function) var summaryFunc = me.textSearchSummary.summaryFunc; me.browser.records.forEach(function(record){ var f; if(me.textFilter.multiMode==='or') f = ! query.every(function(v_i){ var v = summaryFunc.call(record.data,record); if(v===null || v===undefined) return true; return (""+v).toLowerCase().indexOf(v_i)===-1; }); if(me.textFilter.multiMode==='and') f = query.every(function(v_i){ var v = summaryFunc.call(record.data,record); return (""+v).toLowerCase().indexOf(v_i)!==-1; }); record.setFilterCache(this.filterID,f); },this); }, }); this.textFilter.multiMode = 'and'; }, /** -- */ initDOM_GlobalTextSearch: function(){ var me=this; this.DOM.recordTextSearch = this.DOM.recordDisplayHeader.append("span").attr("class","recordTextSearch"); var x= this.DOM.recordTextSearch.append("div").attr("class","dropZone_textSearch") .on("mouseenter",function(){ this.style.backgroundColor = "rgb(255, 188, 163)"; }) .on("mouseleave",function(){ this.style.backgroundColor = ""; }) .on("mouseup" ,function(){ me.setTextSearchSummary(me.movedSummary); }); x.append("div").attr("class","dropZone_textSearch_text").text("Text search"); this.DOM.recordTextSearch.append("i").attr("class","fa fa-search searchIcon"); this.DOM.recordTextSearch.append("input").attr("class","mainTextSearch_input") .on("keydown",function(){ var x = this; if(this.timer) clearTimeout(this.timer); this.timer = setTimeout( function(){ me.textFilter.filterStr = x.value.toLowerCase(); if(me.textFilter.filterStr!=="") { me.textFilter.addFilter(); } else { me.textFilter.clearFilter(); } x.timer = null; }, 750); }); this.DOM.recordTextSearch.append("span").attr("class","fa fa-times-circle clearSearchText") .attr("mode","and") .each(function(){ this.tipsy = new Tipsy(this, {gravity: 'ne', title: kshf.lang.cur.RemoveFilter }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout",function(){ this.tipsy.hide(); }) .on("click",function() { me.textFilter.clearFilter(); }); this.DOM.recordTextSearch.selectAll(".textSearchMode").data(["and","or"]).enter() .append("span") .attr("class","textSearchMode") .attr("mode",function(d){return d;}) .each(function(d){ this.tipsy = new Tipsy(this, { gravity: 'ne', title: (d==="and") ? "All words<br> must appear." : "At least one word<br> must appear." }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout",function(){ this.tipsy.hide(); }) .on("click",function(d) { me.DOM.recordTextSearch.attr("mode",d); me.textFilter.multiMode = d; me.textFilter.addFilter(); }); }, /** -- */ initDOM_NodeLinkView_Settings: function(){ var me=this; this.DOM.NodeLinkAttrib = this.DOM.recordDisplayHeader.append("span").attr("class","NodeLinkAttrib"); this.DOM.NodeLinkAttrib.append("span").attr("class","fa fa-share-alt NodeLinkAttribIcon") .each(function(d){ this.tipsy = new Tipsy(this, { gravity: 'e', title: "Show/Hide Links" }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout",function(){ this.tipsy.hide(); }) .on("click",function(){ me.DOM.root.attr("hideLinks", me.DOM.root.attr("hideLinks")?null:true ); }); var s = this.DOM.NodeLinkAttrib.append("select") .on("change",function(){ var s = this.selectedOptions[0].__data__; // TODO: change the network calculation });; s.selectAll("option").data(this.config.linkBy).enter().append("option").text(function(d){ return d; }); }, /** -- */ setRecordViewSummary: function(summary){ if(summary===undefined || summary===null) { this.removeRecordViewSummary(); return; } if(this.recordViewSummary===summary) return; if(this.recordViewSummary) this.removeRecordViewSummary(); this.DOM.root.attr('hasRecordView',true); this.recordViewSummary = summary; this.recordViewSummary.isRecordView = true; this.recordViewSummary.refreshNuggetDisplay(); if(this.displayType==="list" || this.displayType==="grid"){ this.sortRecords(); this.refreshRecordDOM(); this.setSortColumnWidth(this.config.sortColWidth); } else if(this.displayType==='map'){ this.refreshRecordDOM(); } else if(this.displayType==='nodelink'){ this.setNodeLink(); this.refreshRecordDOM(); } this.browser.DOM.root.attr("recordDisplayMapping",this.getRecordEncoding()); // "sort" or "color" }, /** -- */ removeRecordViewSummary: function(){ if(this.recordViewSummary===null) return; this.DOM.root.attr("hasRecordView",false); this.recordViewSummary.isRecordView = false; this.recordViewSummary.refreshNuggetDisplay(); this.recordViewSummary = null; this.browser.DOM.root.attr("recordDisplayMapping",null); }, /** -- */ setTextSearchSummary: function(summary){ if(summary===undefined || summary===null) return; this.textSearchSummary = summary; this.textSearchSummary.isTextSearch = true; this.DOM.recordTextSearch .attr("isActive",true) .select("input").attr("placeholder", kshf.lang.cur.Search+": "+summary.summaryName); this.setTextFilter(); }, /** -- */ addSortingOption: function(summary){ // If parameter summary is already a sorting option, nothing else to do if(this.sortingOpts.some(function(o){ return o===summary; })) return; this.sortingOpts.push(summary); summary.sortLabel = summary.summaryFunc; summary.sortInverse = false; summary.sortFunc = this.getSortFunc(summary.summaryFunc); this.prepSortingOpts(); this.refreshSortingOptions(); }, /** -- */ initDOM_SortSelect: function(){ var me=this; this.DOM.header_listSortColumn = this.DOM.recordDisplayHeader.append("div").attr("class","header_listSortColumn"); this.DOM.listSortOptionSelect = this.DOM.header_listSortColumn.append("select") .attr("class","listSortOptionSelect") .on("change", function(){ me.setSortingOpt_Active(this.selectedIndex); }); this.refreshSortingOptions(); this.DOM.removeSortOption = this.DOM.recordDisplayHeader .append("span").attr("class","removeSortOption_wrapper") .append("span").attr("class","removeSortOption fa") .each(function(){ this.tipsy = new Tipsy(this, {gravity: 'n', title: "Remove current sorting option" }); }) .style("display",(this.sortingOpts.length<2)?"none":"inline-block") .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout",function(d,i){ this.tipsy.hide(); }) .on("click",function(){ var index=-1; me.sortingOpts.forEach(function(o,i){ if(o===me.sortingOpt_Active) index=i; }) if(index!==-1){ me.sortingOpts.splice(index,1); if(index===me.sortingOpts.length) index--; me.setSortingOpt_Active(index); me.refreshSortingOptions(); me.DOM.listSortOptionSelect[0][0].selectedIndex = index; } }); this.DOM.recordDisplayHeader.append("span").attr("class","sortColumn sortButton fa") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'w', title: kshf.lang.cur.ReverseOrder }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout",function(){ this.tipsy.hide(); }) .on("click",function(d){ // NOTE: Only on list/grid views me.sortingOpt_Active.inverse = me.sortingOpt_Active.inverse?false:true; this.setAttribute("inverse",me.sortingOpt_Active.inverse); // TODO: Do not show no-value items on top, reversing needs to be a little smarter. me.browser.records.reverse(); me.updateRecordRanks(); me.refreshRecordDOM(); me.refreshRecordRanks(me.DOM.recordRanks); me.DOM.kshfRecords = me.DOM.recordGroup.selectAll(".kshfRecord") .data(me.browser.records, function(record){ return record.id(); }) .order(); kshf.Util.scrollToPos_do(me.DOM.recordGroup[0][0],0); }); }, /** -- */ refreshRecordRanks: function(d3_selection){ if(!this.showRank) return; // Do not refresh if not shown... d3_selection.text(function(record){ return (record.recordRank<0)?"":record.recordRank+1; }); }, /** -- */ setSortColumnWidth: function(v){ if(this.displayType!=='list') return; this.sortColWidth = Math.max(Math.min(v,110),30); // between 30 and 110 pixels this.DOM.recordsSortCol.style("width",this.sortColWidth+"px"); this.refreshAdjustSortColumnWidth(); }, /** -- */ refreshRecordSortLabels: function(d3_selection){ if(this.displayType!=="list") return; // Only list-view allows sorting if(d3_selection===undefined) d3_selection = this.DOM.recordsSortCol; var me=this; var labelFunc=this.sortingOpt_Active.sortLabel; var sortColformat = d3.format(".s"); if(this.sortingOpt_Active.isTimeStamp()){ sortColformat = d3.time.format("%Y"); } d3_selection.html(function(d){ var s=labelFunc.call(d.data,d); if(s===null || s===undefined) return ""; this.setAttribute("title",s); if(typeof s!=="string") s = sortColformat(s); return me.sortingOpt_Active.printWithUnitName(s); }); }, /** -- */ refreshSortingOptions: function(){ if(this.DOM.listSortOptionSelect===undefined) return; this.DOM.listSortOptionSelect.selectAll("option").remove(); var me=this; var x = this.DOM.listSortOptionSelect.selectAll("option").data(this.sortingOpts); x.enter().append("option").html(function(summary){ return summary.summaryName; }) x.exit().each(function(summary){ summary.sortingSummary = false; }); this.sortingOpts.forEach(function(summary, i){ if(summary===me.sortingOpt_Active) { var DOM = me.DOM.listSortOptionSelect[0][0]; DOM.selectedIndex = i; if(DOM.dispatchEvent && (!bowser.msie && !bowser.msedge)) DOM.dispatchEvent(new Event('change')); } }); }, /** -- */ prepSortingOpts: function(){ this.sortingOpts.forEach(function(sortOpt,i){ if(sortOpt.summaryName) return; // It already points to a summary if(typeof(sortOpt)==="string"){ sortOpt = { title: sortOpt }; } // Old API if(sortOpt.title) sortOpt.name = sortOpt.title; var summary = this.browser.summaries_by_name[sortOpt.name]; if(summary===undefined){ if(typeof(sortOpt.value)==="string"){ summary = this.browser.changeSummaryName(sortOpt.value,sortOpt.name); } else{ summary = this.browser.createSummary(sortOpt.name,sortOpt.value, "interval"); if(sortOpt.unitName){ summary.setUnitName(sortOpt.unitName); } } } summary.sortingSummary = true; summary.sortLabel = sortOpt.label || summary.summaryFunc; summary.sortInverse = sortOpt.inverse || false; summary.sortFunc = sortOpt.sortFunc || this.getSortFunc(summary.summaryFunc); this.sortingOpts[i] = summary; },this); if(this.DOM.removeSortOption) this.DOM.removeSortOption.style("display",(this.sortingOpts.length<2)?"none":"inline-block"); }, /** -- */ alphabetizeSortingOptions: function(){ this.sortingOpts.sort(function(s1,s2){ return s1.summaryName.localeCompare(s2.summaryName, { sensitivity: 'base' }); }); }, /** -- */ setSortingOpt_Active: function(index){ if(this.sortingOpt_Active){ var curHeight = this.sortingOpt_Active.getHeight(); this.sortingOpt_Active.clearAsRecordSorting(); this.sortingOpt_Active.setHeight(curHeight); } if(typeof index === "number"){ if(index<0 || index>=this.sortingOpts.length) return; this.sortingOpt_Active = this.sortingOpts[index]; } else if(index instanceof kshf.Summary_Base){ this.sortingOpt_Active = index; } { var curHeight = this.sortingOpt_Active.getHeight(); this.sortingOpt_Active.setAsRecordSorting(); this.sortingOpt_Active.setHeight(curHeight); } // If the record view summary is not set, no need to proceed with sorting or visual if(this.recordViewSummary===null) return; if(this.DOM.root===undefined) return; if(this.displayType==="map" || this.displayType==="nodelink"){ this.refreshRecordColors(); } else { this.sortRecords(); if(this.DOM.recordGroup===undefined) return; this.refreshRecordDOM(); this.refreshRecordRanks(this.DOM.recordRanks); kshf.Util.scrollToPos_do(this.DOM.recordGroup[0][0],0); this.DOM.kshfRecords = this.DOM.recordGroup.selectAll(".kshfRecord") .data(this.browser.records, function(record){ return record.id(); }) .order(); this.refreshRecordSortLabels(); } }, /** -- */ refreshAdjustSortColumnWidth: function(){ if(this.displayType!=="list") return; this.DOM.adjustSortColumnWidth.style("left", (this.sortColWidth-2)+(this.showRank?15:0)+"px") }, /** -- */ setShowRank: function(v){ this.showRank = v; this.DOM.root.attr('showRank',this.showRank); this.refreshRecordRanks(this.DOM.recordRanks); this.refreshAdjustSortColumnWidth(); }, /** -- */ refreshNodeLinks: function(){ this.generateNodeLinks(); this.nodelink_nodes = this.browser.records.filter(function(record){ return record.isWanted; }); this.nodelink_Force .nodes(this.nodelink_nodes) .links(this.nodelink_links) .start(); if(this.nodelink_links.length>1000) this.DOM.root.attr("hideLinks",true); }, /** -- */ generateNodeLinks: function(){ this.nodelink_links = []; var recordsIndexed = kshf.dt_id[browser.primaryTableName]; var linkAttribName = this.config.linkBy[0]; this.browser.records.forEach(function(recordFrom){ if(!recordFrom.isWanted) return; var links = recordFrom.data[linkAttribName]; if(links) { links.forEach(function(recordTo_id){ var recordTo = recordsIndexed[recordTo_id]; if(recordTo) { if(!recordTo.isWanted) return; this.nodelink_links.push({source:recordFrom, target: recordTo}); } },this); } },this); }, /** -- */ initializeNetwork: function(){ this.nodelink_Force.size([this.curWidth, this.curHeight]).start(); if(this.nodelink_links.length>1000) this.DOM.root.attr("hideLinks",true); this.DOM.root.attr("NodeLinkState","started"); }, refreshNodeVis: function(){ if(this.DOM.recordLinks===undefined) return; // position & direction of the line this.DOM.recordLinks.attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); // position of the record var s = 1/this.nodeZoomBehavior.scale(); this.DOM.kshfRecords.attr("transform", function(d){ return "translate("+d.x+","+d.y+") scale("+s+")"; }); }, /** -- */ setNodeLink: function(){ var me=this; this.browser.records.forEach(function(record){ record.DOM.links_To = []; record.DOM.links_From = []; record.links_To = []; record.links_From = []; }); this.nodelink_links = []; var recordsIndexed = kshf.dt_id[browser.primaryTableName]; var linkAttribName = this.config.linkBy[0]; this.browser.records.forEach(function(recordFrom){ var links = recordFrom.data[linkAttribName]; if(links) { links.forEach(function(recordTo_id){ var recordTo = recordsIndexed[recordTo_id]; if(recordTo) { recordFrom.links_To.push(recordTo); recordTo.links_From.push(recordFrom); } },this); } },this); this.generateNodeLinks(); this.DOM.recordLinks = this.DOM.linkGroup.selectAll(".recordLink").data(this.nodelink_links) .enter().append("line").attr("class", "recordLink") .each(function(link){ var recordFrom = link.source; var recordTo = link.target; recordFrom.DOM.links_To.push(this); recordTo.DOM.links_From.push(this); }); this.nodelink_Force = d3.layout.force() .charge(-60) .gravity(0.8) .alpha(0.4) .nodes(this.browser.records) .links(this.nodelink_links) .on("start",function(){ me.DOM.root.attr("NodeLinkState","started"); me.DOM.root.attr("hideLinks",true); }) .on("end", function(){ me.DOM.root.attr("NodeLinkState","stopped"); me.DOM.root.attr("hideLinks",null); }) .on("tick", function(){ me.refreshNodeVis(); }); }, /** -- */ refreshRecordColors: function(){ if(!this.recordViewSummary) return; var me=this; var s_f = this.sortingOpt_Active.summaryFunc; var s_log; if(this.sortingOpt_Active.scaleType==='log'){ this.recordColorScale = d3.scale.log(); s_log = true; } else { this.recordColorScale = d3.scale.linear(); s_log = false; } var min_v = this.sortingOpt_Active.intervalRange.min; var max_v = this.sortingOpt_Active.intervalRange.max; if(this.sortingOpt_Active.intervalRange.active){ min_v = this.sortingOpt_Active.intervalRange.active.min; max_v = this.sortingOpt_Active.intervalRange.active.max; } if(min_v===undefined) min_v = d3.min(this.browser.records, function(d){ return s_f.call(d.data); }); if(max_v===undefined) max_v = d3.max(this.browser.records, function(d){ return s_f.call(d.data); }); this.recordColorScale .range([0, 9]) .domain( [min_v, max_v] ); this.colorQuantize = d3.scale.quantize() .domain([0,9]) .range(kshf.colorScale[me.browser.mapColorTheme]); var undefinedFill = (this.displayType==="map") ? "url(#diagonalHatch)" : "white"; var fillFunc = function(d){ var v = s_f.call(d.data); if(s_log && v<=0) v=undefined; if(v===undefined) return undefinedFill; var vv = me.recordColorScale(v); if(me.sortingOpt_Active.invertColorScale) vv = 9 - vv; return me.colorQuantize(vv); }; if(this.displayType==="map") { this.DOM.kshfRecords.each(function(d){ var v = s_f.call(d.data); if(s_log && v<=0) v=undefined; if(v===undefined) { this.style.fill = undefinedFill; this.style.stroke = "gray"; return; } var vv = me.recordColorScale(v); if(me.sortingOpt_Active.invertColorScale) vv = 9 - vv; this.style.fill = me.colorQuantize(vv); this.style.stroke = me.colorQuantize(vv>=5?0:9); }); } if(this.displayType==="nodelink") { this.DOM.kshfRecords.selectAll("circle").style("fill", function(d){ var v = s_f.call(d.data); if(s_log && v<=0) v=undefined; if(v===undefined) return undefinedFill; var vv = me.recordColorScale(v); if(me.sortingOpt_Active.invertColorScale) vv = 9 - vv; return me.colorQuantize(vv); }); } }, /** -- */ highlightRelated: function(recordFrom){ recordFrom.DOM.links_To.forEach(function(dom){ dom.style.stroke = "green"; dom.style.strokeOpacity = 1; dom.style.display = "block"; }); var links = recordFrom.data[this.config.linkBy[0]]; if(!links) return; var recordsIndexed = kshf.dt_id[browser.primaryTableName]; links.forEach(function(recordTo_id){ var recordTo = recordsIndexed[recordTo_id]; if(recordTo) { if(recordTo.DOM.record){ d3.select(recordTo.DOM.record.parentNode.appendChild(recordTo.DOM.record)); recordTo.DOM.record.setAttribute("selection","related"); } } },this); }, /** -- */ unhighlightRelated: function(recordFrom){ recordFrom.DOM.links_To.forEach(function(dom){ dom.style.stroke = null; dom.style.strokeOpacity = null; dom.style.display = null; }); var links = recordFrom.data[this.config.linkBy[0]]; if(!links) return; var recordsIndexed = kshf.dt_id[browser.primaryTableName]; links.forEach(function(recordTo_id){ var recordTo = recordsIndexed[recordTo_id]; if(recordTo) { if(recordTo.DOM.record){ recordTo.DOM.record.removeAttribute("selection"); } } },this); }, /** Insert records into the UI, called once on load */ refreshRecordDOM: function(){ var me=this, x; var records = (this.displayType==="map")? this.browser.records : this.browser.records.filter(function(record){ return record.isWanted && (record.recordRank<me.maxVisibleItems); }); var newRecords = this.DOM.recordGroup.selectAll(".kshfRecord") .data(records, function(record){ return record.id(); }).enter(); var nodeType = "div"; if(this.displayType==='map'){ nodeType = 'path'; } else if(this.displayType==='nodelink'){ nodeType = 'g'; } // Shared structure per record view newRecords = newRecords .append( nodeType ) .attr('class','kshfRecord') .attr('details',false) .attr("rec_compared",function(record){ return record.selectCompared_str?record.selectCompared_str:null;}) .attr("id",function(record){ return "kshfRecord_"+record.id(); }) // can be used to apply custom CSS .each(function(record){ record.DOM.record = this; if(me.displayType==="map"){ this.tipsy = new Tipsy(this, { gravity: 'e', title: function(){ var s=""; return ""+ "<span class='mapItemName'>"+me.recordViewSummary.summaryFunc.call(record.data,record)+"</span>"+ "<span class='mapTooltipLabel'>"+me.sortingOpt_Active.summaryName+"</span>: "+ "<span class='mapTooltipValue'>"+me.sortingOpt_Active.printWithUnitName( me.sortingOpt_Active.summaryFunc.call(record.data,record))+"</span>"; } }); } }) .on("mouseenter",function(record){ if(this.tipsy) { this.tipsy.show(); this.tipsy.jq_tip[0].style.left = (d3.event.pageX-this.tipsy.tipWidth-10)+"px"; this.tipsy.jq_tip[0].style.top = (d3.event.pageY-this.tipsy.tipHeight/2)+"px"; } if(me.browser.mouseSpeed<0.2) { if(me.displayType==="nodelink") me.highlightRelated(record); record.highlightRecord(); } else { // mouse is moving fast, should wait a while... this.highlightTimeout = window.setTimeout( function(){ if(me.displayType==="nodelink") me.highlightRelated(record); record.highlightRecord(); }, me.browser.mouseSpeed*300); } if(me.displayType==="map" || me.displayType==="nodelink"){ d3.select(this.parentNode.appendChild(this)); } d3.event.stopPropagation(); d3.event.preventDefault(); }) .on("mouseleave",function(record){ if(this.highlightTimeout) window.clearTimeout(this.highlightTimeout); if(this.tipsy) this.tipsy.hide(); if(me.displayType==="nodelink") me.unhighlightRelated(record); record.unhighlightRecord(); }) .on("mousedown", function(){ this._mousemove = false; }) .on("mousemove", function(){ this._mousemove = true; if(this.tipsy){ this.tipsy.jq_tip[0].style.left = (d3.event.pageX-this.tipsy.tipWidth-10)+"px"; this.tipsy.jq_tip[0].style.top = (d3.event.pageY-this.tipsy.tipHeight/2)+"px"; } }) .on("click",function(d){ // Do not show the detail view if the mouse was used to drag the map if(this._mousemove) return; if(me.displayType==="map" || me.displayType==='nodelink'){ me.browser.updateItemZoomText(d); } }); if(this.displayType==="list" || this.displayType==="grid"){ // RANK x = newRecords.append("span").attr("class","recordRank") .each(function(d){ this.tipsy = new Tipsy(this, { gravity: 'e', title: function(){ return kshf.Util.ordinal_suffix_of((d.recordRank+1)); } }); }) .on("mouseenter",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }); this.refreshRecordRanks(x); // SORTING VALUE LABELS if(this.displayType==='list'){ x = newRecords.append("div").attr("class","recordSortCol").style("width",this.sortColWidth+"px"); this.refreshRecordSortLabels(x); } // TOGGLE DETAIL newRecords.append("div").attr("class","recordToggleDetail") .each(function(d){ this.tipsy = new Tipsy(this, { gravity:'s', title: function(){ if(me.detailsToggle==="one" && this.displayType==='list') return d.showDetails===true?"Show less":"Show more"; return kshf.lang.cur.ShowMoreInfo; } }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .append("span").attr("class","item_details_toggle fa") .on("click", function(record){ this.parentNode.tipsy.hide(); if(me.detailsToggle==="one" && me.displayType==='list'){ record.setRecordDetails(!record.showDetails); } if(me.detailsToggle==="zoom"){ me.browser.updateItemZoomText(record); } }); // Insert the custom content! // Note: the value was already evaluated and stored in the record object var recordViewID = this.recordViewSummary.summaryID; newRecords.append("div").attr("class","content") .html(function(record){ return me.recordViewSummary.summaryFunc.call(record.data, record); }); // Fixes ordering problem when new records are made visible on the list // TODO: Try to avoid this. this.DOM.recordGroup.selectAll(".kshfRecord") .data(records, function(record){ return record.id(); }) .order(); } if(this.displayType==="nodelink"){ newRecords.append("circle").attr("r",4); newRecords.append("text").attr("class","kshfRecord_label") .attr("dy",4).attr("dx",6) .html(function(record){ return me.recordViewSummary.summaryFunc.call(record.data, record); }); } // Call the domCb function for all the records that have been inserted to the page if(this.config.domCb) { newRecords.each(function(record){ me.config.domCb.call(record.data,record); }); } this.DOM.kshfRecords = this.DOM.recordGroup.selectAll(".kshfRecord"); if(this.displayType==="map") { this.map_zoomToActive(); this.map_projectRecords(); this.refreshRecordColors(); } else if(this.displayType==="nodelink"){ this.refreshRecordColors(); } else { this.DOM.recordsSortCol = this.DOM.recordGroup.selectAll(".recordSortCol"); this.DOM.recordRanks = this.DOM.recordGroup.selectAll(".recordRank"); } this.updateRecordVisibility(); }, /** -- */ showMoreRecordsOnList: function(){ if(this.displayType==="map") return; this.DOM.showMore.attr("showMoreVisible",false); this.maxVisibleItems += Math.min(this.maxVisibleItems,250); this.refreshRecordDOM(); }, /** Sort all records given the active sort option * Records are only sorted on init & when active sorting option changes. * They are not resorted on filtering. ** Filtering does not affect record sorting. */ sortRecords: function(){ var sortValueFunc = this.sortingOpt_Active.summaryFunc; var sortFunc = this.sortingOpt_Active.sortFunc; var inverse = this.sortingOpt_Active.sortInverse; this.browser.records.sort( function(record_A,record_B){ // Put filtered/remove data to later position // !! Don't do above!! Then, when you filter set, you'd need to re-order // Now, you don't need to re-order after filtering, which is record_A nice property to have. var v_a = sortValueFunc.call(record_A.data,record_A); var v_b = sortValueFunc.call(record_B.data,record_B); if(isNaN(v_a)) v_a = undefined; if(isNaN(v_b)) v_b = undefined; if(v_a===null) v_a = undefined; if(v_b===null) v_b = undefined; if(v_a===undefined && v_b!==undefined) return 1; if(v_b===undefined && v_a!==undefined) return -1; if(v_b===undefined && v_a===undefined) return 0; var dif=sortFunc(v_a,v_b); if(dif===0) dif=record_B.id()-record_A.id(); if(inverse) return -dif; return dif; // use unique IDs to add sorting order as the last option } ); this.updateRecordRanks(); }, /** Returns the sort value type for given sort Value function */ getSortFunc: function(sortValueFunc){ // 0: string, 1: date, 2: others var sortValueFunction, same; // find appropriate sortvalue type for(var k=0, same=0; true ; k++){ if(same===3 || k===this.browser.records.length) break; var item = this.browser.records[k]; var f = sortValueFunc.call(item.data,item); var sortValueType_temp2; switch(typeof f){ case 'string': sortValueType_temp2 = kshf.Util.sortFunc_List_String; break; case 'number': sortValueType_temp2 = kshf.Util.sortFunc_List_Number; break; case 'object': if(f instanceof Date) sortValueType_temp2 = kshf.Util.sortFunc_List_Date; else sortValueType_temp2 = kshf.Util.sortFunc_List_Number; break; default: sortValueType_temp2 = kshf.Util.sortFunc_List_Number; break; } if(sortValueType_temp2===sortValueFunction){ same++; } else { sortValueFunction = sortValueType_temp2; same=0; } } return sortValueFunction; }, /** Updates visibility of individual records */ updateRecordVisibility: function(){ if(this.DOM.kshfRecords===undefined) return; var me = this; var visibleItemCount=0; if(me.displayType==="map"){ this.DOM.kshfRecords.each(function(record){ this.style.opacity = record.isWanted?0.9:0.2; this.style.pointerEvents = record.isWanted?"":"none"; this.style.display = "block"; // Have this for now bc switching views can invalidate display setting }); } else if(me.displayType==="nodelink"){ this.browser.records.forEach(function(record){ if(record.DOM.record) record.DOM.record.style.display = record.isWanted?"block":"none"; }); this.DOM.recordLinks.each(function(link){ var recordFrom = link.source; var recordTo = link.target; this.style.display = (!recordFrom.isWanted || !recordTo.isWanted) ? "none" : null; }); } else { this.DOM.kshfRecords.each(function(record){ var isVisible = (record.recordRank>=0) && (record.recordRank<me.maxVisibleItems); if(isVisible) visibleItemCount++; this.style.display = isVisible?null:'none'; }); var hiddenItemCount = this.browser.recordsWantedCount-visibleItemCount; this.DOM.showMore.select(".CountAbove").html("&#x25B2;"+visibleItemCount+" shown"); this.DOM.showMore.select(".CountBelow").html(hiddenItemCount+" below&#x25BC;"); }; }, /** -- */ updateAfterFilter: function(){ if(this.recordViewSummary===null) return; if(this.displayType==="map") { this.updateRecordVisibility(); //this.map_zoomToActive(); } else if(this.displayType==="nodelink") { this.updateRecordVisibility(); this.DOM.NodeLinkAnim_Refresh.style('display','inline-block'); // this.refreshNodeLinks(); } else { var me=this; var startTime = null; var scrollDom = this.DOM.recordGroup[0][0]; var scrollInit = scrollDom.scrollTop; var easeFunc = d3.ease('cubic-in-out'); var animateToTop = function(timestamp){ var progress; if(startTime===null) startTime = timestamp; // complete animation in 500 ms progress = (timestamp - startTime)/1000; scrollDom.scrollTop = (1-easeFunc(progress))*scrollInit; if(scrollDom.scrollTop!==0){ window.requestAnimationFrame(animateToTop); return; } me.updateRecordRanks(); me.refreshRecordDOM(); me.refreshRecordRanks(me.DOM.recordRanks); }; window.requestAnimationFrame(animateToTop); } }, /** -- */ updateRecordRanks: function(){ var wantedCount = 0; var unwantedCount = 1; this.browser.records.forEach(function(record){ record.recordRank_pre = record.recordRank; if(record.isWanted){ record.recordRank = wantedCount; wantedCount++; } else { record.recordRank = -unwantedCount; unwantedCount++; } }); this.maxVisibleItems = this.maxVisibleItems_Default; }, /** -- */ viewAs: function(d){ d = d.toLowerCase(); this.displayType = d; this.DOM.root.attr("displayType",this.displayType); if(this.displayType==="map"){ this.initDOM_MapView(); this.DOM.recordDisplayHeader.select(".recordView_HeaderSet").style("display","inline-block"); this.DOM.root.select(".recordView_SetList").style("display","inline-block"); if(this.nodelink_Force) this.nodelink_Force.stop(); } else if(this.displayType==="nodelink"){ this.initDOM_NodeLinkView(); this.DOM.recordDisplayHeader.select(".recordView_HeaderSet").style("display","inline-block"); this.DOM.root.select(".recordView_SetList").style("display","inline-block"); } else { this.initDOM_ListView(); this.DOM.root.select(".recordView_SetList").style("display",null); if(this.nodelink_Force) this.nodelink_Force.stop(); } this.DOM.root.select(".recordView_SetMap").style("display", (this.config.geo && this.displayType!=="map") ? "inline-block" : null ); this.DOM.root.select(".recordView_SetNodeLink").style("display", (this.config.linkBy.length>0 && this.displayType!=="nodelink") ? "inline-block" : null ); if(this.recordViewSummary) { if(this.displayType==="list" || this.displayType==="grid"){ this.sortRecords(); this.refreshRecordDOM(); this.setSortColumnWidth(this.config.sortColWidth || 50); // default: 50px; } else if(this.displayType==='map'){ this.refreshRecordColors(); } else if(this.displayType==='nodelink'){ this.refreshRecordColors(); } this.updateRecordVisibility(); this.browser.DOM.root.attr("recordDisplayMapping",this.getRecordEncoding()); // "sort" or "color" } }, /** -- */ exportConfig: function(){ var c={}; c.displayType = this.displayType; if(this.textSearchSummary){ c.textSearch = this.textSearchSummary.summaryName; } if(typeof(this.recordViewSummary.summaryColumn)==="string"){ c.recordView = this.recordViewSummary.summaryColumn; } else { c.recordView = this.recordViewSummary.summaryFunc.toString(); } c.sortBy = []; browser.recordDisplay.sortingOpts.forEach(function(summary){ c.sortBy.push(summary.summaryName); }); if(c.sortBy.length===1) c.sortBy = c.sortBy[0]; c.sortColWidth = this.sortColWidth; c.detailsToggle = this.detailsToggle; return c; } }; kshf.Panel = function(options){ this.browser = options.browser; this.name = options.name; this.width_catLabel = options.width_catLabel; this.width_catBars = 0; // placeholder this.width_catMeasureLabel = 1; // placeholder this.summaries = []; this.DOM = {}; this.DOM.root = options.parentDOM.append("div") .attr("hasSummaries",false) .attr("class", "panel panel_"+options.name+ ((options.name==="left"||options.name==="right")?" panel_side":"")) ; this.initDOM_AdjustWidth(); this.initDOM_DropZone(); }; kshf.Panel.prototype = { /** -- */ getWidth_Total: function(){ if(this.name==="bottom") { var w = this.browser.getWidth_Total(); if(this.browser.authoringMode) w-=kshf.attribPanelWidth; return w; } return this.width_catLabel + this.width_catMeasureLabel + this.width_catBars + kshf.scrollWidth; }, /** -- */ addSummary: function(summary,index){ var curIndex=-1; this.summaries.forEach(function(s,i){ if(s===summary) curIndex=i; }); if(curIndex===-1){ // summary is new to this panel if(index===this.summaries.length) this.summaries.push(summary); else this.summaries.splice(index,0,summary); this.DOM.root.attr("hasSummaries",true); this.updateWidth_QueryPreview(); this.refreshAdjustWidth(); } else { // summary was in the panel. Change position this.summaries.splice(curIndex,1); this.summaries.splice(index,0,summary); } this.summaries.forEach(function(s,i){ s.panelOrder = i; }); this.addDOM_DropZone(summary.DOM.root[0][0]); this.refreshAdjustWidth(); }, /** -- */ removeSummary: function(summary){ var indexFrom = -1; this.summaries.forEach(function(s,i){ if(s===summary) indexFrom = i; }); if(indexFrom===-1) return; // given summary is not within this panel var toRemove=this.DOM.root.selectAll(".dropZone_between_wrapper")[0][indexFrom]; toRemove.parentNode.removeChild(toRemove); this.summaries.splice(indexFrom,1); this.summaries.forEach(function(s,i){ s.panelOrder = i; }); this.refreshDropZoneIndex(); if(this.summaries.length===0) { this.DOM.root//.attr("hasSummaries",false); .attr("hasSummaries",false); } else { this.updateWidth_QueryPreview(); } summary.panel = undefined; this.refreshAdjustWidth(); }, /** -- */ addDOM_DropZone: function(beforeDOM){ var me=this; var zone; if(beforeDOM){ zone = this.DOM.root.insert("div",function(){return beforeDOM;}); } else { zone = this.DOM.root.append("div"); } zone.attr("class","dropZone_between_wrapper") .on("mouseenter",function(){ this.setAttribute("hovered",true); this.children[0].setAttribute("readyToDrop",true); }) .on("mouseleave",function(){ this.setAttribute("hovered",false); this.children[0].setAttribute("readyToDrop",false); }) .on("mouseup",function(){ var movedSummary = me.browser.movedSummary; if(movedSummary.panel){ // if the summary was in the panels already movedSummary.DOM.root[0][0].nextSibling.style.display = ""; movedSummary.DOM.root[0][0].previousSibling.style.display = ""; } movedSummary.addToPanel(me,this.__data__); me.browser.updateLayout(); }) ; var zone2 = zone.append("div").attr("class","dropZone dropZone_summary dropZone_between"); zone2.append("div").attr("class","dropIcon fa fa-angle-double-down"); zone2.append("div").attr("class","dropText").text("Drop summary"); this.refreshDropZoneIndex(); }, /** -- */ initDOM_DropZone: function(dom){ var me=this; this.DOM.dropZone_Panel = this.DOM.root.append("div").attr("class","dropZone dropZone_summary dropZone_panel") .attr("readyToDrop",false) .on("mouseenter",function(event){ this.setAttribute("readyToDrop",true); this.style.width = me.getWidth_Total()+"px"; }) .on("mouseleave",function(event){ this.setAttribute("readyToDrop",false); this.style.width = null; }) .on("mouseup",function(event){ // If this panel has summaries within, dropping makes no difference. if(me.summaries.length!==0) return; var movedSummary = me.browser.movedSummary; if(movedSummary===undefined) return; if(movedSummary.panel){ // if the summary was in the panels already movedSummary.DOM.root[0][0].nextSibling.style.display = ""; movedSummary.DOM.root[0][0].previousSibling.style.display = ""; } movedSummary.addToPanel(me); me.browser.updateLayout(); }) ; this.DOM.dropZone_Panel.append("span").attr("class","dropIcon fa fa-angle-double-down"); this.DOM.dropZone_Panel.append("div").attr("class","dropText").text("Drop summary"); this.addDOM_DropZone(); }, /** -- */ initDOM_AdjustWidth: function(){ if(this.name==='middle' || this.name==='bottom') return; // cannot have adjust handles for now var me=this; var root = this.browser.DOM.root; this.DOM.panelAdjustWidth = this.DOM.root.append("span") .attr("class","panelAdjustWidth") .on("mousedown", function (d, i) { if(d3.event.which !== 1) return; // only respond to left-click var adjustDOM = this; adjustDOM.setAttribute("dragging",""); root.style('cursor','ew-resize'); me.browser.DOM.pointerBlock.attr("active",""); me.browser.setNoAnim(true); var mouseDown_x = d3.mouse(document.body)[0]; var mouseDown_width = me.width_catBars; d3.select("body").on("mousemove", function() { var mouseMove_x = d3.mouse(document.body)[0]; var mouseDif = mouseMove_x-mouseDown_x; if(me.name==='right') mouseDif *= -1; var oldhideBarAxis = me.hideBarAxis; me.setWidthCatBars(mouseDown_width+mouseDif); if(me.hideBarAxis!==oldhideBarAxis){ me.browser.updateLayout_Height(); } // TODO: Adjust other panel widths }).on("mouseup", function(){ adjustDOM.removeAttribute("dragging"); root.style('cursor','default'); me.browser.DOM.pointerBlock.attr("active",null); me.browser.setNoAnim(false); // unregister mouse-move callbacks d3.select("body").on("mousemove", null).on("mouseup", null); }); d3.event.preventDefault(); }) .on("click",function(){ d3.event.stopPropagation(); d3.event.preventDefault(); }); }, /** -- */ refreshDropZoneIndex: function(){ var me = this; this.DOM.root.selectAll(".dropZone_between_wrapper") .attr("panel_index",function(d,i){ this.__data__ = i; if(i===0) return "first"; if(i===me.summaries.length) return "last"; return "middle"; }) ; }, /** -- */ refreshAdjustWidth: function(){ if(this.name==='middle' || this.name==='bottom') return; // cannot have adjust handles for now this.DOM.panelAdjustWidth.style("opacity",(this.summaries.length>0)?1:0); }, /** -- */ setTotalWidth: function(_w_){ this.width_catBars = _w_-this.width_catLabel-this.width_catMeasureLabel-kshf.scrollWidth; }, /** -- */ getNumOfOpenSummaries: function(){ return this.summaries.reduce(function(prev,cur){return prev+!cur.collapsed;},0); }, /** -- */ collapseAllSummaries: function(){ this.summaries.forEach(function(summary){ summary.setCollapsed(true); }); }, /** -- */ setWidthCatLabel: function(_w_){ console.log(_w_); _w_ = Math.max(90,_w_); // use at least 90 pixels for the category label. if(_w_===this.width_catLabel) return; var widthDif = this.width_catLabel-_w_; this.width_catLabel = _w_; this.summaries.forEach(function(summary){ if(summary.refreshLabelWidth!==undefined){ summary.refreshLabelWidth(); } }); this.setWidthCatBars(this.width_catBars+widthDif); }, /** -- */ setWidthCatBars: function(_w_){ _w_ = Math.max(_w_,0); this.hideBars = _w_<=5; this.hideBarAxis = _w_<=20; if(this.hideBars===false){ this.DOM.root.attr("hidebars",false); } else { this.DOM.root.attr("hidebars",true); } if(this.hideBarAxis===false){ this.DOM.root.attr("hideBarAxis",false); } else { this.DOM.root.attr("hideBarAxis",true); } this.width_catBars = _w_; this.updateSummariesWidth(); if(this.name!=="middle") this.browser.updateMiddlePanelWidth(); }, /** --- */ updateSummariesWidth: function(){ this.summaries.forEach(function(summary){ summary.refreshWidth(); }); }, /** --- */ updateWidth_QueryPreview: function(){ var maxTotalCount = d3.max(this.summaries, function(summary){ if(summary.getMaxAggr_Total===undefined) return 0; return summary.getMaxAggr_Total(); }); var oldPreviewWidth = this.width_catMeasureLabel; this.width_catMeasureLabel = 10; var digits = 1; while(maxTotalCount>9){ digits++; maxTotalCount = Math.floor(maxTotalCount/10); } if(digits>3) { digits = 2; this.width_catMeasureLabel+=4; // "." character is used to split. It takes some space } this.width_catMeasureLabel += digits*6; if(oldPreviewWidth!==this.width_catMeasureLabel){ this.summaries.forEach(function(summary){ if(summary.refreshLabelWidth) summary.refreshLabelWidth(); }); } }, }; /** * @constructor */ kshf.Browser = function(options){ this.options = options; if(kshf.lang.cur===null) kshf.lang.cur = kshf.lang.en; // English is Default language // BASIC OPTIONS this.summaryCount = 0; this.filterCount = 0; this.summaries = []; this.summaries_by_name = {}; this.panels = {}; this.filters = []; this.authoringMode = false; this.vizActive = { Highlighted: false, Compared_A: false, Compared_B: false, Compared_C: false }; this.ratioModeActive = false; this.percentModeActive = false; this.isFullscreen = false; this.highlightSelectedSummary = null; this.highlightCrumbTimeout_Hide = undefined; this.showDropZones = false; this.mapColorTheme = "converge"; this.measureFunc = "Count"; this.mouseSpeed = 0; // includes touch-screens... this.noAnim = false; this.domID = options.domID; this.selectedAggr = { Compared_A: null, Compared_B: null, Compared_C: null, Highlighted: null } this.allAggregates = []; this.allRecordsAggr = new kshf.Aggregate(); this.allRecordsAggr.init(); this.allAggregates.push(this.allRecordsAggr); // Callbacks this.newSummaryCb = options.newSummaryCb; this.readyCb = options.readyCb; this.preview_not = false; this.itemName = options.itemName || ""; if(options.itemDisplay) options.recordDisplay = options.itemDisplay; if(typeof this.options.enableAuthoring === "undefined") this.options.enableAuthoring = false; this.DOM = {}; this.DOM.root = d3.select(this.domID) .classed("kshf",true) .attr("noanim",true) .attr("measureFunc",this.measureFunc) .style("position","relative") //.style("overflow-y","hidden") .on("mousemove",function(d,e){ // Action logging... if(typeof logIf === "object"){ logIf.setSessionID(); } // Compute mouse moving speed, to adjust repsonsiveness if(me.lastMouseMoveEvent===undefined){ me.lastMouseMoveEvent = d3.event; return; } var timeDif = d3.event.timeStamp - me.lastMouseMoveEvent.timeStamp; if(timeDif===0) return; var xDif = Math.abs(d3.event.x - me.lastMouseMoveEvent.x); var yDif = Math.abs(d3.event.y - me.lastMouseMoveEvent.y); // controls highlight selection delay me.mouseSpeed = Math.min( Math.sqrt(xDif*xDif + yDif*yDif) / timeDif , 2); me.lastMouseMoveEvent = d3.event; }); // remove any DOM elements under this domID, kshf takes complete control over what's inside var rootDomNode = this.DOM.root[0][0]; while (rootDomNode.hasChildNodes()) rootDomNode.removeChild(rootDomNode.lastChild); this.DOM.pointerBlock = this.DOM.root.append("div").attr("class","pointerBlock"); this.DOM.attribDragBox = this.DOM.root.append("div").attr("class","attribDragBox"); this.insertDOM_Infobox(); this.insertDOM_WarningBox(); this.DOM.panel_Wrapper = this.DOM.root.append("div").attr("class","panel_Wrapper"); this.insertDOM_PanelBasic(); this.DOM.panelsTop = this.DOM.panel_Wrapper.append("div").attr("class","panels_Above"); this.panels.left = new kshf.Panel({ width_catLabel : options.leftPanelLabelWidth || options.categoryTextWidth || 115, browser: this, name: 'left', parentDOM: this.DOM.panelsTop }); this.DOM.middleColumn = this.DOM.panelsTop.append("div").attr("class","middleColumn"); this.DOM.middleColumn.append("div").attr("class", "recordDisplay") this.panels.middle = new kshf.Panel({ width_catLabel : options.middlePanelLabelWidth || options.categoryTextWidth || 115, browser: this, name: 'middle', parentDOM: this.DOM.middleColumn }); this.panels.right = new kshf.Panel({ width_catLabel : options.rightPanelLabelWidth || options.categoryTextWidth || 115, browser: this, name: 'right', parentDOM: this.DOM.panelsTop }); this.panels.bottom = new kshf.Panel({ width_catLabel : options.categoryTextWidth || 115, browser: this, name: 'bottom', parentDOM: this.DOM.panel_Wrapper }); this.insertDOM_AttributePanel(); var me = this; this.DOM.root.selectAll(".panel").on("mouseleave",function(){ setTimeout( function(){ me.updateLayout_Height(); }, 1500); // update layout after 1.5 seconds }); kshf.loadFont(); kshf.browsers.push(this); kshf.browser = this; if(options.source){ window.setTimeout(function() { me.loadSource(options.source); }, 10); } else { this.panel_infobox.attr("show","source"); } }; kshf.Browser.prototype = { /** -- */ setNoAnim: function(v){ if(v===this.noAnim) return; if(this.finalized===undefined) return; this.noAnim=v; this.DOM.root.attr("noanim",this.noAnim); }, /** -- */ removeSummary: function(summary){ var indexFrom = -1; this.summaries.forEach(function(s,i){ if(s===summary) indexFrom = i; }); if(indexFrom===-1) return; // given summary is not within this panel this.summaries.splice(indexFrom,1); summary.removeFromPanel(); }, /** -- */ getAttribTypeFromFunc: function(attribFunc){ var type = null; this.records.some(function(item,i){ var item=attribFunc.call(item.data,item); if(item===null) return false; if(item===undefined) return false; if(typeof(item)==="number" || item instanceof Date) { type="interval"; return true; } // TODO": Think about boolean summaries if(typeof(item)==="string" || typeof(item)==="boolean") { type = "categorical"; return true; } if(Array.isArray(item)){ type = "categorical"; return true; } return false; },this); return type; }, /** -- */ createSummary: function(name,func,type){ if(this.summaries_by_name[name]!==undefined){ console.log("createSummary: The summary name["+name+"] is already used. Returning existing summary."); return this.summaries_by_name[name]; } if(typeof(func)==="string"){ var x=func; func = function(){ return this[x]; } } var attribFunc = func || function(){ return this[name]; } if(type===undefined){ type = this.getAttribTypeFromFunc(attribFunc); } if(type===null){ console.log("Summary data type could not be detected for summary name:"+name); return; } var summary; if(type==='categorical'){ summary = new kshf.Summary_Categorical(); } if(type==='interval'){ summary = new kshf.Summary_Interval(); } summary.initialize(this,name,func); this.summaries.push(summary); this.summaries_by_name[name] = summary; if(this.newSummaryCb) this.newSummaryCb.call(this,summary); return summary; }, /** -- */ changeSummaryName: function(curName,newName){ if(curName===newName) return; var summary = this.summaries_by_name[curName]; if(summary===undefined){ console.log("The given summary name is not there. Try again"); return; } if(this.summaries_by_name[newName]!==undefined){ if(newName!==this.summaries_by_name[newName].summaryColumn){ console.log("The new summary name is already used. It must be unique. Try again"); return; } } // remove the indexing using oldName IFF the old name was not original column name if(curName!==summary.summaryColumn){ delete this.summaries_by_name[curName]; } this.summaries_by_name[newName] = summary; summary.setSummaryName(newName); return summary; }, /** -- */ getWidth_Total: function(){ return this.divWidth; }, /** This also considers if the available attrib panel is shown */ getWidth_Browser: function(){ return this.divWidth - (this.authoringMode ? kshf.attribPanelWidth : 0); }, /** -- */ domHeight: function(){ return parseInt(this.DOM.root.style("height")); }, /** -- */ domWidth: function(){ return parseInt(this.DOM.root.style("width")); }, /** -- */ createFilter: function(filterOptions){ filterOptions.browser = this; // see if it has been created before TODO var newFilter = new kshf.Filter(filterOptions); this.filters.push(newFilter); return newFilter; }, /* -- */ insertDOM_WarningBox: function(){ this.panel_warningBox = this.DOM.root.append("div").attr("class", "warningBox_wrapper").attr("shown",false) var x = this.panel_warningBox.append("span").attr("class","warningBox"); this.DOM.warningText = x.append("span").attr("class","warningText"); x.append("span").attr("class","dismiss").html("<i class='fa fa-times-circle' style='font-size: 1.3em;'></i>") .on("click",function(){ this.parentNode.parentNode.setAttribute("shown",false); }); }, /** -- */ showWarning: function(v){ this.panel_warningBox.attr("shown",true); this.DOM.warningText.html(v); }, /** -- */ hideWarning: function(){ this.panel_warningBox.attr("shown",false); }, /** -- */ getMeasurableSummaries: function(){ return this.summaries.filter(function(summary){ return (summary.type==='interval') && summary.scaleType!=='time' // && summary.panel!==undefined && summary.intervalRange.min>=0 && summary.summaryName !== this.records[0].idIndex ; },this); }, /** -- */ insertDOM_measureSelect: function(){ var me=this; if(this.DOM.measureSelectBox) return; this.DOM.measureSelectBox = this.DOM.measureSelectBox_Wrapper.append("div").attr("class","measureSelectBox"); this.DOM.measureSelectBox.append("div").attr("class","measureSelectBox_Close fa fa-times-circle") .each(function(d){ this.tipsy = new Tipsy(this, { gravity: 'e', title: "Close" }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout", function(){ this.tipsy.hide(); }) .on("click",function(){ this.tipsy.hide(); me.closeMeasureSelectBox(); }); this.DOM.measureSelectBox.append("div").attr("class","measureSelectBox_Header").text("Choose measure"); var m = this.DOM.measureSelectBox.append("div").attr("class","measureSelectBox_Content"); m.append("span").attr("class","measureSelectBox_Content_FuncType") .selectAll(".measureFunctionType").data([ {v:"Count", l:"Count (#)"}, {v:"Sum", l:"Sum (Total)"}, {v:"Avg", l:"Average"}, ]).enter() .append("div").attr("class", function(d){ return "measureFunctionType measureFunction_"+d.v}) .html(function(d){ return d.l; }) .on("click",function(d){ if(d.v==="Count"){ me.DOM.measureSelectBox.select(".sdsso23oadsa").attr("disabled","true"); me.setMeasureFunction(); // no summary, will revert to count return; } this.setAttribute("selected",""); me.DOM.measureSelectBox.select(".sdsso23oadsa").attr("disabled",null); me.setMeasureFunction( me.DOM.sdsso23oadsa[0][0].selectedOptions[0].__data__ , d.v); }); this.DOM.sdsso23oadsa = m.append("div").attr("class","measureSelectBox_Content_Summaries") .append("select").attr("class","sdsso23oadsa") .attr("disabled",this.measureFunc==="Count"?"true":null) .on("change",function(){ var s = this.selectedOptions[0].__data__; me.setMeasureFunction(s,me.measureFunc); }); this.DOM.sdsso23oadsa .selectAll(".measureSummary").data(this.getMeasurableSummaries()).enter() .append("option") .attr("class",function(summary){ return "measureSummary measureSummary_"+summary.summaryID;; }) .attr("value",function(summary){ return summary.summaryID; }) .attr("selected", function(summary){ return summary===me.measureSummary?"true":null }) .html(function(summary){ return summary.summaryName; }) m.append("span").attr("class","measureSelectBox_Content_RecordName").html(" of "+this.itemName); }, /** -- */ closeMeasureSelectBox: function(){ this.DOM.measureSelectBox_Wrapper.attr("showMeasureBox",false); // Close box this.DOM.measureSelectBox = undefined; var d = this.DOM.measureSelectBox_Wrapper[0][0]; while (d.hasChildNodes()) d.removeChild(d.lastChild); }, /** -- */ refreshMeasureSelectAction: function(){ this.DOM.recordInfo.attr('changeMeasureBox', (this.getMeasurableSummaries().length!==0)? 'true' : null); }, /** -- */ insertDOM_PanelBasic: function(){ var me=this; this.DOM.panel_Basic = this.DOM.panel_Wrapper.append("div").attr("class","panel_Basic"); this.DOM.measureSelectBox_Wrapper = this.DOM.panel_Basic.append("span").attr("class","measureSelectBox_Wrapper") .attr("showMeasureBox",false); this.DOM.recordInfo = this.DOM.panel_Basic.append("span") .attr("class","recordInfo editableTextContainer") .attr("edittitle",false) .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'n', title: "Change measure" }); }) .on("mouseenter",function(){ if(me.authoringMode || me.getMeasurableSummaries().length===0) return; this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }) .on("click",function(){ if(me.authoringMode || me.getMeasurableSummaries().length===0) return; this.tipsy.hide(); if(me.DOM.measureSelectBox) { me.closeMeasureSelectBox(); return; } me.insertDOM_measureSelect(); me.DOM.measureSelectBox_Wrapper.attr("showMeasureBox",true); }); this.DOM.activeRecordMeasure = this.DOM.recordInfo.append("span").attr("class","activeRecordMeasure"); this.DOM.measureFuncType = this.DOM.recordInfo.append("span").attr("class","measureFuncType"); this.DOM.recordName = this.DOM.recordInfo.append("span").attr("class","recordName editableText") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'w', title: function(){ var curState=this.parentNode.getAttribute("edittitle"); return (curState===null || curState==="false") ? kshf.lang.cur.EditTitle : "OK"; } }) }) .attr("contenteditable",false) .on("mousedown", function(){ d3.event.stopPropagation(); }) .on("mouseenter",function(){ this.tipsy.show(); d3.event.stopPropagation(); d3.event.preventDefault(); }) .on("mouseleave",function(){ this.tipsy.hide(); }) .on("mousedown", function(){ d3.event.stopPropagation(); d3.event.preventDefault(); }) .on("blur",function(){ this.parentNode.setAttribute("edittitle",false); this.setAttribute("contenteditable", false); me.itemName = this.textContent; }) .on("keydown",function(){ if(event.keyCode===13){ // ENTER this.parentNode.setAttribute("edittitle",false); this.setAttribute("contenteditable", false); me.itemName = this.textContent; } }) .on("click",function(){ this.tipsy.hide(); var curState=this.parentNode.getAttribute("edittitle"); if(curState===null || curState==="false"){ this.parentNode.setAttribute("edittitle",true); var parentDOM = d3.select(this.parentNode); var v=parentDOM.select(".recordName")[0][0]; v.setAttribute("contenteditable",true); v.focus(); } else { this.parentNode.setAttribute("edittitle",false); var parentDOM = d3.select(this.parentNode); var v=parentDOM.select(".recordName")[0][0]; v.setAttribute("contenteditable",false); me.itemName = this.textContent; } }); this.DOM.breadcrumbs = this.DOM.panel_Basic.append("span").attr("class","breadcrumbs"); this.initDOM_ClearAllFilters(); var rightBoxes = this.DOM.panel_Basic.append("span").attr("class","rightBoxes"); // Attribute panel if (typeof saveAs !== 'undefined') { // FileSaver.js is included rightBoxes.append("i").attr("class","saveBrowserConfig fa fa-download") .each(function(d){ this.tipsy = new Tipsy(this, { gravity: 'ne', title: "Download Browser Configuration" }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout", function(){ this.tipsy.hide(); }) .on("click",function(){ var c = JSON.stringify(me.exportConfig(),null,' '); var blob = new Blob([c]);//, {type: "text/plain;charset=utf-8"}); saveAs(blob, "kshf_config.json"); }); } rightBoxes.append("i").attr("class","configUser fa") .each(function(d){ this.tipsy = new Tipsy(this, { gravity: 'n', title: function(){ return kshf.gistLogin? ("Welcome, <i class='fa fa-github'></i> <b>"+kshf.gistLogin+"</b>.<br><br>"+ "Click to logout.<br><br>"+"Shift-click to set gist "+(kshf.gistPublic?"secret":"public")+"."): "Sign-in using github"; } }); }) .attr("auth", false) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout", function(){ this.tipsy.hide(); }) .on("click",function(){ if(this.getAttribute("auth")==="true"){ if (d3.event.shiftKey) { kshf.gistPublic = !kshf.gistPublic; // invert public setting this.setAttribute("public",kshf.gistPublic); alert("Future uploads will be "+(kshf.gistPublic?"public":"secret")+".") return; } // de-authorize kshf.githubToken = undefined; kshf.gistLogin = undefined; this.setAttribute("auth",false) } else { kshf.githubToken = window.prompt("Your Github token (only needs access to gist)", ""); if(this.githubToken!==""){ kshf.getGistLogin(); this.setAttribute("auth",true); } } }); rightBoxes.append("i").attr("class","saveBrowserConfig fa fa-cloud-upload") .each(function(d){ this.tipsy = new Tipsy(this, { gravity: 'ne', title: "Upload Browser Config to Cloud" }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout", function(){ this.tipsy.hide(); }) .on("click",function(){ if(!confirm("The browser will be saved "+ ((kshf.gistLogin)? "to your github as "+(kshf.gistPublic?"public":"secret")+" gist.": "anonymously and public.") )){ return; } var e = me.exportConfig(); var c = JSON.stringify(e,null,' '); // Add authentication data if authentication token is set var headers = {}; if(kshf.gistLogin) headers.Authorization = "token "+kshf.githubToken; // Set description (from page title if it exists) var description = "Keshif Browser Configuration"; // In demo pages, demo_PageTitle gives more context - use it as description if(d3.select("#demo_PageTitle")[0][0]){ description = d3.select("#demo_PageTitle").html(); } var githubLoad = { description: description, public: kshf.gistPublic, files: { "kshf_config.json": { content: c }, } }; // Add style file, if custom style exists var badiStyle = d3.select("#kshfStyle"); if(badiStyle[0].length > 0 && badiStyle[0][0]!==null){ githubLoad.files["kshf_style.css"] = { content: badiStyle.text()}; } function gist_createNew(){ $.ajax( 'https://api.github.com/gists', { method: "POST", dataType: 'json', data: JSON.stringify(githubLoad), headers: headers, success: function(response){ // Keep Gist Info (you may edit/fork it next) kshf.gistInfo = response; var gistURL = response.html_url; var gistID = gistURL.replace(/.*github.*\//g,''); var keshifGist = "keshif.me/gist?"+gistID; me.showWarning( "The browser is saved to "+ "<a href='"+gistURL+"' target='_blank'>"+gistURL.replace("https://","")+"</a>.<br> "+ "To load it again, visit <a href='http://"+keshifGist+"' target='_blank'>"+keshifGist+"</a>" ) }, }, 'json' ); }; // UNAUTHORIZED / ANONYMOUS if(kshf.gistLogin===undefined){ // You cannot fork or edit a gist as anonymous user. gist_createNew(); return; } // AUTHORIZED, NEW GIST if(kshf.gistInfo===undefined){ gist_createNew(); // New gist return; } // AUTHOIZED, EXISTING GIST, FROM ANOTHER USER if(kshf.gistInfo.owner===undefined || kshf.gistInfo.owner.login !== kshf.gistLogin){ // Fork it $.ajax( 'https://api.github.com/gists/'+kshf.gistInfo.id+"/forks", { method: "POST", dataType: 'json', data: JSON.stringify(githubLoad), async: false, headers: headers, success: function(response){ kshf.gistInfo = response; // ok, now my gist }, }, 'json' ); } // AUTHORIZED, EXISTING GIST, MY GIST if(kshf.gistInfo.owner.login === kshf.gistLogin){ // edit $.ajax( 'https://api.github.com/gists/'+kshf.gistInfo.id, { method: "PATCH", dataType: 'json', data: JSON.stringify(githubLoad), headers: headers, success: function(response){ var gistURL = response.html_url; var gistID = gistURL.replace(/.*github.*\//g,''); var keshifGist = "keshif.me/gist?"+gistID; me.showWarning( "The browser is edited in "+ "<a href='"+gistURL+"' target='_blank'>"+gistURL.replace("https://","")+"</a>.<br> "+ "To load it again, visit <a href='http://"+keshifGist+"' target='_blank'>"+keshifGist+"</a>" ) }, }, 'json' ); } }); rightBoxes.append("i").attr("class","showConfigButton fa fa-cog") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'ne', title: kshf.lang.cur.ModifyBrowser }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout", function(){ this.tipsy.hide(); }) .on("click",function(){ me.enableAuthoring(); }); // Datasource this.DOM.datasource = rightBoxes.append("a").attr("class","fa fa-table datasource") .attr("target","_blank") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'ne', title: kshf.lang.cur.OpenDataSource }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout",function(d,i){ this.tipsy.hide(); }); // Info & Credits rightBoxes.append("i").attr("class","fa fa-info-circle credits") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'ne', title: kshf.lang.cur.ShowInfoCredits }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout",function(d,i){ this.tipsy.hide(); }) .on("click",function(){ me.showInfoBox();}); // Info & Credits rightBoxes.append("i").attr("class","fa fa-arrows-alt fullscreen") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'ne', title: kshf.lang.cur.ShowFullscreen }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout",function(d,i){ this.tipsy.hide(); }) .on("click",function(){ me.showFullscreen();}); var adsdasda = this.DOM.panel_Basic.append("div").attr("class","totalGlyph aggrGlyph"); this.DOM.totalGlyph = adsdasda.selectAll("[class*='measure_']") .data(["Total","Active","Highlighted","Compared_A","Compared_B","Compared_C"]) .enter() .append("span").attr("class", function(d){ return "measure_"+d;}) }, /** Inserts a summary block to the list breadcrumb DOM */ /** Don't call this directly */ insertDOM_crumb: function(_className, _filter){ var x; var me=this; // breadcrumbs must be always visible (as the basic panel) x = this.DOM.breadcrumbs.append("span") .attr("class","crumb crumbMode_"+_className) .each(function(){ if(_className!=="Highlighted"){ // Move the node to a sibling before var l=this.parentNode.childNodes.length; if(l>1){ var n=this.parentNode.childNodes[l-2]; this.parentNode.insertBefore(this,n); } } this.tipsy = new Tipsy(this, { gravity: 'n', title: function(){ switch(_className){ case "Filtered": return kshf.lang.cur.RemoveFilter; case "Highlighted": return "Remove Highlight"; case "Compared_A": case "Compared_B": case "Compared_C": return kshf.lang.cur.Unlock; } } }); }) .on("mouseenter",function(){ this.tipsy.show(); if(_className.substr(0,8)==="Compared"){ me.refreshMeasureLabels(_className); } }) .on("mouseleave",function(){ this.tipsy.hide(); if(_className.substr(0,8)==="Compared"){ me.refreshMeasureLabels(); } }) .on("click",function(){ this.tipsy.hide(); if(_className==="Filtered") { _filter.clearFilter(); // delay layout height update setTimeout( function(){ me.updateLayout_Height();}, 1000); } else if(_className==="Highlighted") { me.clearSelect_Highlight(); me.clearCrumbAggr("Highlighted"); } else { me.clearSelect_Compare(_className.substr(9)); // TODO: _className Compared_A / className, etc me.clearCrumbAggr(_className); me.refreshMeasureLabels(); } }); x.append("span").attr("class","clearCrumbButton inCrumb").append("span").attr("class","fa"); var y = x.append("span").attr("class","crumbText"); y.append("span").attr("class","crumbHeader"); y.append("span").attr("class","filterDetails"); // animate appear window.getComputedStyle(x[0][0]).opacity; // force redraw x.attr("ready",true); return x; }, /** -- */ getActiveComparedCount: function(){ return this.vizActive.Compared_A + this.vizActive.Compared_B + this.vizActive.Compared_C; }, /** -- */ refreshTotalViz: function(){ var me=this; var totalScale = d3.scale.linear() .domain([0, this.allRecordsAggr.measure(this.ratioModeActive ? 'Active' : 'Total') ]) .range([0, this.getWidth_Browser()]) .clamp(true); var totalC = this.getActiveComparedCount(); totalC++; // 1 more for highlight var VizHeight = 8; var curC = 0; var stp = VizHeight / totalC; this.DOM.totalGlyph.each(function(d){ if(d==="Total" || d==="Highlighted" || d==="Active"){ kshf.Util.setTransform(this, "scale("+totalScale(me.allRecordsAggr.measure(d))+","+VizHeight+")"); } else { kshf.Util.setTransform(this, "translateY("+(stp*curC)+"px) "+ "scale("+totalScale(me.allRecordsAggr.measure(d))+","+stp+")"); curC++; } }); }, /** --- */ initDOM_ClearAllFilters: function(){ var me=this; this.DOM.filterClearAll = this.DOM.panel_Basic.append("span").attr("class","filterClearAll") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'n', title: kshf.lang.cur.RemoveAllFilters }); }) .on("mouseenter",function(){ this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }) .on("click",function(){ this.tipsy.hide(); me.clearFilters_All(); }); this.DOM.filterClearAll.append("span").attr("class","title").text(kshf.lang.cur.ShowAll); this.DOM.filterClearAll.append("div").attr("class","clearFilterButton allFilter") .append("span").attr("class","fa fa-times"); }, /* -- */ insertDOM_Infobox: function(){ var me=this; var creditString=""; creditString += "<div align='center'>"; creditString += "<div class='header'>Data made explorable by <span class='libName'>Keshif</span>.</div>"; creditString += "<div align='center' class='boxinbox project_credits'>"; creditString += "<div>Developed by</div>"; creditString += " <a href='http://www.cs.umd.edu/hcil/' target='_blank'><img src='https://wiki.umiacs.umd.edu/hcil/images/"+ "1/10/HCIL_logo_small_no_border.gif' style='height:50px'></a>"; creditString += " <a class='myName' href='http://www.adilyalcin.me' target='_blank'>M. Adil Yalçın</a>"; creditString += " <a href='http://www.umd.edu' target='_blank'><img src='http://www.trademarks.umd.edu/marks/gr/informal.gif' "+ "style='height:50px'></a>"; creditString += "</div>"; creditString += ""; creditString += "<div align='center' class='boxinbox project_credits'>"; creditString += "<div style='float:right; text-align: right'>" creditString += "<iframe src='http://ghbtns.com/github-btn.html?user=adilyalcin&repo=Keshif&type=watch&count=true' "+ "allowtransparency='true' frameborder='0' scrolling='0' width='90px' height='20px'></iframe><br/>"; creditString += "</div>"; creditString += "<div style='float:left; padding-left: 10px'>" creditString += "<iframe src='http://ghbtns.com/github-btn.html?user=adilyalcin&repo=Keshif&type=fork&count=true' "+ "allowtransparency='true' frameborder='0' scrolling='0' width='90px' height='20px'></iframe>"; creditString += "</div>"; creditString += " 3rd party libraries used<br/>"; creditString += " <a href='http://d3js.org/' target='_blank'>D3</a> -"; creditString += " <a href='http://jquery.com' target='_blank'>JQuery</a> -"; creditString += " <a href='https://developers.google.com/chart/' target='_blank'>GoogleDocs</a>"; creditString += "</div><br/>"; creditString += ""; creditString += "<div align='center' class='project_fund'>"; creditString += "Keshif (<i>keşif</i>) means discovery / exploration in Turkish.<br/>"; creditString += ""; this.panel_infobox = this.DOM.root.append("div").attr("class", "panel panel_infobox"); this.panel_infobox.append("div").attr("class","background") .on("click",function(){ var activePanel = this.parentNode.getAttribute("show"); if(activePanel==="credit" || activePanel==="itemZoom"){ me.panel_infobox.attr("show","none"); } }) ; this.DOM.loadingBox = this.panel_infobox.append("div").attr("class","infobox_content infobox_loading"); // this.DOM.loadingBox.append("span").attr("class","fa fa-spinner fa-spin"); var ssdsd = this.DOM.loadingBox.append("span").attr("class","spinner"); ssdsd.append("span").attr("class","spinner_x spinner_1"); ssdsd.append("span").attr("class","spinner_x spinner_2"); ssdsd.append("span").attr("class","spinner_x spinner_3"); ssdsd.append("span").attr("class","spinner_x spinner_4"); ssdsd.append("span").attr("class","spinner_x spinner_5"); var hmmm=this.DOM.loadingBox.append("div").attr("class","status_text"); hmmm.append("span").attr("class","status_text_sub info").text(kshf.lang.cur.LoadingData); this.DOM.status_text_sub_dynamic = hmmm.append("span").attr("class","status_text_sub dynamic"); var infobox_credit = this.panel_infobox.append("div").attr("class","infobox_content infobox_credit"); infobox_credit.append("div").attr("class","infobox_close_button") .on("click",function(){ me.panel_infobox.attr("show","none"); }) .append("span").attr("class","fa fa-times"); infobox_credit.append("div").attr("class","all-the-credits").html(creditString); this.insertSourceBox(); this.DOM.infobox_itemZoom = this.panel_infobox.append("span").attr("class","infobox_content infobox_itemZoom"); this.DOM.infobox_itemZoom.append("div").attr("class","infobox_close_button") .on("click",function(){ me.panel_infobox.attr("show","none"); }) .append("span").attr("class","fa fa-times"); this.DOM.infobox_itemZoom_content = this.DOM.infobox_itemZoom.append("span").attr("class","content"); }, /** -- */ insertSourceBox: function(){ var me = this; var x,y,z; var source_type = "GoogleSheet"; var sourceURL = null, sourceSheet = "", localFile = undefined; var readyToLoad=function(){ if(localFile) return true; return sourceURL!==null && sourceSheet!==""; }; this.DOM.infobox_source = this.panel_infobox.append("div").attr("class","infobox_content infobox_source") .attr("selected_source_type",source_type); this.DOM.infobox_source.append("div").attr("class","sourceHeader").text("Where's your data?"); var source_wrapper = this.DOM.infobox_source.append("div").attr("class","source_wrapper"); x = source_wrapper.append("div").attr("class","sourceOptions"); x.append("span").attr("class","sourceOption").html( "<img src='https://lh3.ggpht.com/e3oZddUHSC6EcnxC80rl_6HbY94sM63dn6KrEXJ-C4GIUN-t1XM0uYA_WUwyhbIHmVMH=w300-rw' "+ " style='height: 12px;'> Google Sheet").attr("source_type","GoogleSheet"); x.append("span").attr("class","sourceOption").html( "<img src='https://developers.google.com/drive/images/drive_icon.png' style='height:12px; position: "+ "relative; top: 2px'> Google Drive Folder") .attr("source_type","GoogleDrive"); x.append("span").attr("class","sourceOption").html( "<i class='fa fa-dropbox'></i> Dropbox Folder").attr("source_type","Dropbox"); x.append("span").attr("class","sourceOption") .html("<i class='fa fa-file'></i> Local File").attr("source_type","LocalFile"); x.selectAll(".sourceOption").on("click",function(){ source_type=this.getAttribute("source_type"); me.DOM.infobox_source.attr("selected_source_type",source_type); var placeholder; switch(source_type){ case "GoogleSheet": placeholder = 'https://docs.google.com/spreadsheets/d/**************'; break; case "GoogleDrive": placeholder = 'https://******.googledrive.com/host/**************/'; break; case "Dropbox": placeholder = "https://dl.dropboxusercontent.com/u/**************/"; } gdocLink.attr("placeholder",placeholder); }); x = source_wrapper.append("div"); var gdocLink = x.append("input") .attr("type","text") .attr("class","gdocLink") .attr("placeholder",'https://docs.google.com/spreadsheets/d/**************') .on("keyup",function(){ gdocLink_ready.style("opacity",this.value===""?"0":"1"); var input = this.value; if(source_type==="GoogleSheet"){ var firstIndex = input.indexOf("docs.google.com/spreadsheets/d/"); if(firstIndex!==-1){ var input = input.substr(firstIndex+31); // focus after the base url if(input.indexOf("/")!==-1){ input = input.substr(0,input.indexOf("/")); } } if(input.length===44){ sourceURL = input; gdocLink_ready.attr("ready",true); } else { sourceURL = null; gdocLink_ready.attr("ready",false); } } if(source_type==="GoogleDrive"){ var firstIndex = input.indexOf(".googledrive.com/host/"); if(firstIndex!==-1){ // Make sure last character is "/" if(input[input.length-1]!=="/") input+="/"; sourceURL = input; gdocLink_ready.attr("ready",true); } else { sourceURL = null; gdocLink_ready.attr("ready",false); } } if(source_type==="Dropbox"){ var firstIndex = input.indexOf("dl.dropboxusercontent.com/"); if(firstIndex!==-1){ // Make sure last character is "/" if(input[input.length-1]!=="/") input+="/"; sourceURL = input; gdocLink_ready.attr("ready",true); } else { sourceURL = null; gdocLink_ready.attr("ready",false); } } actionButton.attr("disabled",!readyToLoad()); }); var fileLink = x.append("input") .attr("type","file") .attr("class","fileLink") .on("change",function(){ gdocLink_ready.style("opacity",0); var files = d3.event.target.files; // FileList object if(files.length>1){ alert("Please select only one file."); return; } if(files.length===0){ alert("Please select a file."); return; } localFile = files[0]; switch(localFile.type){ case "application/json": // json localFile.fileType = "json"; localFile.name = localFile.name.replace(".json",""); break; case "text/csv": // csv localFile.fileType = "csv"; localFile.name = localFile.name.replace(".csv",""); break; case "text/tab-separated-values": // tsv localFile.fileType = "tsv"; localFile.name = localFile.name.replace(".tsv",""); break; default: localFile = undefined; actionButton.attr("disabled",true); alert("The selected file type is not supported (csv, tsv, json)"); return; } localFile.name = localFile.name.replace("_"," "); gdocLink_ready.style("opacity",1); gdocLink_ready.attr("ready",true); actionButton.attr("disabled",false); }); x.append("span").attr("class","fa fa-info-circle") .each(function(summary){ this.tipsy = new Tipsy(this, { gravity: 's', title: function(){ if(source_type==="GoogleSheet") return "The link to your Google Sheet"; if(source_type==="GoogleDrive") return "The link to *hosted* Google Drive folder"; if(source_type==="Dropbox") return "The link to your *Public* Dropbox folder"; if(source_type==="LocalFile") return "Select your CSV/TSV/JSON file or drag-and-drop here."; } }); }) .on("mouseenter",function(){ this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }); var gdocLink_ready = x.append("span").attr("class","gdocLink_ready fa").attr("ready",false); var sheetInfo = this.DOM.infobox_source.append("div").attr("class","sheetInfo"); x = sheetInfo.append("div").attr("class","sheet_wrapper") x.append("div").attr("class","subheading tableHeader") ; x = sheetInfo.append("div").attr("class","sheet_wrapper sheetName_wrapper") x.append("span").attr("class","subheading").text("Name"); x.append("span").attr("class","fa fa-info-circle") .each(function(summary){ this.tipsy = new Tipsy(this, { gravity: 's', title: function(){ var v; if(source_type==="GoogleSheet") v="The name of the data sheet in your Google Sheet."; if(source_type==="GoogleDrive") v="The file name in the folder."; if(source_type==="Dropbox") v="The file name in the folder."; v+="<br>Also describes what each data row represents" return v; } }); }) .on("mouseenter",function(){ this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }); this.DOM.tableName = x.append("input").attr("type","text").attr("class","tableName") .on("keyup",function(){ sourceSheet = this.value; actionButton.attr("disabled",!readyToLoad()); }); z=x.append("span").attr("class","fileType_wrapper"); z.append("span").text("."); var DOMfileType = z.append("select").attr("class","fileType"); DOMfileType.append("option").attr("value","csv").text("csv"); DOMfileType.append("option").attr("value","tsv").text("tsv"); DOMfileType.append("option").attr("value","json").text("json"); x = sheetInfo.append("div").attr("class","sheet_wrapper sheetColumn_ID_wrapper") x.append("span").attr("class","subheading").text("ID column"); x.append("span").attr("class","fa fa-info-circle") .each(function(summary){ this.tipsy = new Tipsy(this, { gravity: 's', title: "The column that uniquely identifies each item.<br><br>If no such column, skip." }); }) .on("mouseenter",function(){ this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }); this.DOM.sheetColumn_ID = x.append("input").attr("class","sheetColumn_ID").attr("type","text").attr("placeholder","id"); var actionButton = this.DOM.infobox_source.append("div").attr("class","actionButton") .text("Explore it with Keshif") .attr("disabled",true) .on("click",function(){ if(!readyToLoad()){ alert("Please input your data source link and sheet name."); return; } me.options.enableAuthoring = true; // Enable authoring on data load var sheetID = me.DOM.sheetColumn_ID[0][0].value; if(sheetID==="") sheetID = "id"; switch(source_type){ case "GoogleSheet": me.loadSource({ gdocId: sourceURL, tables: {name:sourceSheet, id:sheetID} }); break; case "GoogleDrive": me.loadSource({ dirPath: sourceURL, fileType: DOMfileType[0][0].value, tables: {name:sourceSheet, id:sheetID} }); break; case "Dropbox": me.loadSource({ dirPath: sourceURL, fileType: DOMfileType[0][0].value, tables: {name:sourceSheet, id:sheetID} }); break; case "LocalFile": localFile.id = sheetID; me.loadSource({ dirPath: "", // TODO: temporary tables: localFile }); break; } }); }, /** -- */ insertDOM_AttributePanel: function(){ var me=this; this.DOM.attributePanel = this.DOM.root.append("div").attr("class","attributePanel"); var xx= this.DOM.attributePanel.append("div").attr("class","attributePanelHeader"); xx.append("span").text("Available Attributes"); xx.append("span").attr("class","hidePanel fa fa-times") .each(function(){ this.tipsy = new Tipsy(this, { gravity: "w", title: "Close panel" }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .on("click",function(){ me.enableAuthoring(); }); var attributePanelControl = this.DOM.attributePanel.append("div").attr("class","attributePanelControl"); attributePanelControl.append("span").attr("class","attribFilterIcon fa fa-filter"); // ******************************************************* // TEXT SEARCH // ******************************************************* this.DOM.attribTextSearch = attributePanelControl.append("span").attr("class","textSearchBox attribTextSearch"); this.DOM.attribTextSearchControl = this.DOM.attribTextSearch.append("span") .attr("class","textSearchControl fa") .on("click",function() { me.DOM.attribTextSearchControl.attr("showClear",false)[0][0].value=""; me.summaries.forEach(function(summary){ if(summary.DOM.nugget===undefined) return; summary.DOM.nugget.attr("filtered",false); }); }); this.DOM.attribTextSearch.append("input") .attr("class","textSearchInput") .attr("type","text") .attr("placeholder",kshf.lang.cur.Search) .on("input",function(){ if(this.timer) clearTimeout(this.timer); var x = this; var queryString = x.value.toLowerCase(); me.DOM.attribTextSearchControl.attr("showClear", (queryString!=="") ) this.timer = setTimeout( function(){ me.summaries.forEach(function(summary){ if(summary.DOM.nugget===undefined) return; summary.DOM.nugget.attr("filtered",(summary.summaryName.toLowerCase().indexOf(queryString)===-1)); }); }, 750); }); attributePanelControl.append("span").attr("class","addAllSummaries") .append("span").attr("class","fa fa-magic") // fa-caret-square-o-right .each(function(){ this.tipsy = new Tipsy(this, { gravity: "e", title: "Add all to browser" }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .on("click",function(){ me.autoCreateBrowser(); }); this.DOM.attributeList = this.DOM.attributePanel.append("div").attr("class","attributeList"); this.DOM.dropZone_AttribList = this.DOM.attributeList.append("div").attr("class","dropZone dropZone_AttribList") .attr("readyToDrop",false) .on("mouseenter",function(event){ this.setAttribute("readyToDrop",true); }) .on("mouseleave",function(event){ this.setAttribute("readyToDrop",false); }) .on("mouseup",function(event){ var movedSummary = me.movedSummary; movedSummary.removeFromPanel(); movedSummary.clearDOM(); movedSummary.browser.updateLayout(); me.movedSummary = null; }); this.DOM.dropZone_AttribList.append("span").attr("class","dropIcon fa fa-angle-double-down"); this.DOM.dropZone_AttribList.append("div").attr("class","dropText").text("Remove summary"); this.DOM.attributeList.append("div").attr("class","newAttribute").html("<i class='fa fa-plus-square'></i>") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'n', title: 'Add new attribute' }); }) .on("mouseenter",function(){ this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }) .on("click",function(){ var name = prompt("The attribute name"); if(name===null) return; // cancel var func = prompt("The attribute function"); if(func===null) return; // cancel var safeFunc = undefined; try { eval("\"use strict\"; safeFunc = function(d){"+func+"}"); } catch (e){ console.log("Eval error:"); console.log(e.message); console.log(e.name); console.log(e.fileName); console.log(e.lineNumber); console.log(e.columnNumber); console.log(e.stack); } if(typeof safeFunc !== "function"){ alert("You did not specify a function with correct format. Cannot specify new attribute."); return; } me.createSummary(name,safeFunc); }); }, /** -- */ updateItemZoomText: function(item){ var str=""; for(var column in item.data){ var v=item.data[column]; if(v===undefined || v===null) continue; str+="<b>"+column+":</b> "+ v.toString()+"<br>"; } this.DOM.infobox_itemZoom_content.html(str); this.panel_infobox.attr("show","itemZoom"); // this.DOM.infobox_itemZoom_content.html(item.data.toString()); }, /** -- deprecated */ showAttributes: function(v){ return this.enableAuthoring(); }, /** -- */ enableAuthoring: function(v){ if(v===undefined) v = !this.authoringMode; // if undefined, invert this.authoringMode = v; this.DOM.root.attr("authoringMode",this.authoringMode?"true":null); this.updateLayout(); var lastIndex = 0, me=this; var initAttib = function(){ var start = Date.now(); me.summaries[lastIndex++].initializeAggregates(); var end = Date.now(); if(lastIndex!==me.summaries.length){ setTimeout(initAttib,end-start); } else { me.reorderNuggetList(); } }; setTimeout(initAttib,150); }, /** -- */ showFullscreen: function(){ this.isFullscreen = this.isFullscreen?false:true; var elem = this.DOM.root[0][0]; if(this.isFullscreen){ if (elem.requestFullscreen) { elem.requestFullscreen(); } else if (elem.msRequestFullscreen) { elem.msRequestFullscreen(); } else if (elem.mozRequestFullScreen) { elem.mozRequestFullScreen(); } else if (elem.webkitRequestFullscreen) { elem.webkitRequestFullscreen(); } } else { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); } } }, /** -- */ showInfoBox: function(){ this.panel_infobox.attr("show","credit"); }, /** -- */ loadSource: function(v){ this.source = v; this.panel_infobox.attr("show","loading"); // Compability with older versions.. Used to specify "sheets" instead of "tables" if(this.source.sheets){ this.source.tables = this.source.sheets; } if(this.source.tables){ if(!Array.isArray(this.source.tables)) this.source.tables = [this.source.tables]; this.source.tables.forEach(function(tableDescr, i){ if(typeof tableDescr === "string") this.source.tables[i] = {name: tableDescr}; }, this); // Reset loadedTableCount this.source.loadedTableCount=0; this.DOM.status_text_sub_dynamic .text("("+this.source.loadedTableCount+"/"+this.source.tables.length+")"); this.primaryTableName = this.source.tables[0].name; if(this.source.gdocId){ this.source.url = this.source.url || ("https://docs.google.com/spreadsheets/d/"+this.source.gdocId); } this.source.tables.forEach(function(tableDescr){ if(tableDescr.id===undefined) tableDescr.id = "id"; // if this table name has been loaded, skip this one if(kshf.dt[tableDescr.name]!==undefined){ this.incrementLoadedTableCount(); return; } if(this.source.gdocId){ this.loadTable_Google(tableDescr); } else { switch(this.source.fileType || tableDescr.fileType){ case "json": this.loadTable_JSON(tableDescr); break; case "csv": case "tsv": this.loadTable_CSV(tableDescr); break; } } },this); } else { if(this.source.callback) this.source.callback(this); } }, loadTable_Google: function(sheet){ var me=this; var headers=1; if(sheet.headers){ headers = sheet.headers; } var qString='https://docs.google.com/spreadsheet/tq?key='+this.source.gdocId+'&headers='+headers; if(sheet.sheetID){ qString+='&gid='+sheet.sheetID; } else { qString+='&sheet='+sheet.name; } if(sheet.range){ qString+="&range="+sheet.range; } var googleQuery = new google.visualization.Query(qString); if(sheet.query) googleQuery.setQuery(sheet.query); googleQuery.send( function(response){ if(kshf.dt[sheet.name]!==undefined){ me.incrementLoadedTableCount(); return; } if(response.isError()) { me.panel_infobox.select("div.status_text .info") .text("Cannot load data"); me.panel_infobox.select("span.spinner").selectAll("span").remove(); me.panel_infobox.select("span.spinner").append('i').attr("class","fa fa-warning"); me.panel_infobox.select("div.status_text .dynamic") .text("("+response.getMessage()+")"); return; } var j,r,i,arr=[],idIndex=-1,itemId=0; var dataTable = response.getDataTable(); var numCols = dataTable.getNumberOfColumns(); // find the index with sheet.id (idIndex) for(i=0; true ; i++){ if(i===numCols || dataTable.getColumnLabel(i).trim()===sheet.id) { idIndex = i; break; } } var tmpTable=[]; // create the column name tables for(j=0; j<dataTable.getNumberOfColumns(); j++){ tmpTable.push(dataTable.getColumnLabel(j).trim()); } // create the item array arr.length = dataTable.getNumberOfRows(); // pre-allocate for speed for(r=0; r<dataTable.getNumberOfRows() ; r++){ var c={}; for(i=0; i<numCols ; i++) { c[tmpTable[i]] = dataTable.getValue(r,i); } // push unique id as the last column if necessary if(c[sheet.id]===undefined) c[sheet.id] = itemId++; arr[r] = new kshf.Record(c,sheet.id); } me.finishDataLoad(sheet,arr); }); }, /** -- */ loadTable_CSV: function(tableDescr){ var me=this; function processCSVText(data){ // if data is already loaded, nothing else to do... if(kshf.dt[tableDescr.name]!==undefined){ me.incrementLoadedTableCount(); return; } var arr = []; var idColumn = tableDescr.id; var config = {}; config.dynamicTyping = true; config.header = true; // header setting can be turned off if(tableDescr.header===false) config.header = false; if(tableDescr.preview!==undefined) config.preview = tableDescr.preview; if(tableDescr.fastMode!==undefined) config.fastMode = tableDescr.fastMode; if(tableDescr.dynamicTyping!==undefined) config.dynamicTyping = tableDescr.dynamicTyping; var parsedData = Papa.parse(data, config); parsedData.data.forEach(function(row,i){ if(row[idColumn]===undefined) row[idColumn] = i; arr.push(new kshf.Record(row,idColumn)); }) me.finishDataLoad(tableDescr, arr); } if(tableDescr instanceof File){ // Load using FileReader var reader = new FileReader(); reader.onload = function(e) { processCSVText(e.target.result); }; reader.readAsText(tableDescr); } else { // Load using URL var fileName=this.source.dirPath+tableDescr.name+"."+this.source.fileType; $.ajax({ url: fileName, type: "GET", async: (this.source.callback===undefined)?true:false, contentType: "text/csv", success: processCSVText }); } }, /** Note: Requires json root to be an array, and each object will be passed to keshif item. */ loadTable_JSON: function(tableDescr){ var me = this; function processJSONText(data){ // File may describe keshif config. Load from config file here! if(data.domID){ me.options = data; me.loadSource(data.source); return; }; // if data is already loaded, nothing else to do... if(kshf.dt[tableDescr.name]!==undefined){ me.incrementLoadedTableCount(); return; } var arr = []; var idColumn = tableDescr.id; data.forEach(function(dataItem,i){ if(dataItem[idColumn]===undefined) dataItem[idColumn] = i; arr.push(new kshf.Record(dataItem, idColumn)); }); me.finishDataLoad(tableDescr, arr); }; if(tableDescr instanceof File){ // Load using FileReader var reader = new FileReader(); reader.onload = function(e) { processJSONText( JSON.parse(e.target.result)); }; reader.readAsText(tableDescr); } else { var fileName = this.source.dirPath+tableDescr.name+".json"; $.ajax({ url: fileName+"?dl=0", type: "GET", async: (this.source.callback===undefined)?true:false, dataType: "json", success: processJSONText }); } }, /** -- */ finishDataLoad: function(table,arr) { kshf.dt[table.name] = arr; var id_table = {}; arr.forEach(function(record){id_table[record.id()] = record;}); kshf.dt_id[table.name] = id_table; this.incrementLoadedTableCount(); }, /** -- */ incrementLoadedTableCount: function(){ var me=this; this.source.loadedTableCount++; this.panel_infobox.select("div.status_text .dynamic") .text("("+this.source.loadedTableCount+"/"+this.source.tables.length+")"); // finish loading if(this.source.loadedTableCount===this.source.tables.length) { if(this.source.callback===undefined){ this.loadCharts(); } else { this.source.callback(this); } } }, /** -- */ loadCharts: function(){ if(this.primaryTableName===undefined){ alert("Cannot load keshif. Please define browser.primaryTableName."); return; } this.records = kshf.dt[this.primaryTableName]; this.records.forEach(function(r){ this.allRecordsAggr.addRecord(r); },this); if(this.itemName==="") { this.itemName = this.primaryTableName; } var me=this; this.panel_infobox.select("div.status_text .info").text(kshf.lang.cur.CreatingBrowser); this.panel_infobox.select("div.status_text .dynamic").text(""); window.setTimeout(function(){ me._loadCharts(); }, 50); }, /** -- */ _loadCharts: function(){ var me=this; if(this.options.loadedCb){ if(typeof this.options.loadedCb === "string" && this.options.loadedCb.substr(0,8)==="function"){ // Evaluate string to a function!! eval("\"use strict\"; this.options.loadedCb = "+this.options.loadedCb); } if(typeof this.options.loadedCb === "function") { this.options.loadedCb.call(this); } } // Create a summary for each existing column in the data for(var column in this.records[0].data){ if(typeof(column)==="string") this.createSummary(column); } // Should do this here, because bottom panel width calls for browser width, and this reads the browser width... this.divWidth = this.domWidth(); if(this.options.summaries) this.options.facets = this.options.summaries; this.options.facets = this.options.facets || []; this.options.facets.forEach(function(facetDescr){ // String -> resolve to name if(typeof facetDescr==="string"){ facetDescr = {name: facetDescr}; } // ************************************************** // API compability - process old keys if(facetDescr.title){ facetDescr.name = facetDescr.title; } if(facetDescr.sortingOpts){ facetDescr.catSortBy = facetDescr.sortingOpts } if(facetDescr.layout){ facetDescr.panel = facetDescr.layout; } if(facetDescr.intervalScale){ facetDescr.scaleType = facetDescr.intervalScale; } if(facetDescr.attribMap){ facetDescr.value = facetDescr.attribMap; } if(typeof(facetDescr.value)==="string"){ // it may be a function definition if so, evaluate if(facetDescr.value.substr(0,8)==="function"){ // Evaluate string to a function!! eval("\"use strict\"; facetDescr.value = "+facetDescr.value); } } if( facetDescr.catLabel || facetDescr.catTooltip || facetDescr.catSplit || facetDescr.catTableName || facetDescr.catSortBy || facetDescr.catMap){ facetDescr.type="categorical"; } else if(facetDescr.scaleType || facetDescr.showPercentile || facetDescr.unitName ){ facetDescr.type="interval"; } var summary = this.summaries_by_name[facetDescr.name]; if(summary===undefined){ if(typeof(facetDescr.value)==="string"){ var summary = this.summaries_by_name[facetDescr.value]; if(summary===undefined){ summary = this.createSummary(facetDescr.value); } summary = this.changeSummaryName(facetDescr.value,facetDescr.name); } else if(typeof(facetDescr.value)==="function"){ summary = this.createSummary(facetDescr.name,facetDescr.value,facetDescr.type); } else { return; } } else { if(facetDescr.value){ // Requesting a new summarywith the same name. summary.destroy(); summary = this.createSummary(facetDescr.name,facetDescr.value,facetDescr.type); } } if(facetDescr.catSplit){ summary.setCatSplit(facetDescr.catSplit); } if(facetDescr.type){ facetDescr.type = facetDescr.type.toLowerCase(); if(facetDescr.type!==summary.type){ summary.destroy(); if(facetDescr.value===undefined){ facetDescr.value = facetDescr.name; } if(typeof(facetDescr.value)==="string"){ summary = this.createSummary(facetDescr.value,null,facetDescr.type); if(facetDescr.value!==facetDescr.name) this.changeSummaryName(facetDescr.value,facetDescr.name); } else if(typeof(facetDescr.value)==="function"){ summary = this.createSummary(facetDescr.name,facetDescr.value,facetDescr.type); } } } // If summary object is not found/created, nothing else to do if(summary===undefined) return; summary.initializeAggregates(); // Common settings if(facetDescr.collapsed){ summary.setCollapsed(true); } if(facetDescr.description) { summary.setDescription(facetDescr.description); } // THESE AFFECT HOW CATEGORICAL VALUES ARE MAPPED if(summary.type==='categorical'){ if(facetDescr.catTableName){ summary.setCatTable(facetDescr.catTableName); } if(facetDescr.catLabel){ // if this is a function definition, evaluate it if(typeof facetDescr.catLabel === "string" && facetDescr.catLabel.substr(0,8)==="function"){ eval("\"use strict\"; facetDescr.catLabel = "+facetDescr.catLabel); } summary.setCatLabel(facetDescr.catLabel); } if(facetDescr.catTooltip){ summary.setCatTooltip(facetDescr.catTooltip); } if(facetDescr.catMap){ summary.setCatGeo(facetDescr.catMap); } if(facetDescr.minAggrValue) { summary.setMinAggrValue(facetDescr.minAggrValue); } if(facetDescr.catSortBy!==undefined){ summary.setSortingOptions(facetDescr.catSortBy); } if(facetDescr.panel!=="none"){ facetDescr.panel = facetDescr.panel || 'left'; summary.addToPanel(this.panels[facetDescr.panel]); } if(facetDescr.viewAs){ summary.viewAs(facetDescr.viewAs); } } if(summary.type==='interval'){ summary.unitName = facetDescr.unitName || summary.unitName; if(facetDescr.showPercentile) { summary.showPercentileChart(facetDescr.showPercentile); } summary.optimumTickWidth = facetDescr.optimumTickWidth || summary.optimumTickWidth; // add to panel before you set scale type and other options: TODO: Fix if(facetDescr.panel!=="none"){ facetDescr.panel = facetDescr.panel || 'left'; summary.addToPanel(this.panels[facetDescr.panel]); } if(facetDescr.scaleType) { summary.setScaleType(facetDescr.scaleType,true); } } },this); this.panels.left.updateWidth_QueryPreview(); this.panels.right.updateWidth_QueryPreview(); this.panels.middle.updateWidth_QueryPreview(); this.recordDisplay = new kshf.RecordDisplay(this,this.options.recordDisplay||{}); if(this.options.measure){ var summary = this.summaries_by_name[this.options.measure]; this.setMeasureFunction(summary,"Sum"); } this.DOM.recordName.html(this.itemName); if(this.source.url){ this.DOM.datasource.style("display","inline-block").attr("href",this.source.url); } this.checkBrowserZoomLevel(); this.loaded = true; var x = function(){ var totalWidth = this.divWidth; var colCount = 0; if(this.panels.left.summaries.length>0){ totalWidth-=this.panels.left.width_catLabel+kshf.scrollWidth+this.panels.left.width_catMeasureLabel; colCount++; } if(this.panels.right.summaries.length>0){ totalWidth-=this.panels.right.width_catLabel+kshf.scrollWidth+this.panels.right.width_catMeasureLabel; colCount++; } if(this.panels.middle.summaries.length>0){ totalWidth-=this.panels.middle.width_catLabel+kshf.scrollWidth+this.panels.middle.width_catMeasureLabel; colCount++; } return Math.floor((totalWidth)/8); }; var defaultBarChartWidth = x.call(this); this.panels.left.setWidthCatBars(this.options.barChartWidth || defaultBarChartWidth); this.panels.right.setWidthCatBars(this.options.barChartWidth || defaultBarChartWidth); this.panels.middle.setWidthCatBars(this.options.barChartWidth || defaultBarChartWidth); this.panels.bottom.updateSummariesWidth(this.options.barChartWidth || defaultBarChartWidth); this.updateMiddlePanelWidth(); this.refresh_filterClearAll(); this.records.forEach(function(record){ record.updateWanted(); }); this.update_Records_Wanted_Count(); this.updateAfterFilter(); this.updateLayout_Height(); // hide infobox this.panel_infobox.attr("show","none"); this.reorderNuggetList(); if(this.recordDisplay.displayType==='nodelink'){ this.recordDisplay.initializeNetwork(); } if(typeof this.readyCb === "string" && this.readyCb.substr(0,8)==="function"){ eval("\"use strict\"; this.readyCb = "+this.readyCb); } if(typeof this.readyCb === "function") { this.readyCb(this); } this.finalized = true; setTimeout(function(){ if(me.options.enableAuthoring) me.enableAuthoring(true); if(me.recordDisplay.displayType==="map"){ setTimeout(function(){ me.recordDisplay.map_zoomToActive(); }, 1000); } me.setNoAnim(false); },1000); }, /** -- */ unregisterBodyCallbacks: function(){ // TODO: Revert to previous handlers... d3.select("body").style('cursor','auto') .on("mousemove",null) .on("mouseup",null) .on("keydown",null); }, /** -- */ prepareDropZones: function(summary,source){ this.movedSummary = summary; this.showDropZones = true; this.DOM.root .attr("showdropzone",true) .attr("dropattrtype",summary.getDataType()) .attr("dropSource",source); this.DOM.attribDragBox.style("display","block").html(summary.summaryName); }, /** -- */ clearDropZones: function(){ this.showDropZones = false; this.unregisterBodyCallbacks(); this.DOM.root.attr("showdropzone",null); this.DOM.attribDragBox.style("display","none"); if(this.movedSummary && !this.movedSummary.uniqueCategories()){ // ? } this.movedSummary = undefined; }, /** -- */ reorderNuggetList: function(){ this.summaries = this.summaries.sort(function(a,b){ var a_cat = a instanceof kshf.Summary_Categorical; var b_cat = b instanceof kshf.Summary_Categorical; if(a_cat && !b_cat) return -1; if(!a_cat && b_cat) return 1; if(a_cat && b_cat && a._cats && b._cats){ return a._cats.length - b._cats.length; } return a.summaryName.localeCompare(b.summaryName, { sensitivity: 'base' }); }); var x=this.DOM.attributeList; x.selectAll(".nugget").data(this.summaries, function(summary){return summary.summaryID;}).order(); }, /** -- */ autoCreateBrowser: function(){ this.summaries.forEach(function(summary,i){ if(summary.uniqueCategories()) return; if(summary.type==="categorical" && summary._cats.length>1000) return; if(summary.panel) return; this.autoAddSummary(summary); this.updateLayout_Height(); },this); this.updateLayout(); }, /** -- */ autoAddSummary: function(summary){ if(summary.uniqueCategories()){ this.recordDisplay.setRecordViewSummary(summary); if(this.recordDisplay.textSearchSummary===null) this.recordDisplay.setTextSearchSummary(summary); return; } // If tithis, add to bottom panel var target_panel; if(summary.isTimeStamp()) { target_panel = 'bottom'; } else if(summary.type==='categorical') { target_panel = 'left'; if(this.panels.left.summaries.length>Math.floor(this.panels.left.height/150)) target_panel = 'middle'; } else if(summary.type==='interval') { target_panel = 'right'; if(this.panels.right.summaries.length>Math.floor(this.panels.right.height/150)) target_panel = 'middle'; } summary.addToPanel(this.panels[target_panel]); }, /** -- */ clearFilters_All: function(force){ var me=this; if(this.skipSortingFacet){ // you can now sort the last filtered summary, attention is no longer there. this.skipSortingFacet.dirtySort = false; this.skipSortingFacet.DOM.catSortButton.attr("resort",false); } // clear all registered filters this.filters.forEach(function(filter){ filter.clearFilter(false,false); }) if(force!==false){ this.records.forEach(function(record){ if(!record.isWanted) record.updateWanted(); // Only update records which were not wanted before. }); this.update_Records_Wanted_Count(); this.refresh_filterClearAll(); this.updateAfterFilter(); // more results } setTimeout( function(){ me.updateLayout_Height(); }, 1000); // update layout after 1.75 seconds }, /** -- */ refresh_ActiveRecordCount: function(){ if(this.allRecordsAggr.recCnt.Active===0){ this.DOM.activeRecordMeasure.html("No"); return; } var numStr = this.allRecordsAggr.measure('Active').toLocaleString(); if(this.measureSummary){ numStr = this.measureSummary.printWithUnitName(numStr); } this.DOM.activeRecordMeasure.html(numStr); }, /** -- */ update_Records_Wanted_Count: function(){ this.recordsWantedCount = 0; this.records.forEach(function(record){ if(record.isWanted) this.recordsWantedCount++; },this); this.refreshTotalViz(); this.refresh_ActiveRecordCount(); }, /** -- */ updateAfterFilter: function () { kshf.browser = this; this.clearSelect_Compare('A'); this.clearSelect_Compare('B'); this.clearSelect_Compare('C'); this.clearCrumbAggr('Compared_A'); this.summaries.forEach(function(summary){ summary.updateAfterFilter(); }); this.recordDisplay.updateAfterFilter(); }, /** -- */ refresh_filterClearAll: function(){ this.DOM.filterClearAll.attr("active", this.filters.some(function(filter){ return filter.isFiltered; }) ); }, /** Ratio mode is when glyphs scale to their max */ setMeasureAxisMode: function(how){ this.ratioModeActive = how; this.DOM.root.attr("relativeMode",how?how:null); this.setPercentLabelMode(how); this.summaries.forEach(function(summary){ summary.refreshViz_All(); }); this.refreshMeasureLabels(); this.refreshTotalViz(); }, /** -- */ refreshMeasureLabels: function(t){ this.measureLabelType = t; this.DOM.root.attr("measureLabelType",this.measureLabelType ? this.measureLabelType : null) this.summaries.forEach(function(summary){ summary.refreshMeasureLabel(); }); }, /** -- */ setPercentLabelMode: function(how){ this.percentModeActive = how; this.DOM.root.attr("percentLabelMode",how?"true":null); this.summaries.forEach(function(summary){ if(!summary.inBrowser()) return; summary.refreshMeasureLabel(); if(summary.viewType==='map'){ summary.refreshMapBounds(); } summary.refreshViz_Axis(); }); }, /** -- */ clearSelect_Compare: function(cT){ this.DOM.root.attr("selectCompared_"+cT,null); this.vizActive["Compared_"+cT] = false; if(this.selectedAggr["Compared_"+cT]){ this.selectedAggr["Compared_"+cT].clearCompare(cT); this.selectedAggr["Compared_"+cT] = null; } var ccT = "Compared_"+cT; this.allAggregates.forEach(function(aggr){ aggr._measure[ccT] = 0; aggr.recCnt[ccT] = 0; }); this.summaries.forEach(function(summary){ summary.refreshViz_Compare_All(); }); }, /** -- */ setSelect_Compare: function(selSummary, selAggregate, noReclick){ if(selAggregate.compared){ var x = "Compared_"+selAggregate.compared; this.clearSelect_Compare(selAggregate.compared); if(noReclick) { this.clearCrumbAggr(x); return; } } var cT = "A"; // Which compare type to store? A, B, C if(this.DOM.root.attr("selectCompared_A")){ cT = this.DOM.root.attr("selectCompared_B") ? "C" : "B"; } var compId = "Compared_"+cT; this.vizActive["Compared_"+cT] = true; this.DOM.root.attr("selectCompared_"+cT,true); this.selectedAggr[compId] = selAggregate; this.selectedAggr[compId].selectCompare(cT); if(!this.preview_not){ this.allAggregates.forEach(function(aggr){ aggr._measure[compId] = aggr._measure.Highlighted; aggr.recCnt[compId] = aggr.recCnt.Highlighted; },this); } else { this.allAggregates.forEach(function(aggr){ aggr._measure[compId] = aggr._measure.Active - aggr._measure.Highlighted; aggr.recCnt[compId] = aggr.recCnt.Active - aggr.recCnt.Highlighted; },this); } this.summaries.forEach(function(summary){ if(this.measureFunc==="Avg" && summary.updateChartScale_Measure){ // refreshes all visualizations automatically summary.updateChartScale_Measure(); } else { summary.refreshViz_Compare_All(); } },this); this.refreshTotalViz(); this.setCrumbAggr(compId,selSummary); }, /** -- */ clearSelect_Highlight: function(){ var me = this; this.vizActive.Highlighted = false; this.DOM.root.attr("selectHighlight",null); this.highlightSelectedSummary = null; if(this.selectedAggr.Highlighted){ this.selectedAggr.Highlighted.clearHighlight(); this.selectedAggr.Highlighted = undefined; } this.allAggregates.forEach(function(aggr){ aggr._measure.Highlighted = 0; aggr.recCnt.Highlighted = 0; }); this.summaries.forEach(function(summary){ summary.refreshViz_Highlight(); }); this.refreshTotalViz(); // if the crumb is shown, start the hide timeout if(this.highlightCrumbTimeout_Hide) clearTimeout(this.highlightCrumbTimeout_Hide); this.highlightCrumbTimeout_Hide = setTimeout(function(){ me.clearCrumbAggr("Highlighted"); this.highlightCrumbTimeout_Hide = undefined; },1000); }, /** -- */ setSelect_Highlight: function(selSummary,selAggregate, headerName){ var me=this; this.vizActive.Highlighted = true; this.DOM.root.attr("selectHighlight",true); this.highlightSelectedSummary = selSummary; this.selectedAggr.Highlighted = selAggregate; this.selectedAggr.Highlighted.selectHighlight(); this.summaries.forEach(function(summary){ summary.refreshViz_Highlight(); }); this.refreshTotalViz(); clearTimeout(this.highlightCrumbTimeout_Hide); this.highlightCrumbTimeout_Hide = undefined; this.setCrumbAggr("Highlighted",selSummary,headerName); }, /** -- */ setCrumbAggr: function(selectType, selectedSummary, headerName){ var crumb = this.DOM.breadcrumbs.select(".crumbMode_"+selectType); if(crumb[0][0]===null) crumb = this.insertDOM_crumb(selectType); if(headerName===undefined) headerName = selectedSummary.summaryName; crumb.select(".crumbHeader" ).html(headerName); if(selectedSummary) crumb.select(".filterDetails").html( (this.selectedAggr[selectType] instanceof kshf.Aggregate_EmptyRecords) ? kshf.lang.cur.NoData : selectedSummary.printAggrSelection(this.selectedAggr[selectType]) ); }, /** -- */ clearCrumbAggr: function(selectType){ var crumb = this.DOM.breadcrumbs.select(".crumbMode_"+selectType); if(crumb[0][0]===null) return; crumb.attr("ready",false); setTimeout(function(){ crumb[0][0].parentNode.removeChild(crumb[0][0]); }, 350); }, /** -- */ getMeasureFuncTypeText: function(){ return this.measureSummary ? (((this.measureFunc==="Sum")?"Total ":"Average ")+this.measureSummary.summaryName+" of ") : ""; }, /** funType: "Sum" or "Avg" */ setMeasureFunction: function(summary, funcType){ if(summary===undefined || summary.type!=='interval' || summary.scaleType==='time'){ // Clearing measure summary (defaulting to count) if(this.measureSummary===undefined) return; // No update this.measureSummary = undefined; this.records.forEach(function(record){ record.measure_Self = 1; }); this.measureFunc = "Count"; } else { if(this.measureSummary===summary && this.measureFunc===funcType) return; // No update this.measureSummary = summary; this.measureFunc = funcType; summary.initializeAggregates(); this.records.forEach(function(record){ record.measure_Self = summary.getRecordValue(record); }); } this.DOM.measureFuncType.html(this.getMeasureFuncTypeText()); this.DOM.root.attr("measureFunc",this.measureFunc); if(this.measureFunc==="Avg"){ // Remove ratio and percent modes if(this.ratioModeActive){ this.setMeasureAxisMode(false); } if(this.percentModeActive){ this.setPercentLabelMode(false); } } this.allAggregates.forEach(function(aggr){ aggr.resetAggregateMeasures(); }); this.summaries.forEach(function(summary){ summary.updateAfterFilter(); }); this.update_Records_Wanted_Count(); }, /** -- */ checkBrowserZoomLevel: function(){ // Using devicePixelRatio works in Chrome and Firefox, but not in Safari // I have not tested IE yet. if(window.devicePixelRatio!==undefined){ if(window.devicePixelRatio!==1 && window.devicePixelRatio!==2){ var me=this; setTimeout(function(){ me.showWarning("Please reset your browser zoom level for the best experience.") },1000); } else { this.hideWarning(); } } else { this.hideWarning(); } }, /** -- */ updateLayout: function(){ if(this.loaded!==true) return; this.divWidth = this.domWidth(); this.updateLayout_Height(); this.updateMiddlePanelWidth(); this.refreshTotalViz(); }, /** -- */ updateLayout_Height: function(){ var me=this; var divHeight_Total = this.domHeight(); var panel_Basic_height = Math.max(parseInt(this.DOM.panel_Basic.style("height")),24)+6; divHeight_Total-=panel_Basic_height; // initialize all summaries as not yet processed. this.summaries.forEach(function(summary){ if(summary.inBrowser()) summary.heightProcessed = false; }); var bottomPanelHeight=0; // process bottom summary if(this.panels.bottom.summaries.length>0){ var targetHeight=divHeight_Total/3; // they all share the same target height this.panels.bottom.summaries.forEach(function(summary){ targetHeight = Math.min(summary.getHeight_RangeMax(),targetHeight); summary.setHeight(targetHeight); summary.heightProcessed = true; bottomPanelHeight += summary.getHeight(); }); } var doLayout = function(sectionHeight,summaries){ sectionHeight-=1;// just use 1-pixel gap var finalPass = false; var lastRound = false; var processedFacets=0; summaries.forEach(function(summary){ if(summary.heightProcessed) processedFacets++; }); while(true){ var remainingFacetCount = summaries.length-processedFacets; if(remainingFacetCount===0) break; var processedFacets_pre = processedFacets; function finishSummary(summary){ sectionHeight-=summary.getHeight(); summary.heightProcessed = true; processedFacets++; remainingFacetCount--; }; summaries.forEach(function(summary){ if(summary.heightProcessed) return; // Empty or collapsed summaries: Fixed height, nothing to change; if(summary.isEmpty() || summary.collapsed) { finishSummary(summary); return; } // in last round, if summary can expand, expand it further if(lastRound===true && summary.heightProcessed && summary.getHeight_RangeMax()>summary.getHeight()){ sectionHeight+=summary.getHeight(); summary.setHeight(sectionHeight); sectionHeight-=summary.getHeight(); return; } if(remainingFacetCount===0) return; // Fairly distribute remaining size across all remaining summaries. var targetHeight = Math.floor(sectionHeight/remainingFacetCount); // auto-collapse summary if you do not have enough space if(finalPass && targetHeight<summary.getHeight_RangeMin()){ summary.setCollapsed(true); finishSummary(summary); return; } if(summary.getHeight_RangeMax()<=targetHeight){ summary.setHeight(summary.getHeight_RangeMax()); finishSummary(summary); } else if(finalPass){ summary.setHeight(targetHeight); finishSummary(summary); } },this); finalPass = processedFacets_pre===processedFacets; if(lastRound===true) break; if(remainingFacetCount===0) lastRound = true; } return sectionHeight; }; var topPanelsHeight = divHeight_Total; this.panels.bottom.DOM.root.style("height",bottomPanelHeight+"px"); topPanelsHeight-=bottomPanelHeight; this.DOM.panelsTop.style("height",topPanelsHeight+"px"); // Left Panel if(this.panels.left.summaries.length>0){ this.panels.left.height = topPanelsHeight; doLayout.call(this,topPanelsHeight,this.panels.left.summaries); } // Right Panel if(this.panels.right.summaries.length>0){ this.panels.right.height = topPanelsHeight; doLayout.call(this,topPanelsHeight,this.panels.right.summaries); } // Middle Panel var midPanelHeight = 0; if(this.panels.middle.summaries.length>0){ var panelHeight = topPanelsHeight; if(this.recordDisplay.recordViewSummary){ panelHeight -= 200; // give 200px fo the list display } else { panelHeight -= this.recordDisplay.DOM.root[0][0].offsetHeight; } midPanelHeight = panelHeight - doLayout.call(this,panelHeight, this.panels.middle.summaries); } this.panels.middle.DOM.root.style("height",midPanelHeight+"px"); // The part where summary DOM is updated this.summaries.forEach(function(summary){ if(summary.inBrowser()) summary.refreshHeight(); }); if(this.recordDisplay){ // get height of header var listDisplayHeight = divHeight_Total - this.recordDisplay.DOM.recordDisplayHeader[0][0].offsetHeight - midPanelHeight - bottomPanelHeight; if(this.showDropZones && this.panels.middle.summaries.length===0) listDisplayHeight*=0.5; this.recordDisplay.setHeight(listDisplayHeight); } }, /** -- */ updateMiddlePanelWidth: function(){ // for some reason, on page load, this variable may be null. urgh. var widthMiddlePanel = this.getWidth_Browser(); var marginLeft = 0; var marginRight = 0; if(this.panels.left.summaries.length>0){ marginLeft=2; widthMiddlePanel-=this.panels.left.getWidth_Total()+2; } if(this.panels.right.summaries.length>0){ marginRight=2; widthMiddlePanel-=this.panels.right.getWidth_Total()+2; } this.panels.left.DOM.root.style("margin-right",marginLeft+"px") this.panels.right.DOM.root.style("margin-left",marginRight+"px") this.panels.middle.setTotalWidth(widthMiddlePanel); this.panels.middle.updateSummariesWidth(); this.panels.bottom.setTotalWidth(this.divWidth); this.panels.bottom.updateSummariesWidth(); this.DOM.middleColumn.style("width",widthMiddlePanel+"px"); this.recordDisplay.refreshWidth(widthMiddlePanel); }, /** -- */ getMeasureLabel: function(aggr,summary){ var _val; if(!(aggr instanceof kshf.Aggregate)){ _val = aggr; } else { if(!aggr.isVisible) return ""; if(this.measureLabelType){ _val = aggr.measure(this.measureLabelType); } else { if(summary && summary === this.highlightSelectedSummary && !summary.isMultiValued){ _val = aggr.measure('Active'); } else { _val = this.vizActive.Highlighted? (this.preview_not? aggr._measure.Active - aggr._measure.Highlighted : aggr.measure('Highlighted') ) : aggr.measure('Active'); } } if(this.percentModeActive){ // Cannot be Avg-function if(aggr._measure.Active===0) return ""; if(this.ratioModeActive){ if(this.measureLabelType===undefined && !this.vizActive.Highlighted) return ""; _val = 100*_val/aggr._measure.Active; } else { _val = 100*_val/this.allRecordsAggr._measure.Active; } } } if(_val<0) _val=0; // TODO? There is it, again... Just sanity I guess if(this.measureFunc!=="Count"){ // Avg or Sum _val = Math.round(_val); } if(this.percentModeActive){ if(aggr.DOM && aggr.DOM.aggrGlyph.nodeName==="g"){ return _val.toFixed(0)+"%"; } else { return _val.toFixed(0)+"<span class='unitName'>%</span>"; } } else if(this.measureSummary){ // Print with the measure summary unit return this.measureSummary.printWithUnitName(kshf.Util.formatForItemCount( _val),(aggr.DOM && aggr.DOM.aggrGlyph.nodeName==="g") ); } else { return kshf.Util.formatForItemCount(_val); } }, /** -- */ exportConfig: function(){ var config = {}; config.domID = this.domID; config.itemName = this.itemName; config.source = this.source; delete config.source.loadedTableCount; config.summaries = []; config.leftPanelLabelWidth = this.panels.left.width_catLabel; config.rightPanelLabelWidth = this.panels.right.width_catLabel; config.middlePanelLabelWidth = this.panels.middle.width_catLabel; if(typeof this.options.loadedCb === "function"){ config.loadedCb = this.options.loadedCb.toString(); } if(typeof this.readyCb === "function"){ config.readyCb = this.readyCb.toString(); } ['left', 'right', 'middle', 'bottom'].forEach(function(p){ // Need to export summaries in-order of the panel appearance // TODO: Export summaries not within browser... this.panels[p].summaries.forEach(function(summary){ config.summaries.push(summary.exportConfig()); }); },this); if(this.recordDisplay.recordViewSummary){ config.recordDisplay = this.recordDisplay.exportConfig(); } return config; } }; // *********************************************************************************************************** // *********************************************************************************************************** kshf.Summary_Base = function(){} kshf.Summary_Base.prototype = { initialize: function(browser,name,attribFunc){ this.summaryID = browser.summaryCount++; this.browser = browser; this.summaryName = name; this.summaryColumn = attribFunc?null:name; this.summaryFunc = attribFunc || function(){ return this[name]; }; this.missingValueAggr = new kshf.Aggregate_EmptyRecords(); this.missingValueAggr.init(); this.browser.allAggregates.push(this.missingValueAggr); this.DOM = {}; this.DOM.inited = false; if(kshf.Summary_Set && this instanceof kshf.Summary_Set) return; this.chartScale_Measure = d3.scale.linear().clamp(true); this.records = this.browser.records; if(this.records===undefined||this.records===null||this.records.length===0){ alert("Error: Browser.records is not defined..."); return; } this.isRecordView = false; // Only used when summary is inserted into browser this.collapsed_pre = false; this.collapsed = false; this.aggr_initialized = false; this.createSummaryFilter(); this.insertNugget(); }, /** -- */ setSummaryName: function(name){ this.summaryName = name; if(this.DOM.summaryName_text){ this.DOM.summaryName_text.html(this.summaryName); } this.summaryFilter._refreshFilterSummary(); // This summary may be used for sorting options. Refresh the list if(this.browser.recordDisplay){ if(this.sortingSummary) this.browser.recordDisplay.refreshSortingOptions(); } if(this.isTextSearch){ this.browser.recordDisplay.DOM.recordTextSearch.select("input") .attr("placeholder",kshf.lang.cur.Search+": "+this.summaryName); } if(this.sortFunc){ this.browser.recordDisplay.refreshSortingOptions(); } if(this.DOM.nugget){ this.DOM.nugget.select(".summaryName").html(this.summaryName); this.DOM.nugget.attr("state",function(summary){ if(summary.summaryColumn===null) return "custom"; // calculated if(summary.summaryName===summary.summaryColumn) return "exact"; return "edited"; }); } }, /** -- */ setShowSetMatrix: function(v){ this.show_set_matrix = v; this.DOM.root.attr("show_set_matrix",this.show_set_matrix); if(this.setSummary===undefined){ this.setSummary = new kshf.Summary_Set(); this.setSummary.initialize(this.browser,this); this.browser.summaries.push(this.setSummary); } }, /** -- */ getDataType: function(){ if(this.type==='categorical') { var str="categorical"; if(!this.aggr_initialized) return str+=" uninitialized"; if(this.uniqueCategories()) str+=" unique"; str+=this.isMultiValued?" multivalue":" singlevalue"; return str; } if(this.type==='interval') { if(!this.aggr_initialized) return str+=" uninitialized"; if(this.isTimeStamp()) return "interval time"; return "interval numeric"; // if(this.hasFloat) return "floating"; return "integer"; } return "?"; }, /** -- */ destroy_full: function(){ this.destroy(); // TODO: Properly destroy this using nugget handlers... var nuggetDOM = this.DOM.nugget[0][0]; if(nuggetDOM && nuggetDOM.parentNode) nuggetDOM.parentNode.removeChild(nuggetDOM); }, /** -- */ destroy: function(){ delete this.browser.summaries_by_name[this.summaryName]; if(this.summaryColumn) delete this.browser.summaries_by_name[this.summaryColumn]; this.browser.removeSummary(this); if(this.DOM.root){ this.DOM.root[0][0].parentNode.removeChild(this.DOM.root[0][0]); } if(this.DOM.nugget){ this.DOM.nugget[0][0].parentNode.removeChild(this.DOM.nugget[0][0]); } }, /** -- */ inBrowser: function(){ return this.panel!==undefined; }, /** -- */ isTimeStamp: function(){ return false; // False by default }, /** -- */ clearDOM: function(){ var dom = this.DOM.root[0][0]; dom.parentNode.removeChild(dom); }, /** -- */ getWidth: function(){ return this.panel.getWidth_Total(); }, /** -- */ getHeight: function(){ if(this.isEmpty() || this.collapsed) return this.getHeight_Header(); return this.getHeight_Header() + this.getHeight_Content(); }, /** -- */ getHeight_Header: function(){ if(!this.DOM.inited) return 0; if(this._height_header==undefined) { this._height_header = this.DOM.headerGroup[0][0].offsetHeight; } return this._height_header; }, /** -- */ uniqueCategories: function(){ if(this.browser && this.browser.records[0].idIndex===this.summaryName) return true; return false; }, /** -- */ isFiltered: function(){ return this.summaryFilter.isFiltered; }, /** -- */ isEmpty: function(){ alert("Nope. Sth is wrong."); // should not be executed return true; }, /** -- */ getFuncString: function(){ var str=this.summaryFunc.toString(); // replace the beginning, and the end return str.replace(/function\s*\(\w*\)\s*{\s*/,"").replace(/}$/,""); }, /** -- */ addToPanel: function(panel, index){ if(index===undefined) index = panel.summaries.length; // add to end if(this.panel===undefined){ this.panel = panel; } else if(this.panel && this.panel!==panel){ this.panel.removeSummary(this); this.panel = panel; } else{ // this.panel === panel var curIndex; // this.panel is the same as panel... this.panel.summaries.forEach(function(s,i){ if(s===this) curIndex = i; },this); // inserting the summary to the same index as current one if(curIndex===index) return; var toRemove=this.panel.DOM.root.selectAll(".dropZone_between_wrapper")[0][curIndex]; toRemove.parentNode.removeChild(toRemove); } var beforeDOM = this.panel.DOM.root.selectAll(".dropZone_between_wrapper")[0][index]; if(this.DOM.root){ this.DOM.root.style("display",""); panel.DOM.root[0][0].insertBefore(this.DOM.root[0][0],beforeDOM); } else { this.initDOM(beforeDOM); } panel.addSummary(this,index); this.panel.refreshDropZoneIndex(); this.refreshNuggetDisplay(); if(this.type=="categorical"){ this.refreshLabelWidth(); } if(this.type==='interval'){ if(this.browser.recordDisplay) this.browser.recordDisplay.addSortingOption(this); } this.refreshWidth(); this.browser.refreshMeasureSelectAction(); }, /** -- */ removeFromPanel: function(){ if(this.panel===undefined) return; this.panel.removeSummary(this); this.refreshNuggetDisplay(); }, /** -- */ insertNugget: function(){ var me=this; if(this.DOM.nugget) return; this.attribMoved = false; this.DOM.nugget = this.browser.DOM.attributeList .append("div").attr("class","nugget editableTextContainer") .each(function(){ this.__data__ = me; }) .attr("title", (this.summaryColumn!==undefined) ? this.summaryColumn : undefined ) .attr("state",function(){ if(me.summaryColumn===null) return "custom"; // calculated if(me.summaryName===me.summaryColumn) return "exact"; return "edited"; }) .attr("datatype", this.getDataType() ) .attr("aggr_initialized", this.aggr_initialized ) .on("dblclick",function(){ me.browser.autoAddSummary(me); me.browser.updateLayout(); }) .on("mousedown",function(){ if(d3.event.which !== 1) return; // only respond to left-click var _this = this; me.attribMoved = false; d3.select("body") .on("keydown", function(){ if(event.keyCode===27){ // Escape key _this.removeAttribute("moved"); me.browser.clearDropZones(); } }) .on("mousemove", function(){ if(!me.attribMoved){ _this.setAttribute("moved",""); me.browser.prepareDropZones(me,"attributePanel"); me.attribMoved = true; } var mousePos = d3.mouse(me.browser.DOM.root[0][0]); kshf.Util.setTransform(me.browser.DOM.attribDragBox[0][0], "translate("+(mousePos[0]-20)+"px,"+(mousePos[1]+5)+"px)"); d3.event.stopPropagation(); d3.event.preventDefault(); }) .on("mouseup", function(){ if(!me.attribMoved) return; _this.removeAttribute("moved"); me.browser.DOM.root.attr("drag_cursor",null); me.browser.clearDropZones(); d3.event.preventDefault(); }); d3.event.preventDefault(); }) .on("mouseup",function(){ if(me.attribMoved===false) me.browser.unregisterBodyCallbacks(); }); this.DOM.nuggetViz = this.DOM.nugget.append("span").attr("class","nuggetViz") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'e', title: function(){ return (!me.aggr_initialized) ? "Initialize" : me.getDataType(); } }); }) .on("mousedown",function(){ if(!me.aggr_initialized){ d3.event.stopPropagation(); d3.event.preventDefault(); } }) .on("click",function(){ if(!me.aggr_initialized) me.initializeAggregates(); }); this.DOM.nuggetViz.append("span").attr("class","nuggetInfo fa"); this.DOM.nuggetViz.append("span").attr("class","nuggetChart"); this.DOM.nugget.append("span").attr("class","summaryName editableText") .attr("contenteditable",false) .html(this.summaryName) .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'w', title: kshf.lang.cur.EditTitle }); }) .on("mouseenter",function(){ this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }) .on("mousedown",function(){ this.tipsy.hide(); var parentDOM = d3.select(this.parentNode); var summaryName = parentDOM.select(".summaryName"); var summaryName_DOM = parentDOM.select(".summaryName")[0][0]; var curState=this.parentNode.getAttribute("edittitle"); if(curState===null || curState==="false"){ this.parentNode.setAttribute("edittitle",true); summaryName_DOM.setAttribute("contenteditable",true); summaryName_DOM.focus(); } else { /* this.parentNode.setAttribute("edittitle",false); summaryName_DOM.setAttribute("contenteditable",false); me.browser.changeSummaryName(me.summaryName,summaryName_DOM.textContent); */ } // stop dragging event start d3.event.stopPropagation(); d3.event.preventDefault(); }) .on("blur",function(){ this.parentNode.setAttribute("edittitle",false); this.setAttribute("contenteditable",false); me.browser.changeSummaryName(me.summaryName,this.textContent); d3.event.preventDefault(); d3.event.stopPropagation(); }) .on("keydown",function(){ if(d3.event.keyCode===13){ // ENTER this.parentNode.setAttribute("edittitle",false); this.setAttribute("contenteditable",false); me.browser.changeSummaryName(me.summaryName,this.textContent); d3.event.preventDefault(); d3.event.stopPropagation(); } }); this.DOM.nugget.append("div").attr("class","fa fa-code editCodeButton") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'w', title: kshf.lang.cur.EditFormula }); }) .on("mouseenter",function(){ this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }) .on("mousedown",function(){ d3.event.stopPropagation(); d3.event.preventDefault(); }) .on("click",function(){ var safeFunc, func = window.prompt("Specify the function:", me.getFuncString()); if(func!==null){ var safeFunc; eval("\"use strict\"; safeFunc = function(d){"+func+"}"); me.browser.createSummary(me.summaryName,safeFunc); } // stop dragging event start d3.event.stopPropagation(); d3.event.preventDefault(); }); this.DOM.nugget.append("div").attr("class","splitCatAttribute_Button fa fa-scissors") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'w', title: "Split" }); }) .on("mouseenter",function(){ this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }) .on("click",function(){ d3.event.stopPropagation(); d3.event.preventDefault(); var catSplit = window.prompt('Split by text: (Ex: Splitting "A;B;C" by ";" will create 3 separate values: A,B,C', ""); if(catSplit!==null){ me.setCatSplit(catSplit); } // stop dragging event start d3.event.stopPropagation(); d3.event.preventDefault(); }); this.DOM.nugget.append("div").attr("class","addFromAttribute_Button fa fa-plus-square") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'w', title: function(){ if(me.isMultiValued) return "Extract \"# of"+me.summaryName+"\""; if(me.isTimeStamp() ) { if(me.timeTyped.month && me.summary_sub_month===undefined){ return "Extract Month of "+me.summaryName; } if(me.timeTyped.day && me.summary_sub_day===undefined){ return "Extract WeekDay of "+me.summaryName; } if(me.timeTyped.hour && me.summary_sub_hour===undefined){ return "Extract Hour of "+me.summaryName; } } return "?"; } }); }) .on("mouseenter",function(){ this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }) .on("click",function(){ d3.event.stopPropagation(); d3.event.preventDefault(); if(me.isMultiValued && !me.hasDegreeSummary){ var summary = me.browser.createSummary( "# of "+me.summaryName, function(d){ var arr=d._valueCache[me.summaryID]; return (arr===null) ? null : arr.length; }, 'interval' ); summary.initializeAggregates(); me.hasDegreeSummary = true; this.style.display = "none"; return; } if(me.isTimeStamp()){ if(me.timeTyped.month && me.summary_sub_month===undefined){ me.createMonthSummary(); } else if(me.timeTyped.day && me.summary_sub_day===undefined){ me.createDaySummary(); } else if(me.timeTyped.hour && me.summary_sub_hour===undefined){ me.createHourSummary(); } } }); this.refreshNuggetDisplay(); if(this.aggr_initialized) this.refreshViz_Nugget(); }, /** -- */ refreshNuggetDisplay: function(){ if(this.DOM.nugget===undefined) return; var me=this; var nuggetHidden = (this.panel||this.isRecordView); if(nuggetHidden){ this.DOM.nugget.attr('anim','disappear'); setTimeout(function(){ me.DOM.nugget.attr('hidden','true'); },700); } else { this.DOM.nugget.attr("hidden",false); setTimeout(function(){ me.DOM.nugget.attr('anim','appear'); },300); } }, /** -- */ insertRoot: function(beforeDOM){ this.DOM.root = this.panel.DOM.root.insert("div", function(){ return beforeDOM; }); this.DOM.root .attr("class","kshfSummary") .attr("summary_id",this.summaryID) .attr("collapsed",this.collapsed) .attr("filtered",false) .attr("showConfig",false); }, /** -- */ insertHeader: function(){ var me = this; this.DOM.headerGroup = this.DOM.root.append("div").attr("class","headerGroup") .on("mousedown", function(){ if(d3.event.which !== 1) return; // only respond to left-click if(!me.browser.authoringMode) { d3.event.preventDefault(); return; } var _this = this; var _this_nextSibling = _this.parentNode.nextSibling; var _this_previousSibling = _this.parentNode.previousSibling; var moved = false; d3.select("body") .style('cursor','move') .on("keydown", function(){ if(event.keyCode===27){ // ESP key _this.style.opacity = null; me.browser.clearDropZones(); } }) .on("mousemove", function(){ if(!moved){ _this_nextSibling.style.display = "none"; _this_previousSibling.style.display = "none"; _this.parentNode.style.opacity = 0.5; me.browser.prepareDropZones(me,"browser"); moved = true; } var mousePos = d3.mouse(me.browser.DOM.root[0][0]); kshf.Util.setTransform(me.browser.DOM.attribDragBox[0][0], "translate("+(mousePos[0]-20)+"px,"+(mousePos[1]+5)+"px)"); d3.event.stopPropagation(); d3.event.preventDefault(); }) .on("mouseup", function(){ // Mouse up on the body me.browser.clearDropZones(); if(me.panel!==undefined || true) { _this.parentNode.style.opacity = null; _this_nextSibling.style.display = ""; _this_previousSibling.style.display = ""; } d3.event.preventDefault(); }); d3.event.preventDefault(); }) ; var header_display_control = this.DOM.headerGroup.append("span").attr("class","header_display_control"); header_display_control.append("span").attr("class","buttonSummaryCollapse fa fa-collapse") .each(function(){ this.tipsy = new Tipsy(this, { gravity: function(){ return me.panelOrder!==0?'sw':'nw'; }, title: function(){ return me.collapsed?kshf.lang.cur.OpenSummary:kshf.lang.cur.MinimizeSummary; } }) }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .on("mousedown", function(){ d3.event.preventDefault(); d3.event.stopPropagation(); }) .on("click",function(){ this.tipsy.hide(); if(me instanceof kshf.Summary_Set){ me.setListSummary.setShowSetMatrix(false); } else { me.setCollapsedAndLayout(!me.collapsed); } }) ; header_display_control.append("span").attr("class","buttonSummaryExpand fa fa-arrows-alt") .each(function(){ this.tipsy = new Tipsy(this, { gravity: function(){ return me.panelOrder!==0?'sw':'nw'; }, title: kshf.lang.cur.MaximizeSummary }) }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .on("mousedown", function(){ d3.event.preventDefault(); d3.event.stopPropagation(); }) .on("click",function(){ me.panel.collapseAllSummaries(); me.setCollapsedAndLayout(false); // uncollapse this one }) ; header_display_control.append("span").attr("class","buttonSummaryRemove fa fa-remove") .each(function(){ this.tipsy = new Tipsy(this, { gravity: function(){ return me.panelOrder!==0?'sw':'nw'; }, title: kshf.lang.cur.RemoveSummary }) }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .on("mousedown", function(){ d3.event.preventDefault(); d3.event.stopPropagation(); }) .on("click",function(){ this.tipsy.hide(); me.removeFromPanel(); me.clearDOM(); me.browser.updateLayout(); }) ; this.DOM.summaryName = this.DOM.headerGroup.append("span") .attr("class","summaryName editableTextContainer") .attr("edittitle",false) .on("click",function(){ if(me.collapsed) me.setCollapsedAndLayout(false); }); this.DOM.summaryName.append("span").attr("class","chartFilterButtonParent").append("div") .attr("class","clearFilterButton rowFilter inSummary") .each(function(d){ this.tipsy = new Tipsy(this, { gravity: function(){ return me.panelOrder!==0?'s':'n'; }, title: kshf.lang.cur.RemoveFilter }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .on("mousedown", function(){ d3.event.preventDefault(); d3.event.stopPropagation(); }) .on("click", function(d,i){ this.tipsy.hide(); me.summaryFilter.clearFilter(); }) .append("span").attr("class","fa fa-times"); this.DOM.summaryName_text = this.DOM.summaryName.append("span").attr("class","summaryName_text editableText") .attr("contenteditable",false) .each(function(summary){ this.tipsy = new Tipsy(this, { gravity: 'w', title: kshf.lang.cur.EditTitle }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .on("mousedown", function(){ // stop dragging event start d3.event.stopPropagation(); d3.event.preventDefault(); }) .on("click", function(){ var curState=this.parentNode.getAttribute("edittitle"); if(curState===null || curState==="false"){ this.parentNode.setAttribute("edittitle",true); var parentDOM = d3.select(this.parentNode); var v=parentDOM.select(".summaryName_text")[0][0]; v.setAttribute("contenteditable",true); v.focus(); } else { this.parentNode.setAttribute("edittitle",false); var parentDOM = d3.select(this.parentNode); var v=parentDOM.select(".summaryName_text")[0][0]; v.setAttribute("contenteditable",false); me.browser.changeSummaryName(me.summaryName,v.textContent); } }) .on("blur",function(){ this.parentNode.setAttribute("edittitle",false); this.setAttribute("contenteditable", false); me.browser.changeSummaryName(me.summaryName,this.textContent); }) .on("keydown",function(){ if(event.keyCode===13){ // ENTER this.parentNode.setAttribute("edittitle",false); this.setAttribute("contenteditable", false); me.browser.changeSummaryName(me.summaryName,this.textContent); } }) .html(this.summaryName); this.DOM.summaryIcons = this.DOM.headerGroup.append("span").attr("class","summaryIcons"); this.DOM.summaryIcons.append("span").attr("class", "hasMultiMappings fa fa-tags") .each(function(d){ this.tipsy = new Tipsy(this, { gravity: 'ne', title: "Show relations within "+me.summaryName+"" }); }) .style("display", (this.isMultiValued && this._cats.length>5) ? "inline-block" : "none") .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .on("click",function(){ me.setShowSetMatrix(!me.show_set_matrix); }); this.DOM.summaryConfigControl = this.DOM.summaryIcons.append("span") .attr("class","summaryConfigControl fa fa-gear") .each(function(d){ this.tipsy = new Tipsy(this, { gravity:'ne', title: "Configure" }); }) .on("mouseover",function(d){ this.tipsy.show(); }) .on("mouseout" ,function(d){ this.tipsy.hide(); }) .on("click",function(d){ this.tipsy.hide(); me.DOM.root.attr("showConfig",me.DOM.root.attr("showConfig")==="false"); }); this.DOM.summaryForRecordDisplay = this.DOM.summaryIcons.append("span") .attr("class", "useForRecordDisplay fa") .each(function(d){ this.tipsy = new Tipsy(this, { gravity: 'ne', title: function(){ return "Use to "+me.browser.recordDisplay.getRecordEncoding()+" "+me.browser.itemName; } }); }) .on("mouseover",function(d){ this.tipsy.show(); }) .on("mouseout" ,function(d){ this.tipsy.hide(); }) .on("click",function(d){ if(me.browser.recordDisplay.recordViewSummary===null) return; me.browser.recordDisplay.setSortingOpt_Active(me); me.browser.recordDisplay.refreshSortingOptions(); }); this.DOM.summaryViewAs = this.DOM.summaryIcons.append("span") .attr("class","summaryViewAs fa") .attr("viewAs","map") .each(function(d){ this.tipsy = new Tipsy(this, { gravity: 'ne', title: function(){ return "View as "+(me.viewType==='list'?'Map':'List'); } }); }) .on("mouseover",function(d){ this.tipsy.show(); }) .on("mouseout" ,function(d){ this.tipsy.hide(); }) .on("click",function(d){ this.tipsy.hide(); this.setAttribute("viewAs",me.viewType); me.viewAs( (me.viewType==='list') ? 'map' : 'list' ); }); this.DOM.summaryDescription = this.DOM.summaryIcons.append("span") .attr("class","summaryDescription fa fa-info-circle") .each(function(d){ this.tipsy = new Tipsy(this, { gravity:'ne', title:function(){return me.description;} }); }) .on("mouseover",function(d){ this.tipsy.show(); }) .on("mouseout" ,function(d){ this.tipsy.hide(); }); this.setDescription(this.description); this.DOM.summaryConfig = this.DOM.root.append("div").attr("class","summaryConfig"); this.DOM.wrapper = this.DOM.root.append("div").attr("class","wrapper"); this.insertDOM_EmptyAggr(); }, /** -- */ setDescription: function(description){ this.description = description; if(this.DOM.summaryDescription===undefined) return; this.DOM.summaryDescription.style("display",this.description===undefined?null:"inline"); }, /** -- */ insertChartAxis_Measure: function(dom, pos1, pos2){ var me=this; this.DOM.chartAxis_Measure = dom.append("div").attr("class","chartAxis_Measure"); this.DOM.chartAxis_Measure.append("span").attr("class","measurePercentControl") .each(function(){ this.tipsy = new Tipsy(this, { gravity: pos1, title: function(){ return "<span class='fa fa-eye'></span> "+kshf.lang.cur[(me.browser.percentModeActive?'Absolute':'Percent')]; }, }) }) .on("click",function(){ this.tipsy.hide(); me.browser.setPercentLabelMode(!me.browser.percentModeActive); }) .on("mouseover",function(){ me.browser.DOM.root.selectAll(".measurePercentControl").attr("highlight",true); this.tipsy.show(); }) .on("mouseout",function(){ me.browser.DOM.root.selectAll(".measurePercentControl").attr("highlight",false); this.tipsy.hide(); }); // Two controls, one for each side of the scale this.DOM.chartAxis_Measure.selectAll(".relativeModeControl").data(["left","right"]) .enter().append("span") .attr("class",function(d){ return "relativeModeControl measureAxis_"+d+" relativeModeControl_"+d; }) .each(function(d){ var pos = pos2; if(pos2==='nw' && d==="right") pos = 'ne'; this.tipsy = new Tipsy(this, { gravity: pos, title: function(){ return (me.browser.ratioModeActive?kshf.lang.cur.Absolute:kshf.lang.cur.Relative)+" "+ kshf.lang.cur.Width+ " <span class='fa fa-arrows-h'></span>"; }, }); }) .on("click",function(){ this.tipsy.hide(); me.browser.setMeasureAxisMode(!me.browser.ratioModeActive); }) .on("mouseover",function(){ me.browser.DOM.root.selectAll(".relativeModeControl").attr("highlight",true); this.tipsy.show(); }) .on("mouseout",function(){ me.browser.DOM.root.selectAll(".relativeModeControl").attr("highlight",false); this.tipsy.hide(); }); this.DOM.chartAxis_Measure_TickGroup = this.DOM.chartAxis_Measure.append("div").attr("class","tickGroup"); this.DOM.highlightedMeasureValue = this.DOM.chartAxis_Measure.append("div").attr("class","highlightedMeasureValue longRefLine"); this.DOM.highlightedMeasureValue.append("div").attr('class','fa fa-mouse-pointer highlightedAggrValuePointer'); }, /** -- */ setCollapsedAndLayout: function(hide){ this.setCollapsed(hide); this.browser.updateLayout_Height(); }, /** -- */ setCollapsed: function(v){ this.collapsed_pre = this.collapsed; this.collapsed = v; if(this.DOM.root){ this.DOM.root .attr("collapsed",this.collapsed) .attr("showConfig",false); if(!this.collapsed) { this.refreshViz_All(); this.refreshMeasureLabel(); } else { this.DOM.headerGroup.select(".buttonSummaryExpand").style("display","none"); } } }, /** -- */ refreshViz_All: function(){ if(this.isEmpty() || this.collapsed || !this.inBrowser()) return; this.refreshViz_Total(); this.refreshViz_Active(); this.refreshViz_Highlight(); this.refreshViz_Compare_All(); this.refreshViz_Axis(); }, /** -- */ insertDOM_EmptyAggr: function(){ var me = this; this.DOM.missingValueAggr = this.DOM.wrapper.append("span").attr("class","missingValueAggr fa fa-ban") .each(function(){ me.missingValueAggr.DOM.aggrGlyph = this; this.tipsy = new Tipsy(this, {gravity: 'w', title: function(){ var x = me.browser.getMeasureLabel(me.missingValueAggr, me); // TODO: Number should depend on filtering state, and also reflect percentage-mode return "<b>"+x+"</b> "+me.browser.getMeasureFuncTypeText()+me.browser.itemName+" "+kshf.lang.cur.NoData; }}); }) .on("mouseover",function(){ this.tipsy.show(); // TODO: Disable mouse-over action if aggregate has no active item me.browser.setSelect_Highlight(me,me.missingValueAggr); }) .on("mouseout" ,function(){ this.tipsy.hide(); me.browser.clearSelect_Highlight(); }) .on("click", function(){ if(d3.event.shiftKey){ me.browser.setSelect_Compare(me,me.missingValueAggr,true); return; } me.summaryFilter.clearFilter(); if(me.missingValueAggr.filtered){ me.missingValueAggr.filtered = false; this.removeAttribute("filtered"); return; } else { me.missingValueAggr.filtered = true; this.setAttribute("filtered",true); me.summaryFilter.how = "All"; me.summaryFilter.addFilter(); } }); }, /** -- */ refreshViz_EmptyRecords: function(){ if(!this.DOM.missingValueAggr) return; var me=this; var interp = d3.interpolateHsl(d3.rgb(211,211,211)/*lightgray*/, d3.rgb(255,69,0)); this.DOM.missingValueAggr .style("display",this.missingValueAggr.recCnt.Active>0?"block":"none") .style("color", function(){ if(me.missingValueAggr.recCnt.Active===0) return; return interp(me.missingValueAggr.ratioHighlightToActive()); }); }, refreshViz_Compare_All: function(){ var totalC = this.browser.getActiveComparedCount(); if(totalC===0) return; totalC++; // 1 more for highlight if(this.browser.measureFunc==="Avg") totalC++; var activeNum = totalC-2; if(this.browser.vizActive.Compared_A) { this.refreshViz_Compare("A", activeNum, totalC); activeNum--; } if(this.browser.vizActive.Compared_B) { this.refreshViz_Compare("B", activeNum, totalC); activeNum--; } if(this.browser.vizActive.Compared_C) { this.refreshViz_Compare("C", activeNum, totalC); activeNum--; } }, /** -- */ exportConfig: function(){ var config = { name: this.summaryName, panel: this.panel.name, }; // config.value if(this.summaryColumn!==this.summaryName){ config.value = this.summaryColumn; if(config.value===null){ // custom function config.value = this.summaryFunc.toString(); // if it is function, converts it to string representation } } if(this.collapsed) config.collapsed = true; if(this.description) config.description = this.description; if(this.catLabel_attr){ // Indexed string if(this.catLabel_attr!=="id") config.catLabel = this.catLabel_attr; } else if(this.catLabel_table){ // Lookup table config.catLabel = this.catLabel_table; } else if(this.catLabel_Func){ config.catLabel = this.catLabel_Func.toString(); // Function to string } if(this.minAggrValue>1) config.minAggrValue = this.minAggrValue; if(this.unitName) config.unitName = this.unitName; if(this.scaleType_forced) config.intervalScale = this.scaleType_forced; if(this.percentileChartVisible) config.showPercentile = this.percentileChartVisible; // catSortBy if(this.catSortBy){ var _sortBy = this.catSortBy[0]; if(_sortBy.sortKey){ config.catSortBy = _sortBy.sortKey; // string or lookup table } else if(_sortBy.value) { config.catSortBy = _sortBy.value.toString(); } // TODO: support 'inverse' option }; if(this.catTableName_custom){ config.catTableName = this.catTableName; } if(this.catSplit){ config.catSplit = this.catSplit; } if(this.viewType){ if(this.viewType==="map") config.viewAs = this.viewType; } return config; }, /** -- */ refreshMeasureLabel: function(){ if(this.isEmpty() || this.collapsed || !this.inBrowser() || this.DOM.measureLabel===undefined) return; var me=this; this.DOM.measureLabel.html(function(aggr){ return me.browser.getMeasureLabel(aggr,me); }); }, }; kshf.Summary_Categorical = function(){}; kshf.Summary_Categorical.prototype = new kshf.Summary_Base(); var Summary_Categorical_functions = { /** -- */ initialize: function(browser,name,attribFunc){ kshf.Summary_Base.prototype.initialize.call(this,browser,name,attribFunc); this.type='categorical'; this.heightRow_category = 18; this.show_set_matrix = false; this.scrollTop_cache = 0; this.firstCatIndexInView = 0; this.configRowCount = 0; this.minAggrValue = 1; this.catSortBy = []; this.viewType = 'list'; this.setCatLabel("id"); if(this.records.length<=1000) this.initializeAggregates(); }, /** -- */ initializeAggregates: function(){ if(this.aggr_initialized) return; if(this.catTableName===undefined){ // Create new table this.catTableName = this.summaryName+"_h_"+this.summaryID; } this.mapToAggregates(); if(this.catSortBy.length===0) this.setSortingOptions(); this.aggr_initialized = true; this.refreshViz_Nugget(); }, /** -- */ refreshViz_Nugget: function(){ if(this.DOM.nugget===undefined) return; var nuggetChart = this.DOM.nugget.select(".nuggetChart"); this.DOM.nugget .attr("aggr_initialized",this.aggr_initialized) .attr("datatype",this.getDataType()); if(!this.aggr_initialized) return; if(this.uniqueCategories()){ this.DOM.nugget.select(".nuggetInfo").html("<span class='fa fa-tag'></span><br>Unique"); nuggetChart.style("display",'none'); return; } nuggetChart.selectAll(".nuggetBar").data([]).exit().remove(); var totalWidth= 25; var maxAggregate_Total = this.getMaxAggr_Total(); nuggetChart.selectAll(".nuggetBar").data(this._cats).enter() .append("span") .attr("class","nuggetBar") .style("width",function(cat){ return totalWidth*(cat.records.length/maxAggregate_Total)+"px"; }); this.DOM.nugget.select(".nuggetInfo").html( "<span class='fa fa-tag"+(this.isMultiValued?"s":"")+"'></span><br>"+ this._cats.length+"<br>rows<br>"); }, /*********************************** * SIZE (HEIGH/WIDTH) QUERY FUNCTIONS *************************************/ /** -- */ getHeight_RangeMax: function(){ if(this.viewType==="map") { return this.getWidth()*1.5; } if(this.isEmpty()) return this.getHeight_Header(); // minimum 2 categories return this.getHeight_WithoutCats() + this._cats.length*this.heightRow_category; }, /** -- */ getHeight_RangeMin: function(){ if(this.isEmpty()) return this.getHeight_Header(); return this.getHeight_WithoutCats() + Math.min(this.catCount_Visible,2)*this.heightRow_category; }, getHeight_WithoutCats: function(){ return this.getHeight_Header() + this.getHeight_Config() + this.getHeight_Bottom(); }, /** -- */ getHeight_Config: function(){ return (this.showTextSearch?18:0)+(this.catSortBy.length>1?18:0); }, /** -- */ getHeight_Bottom: function(){ if(!this.areAllCatsInDisplay() || !this.panel.hideBarAxis || this._cats.length>4) return 18; return 0; }, /** -- */ getHeight_Content: function(){ return this.categoriesHeight + this.getHeight_Config() + this.getHeight_Bottom(); }, /** -- */ getHeight_VisibleAttrib: function(){ return this.catCount_Visible*this.heightRow_category; }, /** -- */ getWidth_Label: function(){ return this.panel.width_catLabel; }, /** -- */ getWidth_CatChart: function(){ // This will make the bar width extend over to the scroll area. // Doesn't look better, the amount of space saved makes chart harder to read and breaks the regularly spaced flow. /*if(!this.scrollBarShown()){ return this.panel.width_catBars+kshf.scrollWidth-5; }*/ return this.panel.width_catBars; }, /** -- */ areAllCatsInDisplay: function(){ return this.catCount_Visible===this.catCount_InDisplay; }, /** -- */ isEmpty: function(){ if(this._cats && this._cats.length===0) return true; return this.summaryFunc===undefined; }, /** -- */ hasCategories: function(){ if(this._cats && this._cats.length===0) return false; return this.summaryFunc!==undefined; }, /** -- */ uniqueCategories: function(){ if(this._cats===undefined) return true; if(this._cats.length===0) return true; return 1 === d3.max(this._cats, function(aggr){ return aggr.records.length; }); }, /*********************************** * SORTING FUNCTIONS *************************************/ /** -- */ insertSortingOption: function(opt){ this.catSortBy.push( this.prepareSortingOption(opt) ); }, /** -- */ prepareSortingOption: function(opt){ if(Array.isArray(opt)){ var _lookup = {}; opt.forEach(function(s,i){ _lookup[s] = i; }); return { inverse : false, no_resort : true, sortKey : opt, name : 'Custom Order', value : function(){ var v=_lookup[this.id]; if(v!==undefined) return v; return 99999; // unknown is 99999th item } }; } opt.inverse = opt.inverse || false; // Default is false if(opt.value){ if(typeof(opt.value)==="string"){ var x = opt.value; opt.name = opt.name || x; opt.sortKey = x; opt.value = function(){ return this[x]; } } else if(typeof(opt.value)==="function"){ if(opt.name===undefined) opt.name = "custom" } opt.no_resort = true; } else { opt.name = opt.name || "# of Active"; } if(opt.no_resort===undefined) opt.no_resort = (this._cats.length<=4); return opt; }, /** -- */ setSortingOptions: function(opts){ this.catSortBy = opts || {}; if(!Array.isArray(this.catSortBy)) { this.catSortBy = [this.catSortBy]; } else { // if it is an array, it might still be defining a sorting order for the categories if(this.catSortBy.every(function(v){ return (typeof v==="string"); })){ this.catSortBy = [this.catSortBy]; } } this.catSortBy.forEach(function(opt,i){ if(typeof opt==="string" || typeof opt==="function") this.catSortBy[i] = {value: opt}; this.catSortBy[i] = this.prepareSortingOption(this.catSortBy[i]); },this); this.catSortBy_Active = this.catSortBy[0]; this.updateCatSorting(0,true,true); this.refreshSortOptions(); this.refreshSortButton(); }, /** -- */ refreshSortButton: function(){ if(this.DOM.catSortButton===undefined) return; this.DOM.catSortButton .style("display",(this.catSortBy_Active.no_resort?"none":"inline-block")) .attr("inverse",this.catSortBy_Active.inverse); }, /** -- */ refreshSortOptions: function(){ if(this.DOM.optionSelect===undefined) return; this.refreshConfigRowCount(); this.DOM.optionSelect.style("display", (this.catSortBy.length>1)?"block":"none" ); this.DOM.optionSelect.selectAll(".sort_label").data([]).exit().remove(); // remove all existing options this.DOM.optionSelect.selectAll(".sort_label").data(this.catSortBy) .enter().append("option").attr("class", "sort_label").text(function(d){ return d.name; }); }, /** -- */ sortCategories: function(){ var me = this; var inverse = this.catSortBy_Active.inverse; if(this.catSortBy_Active.prep) this.catSortBy_Active.prep.call(this); // idCompareFunc can be based on integer or string comparison var idCompareFunc = function(a,b){return b.id()-a.id();}; if(typeof(this._cats[0].id())==="string") idCompareFunc = function(a,b){return b.id().localeCompare(a.id());}; var theSortFunc; var sortV = this.catSortBy_Active.value; // sortV can only be function. Just having the check for sanity if(sortV && typeof sortV==="function"){ // valueCompareFunc can be based on integer or string comparison var valueCompareFunc = function(a,b){return a-b;}; if(typeof(sortV.call(this._cats[0].data, this._cats[0]))==="string") valueCompareFunc = function(a,b){return a.localeCompare(b);}; // Of the given function takes 2 parameters, assume it defines a nice sorting order. if(sortV.length===2){ theSortFunc = sortV; } else { // The value is a custom value that returns an integer theSortFunc = function(a,b){ var x = valueCompareFunc(sortV.call(a.data,a),sortV.call(b.data,b)); if(x===0) x=idCompareFunc(a,b); if(inverse) x=-x; return x; }; } } else { theSortFunc = function(a,b){ // selected on top of the list if(!a.f_selected() && b.f_selected()) return 1; if( a.f_selected() && !b.f_selected()) return -1; // Rest var x = b.measure('Active') - a.measure('Active'); if(x===0) x = b.measure('Total') - a.measure('Total'); if(x===0) x = idCompareFunc(a,b); // stable sorting. ID's would be string most probably. if(inverse) x=-x; return x; }; } this._cats.sort(theSortFunc); this._cats.forEach(function(cat,i){ cat.orderIndex=i; }); }, /** -- */ setCatLabel: function( accessor ){ // Clear all assignments this.catLabel_attr = null; this.catLabel_table = null; this.catLabel_Func = null; if(typeof(accessor)==="function"){ this.catLabel_Func = accessor; } else if(typeof(accessor)==="string"){ this.catLabel_attr = accessor; this.catLabel_Func = function(){ return this[accessor]; }; } else if(typeof(accessor)==="object"){ // specifies key->value this.catLabel_table = accessor; this.catLabel_Func = function(){ var x = accessor[this.id]; return x?x:this.id; } } else { alert("Bad parameter"); return; } var me=this; if(this.DOM.theLabel) this.DOM.theLabel.html(function(cat){ return me.catLabel_Func.call(cat.data); }); }, /** -- */ setCatTooltip: function( catTooltip ){ if(typeof(catTooltip)==="function"){ this.catTooltip = catTooltip; } else if(typeof(catTooltip)==="string"){ var x = catTooltip; this.catTooltip = function(){ return this[x]; }; } else { this.setCatTooltip = undefined; this.DOM.aggrGlyphs.attr("title",undefined); return; } if(this.DOM.aggrGlyphs) this.DOM.aggrGlyphs.attr("title",function(cat){ return me.catTooltip.call(cat.data); }); }, /** -- */ setCatGeo: function( accessor){ if(typeof(accessor)==="function"){ this.catMap = accessor; } else if(typeof(accessor)==="string" || typeof(accessor)=="number"){ var x = accessor; this.catMap = function(){ return this[x]; }; } else { this.catMap = undefined; return; } if(this.DOM.root) this.DOM.root.attr("hasMap",true); }, /** -- */ setCatTable: function(tableName){ this.catTableName = tableName; this.catTableName_custom = true; if(this.aggr_initialized){ this.mapToAggregates(); this.updateCats(); } }, /** -- */ setCatSplit: function(catSplit){ this.catSplit = catSplit; if(this.aggr_initialized){ // Remove existing aggregations { var aggrs=this.browser.allAggregates; this._cats.forEach(function(aggr){ aggrs.splice(aggrs.indexOf(aggr),1); },this); if(this.DOM.aggrGroup) this.DOM.aggrGroup.selectAll(".aggrGlyph").data([]).exit().remove(); } this.mapToAggregates(); this.updateCats(); this.insertCategories(); this.updateCatSorting(0,true,true); this.refreshViz_Nugget(); } }, /** -- */ createSummaryFilter: function(){ var me=this; this.summaryFilter = this.browser.createFilter( { title: function(){ return me.summaryName }, onClear: function(){ me.clearCatTextSearch(); me.unselectAllCategories(); me._update_Selected(); }, onFilter: function(){ // at least one category is selected in some modality (and/ or/ not) me._update_Selected(); me.records.forEach(function(record){ var recordVal_s = record._valueCache[me.summaryID]; if(me.missingValueAggr.filtered===true){ record.setFilterCache(this.filterID, recordVal_s===null); return; } if(recordVal_s===null){ // survives if AND and OR is not selected record.setFilterCache(this.filterID, this.selected_AND.length===0 && this.selected_OR.length===0 ); return; } // Check NOT selections - If any mapped record is NOT, return false // Note: no other filtering depends on NOT state. // This is for ,multi-level filtering using not query /* if(this.selected_NOT.length>0){ if(!recordVal_s.every(function(record){ return !record.is_NOT() && record.isWanted; })){ record.setFilterCache(this.filterID,false); return; } }*/ function getAggr(v){ return me.catTable_id[v]; }; // If any of the record values are selected with NOT, the record will be removed if(this.selected_NOT.length>0){ if(!recordVal_s.every(function(v){ return !getAggr(v).is_NOT(); })){ record.setFilterCache(this.filterID,false); return; } } // All AND selections must be among the record values if(this.selected_AND.length>0){ var t=0; // Compute the number of record values selected with AND. recordVal_s.forEach(function(v){ if(getAggr(v).is_AND()) t++; }) if(t!==this.selected_AND.length){ record.setFilterCache(this.filterID,false); return; } } // One of the OR selections must be among the record values // Check OR selections - If any mapped record is OR, return true if(this.selected_OR.length>0){ record.setFilterCache(this.filterID, recordVal_s.some(function(v){return (getAggr(v).is_OR());}) ); return; } // only NOT selection record.setFilterCache(this.filterID,true); }, this); }, filterView_Detail: function(){ if(me.missingValueAggr.filtered===true) return kshf.lang.cur.NoData; // 'this' is the Filter // go over all records and prepare the list var selectedItemsText=""; var catTooltip = me.catTooltip; var totalSelectionCount = this.selectedCount_Total(); var query_and = " <span class='AndOrNot AndOrNot_And'>"+kshf.lang.cur.And+"</span> "; var query_or = " <span class='AndOrNot AndOrNot_Or'>"+kshf.lang.cur.Or+"</span> "; var query_not = " <span class='AndOrNot AndOrNot_Not'>"+kshf.lang.cur.Not+"</span> "; if(totalSelectionCount>4){ selectedItemsText = "<b>"+totalSelectionCount+"</b> selected"; // Note: Using selected because selections can include not, or,and etc (a variety of things) } else { var selectedItemsCount=0; // OR selections if(this.selected_OR.length>0){ var useBracket_or = this.selected_AND.length>0 || this.selected_NOT.length>0; if(useBracket_or) selectedItemsText+="["; // X or Y or .... this.selected_OR.forEach(function(category,i){ selectedItemsText+=((i!==0 || selectedItemsCount>0)?query_or:"")+"<span class='attribName'>" +me.catLabel_Func.call(category.data)+"</span>"; selectedItemsCount++; }); if(useBracket_or) selectedItemsText+="]"; } // AND selections this.selected_AND.forEach(function(category,i){ selectedItemsText+=((selectedItemsText!=="")?query_and:"") +"<span class='attribName'>"+me.catLabel_Func.call(category.data)+"</span>"; selectedItemsCount++; }); // NOT selections this.selected_NOT.forEach(function(category,i){ selectedItemsText+=query_not+"<span class='attribName'>"+me.catLabel_Func.call(category.data)+"</span>"; selectedItemsCount++; }); } return selectedItemsText; } }); this.summaryFilter.selected_AND = []; this.summaryFilter.selected_OR = []; this.summaryFilter.selected_NOT = []; this.summaryFilter.selectedCount_Total = function(){ return this.selected_AND.length + this.selected_OR.length + this.selected_NOT.length; }; this.summaryFilter.selected_Any = function(){ return this.selected_AND.length>0 || this.selected_OR.length>0 || this.selected_NOT.length>0; }; this.summaryFilter.selected_All_clear = function(){ kshf.Util.clearArray(this.selected_AND); kshf.Util.clearArray(this.selected_OR); kshf.Util.clearArray(this.selected_NOT); }; }, /** -- * Note: accesses summaryFilter, summaryFunc */ mapToAggregates: function(){ var aggrTable_id = {}; var aggrTable = []; var mmmm=false; // Converting from kshf.Record to kshf.Aggregate if(kshf.dt[this.catTableName] && kshf.dt[this.catTableName][0] instanceof kshf.Record ){ kshf.dt[this.catTableName].forEach(function(record){ var aggr = new kshf.Aggregate(); aggr.init(record.data,record.idIndex); aggrTable_id[aggr.id()] = aggr; aggrTable.push(aggr); this.browser.allAggregates.push(aggr); },this); } else { mmmm = true; } this.catTable_id = aggrTable_id; this._cats = aggrTable; var maxDegree = 0; var hasString = false; this.records.forEach(function(record){ var mapping = this.summaryFunc.call(record.data,record); // Split if(this.catSplit && typeof mapping === "string"){ mapping = mapping.split(this.catSplit); } // make mapping an array if it is not if(!(mapping instanceof Array)) mapping = [mapping]; // Filter invalid / duplicate values var found = {}; mapping = mapping.filter(function(e){ if(e===undefined || e==="" || e===null || found[e]!==undefined) return false; return (found[e] = true); }); // Record is not mapped to any value (missing value) if(mapping.length===0) { record._valueCache[this.summaryID] = null; if(record._aggrCache[this.summaryID]!==this.missingValueAggr) this.missingValueAggr.addRecord(record); return; } record._valueCache[this.summaryID] = []; maxDegree = Math.max(maxDegree, mapping.length); mapping.forEach(function(v){ if(typeof(v)==="string") hasString=true; var aggr = aggrTable_id[v]; if(aggr==undefined) { aggr = new kshf.Aggregate(); aggr.init({id:v},'id'); aggrTable_id[v] = aggr; this._cats.push(aggr); this.browser.allAggregates.push(aggr); } record._valueCache[this.summaryID].push(v); aggr.addRecord(record); },this); }, this); if(mmmm && hasString){ this._cats.forEach(function(aggr){ aggr.data.id = ""+aggr.data.id; }); } this.isMultiValued = maxDegree>1; // add degree summary if attrib has multi-value records and set-vis is enabled if(this.isMultiValued && this.enableSetVis){ this.browser.addSummary( { name:"<i class='fa fa-hand-o-up'></i> # of "+this.summaryName, value: function(record){ var arr=record._valueCache[me.summaryID]; if(arr===null) return null; // maps to no items return arr.length; }, collapsed: true, type: 'interval', panel: this.panel }, this.browser.primaryTableName ); } this.updateCats(); this.unselectAllCategories(); this.refreshViz_EmptyRecords(); }, // Modified internal dataMap function - Skip rows with 0 active item count setMinAggrValue: function(v){ this.minAggrValue = Math.max(1,v); this._cats = this._cats.filter(function(cat){ return cat.records.length>=this.minAggrValue; },this); this.updateCats(); }, /** -- */ updateCats: function(){ // Few categories. Disable resorting after filtering if(this._cats.length<=4) { this.catSortBy.forEach(function(sortOpt){ sortOpt.no_resort=true; }); } this.showTextSearch = this._cats.length>=20; this.updateCatCount_Active(); }, /** -- */ updateCatCount_Active: function(){ this.catCount_Visible = 0; this.catCount_NowVisible = 0; this.catCount_NowInvisible = 0; this._cats.forEach(function(cat){ v = this.isCatActive(cat); cat.isActiveBefore = cat.isActive; cat.isActive = v; if(!cat.isActive && cat.isActiveBefore) this.catCount_NowInvisible++; if(cat.isActive && !cat.isActiveBefore) this.catCount_NowVisible++; if(cat.isActive) this.catCount_Visible++; },this); }, /** -- */ refreshConfigRowCount: function(){ this.configRowCount = 0; if(this.showTextSearch) this.configRowCount++; if(this.catSortBy.length>1) this.configRowCount++; if(this.configRowCount>0) this.DOM.summaryControls.style("display","block"); }, /** -- */ initDOM: function(beforeDOM){ this.initializeAggregates(); var me=this; if(this.DOM.inited===true) return; this.insertRoot(beforeDOM); this.DOM.root .attr("filtered_or",0) .attr("filtered_and",0) .attr("filtered_not",0) .attr("filtered_total",0) .attr("isMultiValued",this.isMultiValued) .attr("summary_type","categorical") .attr("hasMap",this.catMap!==undefined) .attr("viewType",this.viewType); this.insertHeader(); if(!this.isEmpty()) this.init_DOM_Cat(); this.setCollapsed(this.collapsed); this.DOM.summaryConfig_CatHeight = this.DOM.summaryConfig.append("div") .attr("class","summaryConfig_CatHeight summaryConfig_Option"); this.DOM.summaryConfig_CatHeight.append("span").html("<i class='fa fa-arrows-v'></i> Category Height: "); x = this.DOM.summaryConfig_CatHeight.append("span").attr("class","optionGroup"); x.selectAll(".configOption").data( [ {l:"Short",v:18}, {l:"Long", v:35} ]) .enter() .append("span").attr("class",function(d){ return "configOption pos_"+d.v;}) .attr("active",function(d){ return d.v===me.heightRow_category; }) .html(function(d){ return d.l; }) .on("click", function(d){ me.setHeight_Category(d.v); }) this.DOM.inited = true; }, /** -- */ init_DOM_Cat: function(){ var me=this; this.DOM.summaryCategorical = this.DOM.wrapper.append("div").attr("class","summaryCategorical"); this.DOM.summaryControls = this.DOM.summaryCategorical.append("div").attr("class","summaryControls"); this.initDOM_CatTextSearch(); this.initDOM_CatSortButton(); this.initDOM_CatSortOpts(); if(this.showTextSearch) this.DOM.catTextSearch.style("display","block"); this.refreshConfigRowCount(); this.DOM.scrollToTop = this.DOM.summaryCategorical.append("div").attr("class","scrollToTop fa fa-arrow-up") .each(function(){ this.tipsy = new Tipsy(this, {gravity: 'e', title: kshf.lang.cur.ScrollToTop }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .on("click",function(d){ this.tipsy.hide(); kshf.Util.scrollToPos_do(me.DOM.aggrGroup[0][0],0); }); this.DOM.aggrGroup = this.DOM.summaryCategorical.append("div").attr("class","aggrGroup") .on("mousedown",function(){ d3.event.stopPropagation(); d3.event.preventDefault(); }) .on("scroll",function(d){ if(kshf.Util.ignoreScrollEvents===true) return; me.scrollTop_cache = me.DOM.aggrGroup[0][0].scrollTop; me.DOM.scrollToTop.style("visibility", me.scrollTop_cache>0?"visible":"hidden"); me.firstCatIndexInView = Math.floor(me.scrollTop_cache/me.heightRow_category); me.refreshScrollDisplayMore(me.firstCatIndexInView+me.catCount_InDisplay); me.updateCatIsInView(); me.cullAttribs(); me.refreshMeasureLabel(); }); this.DOM.aggrGroup_list = this.DOM.aggrGroup; this.DOM.catMap_Base = this.DOM.summaryCategorical.append("div").attr("class","catMap_Base"); // with this, I make sure that the (scrollable) div height is correctly set to visible number of categories this.DOM.chartBackground = this.DOM.aggrGroup.append("span").attr("class","chartBackground"); this.DOM.chartCatLabelResize = this.DOM.chartBackground.append("span").attr("class","chartCatLabelResize dragWidthHandle") .on("mousedown", function (d, i) { var resizeDOM = this; me.panel.DOM.root.attr("catLabelDragging",true); me.browser.DOM.pointerBlock.attr("active",""); me.browser.DOM.root.style('cursor','col-resize'); me.browser.setNoAnim(true); var mouseDown_x = d3.mouse(d3.select("body")[0][0])[0]; var initWidth = me.panel.width_catLabel; d3.select("body").on("mousemove", function() { var mouseDown_x_diff = d3.mouse(d3.select("body")[0][0])[0]-mouseDown_x; me.panel.setWidthCatLabel(initWidth+mouseDown_x_diff); }).on("mouseup", function(){ me.panel.DOM.root.attr("catLabelDragging",false); me.browser.DOM.pointerBlock.attr("active",null); me.browser.DOM.root.style('cursor','default'); me.browser.setNoAnim(false); d3.select("body").on("mousemove", null).on("mouseup", null); }); d3.event.preventDefault(); }); this.DOM.belowCatChart = this.DOM.summaryCategorical.append("div").attr("class","belowCatChart"); this.insertChartAxis_Measure(this.DOM.belowCatChart,'e','e'); this.DOM.scroll_display_more = this.DOM.belowCatChart.append("div") .attr("class","hasLabelWidth scroll_display_more") .on("click",function(){ kshf.Util.scrollToPos_do( me.DOM.aggrGroup[0][0],me.DOM.aggrGroup[0][0].scrollTop+me.heightRow_category); }); this.insertCategories(); this.refreshLabelWidth(); this.updateCatSorting(0,true,true); }, /** -- */ initDOM_CatSortButton: function(){ var me=this; // Context dependent this.DOM.catSortButton = this.DOM.summaryControls.append("span").attr("class","catSortButton sortButton fa") .on("click",function(d){ if(me.dirtySort){ me.dirtySort = false; me.DOM.catSortButton.attr("resort",true); } else{ me.catSortBy_Active.inverse = me.catSortBy_Active.inverse?false:true; me.refreshSortButton(); } me.updateCatSorting(0,true); }) .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'w', title: function(){ return kshf.lang.cur[me.dirtySort?'Reorder':'ReverseOrder']; } }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }); this.refreshSortButton(); }, /** -- */ initDOM_CatSortOpts: function(){ var me=this; var x = this.DOM.summaryControls.append("span").attr("class","sortOptionSelectGroup hasLabelWidth"); this.DOM.optionSelect = x.append("select").attr("class","optionSelect") .on("change", function(){ me.catSortBy_Active = me.catSortBy[this.selectedIndex]; me.refreshSortButton(); me.updateCatSorting(0,true); }) this.refreshSortOptions(); }, /** -- */ initDOM_CatTextSearch: function(){ var me=this; this.DOM.catTextSearch = this.DOM.summaryControls.append("div").attr("class","textSearchBox catTextSearch hasLabelWidth"); this.DOM.catTextSearchControl = this.DOM.catTextSearch.append("span") .attr("class","textSearchControl fa") .on("click",function() { me.DOM.catTextSearchControl.attr("showClear",false); me.summaryFilter.clearFilter(); }); this.DOM.catTextSearchInput = this.DOM.catTextSearch.append("input") .attr("class","textSearchInput") .attr("type","text") .attr("placeholder",kshf.lang.cur.Search) // .on("mousedown",function(){alert('sdsdd');}) .on("input",function(){ if(this.timer) clearTimeout(this.timer); var x = this; this.timer = setTimeout( function(){ me.unselectAllCategories(); var query = []; // split the query by " character var processed = x.value.toLowerCase().split('"'); processed.forEach(function(block,i){ if(i%2===0) { block.split(/\s+/).forEach(function(q){ query.push(q)}); } else { query.push(block); } }); // Remove the empty strings query = query.filter(function(v){ return v!==""}); if(query.length>0){ me.DOM.catTextSearchControl.attr("showClear",true); var labelFunc = me.catLabel_Func; var tooltipFunc = me.catTooltip; me._cats.forEach(function(_category){ var catLabel = labelFunc.call(_category.data).toString().toLowerCase(); var f = query.every(function(query_str){ if(catLabel.indexOf(query_str)!==-1){ return true; } if(tooltipFunc) { var tooltipText = tooltipFunc.call(_category.data); return (tooltipText && tooltipText.toLowerCase().indexOf(query_str)!==-1); } return false; }); if(f){ _category.set_OR(me.summaryFilter.selected_OR); } else { _category.set_NONE(me.summaryFilter.selected_OR); } }); // All categories are process, and the filtering state is set. Now, process the summary as a whole if(me.summaryFilter.selectedCount_Total()===0){ me.skipTextSearchClear = true; me.summaryFilter.clearFilter(); me.skipTextSearchClear = false; } else { me.summaryFilter.how = "All"; me.missingValueAggr.filtered = false; me.summaryFilter.addFilter(); } } }, 750); }); }, /** returns the maximum active aggregate value per row in chart data */ getMaxAggr_Active: function(){ return d3.max(this._cats, function(aggr){ return aggr.measure('Active'); }); }, /** returns the maximum total aggregate value stored per row in chart data */ getMaxAggr_Total: function(){ if(this._cats===undefined) return 0; if(this.isEmpty()) return 0; return d3.max(this._cats, function(aggr){ return aggr.measure('Total'); }); }, /** -- */ _update_Selected: function(){ if(this.DOM.root) { this.DOM.root .attr("filtered",this.isFiltered()) .attr("filtered_or",this.summaryFilter.selected_OR.length) .attr("filtered_and",this.summaryFilter.selected_AND.length) .attr("filtered_not",this.summaryFilter.selected_NOT.length) .attr("filtered_total",this.summaryFilter.selectedCount_Total()); } var show_box = (this.summaryFilter.selected_OR.length+this.summaryFilter.selected_AND.length)>1; this.summaryFilter.selected_OR.forEach(function(category){ category.DOM.aggrGlyph.setAttribute("show-box",show_box); },this); this.summaryFilter.selected_AND.forEach(function(category){ category.DOM.aggrGlyph.setAttribute("show-box",show_box); },this); this.summaryFilter.selected_NOT.forEach(function(category){ category.DOM.aggrGlyph.setAttribute("show-box","true"); },this); }, /** -- */ unselectAllCategories: function(){ this._cats.forEach(function(aggr){ if(aggr.f_selected() && aggr.DOM.aggrGlyph) aggr.DOM.aggrGlyph.removeAttribute("selection"); aggr.set_NONE(); }); this.summaryFilter.selected_All_clear(); if(this.DOM.inited) this.DOM.missingValueAggr.attr("filtered",null); }, /** -- */ clearCatTextSearch: function(){ if(!this.showTextSearch) return; if(this.skipTextSearchClear) return; this.DOM.catTextSearchControl.attr("showClear",false); this.DOM.catTextSearchInput[0][0].value = ''; }, /** -- */ scrollBarShown: function(){ return this.categoriesHeight<this._cats.length*this.heightRow_category; }, /** -- */ updateChartScale_Measure: function(){ if(!this.aggr_initialized || this.isEmpty()) return; // nothing to do var maxMeasureValue = this.getMaxAggr_Active(); if(this.browser.measureFunc==="Avg"){ ["Highlighted","Compared_A","Compared_B","Compared_C"].forEach(function(distr){ if(!this.browser.vizActive[distr]) return; maxMeasureValue = Math.max(maxMeasureValue, d3.max(this._cats, function(aggr){return aggr.measure(distr);} ) ); },this); } this.chartScale_Measure .rangeRound([0, this.getWidth_CatChart()]) .nice(this.chartAxis_Measure_TickSkip()) .domain([ 0,(maxMeasureValue===0)?1:maxMeasureValue ]); this.refreshViz_All(); }, /** -- */ setHeight: function(newHeight){ var me = this; if(this.isEmpty()) return; // take into consideration the other components in the summary var attribHeight_old = this.categoriesHeight; newHeight -= this.getHeight_Header()+this.getHeight_Config()+this.getHeight_Bottom(); if(this.viewType==='map'){ this.categoriesHeight = newHeight; if(this.categoriesHeight!==attribHeight_old) setTimeout(function(){ me.map_zoomToActive();}, 1000); return; } this.categoriesHeight = Math.min( newHeight, this.heightRow_category*this.catCount_Visible); if(this.cbSetHeight && attribHeight_old!==this.categoriesHeight) this.cbSetHeight(this); }, /** -- */ setHeight_Category: function(h){ var me=this; this.heightRow_category = h; if(this.viewType==='list') { this.refreshHeight_Category(); } else { this.heightRow_category_dirty = true; } }, /** -- */ refreshHeight_Category: function(){ var me=this; this.heightRow_category_dirty = false; this.browser.setNoAnim(true); this.browser.updateLayout(); this.DOM.aggrGlyphs .each(function(aggr){ kshf.Util.setTransform(this, "translate("+aggr.posX+"px,"+(me.heightRow_category*aggr.orderIndex)+"px)"); }) .style("height",this.heightRow_category+"px"); this.DOM.aggrGlyphs.selectAll(".categoryLabel").style("padding-top",(this.heightRow_category/2-8)+"px"); this.DOM.chartBackground.style("height",this.getHeight_VisibleAttrib()+"px"); this.DOM.chartCatLabelResize.style("height",this.getHeight_VisibleAttrib()+"px"); this.DOM.summaryConfig_CatHeight.selectAll(".configOption").attr("active",false); this.DOM.summaryConfig_CatHeight.selectAll(".pos_"+this.heightRow_category).attr("active",true); if(this.cbSetHeight) this.cbSetHeight(this); setTimeout(function(){ me.browser.setNoAnim(false); },100); }, /** -- */ updateAfterFilter: function(){ if(this.isEmpty() || this.collapsed || !this.inBrowser()) return; var me=this; if(this.viewType==='map'){ this.updateCatCount_Active(); //this.map_refreshBounds_Active(); //setTimeout(function(){ me.map_zoomToActive(); }, 1000); this.refreshMeasureLabel(); this.refreshViz_Active(); return; } this.updateChartScale_Measure(); this.refreshMeasureLabel(); this.refreshViz_EmptyRecords(); if(this.show_set_matrix) { this.dirtySort = true; this.DOM.catSortButton.attr('resort',true); } if(!this.dirtySort) { this.updateCatSorting(); } else { this.refreshViz_All(); this.refreshMeasureLabel(); } }, /** -- */ refreshWidth: function(){ if(this.DOM.summaryCategorical===undefined) return; this.updateChartScale_Measure(); this.DOM.summaryCategorical.style("width",this.getWidth()+"px"); this.DOM.summaryName.style("max-width",(this.getWidth()-40)+"px"); this.DOM.chartAxis_Measure.selectAll(".relativeModeControl") .style("width",(this.getWidth()-this.panel.width_catMeasureLabel-this.getWidth_Label()-kshf.scrollWidth)+"px"); this.refreshViz_Axis(); }, /** -- */ refreshViz_Total: function(){ if(this.isEmpty() || this.collapsed) return; if(this.viewType==='map') return; // Maps do not display total distribution. if(this.browser.ratioModeActive){ // Do not need to update total. Total value is invisible. Percent view is based on active count. this.DOM.measureTotalTip.style("opacity",0); } else { var me = this; var width_Text = this.getWidth_Label()+this.panel.width_catMeasureLabel; this.DOM.measure_Total.each(function(_cat){ kshf.Util.setTransform(this, "translateX("+width_Text+"px) scaleX("+me.chartScale_Measure(_cat.measure('Total'))+")"); }); this.DOM.measureTotalTip .each(function(_cat){ kshf.Util.setTransform(this, "translateX("+(me.chartScale_Measure.range()[1]+width_Text)+"px)"); }) .style("opacity",function(_cat){ return (_cat.measure('Total')>me.chartScale_Measure.domain()[1])?1:0; }); } }, /** -- */ refreshMapBounds: function(){ var maxAggr_Active = this.getMaxAggr_Active(); var boundMin, boundMax; if(this.browser.percentModeActive){ boundMin = 0; boundMax = 100*maxAggr_Active/this.browser.allRecordsAggr.measure('Active'); } else { boundMin = 1; //d3.min(this._cats, function(_cat){ return _cat.measure.Active; }), boundMax = maxAggr_Active; } this.mapColorScale = d3.scale.linear().range([0, 9]).domain([boundMin, boundMax]); this.DOM.catMapColorScale.select(".boundMin").html( this.browser.getMeasureLabel(boundMin,this) ); this.DOM.catMapColorScale.select(".boundMax").html( this.browser.getMeasureLabel(boundMax,this) ); }, /** -- */ refreshViz_Active: function(){ if(this.isEmpty() || this.collapsed) return; var me=this; var ratioMode = this.browser.ratioModeActive; if(this.viewType==='map') { this.refreshMapBounds(); var allRecordsAggr_measure_Active = me.browser.allRecordsAggr.measure('Active'); this.DOM.measure_Active .attr("fill", function(_cat){ var v = _cat.measure('Active'); if(v<=0 || v===undefined ) return "url(#diagonalHatch)"; if(me.browser.percentModeActive){ v = 100*v/allRecordsAggr_measure_Active; } var vv = me.mapColorScale(v); if(ratioMode) vv=0; //if(me.sortingOpt_Active.invertColorScale) vv = 9 - vv; return me.mapColorQuantize(vv); }) .attr("stroke", function(_cat){ var v = _cat.measure('Active'); if(me.browser.percentModeActive){ v = 100*v/allRecordsAggr_measure_Active; } var vv = 9-me.mapColorScale(v); if(ratioMode) vv=8; //if(me.sortingOpt_Active.invertColorScale) vv = 9 - vv; return me.mapColorQuantize(vv); }); return; } var maxWidth = this.chartScale_Measure.range()[1]; var width_Text = this.getWidth_Label()+this.panel.width_catMeasureLabel; this.DOM.measure_Active.each(function(_cat){ kshf.Util.setTransform(this,"translateX("+width_Text+"px) scaleX("+(ratioMode? ((_cat.measure_Active===0)?0:maxWidth): me.chartScale_Measure(_cat.measure('Active')) )+")"); }); this.DOM.attribClickArea.style("width",function(_cat){ return width_Text+(ratioMode? ((_cat.recCnt.Active===0)?0:maxWidth): Math.min((me.chartScale_Measure(_cat.measure('Active'))+10),maxWidth) )+"px"; }); this.DOM.lockButton .attr("inside",function(_cat){ if(ratioMode) return ""; if(maxWidth-me.chartScale_Measure(_cat.measure('Active'))<10) return ""; return null; // nope, not inside }); }, /** -- */ refreshViz_Highlight: function(){ if(this.isEmpty() || this.collapsed || !this.DOM.inited || !this.inBrowser()) return; var me=this; this.refreshViz_EmptyRecords(); this.refreshMeasureLabel(); var ratioMode = this.browser.ratioModeActive; var isThisIt = this===this.browser.highlightSelectedSummary; var maxWidth = this.chartScale_Measure.range()[1]; var width_Text = this.getWidth_Label()+this.panel.width_catMeasureLabel; if(this.browser.vizActive.Highlighted){ if(this.browser.ratioModeActive) { if(this.viewType==="map"){ //this.DOM.highlightedMeasureValue.style("left",(100*(this.mapColorScale(aggr.measure.Highlighted)/9))+"%"); } else { this.DOM.highlightedMeasureValue .style("opacity",1) .style("left",(this.browser.allRecordsAggr.ratioHighlightToTotal()*maxWidth)+"px"); } } } else { this.DOM.highlightedMeasureValue.style("opacity",0); } if(this.viewType=='map'){ if(!this.browser.vizActive.Highlighted){ this.refreshViz_Active(); return; } if(!isThisIt || this.isMultiValued) { var boundMin = ratioMode ? d3.min(this._cats, function(aggr){ if(aggr.recCnt.Active===0 || aggr.recCnt.Highlighted===0) return null; return 100*aggr.ratioHighlightToActive(); }) : 1; //d3.min(this._cats, function(_cat){ return _cat.measure.Active; }), var boundMax = ratioMode ? d3.max(this._cats, function(_cat){ return (_cat._measure.Active===0) ? null : 100*_cat.ratioHighlightToActive(); }) : d3.max(this._cats, function(_cat){ return _cat.measure('Highlighted'); }); this.DOM.catMapColorScale.select(".boundMin").text(Math.round(boundMin)); this.DOM.catMapColorScale.select(".boundMax").text(Math.round(boundMax)); this.mapColorScale = d3.scale.linear() .range([0, 9]) .domain([boundMin,boundMax]); } var allRecordsAggr_measure_Active = me.browser.allRecordsAggr.measure('Active'); this.DOM.measure_Active .attr("fill", function(_cat){ //if(_cat === me.browser.selectedAggr.Highlighted) return ""; var _v; if(me.isMultiValued || me.browser.highlightSelectedSummary!==me){ v = _cat.measure('Highlighted'); if(ratioMode) v = 100*v/_cat.measure('Active'); } else { v = _cat.measure('Active'); if(me.browser.percentModeActive){ v = 100*v/allRecordsAggr_measure_Active; } } if(v<=0 || v===undefined ) return "url(#diagonalHatch)"; return me.mapColorQuantize(me.mapColorScale(v)); }) return; } if(this.viewType==='list'){ var totalC = this.browser.getActiveComparedCount(); if(this.browser.measureFunc==="Avg") totalC++; var barHeight = (this.heightRow_category-8)/(totalC+1); this.DOM.measure_Highlighted.each(function(aggr){ var p = aggr.measure('Highlighted'); if(me.browser.preview_not) p = aggr._measure.Active - aggr._measure.Highlighted; kshf.Util.setTransform(this, "translateX("+width_Text+"px) "+ "scale("+(ratioMode ? ((p/aggr._measure.Active)*maxWidth ) : me.chartScale_Measure(p))+","+barHeight+")"); }); } }, /** -- */ refreshViz_Compare: function(cT, curGroup, totalGroups){ if(this.isEmpty() || this.collapsed || !this.inBrowser()) return; var me=this, ratioMode=this.browser.ratioModeActive, maxWidth = this.chartScale_Measure.range()[1]; var width_Text = this.getWidth_Label()+this.panel.width_catMeasureLabel; var _translateX = "translateX("+width_Text+"px) "; var barHeight = (this.heightRow_category-8)/totalGroups; var _translateY = "translateY("+(barHeight*(curGroup+1))+"px)"; var compId = "Compared_"+cT; this.DOM["measure_Compared_"+cT].each(function(aggr){ var sx = (me.browser.vizActive[compId])? ( ratioMode ? (aggr.ratioCompareToActive(cT)*maxWidth) : me.chartScale_Measure(aggr.measure(compId)) ) : 0; kshf.Util.setTransform(this,_translateX+_translateY+"scale("+sx+","+barHeight+")"); }); }, /** -- */ refreshViz_Axis: function(){ if(this.isEmpty()) return; var me=this; var tickValues, posFunc, transformFunc, maxValue, chartWidth = this.getWidth_CatChart(); var axis_Scale = this.chartScale_Measure; function setCustomAxis(){ axis_Scale = d3.scale.linear() .rangeRound([0, chartWidth]) .nice(me.chartAxis_Measure_TickSkip()) .clamp(true) .domain([0,maxValue]); }; if(this.browser.ratioModeActive) { maxValue = 100; setCustomAxis(); } else if(this.browser.percentModeActive) { maxValue = Math.round(100*me.getMaxAggr_Active()/me.browser.allRecordsAggr.measure('Active')); setCustomAxis(); } // GET TICK VALUES *********************************************************** tickValues = axis_Scale.ticks(this.chartAxis_Measure_TickSkip()); // remove 0-tick tickValues = tickValues.filter(function(d){return d!==0;}); // Remove non-integer values from count if((this.browser.measureFunc==="Count") || (this.browser.measureFunc==="Sum" && !this.browser.measureSummary.hasFloat)){ tickValues = tickValues.filter(function(d){return d%1===0;}); } var tickDoms = this.DOM.chartAxis_Measure_TickGroup.selectAll("span.tick").data(tickValues,function(i){return i;}); transformFunc = function(d){ kshf.Util.setTransform(this,"translateX("+(axis_Scale(d)-0.5)+"px)"); } var x=this.browser.noAnim; if(x===false) this.browser.setNoAnim(true); var tickData_new=tickDoms.enter().append("span").attr("class","tick").each(transformFunc); if(x===false) this.browser.setNoAnim(false); // translate the ticks horizontally on scale tickData_new.append("span").attr("class","line longRefLine") .style("top","-"+(this.categoriesHeight+3)+"px") .style("height",(this.categoriesHeight-1)+"px"); tickData_new.append("span").attr("class","text"); if(this.configRowCount>0){ var h=this.categoriesHeight; var hm=tickData_new.append("span").attr("class","text text_upper").style("top",(-h-21)+"px"); this.DOM.chartAxis_Measure.selectAll(".relativeModeControl_right").style("top",(-h-14)+"px") .style("display","block"); this.DOM.chartAxis_Measure.select(".chartAxis_Measure_background_2").style("display","block"); } this.DOM.chartAxis_Measure_TickGroup.selectAll(".text").html(function(d){ return me.browser.getMeasureLabel(d); }); setTimeout(function(){ me.DOM.chartAxis_Measure.selectAll("span.tick").style("opacity",1).each(transformFunc); }); tickDoms.exit().remove(); }, /** -- */ refreshLabelWidth: function(){ if(this.isEmpty()) return; if(this.DOM.summaryCategorical===undefined) return; var labelWidth = this.getWidth_Label(); var barChartMinX = labelWidth + this.panel.width_catMeasureLabel; this.DOM.chartCatLabelResize.style("left",(labelWidth+1)+"px"); this.DOM.summaryCategorical.selectAll(".hasLabelWidth").style("width",labelWidth+"px"); this.DOM.measureLabel .style("left",labelWidth+"px") .style("width",this.panel.width_catMeasureLabel+"px"); this.DOM.chartAxis_Measure.each(function(){ kshf.Util.setTransform(this,"translateX("+barChartMinX+"px)"); }); this.DOM.catSortButton .style("left",labelWidth+"px") .style("width",this.panel.width_catMeasureLabel+"px"); }, /** -- */ refreshScrollDisplayMore: function(bottomItem){ if(this._cats.length<=4) { this.DOM.scroll_display_more.style("display","none"); return; } var moreTxt = ""+this.catCount_Visible+" "+kshf.lang.cur.Rows; var below = this.catCount_Visible-bottomItem; if(below>0) moreTxt+=" <span class='fa fa-angle-down'></span>"+below+" "+kshf.lang.cur.More; this.DOM.scroll_display_more.html(moreTxt); }, /** -- */ refreshHeight: function(){ if(this.isEmpty()) return; // update catCount_InDisplay var c = Math.floor(this.categoriesHeight / this.heightRow_category); var c = Math.floor(this.categoriesHeight / this.heightRow_category); if(c<0) c=1; if(c>this.catCount_Visible) c=this.catCount_Visible; if(this.catCount_Visible<=2){ c = this.catCount_Visible; } else { c = Math.max(c,2); } this.catCount_InDisplay = c+1; this.catCount_InDisplay = Math.min(this.catCount_InDisplay,this.catCount_Visible); this.refreshScrollDisplayMore(this.firstCatIndexInView+this.catCount_InDisplay); this.updateCatIsInView(); this.cullAttribs(); this.DOM.headerGroup.select(".buttonSummaryExpand").style("display", (this.panel.getNumOfOpenSummaries()<=1||this.areAllCatsInDisplay())? "none": "inline-block" ); this.updateChartScale_Measure(); var h=this.categoriesHeight; this.DOM.wrapper.style("height",(this.collapsed?"0":this.getHeight_Content())+"px"); this.DOM.aggrGroup.style("height",h+"px"); this.DOM.root.style("max-height",(this.getHeight()+1)+"px"); this.DOM.chartAxis_Measure.selectAll(".longRefLine").style("top",(-h+1)+"px").style("height",(h-2)+"px"); this.DOM.chartAxis_Measure.selectAll(".text_upper").style("top",(-h-21)+"px"); this.DOM.chartAxis_Measure.selectAll(".chartAxis_Measure_background_2").style("top",(-h-12)+"px"); if(this.viewType==='map'){ this.DOM.catMap_Base.style("height",h+"px"); if(this.DOM.catMap_SVG) this.DOM.catMap_SVG.style("height",h+"px"); if(this.leafletAttrMap) this.leafletAttrMap.invalidateSize(); } }, /** -- */ isCatActive: function(category){ if(category.f_selected()) return true; if(category.recCnt.Active!==0) return true; // summary is not filtered yet, don't show categories with no records if(!this.isFiltered()) return category.recCnt.Active!==0; if(this.viewType==='map') return category.recCnt.Active!==0; // Hide if multiple options are selected and selection is and // if(this.summaryFilter.selecttype==="SelectAnd") return false; // TODO: Figuring out non-selected, zero-active-item attribs under "SelectOr" is tricky! return true; }, /** -- */ isCatSelectable: function(category){ if(category.f_selected()) return true; if(category.recCnt.Active!==0) return true; // Show if multiple attributes are selected and the summary does not include multi value records if(this.isFiltered() && !this.isMultiValued) return true; // Hide return false; }, /** When clicked on an attribute ... what: AND / OR / NOT / NONE how: MoreResults / LessResults */ filterCategory: function(ctgry, what, how){ if(this.browser.skipSortingFacet){ // you can now sort the last filtered summary, attention is no longer there. this.browser.skipSortingFacet.dirtySort = false; this.browser.skipSortingFacet.DOM.catSortButton.attr("resort",false); } this.browser.skipSortingFacet=this; this.browser.skipSortingFacet.dirtySort = true; this.browser.skipSortingFacet.DOM.catSortButton.attr("resort",true); var i=0; var preTest = (this.summaryFilter.selected_OR.length>0 && (this.summaryFilter.selected_AND.length>0 || this.summaryFilter.selected_NOT.length>0)); // if selection is in same mode, "undo" to NONE. if(what==="NOT" && ctgry.is_NOT()) what = "NONE"; if(what==="AND" && ctgry.is_AND()) what = "NONE"; if(what==="OR" && ctgry.is_OR() ) what = "NONE"; if(what==="NONE"){ if(ctgry.is_AND() || ctgry.is_NOT()){ this.summaryFilter.how = "MoreResults"; } if(ctgry.is_OR()){ this.summaryFilter.how = this.summaryFilter.selected_OR.length===0?"MoreResults":"LessResults"; } ctgry.set_NONE(); if(this.summaryFilter.selected_OR.length===1 && this.summaryFilter.selected_AND.length===0){ this.summaryFilter.selected_OR.forEach(function(a){ a.set_NONE(); a.set_AND(this.summaryFilter.selected_AND); },this); } if(!this.summaryFilter.selected_Any()){ this.dirtySort = false; this.DOM.catSortButton.attr("resort",false); } } if(what==="NOT"){ if(ctgry.is_NONE()){ if(ctgry.recCnt.Active===this.browser.allRecordsAggr.recCnt.Active){ alert("Removing this category will create an empty result list, so it is not allowed."); return; } this.summaryFilter.how = "LessResults"; } else { this.summaryFilter.how = "All"; } ctgry.set_NOT(this.summaryFilter.selected_NOT); } if(what==="AND"){ ctgry.set_AND(this.summaryFilter.selected_AND); this.summaryFilter.how = "LessResults"; } if(what==="OR"){ if(!this.isMultiValued && this.summaryFilter.selected_NOT.length>0){ var temp = []; this.summaryFilter.selected_NOT.forEach(function(a){ temp.push(a); }); temp.forEach(function(a){ a.set_NONE(); }); } if(this.summaryFilter.selected_OR.length===0 && this.summaryFilter.selected_AND.length===1){ this.summaryFilter.selected_AND.forEach(function(a){ a.set_NONE(); a.set_OR(this.summaryFilter.selected_OR); },this); } ctgry.set_OR(this.summaryFilter.selected_OR); this.summaryFilter.how = "MoreResults"; } if(how) this.summaryFilter.how = how; if(preTest){ this.summaryFilter.how = "All"; } if(this.summaryFilter.selected_OR.length>0 && (this.summaryFilter.selected_AND.length>0 || this.summaryFilter.selected_NOT.length>0)){ this.summaryFilter.how = "All"; } if(this.missingValueAggr.filtered===true){ this.summaryFilter.how = "All"; } if(this.summaryFilter.selectedCount_Total()===0){ this.summaryFilter.clearFilter(); return; } this.clearCatTextSearch(); this.missingValueAggr.filtered = false; this.summaryFilter.addFilter(); }, /** -- */ onCatClick: function(ctgry){ if(!this.isCatSelectable(ctgry)) return; if(d3.event.shiftKey){ this.browser.setSelect_Compare(this,ctgry,true); return; } if(this.dblClickTimer){ // double click if(!this.isMultiValued) return; this.unselectAllCategories(); this.filterCategory("AND","All"); return; } if(ctgry.is_NOT()){ this.filterCategory(ctgry,"NOT"); } else if(ctgry.is_AND()){ this.filterCategory(ctgry,"AND"); } else if(ctgry.is_OR()){ this.filterCategory(ctgry,"OR"); } else { // remove the single selection if it is defined with OR if(!this.isMultiValued && this.summaryFilter.selected_Any()){ if(this.summaryFilter.selected_OR.indexOf(ctgry)<0){ var temp = []; this.summaryFilter.selected_OR.forEach(function(a){ temp.push(a); }); temp.forEach(function(a){ a.set_NONE(); }); } if(this.summaryFilter.selected_AND.indexOf(ctgry)<0){ var temp = []; this.summaryFilter.selected_AND.forEach(function(a){ temp.push(a); }); temp.forEach(function(a){ a.set_NONE(); }); } if(this.summaryFilter.selected_NOT.indexOf(ctgry)<0){ var temp = []; this.summaryFilter.selected_NOT.forEach(function(a){ temp.push(a); }); temp.forEach(function(a){ a.set_NONE(); }); } this.filterCategory(ctgry,"AND","All"); } else { this.filterCategory(ctgry,"AND"); } } if(this.isMultiValued){ var x = this; this.dblClickTimer = setTimeout(function() { x.dblClickTimer = null; }, 500); } }, /** -- */ onCatEnter: function(aggr){ if(!this.isCatSelectable(aggr)) return; if(aggr.DOM.matrixRow) aggr.DOM.matrixRow.setAttribute("selection","selected"); aggr.DOM.aggrGlyph.setAttribute("selecttype","and"); aggr.DOM.aggrGlyph.setAttribute("selection","selected"); // Comes after setting select type of the category - visual feedback on selection... if(!this.isMultiValued && this.summaryFilter.selected_AND.length!==0) return; // Show the highlight (preview) if(aggr.is_NOT()) return; if(this.isMultiValued || this.summaryFilter.selected_AND.length===0){ aggr.DOM.aggrGlyph.setAttribute("showlock",true); this.browser.setSelect_Highlight(this,aggr); if(!this.browser.ratioModeActive) { if(this.viewType==="map"){ this.DOM.highlightedMeasureValue.style("left",(100*(this.mapColorScale(aggr.measure('Highlighted'))/9))+"%"); } else { this.DOM.highlightedMeasureValue.style("left",this.chartScale_Measure(aggr.measure('Active'))+"px"); } this.DOM.highlightedMeasureValue.style("opacity",1); } } }, /** -- */ onCatLeave: function(ctgry){ ctgry.unselectAggregate(); if(!this.isCatSelectable(ctgry)) return; this.browser.clearSelect_Highlight(); if(this.viewType==='map') this.DOM.highlightedMeasureValue.style("opacity",0); }, /** -- */ onCatEnter_OR: function(ctgry){ this.browser.clearSelect_Highlight(); ctgry.DOM.aggrGlyph.setAttribute("selecttype","or"); ctgry.DOM.aggrGlyph.setAttribute("selection","selected"); if(this.summaryFilter.selected_OR.length>0){ this.browser.clearSelect_Highlight(); if(this.viewType==='map') this.DOM.highlightedMeasureValue.style("opacity",0); } d3.event.stopPropagation(); }, /** -- */ onCatLeave_OR: function(ctgry){ ctgry.DOM.aggrGlyph.setAttribute("selecttype","and"); }, /** -- */ onCatClick_OR: function(ctgry){ this.filterCategory(ctgry,"OR"); d3.event.stopPropagation(); d3.event.preventDefault(); }, /** -- */ onCatEnter_NOT: function(ctgry){ ctgry.DOM.aggrGlyph.setAttribute("selecttype","not"); ctgry.DOM.aggrGlyph.setAttribute("selection","selected"); this.browser.preview_not = true; this.browser.setSelect_Highlight(this,ctgry); d3.event.stopPropagation(); }, /** -- */ onCatLeave_NOT: function(ctgry){ ctgry.DOM.aggrGlyph.setAttribute("selecttype","and"); this.browser.preview_not = false; this.browser.clearSelect_Highlight(); if(this.viewType==='map') this.DOM.highlightedMeasureValue.style("opacity",0); }, /** -- */ onCatClick_NOT: function(ctgry){ var me=this; this.browser.preview_not = true; this.filterCategory(ctgry,"NOT"); setTimeout(function(){ me.browser.preview_not = false; }, 1000); d3.event.stopPropagation(); d3.event.preventDefault(); }, /** - */ insertCategories: function(){ var me = this; if(typeof this.DOM.aggrGroup === "undefined") return; var aggrGlyphSelection = this.DOM.aggrGroup.selectAll(".aggrGlyph") .data(this._cats, function(aggr){ return aggr.id(); }); var DOM_cats_new = aggrGlyphSelection.enter() .append(this.viewType=='list' ? 'span' : 'g') .attr("class","aggrGlyph "+(this.viewType=='list'?'cat':'map')+"Glyph") .attr("selected",0) .on("mousedown", function(){ this._mousemove = false; }) .on("mousemove", function(){ this._mousemove = true; if(this.tipsy){ this.tipsy.jq_tip[0].style.left = (d3.event.pageX-this.tipsy.tipWidth-10)+"px"; this.tipsy.jq_tip[0].style.top = (d3.event.pageY-this.tipsy.tipHeight/2)+"px"; } }) .attr("title",me.catTooltip?function(_cat){ return me.catTooltip.call(_cat.data); }:null); this.updateCatIsInView(); if(this.viewType==='list'){ DOM_cats_new .style("height",this.heightRow_category+"px") .each(function(_cat){ kshf.Util.setTransform(this,"translateY(0px)"); }) var clickArea = DOM_cats_new.append("span").attr("class", "clickArea") .on("mouseenter",function(_cat){ if(me.browser.mouseSpeed<0.2) { me.onCatEnter(_cat); } else { this.highlightTimeout = window.setTimeout( function(){ me.onCatEnter(_cat) }, me.browser.mouseSpeed*500); } }) .on("mouseleave",function(_cat){ if(this.highlightTimeout) window.clearTimeout(this.highlightTimeout); me.onCatLeave(_cat); }) .on("click", function(aggr){ me.onCatClick(aggr); }); clickArea.append("span").attr("class","lockButton fa") .on("mouseenter",function(aggr){ this.tipsy = new Tipsy(this, { gravity: me.panel.name==='right'?'se':'w', title: function(){ return kshf.lang.cur[ me.browser.selectedAggr["Compared_A"]!==aggr ? 'LockToCompare' : 'Unlock']; } }); this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }) .on("click",function(_cat){ this.tipsy.hide(); me.browser.setSelect_Compare(me,_cat,true); d3.event.preventDefault(); d3.event.stopPropagation(); }); var domAttrLabel = DOM_cats_new.append("span").attr("class", "categoryLabel hasLabelWidth") .style("padding-top",(this.heightRow_category/2-8)+"px"); var filterButtons = domAttrLabel.append("span").attr("class", "filterButtons"); filterButtons.append("span").attr("class","filterButton notButton") .text(kshf.lang.cur.Not) .on("mouseover", function(_cat){ me.onCatEnter_NOT(_cat); }) .on("mouseout", function(_cat){ me.onCatLeave_NOT(_cat); }) .on("click", function(_cat){ me.onCatClick_NOT(_cat); }); filterButtons.append("span").attr("class","filterButton orButton") .text(kshf.lang.cur.Or) .on("mouseover",function(_cat){ me.onCatEnter_OR(_cat); }) .on("mouseout", function(_cat){ me.onCatLeave_OR(_cat); }) .on("click", function(_cat){ me.onCatClick_OR(_cat); }); this.DOM.theLabel = domAttrLabel.append("span").attr("class","theLabel").html(function(_cat){ return me.catLabel_Func.call(_cat.data); }); DOM_cats_new.append("span").attr("class", "measureLabel"); ["Total","Active","Highlighted","Compared_A","Compared_B","Compared_C"].forEach(function(m){ DOM_cats_new.append("span").attr("class", "measure_"+m); }); DOM_cats_new.selectAll("[class^='measure_Compared_']") .on("mouseover" ,function(){ me.browser.refreshMeasureLabels(this.classList[0].substr(8)); d3.event.preventDefault(); d3.event.stopPropagation(); }) .on("mouseleave",function(){ me.browser.refreshMeasureLabels(); d3.event.preventDefault(); d3.event.stopPropagation(); }); DOM_cats_new.append("span").attr("class", "total_tip"); } else { DOM_cats_new .each(function(_cat){ this.tipsy = new Tipsy(this, { gravity: 'e', title: function(){ return "<span class='mapItemName'>"+me.catLabel_Func.call(_cat.data)+"</span>"+ me.browser.getMeasureLabel(_cat)+" "+me.browser.itemName; } }); }) .on("mouseenter",function(_cat){ if(this.tipsy) { this.tipsy.show(); this.tipsy.jq_tip[0].style.left = (d3.event.pageX-this.tipsy.tipWidth-10)+"px"; this.tipsy.jq_tip[0].style.top = (d3.event.pageY-this.tipsy.tipHeight/2)+"px"; } if(me.browser.mouseSpeed<0.2) { me.onCatEnter(_cat); } else { this.highlightTimeout = window.setTimeout( function(){ me.onCatEnter(_cat) }, me.browser.mouseSpeed*500); } }) .on("mouseleave",function(_cat){ if(this.tipsy) this.tipsy.hide(); if(this.highlightTimeout) window.clearTimeout(this.highlightTimeout); me.onCatLeave(_cat); }); DOM_cats_new.append("path").attr("class", "measure_Active"); DOM_cats_new.select(".measure_Active").on("click", function(aggr){ me.onCatClick(aggr); }); DOM_cats_new.append("text").attr("class", "measureLabel"); // label on top of (after) all the rest } this.refreshDOMcats(); }, /** -- */ refreshDOMcats: function(){ this.DOM.aggrGlyphs = this.DOM.aggrGroup.selectAll(".aggrGlyph").each(function(aggr){ aggr.DOM.aggrGlyph = this; }); this.DOM.measureLabel = this.DOM.aggrGlyphs.selectAll(".measureLabel"); this.DOM.measureTotalTip = this.DOM.aggrGlyphs.selectAll(".total_tip"); ["Total","Active","Highlighted","Compared_A","Compared_B","Compared_C"].forEach(function(m){ this.DOM["measure_"+m] = this.DOM.aggrGlyphs.selectAll(".measure_"+m); },this); if(this.viewType==='list'){ this.DOM.attribClickArea = this.DOM.aggrGlyphs.selectAll(".clickArea"); this.DOM.lockButton = this.DOM.aggrGlyphs.selectAll(".lockButton"); } }, /** -- */ updateCatIsInView: function(){ var me=this; if(this.viewType==='map'){ this._cats.forEach(function(_cat){ _cat.isVisible = true; }); return; } this._cats.forEach(function(_cat){ _cat.isVisibleBefore = _cat.isVisible; if(!_cat.isActive){ _cat.isVisible = false; } else if(_cat.orderIndex<me.firstCatIndexInView) { _cat.isVisible = false; } else if(_cat.orderIndex>me.firstCatIndexInView+me.catCount_InDisplay) { _cat.isVisible = false; } else { _cat.isVisible = true; } }); }, /** -- */ cullAttribs: function(){ if(this.viewType==='map') return; // no culling on maps, for now. this.DOM.aggrGlyphs .style("visibility",function(_cat){ return _cat.isVisible?"visible":"hidden"; }) .style("display",function(_cat){ return _cat.isVisible?"block":"none"; }); if(this.onCategoryCull) this.onCategoryCull.call(this); }, /** -- */ updateCatSorting: function(sortDelay,force,noAnim){ if(this.viewType==='map') return; if(this._cats===undefined) return; if(this._cats.length===0) return; if(this.uniqueCategories() && this.panel===undefined) return; // Nothing to sort... if(this.catSortBy_Active.no_resort===true && force!==true) return; var me = this; this.updateCatCount_Active(); this.sortCategories(); if(this.panel===undefined) return; // The rest deals with updating UI if(this.DOM.aggrGlyphs===undefined) return; this.updateCatIsInView(); var xRemoveOffset = (this.panel.name==='right')?-1:-100; // disappear direction, depends on the panel location if(this.cbFacetSort) this.cbFacetSort.call(this); // Items outside the view are not visible, chartBackground expand the box and makes the scroll bar visible if necessary. this.DOM.chartBackground.style("height",this.getHeight_VisibleAttrib()+"px"); var attribGroupScroll = me.DOM.aggrGroup[0][0]; // always scrolls to top row automatically when re-sorted if(this.scrollTop_cache!==0) kshf.Util.scrollToPos_do(attribGroupScroll,0); this.refreshScrollDisplayMore(this.firstCatIndexInView+this.catCount_InDisplay); this.refreshMeasureLabel(); if(noAnim){ this.DOM.aggrGlyphs.each(function(ctgry){ this.style.opacity = 1; this.style.visibility = "visible"; this.style.display = "block"; var x = 0; var y = me.heightRow_category*ctgry.orderIndex; ctgry.posX = x; ctgry.posY = y; kshf.Util.setTransform(this,"translate("+x+"px,"+y+"px)"); }); return; } setTimeout(function(){ // 1. Make items disappear // Note: do not cull with number of items made visible. // We are applying visible and block to ALL attributes as we animate the change me.DOM.aggrGlyphs.each(function(ctgry){ if(ctgry.isActiveBefore && !ctgry.isActive){ // disappear into left panel... this.style.opacity = 0; ctgry.posX = xRemoveOffset; ctgry.posY = ctgry.posY; kshf.Util.setTransform(this,"translate("+ctgry.posX+"px,"+ctgry.posY+"px)"); } if(!ctgry.isActiveBefore && ctgry.isActive){ // will be made visible... ctgry.posY = me.heightRow_category*ctgry.orderIndex; kshf.Util.setTransform(this,"translate("+xRemoveOffset+"px,"+ctgry.posY+"px)"); } if(ctgry.isActive || ctgry.isActiveBefore){ this.style.opacity = 0; this.style.visibility = "visible"; this.style.display = "block"; } }); // 2. Re-sort setTimeout(function(){ me.DOM.aggrGlyphs.each(function(ctgry){ if(ctgry.isActive && ctgry.isActiveBefore){ this.style.opacity = 1; ctgry.posX = 0; ctgry.posY = me.heightRow_category*ctgry.orderIndex; kshf.Util.setTransform(this,"translate("+ctgry.posX+"px,"+ctgry.posY+"px)"); } }); // 3. Make items appear setTimeout(function(){ me.DOM.aggrGlyphs.each(function(ctgry){ if(!ctgry.isActiveBefore && ctgry.isActive){ this.style.opacity = 1; ctgry.posX = 0; ctgry.posY = me.heightRow_category*ctgry.orderIndex; kshf.Util.setTransform(this, "translate("+ctgry.posX+"px,"+ctgry.posY+"px)"); } }); // 4. Apply culling setTimeout(function(){ me.cullAttribs();} , 700); },(me.catCount_NowVisible>0)?300:0); },(me.catCount_NowInvisible>0)?300:0); }, (sortDelay===undefined) ? 1000 : sortDelay ); }, /** -- */ chartAxis_Measure_TickSkip: function(){ var width = this.chartScale_Measure.range()[1]; var ticksSkip = width/25; if(this.getMaxAggr_Active()>100000){ ticksSkip = width/30; } if(this.browser.percentModeActive){ ticksSkip /= 1.1; } return ticksSkip; }, /** -- */ map_projectCategories: function(){ var me = this; this.DOM.measure_Active.attr("d", function(_cat){ _cat._d_ = me.catMap.call(_cat.data,_cat); if(_cat._d_===undefined) return; return me.geoPath(_cat._d_); }); this.DOM.measure_Highlighted.attr("d", function(_cat){ return me.geoPath(_cat._d_); }); this.DOM.measureLabel .attr("transform", function(_cat){ var centroid = me.geoPath.centroid(_cat._d_); return "translate("+centroid[0]+","+centroid[1]+")"; }) .style("display",function(aggr){ var bounds = me.geoPath.bounds(aggr._d_); var width = Math.abs(bounds[0][0]-bounds[1][0]); return (width<me.panel.width_catMeasureLabel)?"none":"block"; }) ; }, /** -- */ map_refreshBounds_Active: function(){ // Insert the bounds for each record path into the bs var bs = []; var me = this; this._cats.forEach(function(_cat){ if(!_cat.isActive) return; var feature = me.catMap.call(_cat.data,_cat); if(typeof feature === 'undefined') return; var b = d3.geo.bounds(feature); if(isNaN(b[0][0])) return; // Change wrapping if(b[0][0]>kshf.wrapLongitude) b[0][0]-=360; if(b[1][0]>kshf.wrapLongitude) b[1][0]-=360; bs.push(L.latLng(b[0][1], b[0][0])); bs.push(L.latLng(b[1][1], b[1][0])); }); this.mapBounds_Active = new L.latLngBounds(bs); }, /** -- */ map_zoomToActive: function(){ if(this.asdsds===undefined){ // First time: just fit bounds this.asdsds = true; this.leafletAttrMap.fitBounds(this.mapBounds_Active); return; } this.leafletAttrMap.flyToBounds( this.mapBounds_Active, { padding: [0,0], pan: {animate: true, duration: 1.2}, zoom: {animate: true} } ); }, /** -- */ map_refreshColorScale: function(){ var me=this; this.DOM.mapColorBlocks .style("background-color", function(d){ if(me.invertColorScale) d = 8-d; return kshf.colorScale[me.browser.mapColorTheme][d]; }); }, /** -- */ viewAs: function(_type){ var me = this; this.viewType = _type; this.DOM.root.attr("viewType",this.viewType); if(this.viewType==='list'){ this.DOM.aggrGroup = this.DOM.aggrGroup_list; if(this.heightRow_category_dirty) this.refreshHeight_Category(); this.refreshDOMcats(); this.updateCatSorting(0,true,true); return; } // 'map' // The map view is already initialized if(this.leafletAttrMap) { this.DOM.aggrGroup = this.DOM.summaryCategorical.select(".catMap_SVG > .aggrGroup"); this.refreshDOMcats(); this.map_refreshBounds_Active(); this.map_zoomToActive(); this.map_projectCategories(); this.refreshViz_Active(); return; } // See http://leaflet-extras.github.io/leaflet-providers/preview/ for alternative layers this.leafletAttrMap = L.map(this.DOM.catMap_Base[0][0] ) .addLayer(new L.TileLayer( kshf.map.tileTemplate, { attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a>', subdomains: 'abcd', maxZoom: 19 })) .on("viewreset",function(){ me.map_projectCategories() }) .on("movestart",function(){ me.DOM.aggrGlyphs.style("display","none"); }) .on("move",function(){ // console.log("MapZoom: "+me.leafletAttrMap.getZoom()); // me.map_projectCategories() }) .on("moveend",function(){ me.DOM.aggrGlyphs.style("display","block"); me.map_projectCategories() }) ; //var width = 500, height = 500; //var projection = d3.geo.albersUsa().scale(900).translate([width / 2, height / 2]); this.geoPath = d3.geo.path().projection( d3.geo.transform({ // Use Leaflet to implement a D3 geometric transformation. point: function(x, y) { if(x>kshf.wrapLongitude) x-=360; var point = me.leafletAttrMap.latLngToLayerPoint(new L.LatLng(y, x)); this.stream.point(point.x, point.y); } }) ); this.mapColorQuantize = d3.scale.quantize() .domain([0,9]) .range(kshf.colorScale.converge); this.DOM.catMap_SVG = d3.select(this.leafletAttrMap.getPanes().overlayPane) .append("svg").attr("xmlns","http://www.w3.org/2000/svg") .attr("class","catMap_SVG"); // The fill pattern definition in SVG, used to denote geo-objects with no data. // http://stackoverflow.com/questions/17776641/fill-rect-with-pattern this.DOM.catMap_SVG.append('defs') .append('pattern') .attr('id', 'diagonalHatch') .attr('patternUnits', 'userSpaceOnUse') .attr('width', 4) .attr('height', 4) .append('path') .attr('d', 'M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2') .attr('stroke', 'gray') .attr('stroke-width', 1); // Add custom controls var DOM_control = d3.select(this.leafletAttrMap.getContainer()).select(".leaflet-control"); DOM_control.append("a") .attr("class","leaflet-control-viewFit").attr("title",kshf.lang.cur.ZoomToFit) .attr("href","#") .html("<span class='viewFit fa fa-arrows-alt'></span>") .on("dblclick",function(){ d3.event.preventDefault(); d3.event.stopPropagation(); }) .on("click",function(){ me.map_refreshBounds_Active(); me.map_zoomToActive(); d3.event.preventDefault(); d3.event.stopPropagation(); }); this.DOM.aggrGroup = this.DOM.catMap_SVG.append("g").attr("class", "leaflet-zoom-hide aggrGroup"); // Now this will insert map svg component this.insertCategories(); this.DOM.catMapColorScale = this.DOM.belowCatChart.append("div").attr("class","catMapColorScale"); this.DOM.catMapColorScale.append("span").attr("class","scaleBound boundMin"); this.DOM.catMapColorScale.append("span").attr("class","scaleBound boundMax"); this.DOM.catMapColorScale.append("span") .attr("class","relativeModeControl fa fa-arrows-h") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'e', title: function(){ return kshf.lang.cur[me.browser.ratioModeActive?'Absolute':'Relative']+" "+kshf.lang.cur.Width; } }); }) .on("click",function(){ this.tipsy.hide(); me.browser.setMeasureAxisMode(!me.browser.ratioModeActive); }) .on("mouseover",function(){ me.browser.DOM.root.selectAll(".relativeModeControl").attr("highlight",true); this.tipsy.show(); }) .on("mouseout",function(){ me.browser.DOM.root.selectAll(".relativeModeControl").attr("highlight",false); this.tipsy.hide(); }); this.DOM.catMapColorScale.append("span").attr("class","measurePercentControl") .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'w', title: function(){ return "<span class='fa fa-eye'></span> "+kshf.lang.cur[(me.browser.percentModeActive?'Absolute':'Percent')]; }, }) }) .on("click",function(){ this.tipsy.hide(); me.browser.setPercentLabelMode(!me.browser.percentModeActive); }) .on("mouseover",function(){ me.browser.DOM.root.selectAll(".measurePercentControl").attr("highlight",true); this.tipsy.show(); }) .on("mouseout",function(){ me.browser.DOM.root.selectAll(".measurePercentControl").attr("highlight",false); this.tipsy.hide(); }); this.DOM.highlightedMeasureValue = this.DOM.catMapColorScale.append("span").attr("class","highlightedMeasureValue"); this.DOM.highlightedMeasureValue.append("div").attr('class','fa fa-mouse-pointer highlightedAggrValuePointer'); this.DOM.mapColorBlocks = this.DOM.catMapColorScale.selectAll(".mapColorBlock") .data([0,1,2,3,4,5,6,7,8]).enter() .append("div").attr("class","mapColorBlock") .each(function(d){ this.tipsy = new Tipsy(this, { gravity: 's', title: function(){ var _minValue = Math.round(me.mapColorScale.invert(d)); var _maxValue = Math.round(me.mapColorScale.invert(d+1)); return Math.round(_minValue)+" to "+Math.round(_maxValue); } }); }) .on("mouseenter",function(d){ this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }); // Set height var h = this.categoriesHeight; this.DOM.catMap_Base.style("height",h+"px"); if(this.DOM.catMap_SVG) this.DOM.catMap_SVG.style("height",h+"px"); if(this.leafletAttrMap) this.leafletAttrMap.invalidateSize(); this.DOM.aggrGroup.style("height",h+"px"); this.map_refreshColorScale(); this.map_refreshBounds_Active(); this.map_zoomToActive(); this.map_projectCategories(); this.refreshMeasureLabel(); this.refreshViz_Active(); }, /** -- */ printAggrSelection: function(aggr){ return this.catLabel_Func.call(aggr.data); } }; for(var index in Summary_Categorical_functions){ kshf.Summary_Categorical.prototype[index] = Summary_Categorical_functions[index]; } /** * Keshif Interval Summary * @constructor */ kshf.Summary_Interval = function(){}; kshf.Summary_Interval.prototype = new kshf.Summary_Base(); var Summary_Interval_functions = { initialize: function(browser,name,attribFunc){ kshf.Summary_Base.prototype.initialize.call(this,browser,name,attribFunc); this.type='interval'; // Call the parent's constructor var me = this; // pixel width settings... this.height_hist = 1; // Initial width (will be updated later...) this.height_hist_min = 15; // Minimum possible histogram height this.height_hist_max = 100; // Maximim possible histogram height this.height_slider = 12; // Slider height this.height_labels = 13; // Height for labels this.height_hist_topGap = 12; // Height for histogram gap on top. this.width_barGap = 2; // The width between neighboring histgoram bars this.width_measureAxisLabel = 30; // .. this.optimumTickWidth = 45; this.hasFloat = false; this.timeTyped = { base: false }; this.unitName = undefined; // the text appended to the numeric value (TODO: should not apply to time) this.percentileChartVisible = false; // Percentile chart is a 1-line chart which shows %10-%20-%30-%40-%50 percentiles this.zoomed = false; this.usedForSorting = false; this.invertColorScale = false; this.highlightRangeLimits_Active = false; // Used for flexible range selection. // TODO: Support multiple compare selections. this.flexAggr_Highlight = new kshf.Aggregate(); this.flexAggr_Compare = new kshf.Aggregate(); this.flexAggr_Highlight.init({}); this.flexAggr_Compare .init({}); this.flexAggr_Highlight.summary = this; this.flexAggr_Compare .summary = this; this.quantile_val = {}; this.quantile_pos = {}; this.histBins = []; this.intervalTicks = []; this.intervalRange = {}; this.intervalTickFormat = function(v){ return (me.hasFloat) ? d3.format("s")(v) : d3.format(".2f")(v); }; if(this.records.length<=1000) this.initializeAggregates(); }, /** -- */ isTimeStamp: function(){ return this.timeTyped.base; }, /** TODO: Only relevant is timeStamp-- */ createMonthSummary: function(){ if(!this.isTimeStamp()) return; if(this.summary_sub_month) return this.summary_sub_month; var summaryID = this.summaryID; this.summary_sub_month = this.browser.createSummary( "Month of "+this.summaryName, function(d){ var arr=d._valueCache[summaryID]; return (arr===null) ? null : arr.getUTCMonth(); }, 'categorical' ); this.summary_sub_month.setSortingOptions("id"); this.summary_sub_month.setCatLabel(_demo.Month); this.summary_sub_month.initializeAggregates(); return this.summary_sub_month; }, /** TODO: Only relevant is timeStamp-- */ createDaySummary: function(){ if(!this.isTimeStamp()) return; if(this.summary_sub_day) return this.summary_sub_day; var summaryID = this.summaryID; this.summary_sub_day = this.browser.createSummary( "WeekDay of "+this.summaryName, function(d){ var arr=d._valueCache[summaryID]; return (arr===null) ? null : arr.getUTCDay(); }, 'categorical' ); this.summary_sub_day.setSortingOptions("id"); this.summary_sub_day.setCatLabel(_demo.DayOfWeek); this.summary_sub_day.initializeAggregates(); return this.summary_sub_day; }, /** TODO: Only relevant is timeStamp-- */ createHourSummary: function(){ if(!this.isTimeStamp()) return; if(this.summary_sub_hour) return this.summary_sub_hour; var summaryID = this.summaryID; this.summary_sub_hour = this.browser.createSummary( "Hour of "+this.summaryName, function(d){ var arr=d._valueCache[summaryID]; return (arr===null) ? null : arr.getUTCHours(); }, 'interval' ); this.summary_sub_hour.initializeAggregates(); this.summary_sub_hour.setUnitName(":00"); return this.summary_sub_hour; }, /** -- */ initializeAggregates: function(){ if(this.aggr_initialized) return; var me = this; this.getRecordValue = function(record){ return record._valueCache[me.summaryID]; }; this.records.forEach(function(record){ var v=this.summaryFunc.call(record.data,record); if(isNaN(v)) v=null; if(v===undefined) v=null; if(v!==null){ if(v instanceof Date){ this.timeTyped.base = true; } else { if(typeof v!=='number'){ v = null; } else{ this.hasFloat = this.hasFloat || v%1!==0; } } } record._valueCache[this.summaryID] = v; if(v===null) this.missingValueAggr.addRecord(record); },this); if(this.timeTyped.base===true){ // Check time resolutions this.timeTyped.month = false; this.timeTyped.hour = false; this.timeTyped.day = false; var tempDay = null; this.records.forEach(function(record){ v = record._valueCache[this.summaryID]; if(v) { if(v.getUTCMonth()!==0) this.timeTyped.month = true; if(v.getUTCHours()!==0) this.timeTyped.hour = true; // Day if(!this.timeTyped.day){ if(tempDay===null) { tempDay = v.getUTCDay(); } else { if(v.getUTCDay()!==tempDay) this.timeTyped.day = true; tempDay = v.getUTCDay(); } } } },this); } // remove records that map to null / undefined this.filteredItems = this.records.filter(function(record){ var v = me.getRecordValue(record); return (v!==undefined && v!==null); }); // Sort the items by their attribute value var sortValue = this.isTimeStamp()? function(a){ return me.getRecordValue(a).getTime(); }: function(a){ return me.getRecordValue(a); }; this.filteredItems.sort(function(a,b){ return sortValue(a)-sortValue(b);}); this.updateIntervalRangeMinMax(); this.detectScaleType(); this.aggr_initialized = true; this.refreshViz_Nugget(); this.refreshViz_EmptyRecords(); }, /** -- */ isEmpty: function(){ return this._isEmpty; }, /** -- */ detectScaleType: function(){ if(this.isEmpty()) return; var me = this; this.stepTicks = false; // TIME SCALE if(this.isTimeStamp()) { this.setScaleType('time',true); return; } // decide scale type based on the filtered records var activeItemV = function(record){ var v = record._valueCache[me.summaryID]; if(v>=me.intervalRange.active.min && v <= me.intervalRange.active.max) return v; // value is within filtered range }; var deviation = d3.deviation(this.filteredItems, activeItemV); var activeRange = this.intervalRange.active.max-this.intervalRange.active.min; var _width_ = this.getWidth_Chart(); var stepRange = (this.intervalRange.active.max-this.intervalRange.active.min)+1; // Apply step range before you check for log - it has higher precedence if(!this.hasFloat){ if( (_width_ / this.getWidth_OptimumTick()) >= stepRange){ this.stepTicks = true; this.setScaleType('linear',false); // converted to step on display return; } } // LOG SCALE if(deviation/activeRange<0.12 && this.intervalRange.active.min>=0){ this.setScaleType('log',false); return; } // The scale can be linear or step after this stage // STEP SCALE if number are floating if(this.hasFloat){ this.setScaleType('linear',false); return; } if( (_width_ / this.getWidth_OptimumTick()) >= stepRange){ this.stepTicks = true; } this.setScaleType('linear',false); }, /** -- */ createSummaryFilter: function(){ var me=this; this.summaryFilter = this.browser.createFilter({ title: function(){ return me.summaryName; }, onClear: function(){ if(this.filteredBin){ this.filteredBin.setAttribute("filtered",false); this.filteredBin = undefined; } me.DOM.root.attr("filtered",false); if(me.zoomed){ me.setZoomed(false); } me.resetIntervalFilterActive(); me.refreshIntervalSlider(); if(me.DOM.missingValueAggr) me.DOM.missingValueAggr.attr("filtered",null); }, onFilter: function(){ me.DOM.root.attr("filtered",true); var valueID = me.summaryID; if(me.missingValueAggr.filtered){ me.records.forEach(function(record){ record.setFilterCache(this.filterID, record._valueCache[valueID]===null); },this); return; } var i_min = this.active.min; var i_max = this.active.max; var isFilteredCb; if(me.isFiltered_min() && me.isFiltered_max()){ if(this.max_inclusive) isFilteredCb = function(v){ return v>=i_min && v<=i_max; }; else isFilteredCb = function(v){ return v>=i_min && v<i_max; }; } else if(me.isFiltered_min()){ isFilteredCb = function(v){ return v>=i_min; }; } else { if(this.max_inclusive) isFilteredCb = function(v){ return v<=i_max; }; else isFilteredCb = function(v){ return v<i_max; }; } if(me.stepTicks){ if(i_min+1===i_max){ isFilteredCb = function(v){ return v===i_min; }; } } // TODO: Optimize: Check if the interval scale is extending/shrinking or completely updated... me.records.forEach(function(record){ var v = record._valueCache[valueID]; record.setFilterCache(this.filterID, (v!==null)?isFilteredCb(v):false); },this); me.DOM.zoomControl.attr("sign", (me.stepTicks && me.scaleType==="linear") ? (this.zoomed ? "minus" : "") : "plus" ); me.refreshIntervalSlider(); }, filterView_Detail: function(){ return (me.missingValueAggr.filtered) ? kshf.lang.cur.NoData : me.printAggrSelection(); }, }); }, /** -- */ printAggrSelection: function(aggr){ var minValue, maxValue; if(aggr){ minValue = aggr.minV; maxValue = aggr.maxV; } else { minValue = this.summaryFilter.active.min; maxValue = this.summaryFilter.active.max; } if(this.stepTicks){ if(minValue+1===maxValue || aggr) { return "<b>"+this.printWithUnitName(minValue)+"</b>"; } } if(this.scaleType==='time'){ return "<b>"+this.intervalTickFormat(minValue)+ "</b> to <b>"+this.intervalTickFormat(maxValue)+"</b>"; } if(this.hasFloat){ minValue = minValue.toFixed(2); maxValue = maxValue.toFixed(2); } var minIsLarger = minValue > this.intervalRange.min; var maxIsSmaller = maxValue < this.intervalRange.max; if(minIsLarger && maxIsSmaller){ return "<b>"+this.printWithUnitName(minValue)+"</b> to <b>"+this.printWithUnitName(maxValue)+"</b>"; } else if(minIsLarger){ return "<b>at least "+this.printWithUnitName(minValue)+"</b>"; } else { return "<b>at most "+this.printWithUnitName(maxValue)+"</b>"; } }, /** -- */ refreshViz_Nugget: function(){ if(this.DOM.nugget===undefined) return; var nuggetChart = this.DOM.nugget.select(".nuggetChart"); this.DOM.nugget .attr("aggr_initialized",this.aggr_initialized) .attr("datatype",this.getDataType()); if(!this.aggr_initialized) return; if(this.uniqueCategories()){ this.DOM.nugget.select(".nuggetInfo").html("<span class='fa fa-tag'></span><br>Unique"); nuggetChart.style("display",'none'); return; } var maxAggregate_Total = this.getMaxAggr_Total(); if(this.intervalRange.min===this.intervalRange.max){ this.DOM.nugget.select(".nuggetInfo").html("only<br>"+this.intervalRange.min); nuggetChart.style("display",'none'); return; } var totalHeight = 17; nuggetChart.selectAll(".nuggetBar").data(this.histBins).enter() .append("span").attr("class","nuggetBar") .style("height",function(aggr){ return totalHeight*(aggr.records.length/maxAggregate_Total)+"px"; }); this.DOM.nugget.select(".nuggetInfo").html( "<span class='num_left'>"+this.intervalTickFormat(this.intervalRange.min)+"</span>"+ "<span class='num_right'>"+this.intervalTickFormat(this.intervalRange.max)+"</span>"); }, /** -- */ updateIntervalRangeMinMax: function(){ this.intervalRange.min = d3.min(this.filteredItems,this.getRecordValue); this.intervalRange.max = d3.max(this.filteredItems,this.getRecordValue); this.intervalRange.active = { min: this.intervalRange.min, max: this.intervalRange.max }; this.resetIntervalFilterActive(); this._isEmpty = this.intervalRange.min===undefined; if(this._isEmpty) this.setCollapsed(true); }, /** -- */ resetIntervalFilterActive: function(){ this.summaryFilter.active = { min: this.intervalRange.min, max: this.intervalRange.max }; }, /** -- */ setScaleType: function(t,force){ if(this.scaleType===t) return; var me=this; this.viewType = t==='time'?'line':'bar'; if(this.DOM.inited) { this.DOM.root.attr("viewType",this.viewType); } if(force===false && this.scaleType_forced) return; this.scaleType = t; if(force) this.scaleType_forced = this.scaleType; if(this.DOM.inited){ this.DOM.summaryConfig.selectAll(".summaryConfig_ScaleType .configOption").attr("active",false); this.DOM.summaryConfig.selectAll(".summaryConfig_ScaleType .pos_"+this.scaleType).attr("active",true); this.DOM.summaryInterval.attr("scaleType",this.scaleType); } if(this.filteredItems === undefined) return; // remove records with value:0 (because log(0) is invalid) if(this.scaleType==='log'){ if(this.intervalRange.min<=0){ var x=this.filteredItems.length; this.filteredItems = this.filteredItems.filter(function(record){ var v=this.getRecordValue(record)!==0; if(v===false) { record._valueCache[this.summaryID] = null; // TODO: Remove from existing aggregate for this summary this.missingValueAggr.addRecord(record); } return v; },this); if(x!==this.filteredItems.length){ // Some records are filtered bc they are 0. this.updateIntervalRangeMinMax(); } } // cannot be zero. var minnn = d3.min(this.filteredItems,function(record){ var v=me.getRecordValue(record); if(v>0) return v; } ); this.intervalRange.active.min = Math.max(minnn, this.intervalRange.active.min); this.summaryFilter.active.min = Math.max(minnn, this.summaryFilter.active.min); } if(this.scaleType==="linear"){ // round the maximum to an integer. If it is an integer already, has no effect. this.intervalRange.active.max = Math.ceil(this.intervalRange.active.max); } this.updateScaleAndBins(true); if(this.usedForSorting) this.browser.recordDisplay.refreshRecordColors(); }, /** -- */ getHeight_RecordEncoding: function(){ if(this.usedForSorting===false) return 0; if(this.browser.recordDisplay===undefined) return 0; if(this.browser.recordDisplay.displayType==="map") return 20; if(this.browser.recordDisplay.displayType==="nodelink") return 20; return 0; }, /** -- */ getHeight_Content: function(){ return this.height_hist + this.getHeight_Extra(); }, /** -- */ getHeight_Percentile: function(){ if(this.percentileChartVisible===false) return 0; if(this.percentileChartVisible==="Basic") return 15; if(this.percentileChartVisible==="Extended") return 32; }, /** -- */ getHeight_Extra: function(){ return 7+ this.height_hist_topGap+ this.height_labels+ this.height_slider+ this.getHeight_Percentile()+ this.getHeight_RecordEncoding(); }, /** -- */ getHeight_Extra_max: function(){ return 7+ this.height_hist_topGap+ this.height_labels+ this.height_slider+ 35; }, /** -- */ getHeight_RangeMax: function(){ return this.height_hist_max + this.getHeight_Header() + this.getHeight_Extra_max(); }, /** -- */ getHeight_RangeMin: function(){ return this.height_hist_min + this.getHeight_Header() + this.getHeight_Extra_max(); }, /** -- */ getWidth_Chart: function(){ if(this.panel===undefined) return 30; return this.getWidth() - this.width_measureAxisLabel - ( this.getWidth()>400 ? this.width_measureAxisLabel : 11 ); }, /** -- */ getWidth_OptimumTick: function(){ if(this.panel===undefined) return 10; return this.optimumTickWidth; }, /** -- */ getWidth_Bin: function(){ return this.aggrWidth-this.width_barGap*2; }, /** -- */ isFiltered_min: function(){ // the active min is different from intervalRange min. if(this.summaryFilter.active.min!==this.intervalRange.min) return true; // if using log scale, assume min is also filtered when max is filtered. if(this.scaleType==='log') return this.isFiltered_max(); return false; }, /** -- */ isFiltered_max: function(){ return this.summaryFilter.active.max!==this.intervalRange.max; }, /** -- */ getMaxAggr_Total: function(){ return d3.max(this.histBins,function(aggr){ return aggr.measure('Total'); }); }, /** -- */ getMaxAggr_Active: function(){ return d3.max(this.histBins,function(aggr){ return aggr.measure('Active'); }); }, /** -- */ refreshPercentileChart: function(){ this.DOM.percentileGroup .style("opacity",this.percentileChartVisible?1:0) .attr("percentileChartVisible",this.percentileChartVisible); if(this.percentileChartVisible){ this.DOM.percentileGroup.style("height",(this.percentileChartVisible==="Basic"?13:30)+"px"); } this.DOM.summaryConfig.selectAll(".summaryConfig_Percentile .configOption").attr("active",false); this.DOM.summaryConfig.selectAll(".summaryConfig_Percentile .pos_"+this.percentileChartVisible).attr("active",true); }, /** -- */ showPercentileChart: function(v){ if(v===true) v="Basic"; this.percentileChartVisible = v; if(this.DOM.inited) { var curHeight = this.getHeight(); this.refreshPercentileChart(); if(this.percentileChartVisible) this.updatePercentiles("Active"); this.setHeight(curHeight); this.browser.updateLayout_Height(); } }, /** -- */ initDOM: function(beforeDOM){ this.initializeAggregates(); if(this.isEmpty()) return; if(this.DOM.inited===true) return; var me = this; this.insertRoot(beforeDOM); this.DOM.root .attr("summary_type","interval") .attr("usedForSorting",this.usedForSorting) .attr("viewType",this.viewType); this.insertHeader(); this.initDOM_IntervalConfig(); this.DOM.summaryInterval = this.DOM.wrapper.append("div").attr("class","summaryInterval") .attr("scaleType",this.scaleType) .attr("zoomed",this.zoomed) .on("mousedown",function(){ d3.event.stopPropagation(); d3.event.preventDefault(); }); this.DOM.histogram = this.DOM.summaryInterval.append("div").attr("class","histogram"); this.DOM.histogram_bins = this.DOM.histogram.append("div").attr("class","aggrGroup") .on("mousemove", function(){ if(d3.event.shiftKey){ var pointerPosition = me.valueScale.invert(d3.mouse(this)[0]); if(this.initPos===undefined){ this.initPos = pointerPosition; } var maxPos = d3.max([this.initPos, pointerPosition]); var minPos = d3.min([this.initPos, pointerPosition]); me.highlightRangeLimits_Active = true; // Set preview selection me.flexAggr_Highlight.records = []; me.filteredItems.forEach(function(record){ var v = me.getRecordValue(record); if(v>=minPos && v<=maxPos) me.flexAggr_Highlight.records.push(record); else record.remForHighlight(true); }); me.flexAggr_Highlight.minV = minPos; me.flexAggr_Highlight.maxV = maxPos; me.browser.setSelect_Highlight(me,me.flexAggr_Highlight); d3.event.preventDefault(); d3.event.stopPropagation(); } else { if(me.highlightRangeLimits_Active){ this.initPos = undefined; me.browser.clearSelect_Highlight(); d3.event.preventDefault(); d3.event.stopPropagation(); } } }) .on("click", function(){ if(d3.event.shiftKey && me.highlightRangeLimits_Active){ // Lock for comparison me.flexAggr_Compare.minV = me.flexAggr_Highlight.minV; me.flexAggr_Compare.maxV = me.flexAggr_Highlight.maxV; me.browser.setSelect_Compare(me,me.flexAggr_Compare,false); this.initPos = undefined; d3.event.preventDefault(); d3.event.stopPropagation(); } }); this.DOM.highlightRangeLimits = this.DOM.histogram_bins.selectAll(".highlightRangeLimits") .data([0,1]).enter() .append("div").attr("class","highlightRangeLimits"); if(this.scaleType==='time'){ this.DOM.timeSVG = this.DOM.histogram.append("svg").attr("class","timeSVG") .attr("xmlns","http://www.w3.org/2000/svg") .style("margin-left",(this.width_barGap)+"px"); } this.insertChartAxis_Measure(this.DOM.histogram, 'w', 'nw'); this.initDOM_Slider(); this.initDOM_RecordMapColor(); this.initDOM_Percentile(); this.updateScaleAndBins(); this.setCollapsed(this.collapsed); this.setUnitName(this.unitName); this.DOM.inited = true; }, /** -- */ setZoomed: function(v){ this.zoomed = v; this.DOM.summaryInterval.attr("zoomed",this.zoomed); if(this.zoomed){ this.intervalRange.active.min = this.summaryFilter.active.min; this.intervalRange.active.max = this.summaryFilter.active.max; this.DOM.zoomControl.attr("sign","minus"); } else { this.intervalRange.active.min = this.intervalRange.min; this.intervalRange.active.max = this.intervalRange.max; this.DOM.zoomControl.attr("sign","plus"); } this.detectScaleType(); this.updateScaleAndBins(); }, /** -- */ setUnitName: function(v){ this.unitName = v; if(this.unitName) this.DOM.unitNameInput[0][0].value = this.unitName; this.refreshTickLabels(); if(this.usedForSorting && this.browser.recordDisplay.recordViewSummary){ this.browser.recordDisplay.refreshRecordSortLabels(); } }, /** -- */ printWithUnitName: function(v,noDiv){ if(v instanceof Date) return this.intervalTickFormat(v); if(this.unitName){ var s; if(noDiv){ s=this.unitName; } else { s = "<span class='unitName'>"+this.unitName+"</span>"; } return (this.unitName==='$' || this.unitName==='€') ? (s+v) : (v+s); } return v; }, /** -- */ setAsRecordSorting: function(){ this.usedForSorting = true; if(this.DOM.root) this.DOM.root.attr("usedForSorting","true"); }, /** -- */ clearAsRecordSorting: function(){ this.usedForSorting = false; if(this.DOM.root) this.DOM.root.attr("usedForSorting","false"); }, /** -- */ initDOM_IntervalConfig: function(){ var me=this, x; var summaryConfig_UnitName = this.DOM.summaryConfig.append("div") .attr("class","summaryConfig_UnitName summaryConfig_Option"); summaryConfig_UnitName.append("span").text("Value Unit: "); this.DOM.unitNameInput = summaryConfig_UnitName.append("input").attr("type","text") .attr("class","unitNameInput") .attr("placeholder",kshf.unitName) .attr("maxlength",5) .on("input",function(){ if(this.timer) clearTimeout(this.timer); var x = this; var queryString = x.value.toLowerCase(); this.timer = setTimeout( function(){ me.setUnitName(queryString); }, 750); });; // Show the linear/log scale transformation only if... if(this.scaleType!=='time' && !this.stepTicks && this.intervalRange.min>=0){ this.DOM.summaryConfig_ScaleType = this.DOM.summaryConfig.append("div") .attr("class","summaryConfig_ScaleType summaryConfig_Option"); this.DOM.summaryConfig_ScaleType.append("span").html("<i class='fa fa-arrows-h'></i> Scale: "); x = this.DOM.summaryConfig_ScaleType.append("span").attr("class","optionGroup"); x.selectAll(".configOption").data( [ {l:"Linear <span style='font-size:0.8em; color: gray'>(1,2,3,4,5)</span>",v:"Linear"}, {l:"Log <span style='font-size:0.8em; color: gray'>(1,2,4,8,16)</span>", v:"Log"} ]) .enter() .append("span").attr("class",function(d){ return "configOption pos_"+d.v.toLowerCase();}) .attr("active",function(d){ return d.v.toLowerCase()===me.scaleType; }) .html(function(d){ return d.l; }) .on("click", function(d){ me.setScaleType(d.v.toLowerCase(),true); }) } var summaryConfig_Percentile = this.DOM.summaryConfig.append("div") .attr("class","summaryConfig_Percentile summaryConfig_Option"); summaryConfig_Percentile.append("span").text("Percentile Charts: ") x = summaryConfig_Percentile.append("span").attr("class","optionGroup"); x.selectAll(".configOption").data( [ {l:"<i class='bl_Active'></i><i class='bl_Highlighted'></i>"+ "<i class='bl_Compared_A'></i><i class='bl_Compared_B'></i><i class='bl_Compared_C'></i> Full",v:"Extended"}, {l:"<i class='bl_Active'></i><i class='bl_Highlighted'></i> Basic",v:"Basic"}, {l:"<i class='fa fa-eye-slash'></i> Hide",v:false} ]).enter() .append("span") .attr("class",function(d){ return "configOption pos_"+d.v;}) .attr("active",function(d){ return d.v===me.percentileChartVisible; }) .html(function(d){ return d.l; }) .on("click", function(d){ me.showPercentileChart(d.v); }); }, /** -- */ initDOM_Percentile: function(){ if(this.DOM.summaryInterval===undefined) return; var me=this; this.DOM.percentileGroup = this.DOM.summaryInterval.append("div").attr("class","percentileGroup"); this.DOM.percentileGroup.append("span").attr("class","percentileTitle").html(kshf.lang.cur.Percentiles); this.DOM.quantile = {}; function addPercentileDOM(parent, distr){ [[10,90],[20,80],[30,70],[40,60]].forEach(function(qb){ this.DOM.quantile[distr+qb[0]+"_"+qb[1]] = parent.append("span") .attr("class","quantile q_range q_"+qb[0]+"_"+qb[1]) .each(function(){ this.tipsy = new Tipsy(this, { gravity: 'sw', title: function(){ return "<span style='font-weight:300'>"+qb[0]+"% - "+qb[1]+"% percentile: </span>"+ "<span style='font-weight:500'>"+me.quantile_val[distr+qb[0]]+"</span> - "+ "<span style='font-weight:500'>"+me.quantile_val[distr+qb[1]]+"</span>"; } }) }) .on("mouseover",function(){ this.tipsy.show(); me.flexAggr_Highlight.records = []; me.filteredItems.forEach(function(record){ var v = me.getRecordValue(record); if(v>=me.quantile_val[distr+qb[0]] && v<=me.quantile_val[distr+qb[1]]) me.flexAggr_Highlight.records.push(record); }); me.flexAggr_Highlight.minV = me.quantile_val[distr+qb[0]]; me.flexAggr_Highlight.maxV = me.quantile_val[distr+qb[1]]; me.highlightRangeLimits_Active = true; me.browser.setSelect_Highlight(me,me.flexAggr_Highlight); }) .on("mouseout" ,function(){ this.tipsy.hide(); me.browser.clearSelect_Highlight(); }) .on("click", function(){ if(d3.event.shiftKey){ me.flexAggr_Compare.minV = me.quantile_val[distr+qb[0]]; me.flexAggr_Compare.maxV = me.quantile_val[distr+qb[1]]; me.browser.setSelect_Compare(me,me.flexAggr_Compare, false); return; } me.summaryFilter.active = { min: me.quantile_val[distr+qb[0]], max: me.quantile_val[distr+qb[1]] }; me.summaryFilter.filteredBin = undefined; me.summaryFilter.addFilter(); }) ; },this); [10,20,30,40,50,60,70,80,90].forEach(function(q){ this.DOM.quantile[distr+q] = parent.append("span") .attr("class","quantile q_pos q_"+q) .each(function(){ this.tipsy = new Tipsy(this, { gravity: 's', title: function(){ return "Median: "+ me.quantile_val[distr+q]; } }); }) .on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }); },this); }; addPercentileDOM.call(this, this.DOM.percentileGroup.append("div").attr("class","percentileChart_Active"), "Active"); addPercentileDOM.call(this, this.DOM.percentileGroup.append("div").attr("class","percentileChart_Highlighted"), "Highlighted"); // Adding blocks in reverse order (C,B,A) so when they are inserted, they are linked to visually next to highlight selection addPercentileDOM.call(this, this.DOM.percentileGroup.append("div").attr("class","percentileChart_Compared_C"), "Compared_C"); addPercentileDOM.call(this, this.DOM.percentileGroup.append("div").attr("class","percentileChart_Compared_B"), "Compared_B"); addPercentileDOM.call(this, this.DOM.percentileGroup.append("div").attr("class","percentileChart_Compared_A"), "Compared_A"); this.refreshPercentileChart(); }, /** -- Uses - this.scaleType - this.intervalRange min & max Updates - this.intervalTickFormat - this.valueScale.nice() Return - the tick values in an array */ getValueTicks: function(optimalTickCount){ var me=this; var ticks; // HANDLE TIME CAREFULLY if(this.scaleType==='time') { // 1. Find the appropriate aggregation interval (day, month, etc) var timeRange_ms = this.intervalRange.active.max-this.intervalRange.active.min; // in milliseconds var timeInterval; var timeIntervalStep = 1; optimalTickCount *= 1.3; if((timeRange_ms/1000) < optimalTickCount){ timeInterval = d3.time.second.utc; this.intervalTickFormat = d3.time.format.utc("%S"); } else if((timeRange_ms/(1000*5)) < optimalTickCount){ timeInterval = d3.time.second.utc; timeIntervalStep = 5; this.intervalTickFormat = d3.time.format.utc("%-S"); } else if((timeRange_ms/(1000*15)) < optimalTickCount){ timeInterval = d3.time.second.utc; timeIntervalStep = 15; this.intervalTickFormat = d3.time.format.utc("%-S"); } else if((timeRange_ms/(1000*60)) < optimalTickCount){ timeInterval = d3.time.minute.utc; timeIntervalStep = 1; this.intervalTickFormat = d3.time.format.utc("%-M"); } else if((timeRange_ms/(1000*60*5)) < optimalTickCount){ timeInterval = d3.time.minute.utc; timeIntervalStep = 5; this.intervalTickFormat = d3.time.format.utc("%-M"); } else if((timeRange_ms/(1000*60*15)) < optimalTickCount){ timeInterval = d3.time.minute.utc; timeIntervalStep = 15; this.intervalTickFormat = d3.time.format.utc("%-M"); } else if((timeRange_ms/(1000*60*60)) < optimalTickCount){ timeInterval = d3.time.hour.utc; timeIntervalStep = 1; this.intervalTickFormat = d3.time.format.utc("%-H"); } else if((timeRange_ms/(1000*60*60*6)) < optimalTickCount){ timeInterval = d3.time.hour.utc; timeIntervalStep = 6; this.intervalTickFormat = d3.time.format.utc("%-H"); } else if((timeRange_ms/(1000*60*60*24)) < optimalTickCount){ timeInterval = d3.time.day.utc; timeIntervalStep = 1; this.intervalTickFormat = d3.time.format.utc("%-e"); } else if((timeRange_ms/(1000*60*60*24*7)) < optimalTickCount){ timeInterval = d3.time.week.utc; this.intervalTickFormat = function(v){ var suffix = kshf.Util.ordinal_suffix_of(v.getUTCDate()); var first=d3.time.format.utc("%-b")(v); return suffix+"<br>"+first; }; this.height_labels = 28; } else if((timeRange_ms/(1000*60*60*24*30)) < optimalTickCount){ timeInterval = d3.time.month.utc; timeIntervalStep = 1; this.intervalTickFormat = function(v){ var threeMonthsLater = timeInterval.offset(v, 3); var first=d3.time.format.utc("%-b")(v); var s=first; if(first==="Jan") s+="<br>"+(d3.time.format("%Y")(threeMonthsLater)); return s; }; this.height_labels = 28; } else if((timeRange_ms/(1000*60*60*24*30*3)) < optimalTickCount){ timeInterval = d3.time.month.utc; timeIntervalStep = 3; this.intervalTickFormat = function(v){ var threeMonthsLater = timeInterval.offset(v, 3); var first=d3.time.format.utc("%-b")(v); var s=first; if(first==="Jan") s+="<br>"+(d3.time.format("%Y")(threeMonthsLater)); return s; }; this.height_labels = 28; } else if((timeRange_ms/(1000*60*60*24*30*6)) < optimalTickCount){ timeInterval = d3.time.month.utc; timeIntervalStep = 6; this.intervalTickFormat = function(v){ var threeMonthsLater = timeInterval.offset(v, 6); var first=d3.time.format.utc("%-b")(v); var s=first; if(first==="Jan") s+="<br>"+(d3.time.format("%Y")(threeMonthsLater)); return s; }; this.height_labels = 28; } else if((timeRange_ms/(1000*60*60*24*365)) < optimalTickCount){ timeInterval = d3.time.year.utc; timeIntervalStep = 1; this.intervalTickFormat = d3.time.format.utc("%Y"); } else if((timeRange_ms/(1000*60*60*24*365*2)) < optimalTickCount){ timeInterval = d3.time.year.utc; timeIntervalStep = 2; this.intervalTickFormat = d3.time.format.utc("%Y"); } else if((timeRange_ms/(1000*60*60*24*365*3)) < optimalTickCount){ timeInterval = d3.time.year.utc; timeIntervalStep = 3; this.intervalTickFormat = d3.time.format.utc("%Y"); } else if((timeRange_ms/(1000*60*60*24*365*5)) < optimalTickCount){ timeInterval = d3.time.year.utc; timeIntervalStep = 5; this.intervalTickFormat = function(v){ var later = timeInterval.offset(v, 4); return d3.time.format.utc("%Y")(v); }; this.height_labels = 28; } else if((timeRange_ms/(1000*60*60*24*365*25)) < optimalTickCount){ timeInterval = d3.time.year.utc; timeIntervalStep = 25; this.intervalTickFormat = d3.time.format.utc("%Y"); } else if((timeRange_ms/(1000*60*60*24*365*100)) < optimalTickCount){ timeInterval = d3.time.year.utc; timeIntervalStep = 100; this.intervalTickFormat = d3.time.format.utc("%Y"); } else { timeInterval = d3.time.year.utc; timeIntervalStep = 500; this.intervalTickFormat = d3.time.format.utc("%Y"); } this.stepTicks = timeIntervalStep===1; this.valueScale.nice(timeInterval, timeIntervalStep); ticks = this.valueScale.ticks(timeInterval, timeIntervalStep); if(this.stepTicks){ ticks.pop(); // remove last tick } } else if(this.stepTicks){ ticks = []; for(var i=this.intervalRange.active.min ; i<=this.intervalRange.active.max; i++){ ticks.push(i); } this.intervalTickFormat = d3.format("d"); } else if(this.scaleType==='log'){ this.valueScale.nice(); // Generate ticks ticks = this.valueScale.ticks(); // ticks cannot be customized directly while(ticks.length > optimalTickCount*1.6){ ticks = ticks.filter(function(d,i){return i%2===0;}); } if(!this.hasFloat) ticks = ticks.filter(function(d){return d%1===0;}); this.intervalTickFormat = d3.format(".1s"); } else { this.valueScale.nice(optimalTickCount); this.valueScale.nice(optimalTickCount); ticks = this.valueScale.ticks(optimalTickCount); this.valueScale.nice(optimalTickCount); ticks = this.valueScale.ticks(optimalTickCount); if(!this.hasFloat) ticks = ticks.filter(function(tick){return tick===0||tick%1===0;}); // Does TICKS have a floating number var ticksFloat = ticks.some(function(tick){ return tick%1!==0; }); var d3Formating = d3.format(ticksFloat?".2f":".2s"); this.intervalTickFormat = function(d){ if(!me.hasFloat && d<10) return d; if(!me.hasFloat && Math.abs(ticks[1]-ticks[0])<1000) return d; var x= d3Formating(d); if(x.indexOf(".00")!==-1) x = x.replace(".00",""); if(x.indexOf(".0")!==-1) x = x.replace(".0",""); return x; } } // Make sure the non-extreme ticks are between intervalRange.active.min and intervalRange.active.max for(var tickNo=1; tickNo<ticks.length-1; ){ var tick = ticks[tickNo]; if(tick<this.intervalRange.active.min){ ticks.splice(tickNo-1,1); // remove the tick } else if(tick > this.intervalRange.active.max){ ticks.splice(tickNo+1,1); // remove the tick } else { tickNo++ } } this.valueScale.domain([ticks[0], ticks[ticks.length-1]]); return ticks; }, /** -- */ getStepWidth: function(){ var _width_ = this.getWidth_Chart(); var stepRange = (this.intervalRange.active.max-this.intervalRange.active.min)+1; return _width_/stepRange; }, /** Uses - optimumTickWidth - this.intervalRang Updates: - scaleType (step vs linear) - valueScale - intervalTickFormat */ updateScaleAndBins: function(force){ var me=this; if(this.isEmpty()) return; switch(this.scaleType){ case 'linear': this.valueScale = d3.scale.linear(); break; case 'log': this.valueScale = d3.scale.log().base(2); break; case 'time': this.valueScale = d3.time.scale.utc(); break; } var _width_ = this.getWidth_Chart(); var stepWidth = this.getStepWidth(); this.valueScale .domain([this.intervalRange.active.min, this.intervalRange.active.max]) .range( this.stepTicks ? [0, _width_-stepWidth] : [0, _width_] ); var ticks = this.getValueTicks( _width_/this.getWidth_OptimumTick() ); // Maybe the ticks still follow step-function ([3,4,5] or [12,13,14,15,16,17] or [2010,2011,2012,2013,2014]) if(!this.stepTicks && !this.hasFloat && this.scaleType==='linear' && ticks.length>2){ // Second: First+1, Last=BeforeLast+1 if( (ticks[1]===ticks[0]+1) && (ticks[ticks.length-1]===ticks[ticks.length-2]+1)) { this.stepTicks = true; if(this.intervalRange.max<ticks[ticks.length-1]){ ticks.pop(); // remove last tick this.intervalRange.active.max = this.intervalRange.max; } this.valueScale .domain([this.intervalRange.active.min, this.intervalRange.active.max]) .range([0, _width_-stepWidth]); } } this.aggrWidth = this.valueScale(ticks[1])-this.valueScale(ticks[0]); if(this.stepTicks && this.scaleType==='time'){ this.valueScale .range([-this.aggrWidth/2+3, _width_-(this.aggrWidth/2)]); } var ticksChanged = (this.intervalTicks.length!==ticks.length) || this.intervalTicks[0]!==ticks[0] || this.intervalTicks[this.intervalTicks.length-1] !== ticks[ticks.length-1] ; if(ticksChanged || force){ this.intervalTicks = ticks; var getRecordValue = this.getRecordValue; // Remove existing aggregates from browser if(this.histBins){ var aggrs=this.browser.allAggregates; this.histBins.forEach(function(aggr){ aggrs.splice(aggrs.indexOf(aggr),1); },this); } this.histBins = []; // Create histBins as kshf.Aggregate this.intervalTicks.forEach(function(tick,i){ var d = new kshf.Aggregate(); d.init(); d.minV = tick; d.maxV = this.intervalTicks[i+1]; d.summary = this; this.histBins.push(d); me.browser.allAggregates.push(d); }, this); if(!this.stepTicks){ this.histBins.pop(); // remove last bin } // distribute records across bins this.filteredItems.forEach(function(record){ var v = getRecordValue(record); if(v===null || v===undefined) return; if(v<this.intervalRange.active.min) return; if(v>this.intervalRange.active.max) return; var binI = null; this.intervalTicks.every(function(tick,i){ if(v>=tick) { binI = i; return true; // keep going } return false; // stop iteration }); if(this.stepTicks) binI = Math.min(binI, this.intervalTicks.length-1); else binI = Math.min(binI, this.intervalTicks.length-2); var bin = this.histBins[binI]; // If the record already had a bin for this summary, remove that bin var existingBinIndex = null; record._aggrCache.some(function(aggr,i){ if(aggr.summary && aggr.summary === this) { existingBinIndex = i; return true; } return false; },this); if(existingBinIndex!==null){ record._aggrCache.splice(existingBinIndex,1); } // ****************************************************************** bin.addRecord(record); },this); this.updateBarScale2Active(); if(this.DOM.root) this.insertVizDOM(); this.updatePercentiles("Active"); } if(this.DOM.root){ if(this.DOM.aggrGlyphs===undefined) this.insertVizDOM(); this.refreshBins_Translate(); this.refreshViz_Scale(); var offset=this.getTickOffset(); this.DOM.labelGroup.selectAll(".tick").style("left",function(d){ return (me.valueScale(d)+offset)+"px"; }); this.refreshIntervalSlider(); } }, /** -- */ getTickOffset: function(){ return (!this.stepTicks) ? 0 : (this.aggrWidth/2); }, /** -- */ insertVizDOM: function(){ if(this.scaleType==='time' && this.DOM.root) { // delete existing DOM: // TODO: Find a way to avoid this? this.DOM.timeSVG.selectAll("*").remove(); this.DOM.measure_Total_Area = this.DOM.timeSVG .append("path").attr("class","measure_Total_Area").datum(this.histBins); this.DOM.measure_Active_Area = this.DOM.timeSVG .append("path").attr("class","measure_Active_Area").datum(this.histBins); this.DOM.lineTrend_ActiveLine = this.DOM.timeSVG.selectAll(".measure_Active_Line") .data(this.histBins, function(d,i){ return i; }) .enter().append("line").attr("class","measure_Active_Line"); this.DOM.measure_Highlighted_Area = this.DOM.timeSVG .append("path").attr("class","measure_Highlighted_Area").datum(this.histBins); this.DOM.measure_Highlighted_Line = this.DOM.timeSVG.selectAll(".measure_Highlighted_Line") .data(this.histBins, function(d,i){ return i; }) .enter().append("line").attr("class","measure_Highlighted_Line"); this.DOM.measure_Compared_Area_A = this.DOM.timeSVG .append("path").attr("class","measure_Compared_Area_A measure_Compared_A").datum(this.histBins); this.DOM.measure_Compared_Line_A = this.DOM.timeSVG.selectAll(".measure_Compared_Line_A") .data(this.histBins, function(d,i){ return i; }) .enter().append("line").attr("class","measure_Compared_Line_A measure_Compared_A"); this.DOM.measure_Compared_Area_B = this.DOM.timeSVG .append("path").attr("class","measure_Compared_Area_B measure_Compared_B").datum(this.histBins); this.DOM.measure_Compared_Line_B = this.DOM.timeSVG.selectAll(".measure_Compared_Line_B") .data(this.histBins, function(d,i){ return i; }) .enter().append("line").attr("class","measure_Compared_Line_B measure_Compared_B"); this.DOM.measure_Compared_Area_C = this.DOM.timeSVG .append("path").attr("class","measure_Compared_Area_C measure_Compared_C").datum(this.histBins); this.DOM.measure_Compared_Line_C = this.DOM.timeSVG.selectAll(".measure_Compared_Line_C") .data(this.histBins, function(d,i){ return i; }) .enter().append("line").attr("class","measure_Compared_Line_C measure_Compared_C"); } this.insertBins(); this.refreshViz_Axis(); this.refreshMeasureLabel(); this.updateTicks(); }, /** -- */ updateTicks: function(){ this.DOM.labelGroup.selectAll(".tick").data([]).exit().remove(); // remove all existing ticks var ddd = this.DOM.labelGroup.selectAll(".tick").data(this.intervalTicks); var ddd_enter = ddd.enter().append("span").attr("class","tick"); ddd_enter.append("span").attr("class","line"); ddd_enter.append("span").attr("class","text"); this.refreshTickLabels(); }, /** -- */ refreshTickLabels: function(){ var me=this; if(this.DOM.labelGroup===undefined) return; this.DOM.labelGroup.selectAll(".tick .text").html(function(d){ if(me.scaleType==='time') return me.intervalTickFormat(d); if(d<1 && d!==0) return me.printWithUnitName( d.toFixed(1) ); else return me.printWithUnitName( me.intervalTickFormat(d) ); }); }, /** -- */ onBinMouseOver: function(aggr){ aggr.DOM.aggrGlyph.setAttribute("showlock",true); aggr.DOM.aggrGlyph.setAttribute("selection","selected"); if(!this.browser.ratioModeActive){ this.DOM.highlightedMeasureValue .style("top",(this.height_hist - this.chartScale_Measure(aggr.measure('Active')))+"px") .style("opacity",1); } this.browser.setSelect_Highlight(this,aggr); }, /** -- */ insertBins: function(){ var me=this; // just remove all aggrGlyphs that existed before. this.DOM.histogram_bins.selectAll(".aggrGlyph").data([]).exit().remove(); var activeBins = this.DOM.histogram_bins.selectAll(".aggrGlyph").data(this.histBins, function(d,i){return i;}); var newBins=activeBins.enter().append("span").attr("class","aggrGlyph rangeGlyph") .each(function(aggr){ aggr.isVisible = true; aggr.DOM.aggrGlyph = this; }) .on("mouseenter",function(aggr){ if(me.highlightRangeLimits_Active) return; var thiss=this; // mouse is moving slow, just do it. if(me.browser.mouseSpeed<0.2) { me.onBinMouseOver(aggr); return; } // mouse is moving fast, should wait a while... this.highlightTimeout = window.setTimeout( function(){ me.onBinMouseOver(aggr) }, me.browser.mouseSpeed*300); }) .on("mouseleave",function(aggr){ if(me.highlightRangeLimits_Active) return; if(this.highlightTimeout) window.clearTimeout(this.highlightTimeout); aggr.unselectAggregate(); me.browser.clearSelect_Highlight(); }) .on("click",function(aggr){ if(me.highlightRangeLimits_Active) return; if(d3.event.shiftKey){ me.browser.setSelect_Compare(me,aggr,true); return; } if(me.summaryFilter.filteredBin===this){ me.summaryFilter.clearFilter(); return; } this.setAttribute("filtered","true"); // store histogram state if(me.scaleType==='time'){ me.summaryFilter.active = { min: aggr.minV, max: aggr.maxV }; } else { me.summaryFilter.active = { min: aggr.minV, max: aggr.maxV }; } me.summaryFilter.filteredBin = null; me.summaryFilter.addFilter(); }); ["Total","Active","Highlighted","Compared_A","Compared_B","Compared_C"].forEach(function(m){ newBins.append("span").attr("class","measure_"+m); }); newBins.selectAll("[class^='measure_Compared_']") .on("mouseover" ,function(){ me.browser.refreshMeasureLabels(this.classList[0].substr(8)); }) .on("mouseleave",function(){ me.browser.refreshMeasureLabels(); }); newBins.append("span").attr("class","total_tip"); newBins.append("span").attr("class","lockButton fa") .each(function(aggr){ this.tipsy = new Tipsy(this, { gravity: 's', title: function(){ return kshf.lang.cur[ me.browser.selectedAggr["Compared_A"]!==aggr ? 'LockToCompare' : 'Unlock']; } }); }) .on("click",function(aggr){ this.tipsy.hide(); me.browser.setSelect_Compare(me,aggr,true); d3.event.stopPropagation(); }) .on("mouseenter",function(aggr){ this.tipsy.options.className = "tipsyFilterLock"; this.tipsy.hide(); this.tipsy.show(); d3.event.stopPropagation(); }) .on("mouseleave",function(aggr){ this.tipsy_title = undefined; this.tipsy.hide(); d3.event.stopPropagation(); }); newBins.append("span").attr("class","measureLabel").each(function(bar){ kshf.Util.setTransform(this,"translateY("+me.height_hist+"px)"); }); this.DOM.aggrGlyphs = this.DOM.histogram_bins.selectAll(".aggrGlyph"); this.DOM.measureLabel = this.DOM.aggrGlyphs.selectAll(".measureLabel"); this.DOM.measureTotalTip = this.DOM.aggrGlyphs.selectAll(".total_tip"); ["Total","Active","Highlighted","Compared_A","Compared_B","Compared_C"].forEach(function(m){ this.DOM["measure_"+m] = this.DOM.aggrGlyphs.selectAll(".measure_"+m); },this); this.DOM.lockButton = this.DOM.aggrGlyphs.selectAll(".lockButton"); }, /** --- */ roundFilterRange: function(){ if(this.scaleType==='time'){ // TODO: Round to meaningful dates return; } // Make sure the range is within the visible limits: this.summaryFilter.active.min = Math.max( this.intervalTicks[0], this.summaryFilter.active.min); this.summaryFilter.active.max = Math.min( this.intervalTicks[this.intervalTicks.length-1], this.summaryFilter.active.max); if(this.stepTicks || !this.hasFloat){ this.summaryFilter.active.min=Math.round(this.summaryFilter.active.min); this.summaryFilter.active.max=Math.round(this.summaryFilter.active.max); } }, /** -- */ map_refreshColorScale: function(){ var me=this; this.DOM.mapColorBlocks .style("background-color", function(d){ if(me.invertColorScale) d = 8-d; return kshf.colorScale[me.browser.mapColorTheme][d]; }); }, /** -- */ initDOM_RecordMapColor: function(){ var me=this; this.DOM.mapColorBar = this.DOM.summaryInterval.append("div").attr("class","mapColorBar"); this.DOM.mapColorBar.append("span").attr("class","invertColorScale fa fa-adjust") .each(function(d){ this.tipsy = new Tipsy(this, { gravity: 'sw', title: "Invert Color Scale" }); }) .on("mouseenter",function(){ this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }) .on("click", function(){ me.invertColorScale = !me.invertColorScale; me.browser.recordDisplay.refreshRecordColors(); me.browser.recordDisplay.map_refreshColorScaleBins(); me.map_refreshColorScale(); }); this.DOM.mapColorBlocks = this.DOM.mapColorBar.selectAll("mapColorBlock") .data([0,1,2,3,4,5,6,7,8]).enter() .append("div").attr("class","mapColorBlock") .each(function(d){ var r = me.valueScale.range()[1]/9; this._minValue = me.valueScale.invert(d*r); this._maxValue = me.valueScale.invert((d+1)*r); this.tipsy = new Tipsy(this, { gravity: 's', title: function(){ return Math.round(this._minValue)+" to "+Math.round(this._maxValue); } }); }) .on("mouseenter",function(d,i){ this.tipsy.show(); this.style.borderColor = (i<4)?"black":"white"; var r = me.valueScale.range()[1]/9; var _minValue = me.valueScale.invert(d*r); var _maxValue = me.valueScale.invert((d+1)*r); me.flexAggr_Highlight.records = []; me.filteredItems.forEach(function(record){ var v = me.getRecordValue(record); if(v>=_minValue && v<=_maxValue) me.flexAggr_Highlight.records.push(record); }); me.flexAggr_Highlight.minV = _minValue; me.flexAggr_Highlight.maxV = _maxValue; me.highlightRangeLimits_Active = true; me.browser.setSelect_Highlight(me,me.flexAggr_Highlight); }) .on("mouseleave",function(){ this.tipsy.hide(); me.browser.clearSelect_Highlight(); }) .on("click",function(){ me.summaryFilter.active = { min: this._minValue, max: this._maxValue }; me.summaryFilter.addFilter(); }); this.map_refreshColorScale(); }, /** -- */ initDOM_Slider: function(){ var me=this; this.DOM.intervalSlider = this.DOM.summaryInterval.append("div").attr("class","intervalSlider"); this.DOM.zoomControl = this.DOM.intervalSlider.append("span").attr("class","zoomControl fa") .attr("sign","plus") .each(function(d){ this.tipsy = new Tipsy(this, { gravity: 'w', title: function(){ return (this.getAttribute("sign")==="plus")?"Zoom into range":"Zoom out"; } }); }) .on("mouseenter",function(){ this.tipsy.show(); }) .on("mouseleave",function(){ this.tipsy.hide(); }) .on("click",function(){ this.tipsy.hide(); me.setZoomed(this.getAttribute("sign")==="plus"); }); var controlLine = this.DOM.intervalSlider.append("div").attr("class","controlLine") .on("mousedown", function(){ if(d3.event.which !== 1) return; // only respond to left-click me.browser.setNoAnim(true); var e=this.parentNode; var initPos = me.valueScale.invert(d3.mouse(e)[0]); d3.select("body").style('cursor','ew-resize') .on("mousemove", function() { var targetPos = me.valueScale.invert(d3.mouse(e)[0]); me.summaryFilter.active.min=d3.min([initPos,targetPos]); me.summaryFilter.active.max=d3.max([initPos,targetPos]); me.roundFilterRange(); me.refreshIntervalSlider(); // wait half second to update if(this.timer) clearTimeout(this.timer); me.summaryFilter.filteredBin = this; this.timer = setTimeout(function(){ if(me.isFiltered_min() || me.isFiltered_max()){ me.summaryFilter.addFilter(); } else { me.summaryFilter.clearFilter(); } },250); }).on("mouseup", function(){ me.browser.setNoAnim(false); d3.select("body").style('cursor','auto').on("mousemove",null).on("mouseup",null); }); d3.event.preventDefault(); }); controlLine.append("span").attr("class","base total"); controlLine.append("span").attr("class","base active") .each(function(){ this.tipsy = new Tipsy(this, { gravity: "s", title: kshf.lang.cur.DragToFilter }); }) // TODO: The problem is, the x-position (left-right) of the tooltip is not correctly calculated // because the size of the bar is set by scaling, not through width.... //.on("mouseover",function(){ this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .on("mousedown", function(){ this.tipsy.hide(); if(d3.event.which !== 1) return; // only respond to left-click if(me.scaleType==='time') return; // time is not supported for now. var e=this.parentNode; var initMin = me.summaryFilter.active.min; var initMax = me.summaryFilter.active.max; var initRange= initMax - initMin; var initPos = d3.mouse(e)[0]; d3.select("body").style('cursor','ew-resize') .on("mousemove", function() { if(me.scaleType==='log'){ var targetDif = d3.mouse(e)[0]-initPos; me.summaryFilter.active.min = me.valueScale.invert(me.valueScale(initMin)+targetDif); me.summaryFilter.active.max = me.valueScale.invert(me.valueScale(initMax)+targetDif); } else if(me.scaleType==='time'){ // TODO return; } else { var targetPos = me.valueScale.invert(d3.mouse(e)[0]); var targetDif = targetPos-me.valueScale.invert(initPos); me.summaryFilter.active.min = initMin+targetDif; me.summaryFilter.active.max = initMax+targetDif; if(me.summaryFilter.active.min<me.intervalRange.active.min){ me.summaryFilter.active.min=me.intervalRange.active.min; me.summaryFilter.active.max=me.intervalRange.active.min+initRange; } if(me.summaryFilter.active.max>me.intervalRange.active.max){ me.summaryFilter.active.max=me.intervalRange.active.max; me.summaryFilter.active.min=me.intervalRange.active.max-initRange; } } me.roundFilterRange(); me.refreshIntervalSlider(); // wait half second to update if(this.timer) clearTimeout(this.timer); me.summaryFilter.filteredBin = this; this.timer = setTimeout(function(){ if(me.isFiltered_min() || me.isFiltered_max()){ me.summaryFilter.addFilter(); } else{ me.summaryFilter.clearFilter(); } },200); }).on("mouseup", function(){ d3.select("body").style('cursor','auto').on("mousemove",null).on("mouseup",null); }); d3.event.preventDefault(); d3.event.stopPropagation(); }); controlLine.selectAll(".handle").data(['min','max']).enter() .append("span").attr("class",function(d){ return "handle "+d; }) .each(function(d,i){ this.tipsy = new Tipsy(this, { gravity: i==0?"w":"e", title: kshf.lang.cur.DragToFilter }); }) .on("mouseover",function(){ if(this.dragging!==true) this.tipsy.show(); }) .on("mouseout" ,function(){ this.tipsy.hide(); }) .on("mousedown", function(d,i){ this.tipsy.hide(); if(d3.event.which !== 1) return; // only respond to left-click var mee = this; var e=this.parentNode; d3.select("body").style('cursor','ew-resize') .on("mousemove", function() { mee.dragging = true; var targetPos = me.valueScale.invert(d3.mouse(e)[0]); me.summaryFilter.active[d] = targetPos; // Swap is min > max if(me.summaryFilter.active.min>me.summaryFilter.active.max){ var t=me.summaryFilter.active.min; me.summaryFilter.active.min = me.summaryFilter.active.max; me.summaryFilter.active.max = t; if(d==='min') d='max'; else d='min'; } me.roundFilterRange(); me.refreshIntervalSlider(); // wait half second to update if(this.timer) clearTimeout(this.timer); me.summaryFilter.filteredBin = this; this.timer = setTimeout( function(){ if(me.isFiltered_min() || me.isFiltered_max()){ me.summaryFilter.addFilter(); } else { me.summaryFilter.clearFilter(); } },200); }).on("mouseup", function(){ mee.dragging = false; d3.select("body").style('cursor','auto').on("mousemove",null).on("mouseup",null); }); d3.event.preventDefault(); d3.event.stopPropagation(); }) .append("span").attr("class","rangeLimitOnChart"); this.DOM.recordValue = controlLine.append("div").attr("class","recordValue"); this.DOM.recordValue.append("span").attr("class","recordValueScaleMark"); this.DOM.recordValueText = this.DOM.recordValue .append("span").attr("class","recordValueText") .append("span").attr("class","recordValueText-v"); this.DOM.labelGroup = this.DOM.intervalSlider.append("div").attr("class","labelGroup"); }, /** -- */ updateBarScale2Active: function(){ this.chartScale_Measure .domain([0, this.getMaxAggr_Active() || 1]) .range ([0, this.height_hist]); }, /** -- */ refreshBins_Translate: function(){ var me=this; var offset = (this.stepTicks)? this.width_barGap : 0; this.DOM.aggrGlyphs .style("width",this.getWidth_Bin()+"px") .each(function(aggr){ kshf.Util.setTransform(this,"translateX("+(me.valueScale(aggr.minV)+offset)+"px)"); }); }, /** -- */ refreshViz_Scale: function(){ this.refreshViz_Total(); this.refreshViz_Active(); }, /** -- */ refreshViz_Total: function(){ if(this.isEmpty() || this.collapsed) return; var me=this; var width=this.getWidth_Bin(); var heightTotal = function(aggr){ if(aggr._measure.Total===0) return 0; if(me.browser.ratioModeActive) return me.height_hist; return me.chartScale_Measure(aggr.measure('Total')); }; if(this.scaleType==='time'){ var durationTime=this.browser.noAnim?0:700; this.timeSVGLine = d3.svg.area().interpolate("cardinal") .x(function(aggr){ return me.valueScale(aggr.minV)+width/2; }) .y0(me.height_hist) .y1(function(aggr){ return (aggr._measure.Total===0) ? (me.height_hist+3) : (me.height_hist-heightTotal(aggr)); }); this.DOM.measure_Total_Area.transition().duration(durationTime).attr("d", this.timeSVGLine); } else { this.DOM.measure_Total.each(function(aggr){ kshf.Util.setTransform(this, "translateY("+me.height_hist+"px) scale("+width+","+heightTotal(aggr)+")"); }); if(!this.browser.ratioModeActive){ this.DOM.measureTotalTip .style("opacity",function(aggr){ return (aggr.measure('Total')>me.chartScale_Measure.domain()[1])?1:0; }) .style("width",width+"px"); } else { this.DOM.measureTotalTip.style("opacity",0); } } }, /** -- */ refreshViz_Active: function(){ if(this.isEmpty() || this.collapsed) return; var me=this; var width = this.getWidth_Bin(); var heightActive = function(aggr){ if(aggr._measure.Active===0) return 0; if(me.browser.ratioModeActive) return me.height_hist; return me.chartScale_Measure(aggr.measure('Active')); }; // Position the lock button this.DOM.lockButton .each(function(aggr){ kshf.Util.setTransform(this,"translateY("+(me.height_hist-heightActive(aggr)-10)+"px)"); }) .attr("inside",function(aggr){ if(me.browser.ratioModeActive) return ""; if(me.height_hist-heightActive(aggr)<6) return ""; }); // Time (line chart) update if(this.scaleType==='time'){ var durationTime = this.browser.noAnim ? 0 : 700; var xFunc = function(aggr){ return me.valueScale(aggr.minV)+width/2; }; this.timeSVGLine = d3.svg.area().interpolate("cardinal") .x(xFunc).y0(me.height_hist+2) .y1(function(aggr){ return (aggr._measure.Active===0) ? me.height_hist+3 : (me.height_hist-heightActive(aggr)+1); }); this.DOM.measure_Active_Area.transition().duration(durationTime).attr("d", this.timeSVGLine); this.DOM.lineTrend_ActiveLine.transition().duration(durationTime) .attr("x1",xFunc) .attr("x2",xFunc) .attr("y1",function(aggr){ return me.height_hist+3; }) .attr("y2",function(aggr){ return (aggr._measure.Active===0) ? (me.height_hist+3) : (me.height_hist - heightActive(aggr)+1); }); } if(!this.isFiltered() || this.scaleType==='time' || this.stepTicks){ // No partial rendering this.DOM.measure_Active.each(function(aggr){ kshf.Util.setTransform(this, "translateY("+me.height_hist+"px) scale("+width+","+heightActive(aggr)+")"); }); } else { // Partial rendering // is filtered & not step scale var filter_min = this.summaryFilter.active.min; var filter_max = this.summaryFilter.active.max; var minPos = this.valueScale(filter_min); var maxPos = this.valueScale(filter_max); this.DOM.measure_Active.each(function(aggr){ var translateX = ""; var width_self=width; var aggr_min = aggr.minV; var aggr_max = aggr.maxV; if(aggr._measure.Active>0){ // it is within the filtered range if(aggr_min<filter_min){ var lostWidth = minPos-me.valueScale(aggr_min); translateX = "translateX("+lostWidth+"px) "; width_self -= lostWidth; } if(aggr_max>filter_max){ width_self -= me.valueScale(aggr_max)-maxPos-me.width_barGap*2; } } kshf.Util.setTransform(this, "translateY("+me.height_hist+"px) "+translateX+"scale("+width_self+","+heightActive(aggr)+")"); }); } }, /** -- */ refreshViz_Compare: function(cT, curGroup, totalGroups){ if(this.isEmpty() || this.collapsed || !this.inBrowser()) return; var me=this; var width = this.getWidth_Bin(); var binWidth = width / totalGroups; var ratioModeActive = this.browser.ratioModeActive; var compId = "Compared_"+cT; if(this.percentileChartVisible==="Extended"){ if(this.browser.vizActive[compId]){ this.DOM.percentileGroup.select(".compared_percentileChart").style("display","block"); if(this.browser.vizActive["Compared_"+cT]) this.updatePercentiles("Compared_"+cT); } else { this.DOM.percentileGroup.select(".compared_percentileChart").style("display","none"); } } var heightCompare = function(aggr){ if(aggr._measure[compId]===0) return 0; return ratioModeActive ? aggr.ratioCompareToActive(cT)*me.height_hist : me.chartScale_Measure(aggr.measure(compId)); }; // Time (line chart) update if(this.scaleType==='time'){ var yFunc = function(aggr){ return (aggr._measure[compId]===0) ? (me.height_hist+3) : (me.height_hist-heightCompare(aggr)); }; var xFunc = function(aggr){ return me.valueScale(aggr.minV)+width/2; }; var dTime = 200; this.timeSVGLine = d3.svg.area().interpolate("cardinal").x(xFunc).y(yFunc); this.DOM["measure_Compared_Area_"+cT].transition().duration(dTime).attr("d", this.timeSVGLine); this.DOM["measure_Compared_Line_"+cT].transition().duration(dTime) .attr("y1",me.height_hist+3 ).attr("y2",yFunc) .attr("x1",xFunc).attr("x2",xFunc); return; } var _translateY = "translateY("+me.height_hist+"px) "; var _translateX = "translateX("+((curGroup+1)*binWidth)+"px) "; if(!this.isFiltered() || this.scaleType==='time' || this.stepTicks){ // No partial rendering this.DOM["measure_Compared_"+cT].each(function(aggr){ kshf.Util.setTransform(this, _translateY+_translateX+"scale("+binWidth+","+heightCompare(aggr)+")"); }); } else { // partial rendering var filter_min = this.summaryFilter.active.min; var filter_max = this.summaryFilter.active.max; var minPos = this.valueScale(filter_min); var maxPos = this.valueScale(filter_max); this.DOM["measure_Compared_"+cT].each(function(aggr){ var translateX = ""; var width_self=(curGroup*binWidth); var aggr_min = aggr.minV; var aggr_max = aggr.maxV; if(aggr._measure.Active>0){ // it is within the filtered range if(aggr_min<filter_min){ var lostWidth = minPos-me.valueScale(aggr_min); translateX = "translateX("+lostWidth+"px) "; width_self -= lostWidth; } if(aggr_max>filter_max){ width_self -= me.valueScale(aggr_max)-maxPos-me.width_barGap*2; } } kshf.Util.setTransform(this, _translateY+translateX+"scale("+(width_self/2)+","+heightCompare(aggr)+")"); }); } }, /** -- */ refreshViz_Highlight: function(){ if(this.isEmpty() || this.collapsed || !this.DOM.inited || !this.inBrowser()) return; var me=this; var width = this.getWidth_Bin(); this.refreshViz_EmptyRecords(); this.refreshMeasureLabel(); var totalC = this.browser.getActiveComparedCount(); if(this.browser.measureFunc==="Avg") totalC++; if(this.browser.vizActive.Highlighted){ this.updatePercentiles("Highlighted"); this.DOM.highlightedMeasureValue .style("top",( this.height_hist * (1-this.browser.allRecordsAggr.ratioHighlightToTotal() ))+"px") .style("opacity",(this.browser.ratioModeActive?1:0)); } else { // Highlight not active this.DOM.percentileGroup.select(".percentileChart_Highlighted").style("opacity",0); this.DOM.highlightedMeasureValue.style("opacity",0); this.refreshMeasureLabel(); this.highlightRangeLimits_Active = false; } this.DOM.highlightRangeLimits .style("opacity",(this.highlightRangeLimits_Active&&this.browser.vizActive.Highlighted)?1:0) .style("left", function(d){ return me.valueScale(me.flexAggr_Highlight[(d===0)?'minV':'maxV'])+"px"; }); var getAggrHeight_Preview = function(aggr){ var p=aggr.measure('Highlighted'); if(me.browser.preview_not) p = aggr.measure('Active')-p; if(me.browser.ratioModeActive){ if(aggr._measure.Active===0) return 0; return (p / aggr.measure('Active'))*me.height_hist; } else { return me.chartScale_Measure(p); } }; if(this.scaleType==='time'){ var yFunc = function(aggr){ return (aggr._measure.Highlighted===0) ? (me.height_hist+3) : (me.height_hist-getAggrHeight_Preview(aggr)); }; var xFunc = function(aggr){ return me.valueScale(aggr.minV)+width/2; }; var dTime=200; this.timeSVGLine = d3.svg.area().interpolate("cardinal") .x(xFunc) .y0(me.height_hist+2) .y1(yFunc); this.DOM.measure_Highlighted_Area.transition().duration(dTime).attr("d", this.timeSVGLine); this.DOM.measure_Highlighted_Line.transition().duration(dTime) .attr("y1",me.height_hist+3) .attr("y2",yFunc) .attr("x1",xFunc) .attr("x2",xFunc); } else { if(!this.browser.vizActive.Highlighted){ var xx = (width / (totalC+1)); var transform = "translateY("+this.height_hist+"px) scale("+xx+",0)"; this.DOM.measure_Highlighted.each(function(){ kshf.Util.setTransform(this,transform); }); return; } var _translateY = "translateY("+me.height_hist+"px) "; var range_min = this.valueScale.domain()[0]; var range_max = this.valueScale.domain()[1]; var rangeFill = false; if(this.isFiltered()){ range_min = Math.max(range_min, this.summaryFilter.active.min); range_max = Math.max(range_min, this.summaryFilter.active.max); rangeFill = true; } if(this.highlightRangeLimits_Active){ range_min = Math.max(range_min, this.flexAggr_Highlight.minV); range_max = Math.max(range_min, this.flexAggr_Highlight.maxV); rangeFill = true; } var minPos = this.valueScale(range_min); var maxPos = this.valueScale(range_max); this.DOM.measure_Highlighted.each(function(aggr){ var _translateX = ""; var barWidth = width; if(aggr._measure.Active>0 && rangeFill){ var aggr_min = aggr.minV; var aggr_max = aggr.maxV; // it is within the filtered range if(aggr_min<range_min){ var lostWidth = minPos-me.valueScale(aggr_min); _translateX = "translateX("+lostWidth+"px) "; barWidth -= lostWidth; } if(aggr_max>range_max){ barWidth -= me.valueScale(aggr_max)-maxPos-me.width_barGap*2; } } if(!rangeFill){ barWidth = barWidth / (totalC+1); //_translateX = "translateX("+barWidth*totalC+"px) "; } var _scale = "scale("+barWidth+","+getAggrHeight_Preview(aggr)+")"; kshf.Util.setTransform(this,_translateY+_translateX+_scale); }); } }, /** -- */ refreshViz_Axis: function(){ if(this.isEmpty() || this.collapsed) return; var me = this, tickValues, maxValue; var chartAxis_Measure_TickSkip = me.height_hist/17; if(this.browser.ratioModeActive || this.browser.percentModeActive) { maxValue = (this.browser.ratioModeActive) ? 100 : Math.round(100*me.getMaxAggr_Active()/me.browser.allRecordsAggr.measure('Active')); tickValues = d3.scale.linear() .rangeRound([0, this.height_hist]) .domain([0,maxValue]) .clamp(true) .ticks(chartAxis_Measure_TickSkip); } else { tickValues = this.chartScale_Measure.ticks(chartAxis_Measure_TickSkip); } // remove non-integer values & 0... tickValues = tickValues.filter(function(d){return d%1===0&&d!==0;}); var tickDoms = this.DOM.chartAxis_Measure_TickGroup.selectAll("span.tick") .data(tickValues,function(i){return i;}); tickDoms.exit().remove(); var tickData_new=tickDoms.enter().append("span").attr("class","tick"); // translate the ticks horizontally on scale tickData_new.append("span").attr("class","line"); tickData_new.append("span").attr("class","text text_left measureAxis_left"); tickData_new.append("span").attr("class","text text_right measureAxis_right"); // Place the doms at the bottom of the histogram, so their position is animated? tickData_new.each(function(){ kshf.Util.setTransform(this,"translateY("+me.height_hist+"px)"); }); this.DOM.chartAxis_Measure_TickGroup.selectAll("span.tick > span.text") .html(function(d){ return me.browser.getMeasureLabel(d); }); setTimeout(function(){ var transformFunc; if(me.browser.ratioModeActive){ transformFunc=function(d){ kshf.Util.setTransform(this,"translateY("+ (me.height_hist-d*me.height_hist/100)+"px)"); }; } else { if(me.browser.percentModeActive){ transformFunc=function(d){ kshf.Util.setTransform(this,"translateY("+(me.height_hist-(d/maxValue)*me.height_hist)+"px)"); }; } else { transformFunc=function(d){ kshf.Util.setTransform(this,"translateY("+(me.height_hist-me.chartScale_Measure(d))+"px)"); }; } } var x = me.browser.noAnim; if(x===false) me.browser.setNoAnim(true); me.DOM.chartAxis_Measure.selectAll(".tick").style("opacity",1).each(transformFunc); if(x===false) me.browser.setNoAnim(false); }); }, /** -- */ refreshIntervalSlider: function(){ var minPos = this.valueScale(this.summaryFilter.active.min); var maxPos = this.valueScale(this.summaryFilter.active.max); // Adjusting min/max position is important because if it is not adjusted, the // tips of the filtering range may not appear at the bar limits, which looks distracting. if(this.summaryFilter.active.min===this.intervalRange.min){ minPos = this.valueScale.range()[0]; } if(this.summaryFilter.active.max===this.intervalRange.max){ maxPos = this.valueScale.range()[1]; if(this.stepTicks){ maxPos += this.getWidth_Bin(); } } this.DOM.intervalSlider.select(".base.active") .attr("filtered",this.isFiltered()) .each(function(d){ this.style.left = minPos+"px"; this.style.width = (maxPos-minPos)+"px"; //kshf.Util.setTransform(this,"translateX("+minPos+"px) scaleX("+(maxPos-minPos)+")"); }); this.DOM.intervalSlider.selectAll(".handle") .each(function(d){ kshf.Util.setTransform(this,"translateX("+((d==="min")?minPos:maxPos)+"px)"); }); }, /** -- */ refreshHeight: function(){ this.DOM.histogram.style("height",(this.height_hist+this.height_hist_topGap)+"px") this.DOM.wrapper.style("height",(this.collapsed?"0":this.getHeight_Content())+"px"); this.DOM.root.style("max-height",(this.getHeight()+1)+"px"); var labelTranslate ="translateY("+this.height_hist+"px)"; if(this.DOM.measureLabel) this.DOM.measureLabel.each(function(bar){ kshf.Util.setTransform(this,labelTranslate); }); if(this.DOM.timeSVG) this.DOM.timeSVG.style("height",(this.height_hist+2)+"px"); }, /** -- */ refreshWidth: function(){ this.detectScaleType(); this.updateScaleAndBins(); if(this.DOM.inited===false) return; var chartWidth = this.getWidth_Chart(); var wideChart = this.getWidth()>400; this.DOM.summaryInterval .attr("measureAxis_right",wideChart?"true":null) .style("width",this.getWidth()+"px") .style("padding-left", this.width_measureAxisLabel+"px") .style("padding-right", ( wideChart ? this.width_measureAxisLabel : 11)+"px"); this.DOM.summaryInterval.selectAll(".measureAxis_right").style("display",wideChart?"block":"none"); this.DOM.summaryName.style("max-width",(this.getWidth()-40)+"px"); if(this.DOM.timeSVG) this.DOM.timeSVG.style("width",(chartWidth+2)+"px") }, /** -- */ setHeight: function(targetHeight){ if(this.histBins===undefined) return; var c = targetHeight - this.getHeight_Header() - this.getHeight_Extra(); if(this.height_hist===c) return; this.height_hist = c; this.updateBarScale2Active(); if(!this.DOM.inited) return; this.refreshBins_Translate(); this.refreshViz_Scale(); this.refreshViz_Highlight(); this.refreshViz_Compare_All(); this.refreshViz_Axis(); this.refreshHeight(); this.DOM.labelGroup.style("height",this.height_labels+"px"); this.DOM.intervalSlider.selectAll(".rangeLimitOnChart") .style("height",(this.height_hist+13)+"px") .style("top",(-this.height_hist-13)+"px"); this.DOM.highlightRangeLimits.style("height",this.height_hist+"px"); }, /** -- */ updateAfterFilter: function(){ if(this.isEmpty() || this.collapsed || !this.inBrowser()) return; this.updateChartScale_Measure(); this.refreshMeasureLabel(); this.refreshViz_EmptyRecords(); this.updatePercentiles("Active"); }, /** -- */ updateChartScale_Measure: function(){ if(!this.aggr_initialized || this.isEmpty()) return; // nothing to do var me=this; this.updateBarScale2Active(); this.refreshBins_Translate(); this.refreshViz_Scale(); this.refreshViz_Highlight(); this.refreshViz_Compare_All(); this.refreshViz_Axis(); }, /** -- */ setRecordValue: function(record){ if(!this.inBrowser()) return; if(this.DOM.inited===false) return; var v = this.getRecordValue(record); if(v===null) return; if(this.valueScale===undefined) return; if(this.scaleType==='log' && v<=0) return; // do not map zero/negative values var me=this; var offset=this.getTickOffset(); this.DOM.recordValue .each(function(){ kshf.Util.setTransform(this,"translateX("+(me.valueScale(v)+offset)+"px)"); }) .style("display","block"); this.DOM.recordValueText.html( this.printWithUnitName(this.intervalTickFormat(v)) ); }, /** -- */ hideRecordValue: function(){ if(!this.DOM.inited) return; this.DOM.recordValue.style("display",null); }, /** -- */ updateQuantiles: function(distr){ var me=this; // get active values into an array // the items are already sorted by their numeric value, it's just a linear pass. var values = []; if(distr==="Active"){ this.filteredItems.forEach(function(record){ if(record.isWanted) values.push(me.getRecordValue(record)); }); } else if(distr==="Highlighted"){ this.filteredItems.forEach(function(record){ if(record.highlighted) values.push(me.getRecordValue(record)); }); } else { var cT = distr.substr(9); // Compared_A / Compared_B / Compared_C this.filteredItems.forEach(function(record){ if(record.selectCompared[cT]) values.push(me.getRecordValue(record)); }); // Below doesn't work: The values will not be in sorted order!! /* this.browser.selectedAggr[distr].records.forEach(function(record){ val v = me.getRecordValue(record); if(v!==null) values.push(v); }); */ } [10,20,30,40,50,60,70,80,90].forEach(function(q){ var x =d3.quantile(values,q/100); this.quantile_val[distr+q] = x; this.quantile_pos[distr+q] = this.valueScale(x); },this); }, /** -- */ updatePercentiles: function(distr){ if(this.percentileChartVisible===false) return; this.updateQuantiles(distr); this.DOM.percentileGroup.select(".percentileChart_"+distr).style("opacity",1); this._updatePercentiles(distr); }, /** -- */ _updatePercentiles: function(distr){ [10,20,30,40,50,60,70,80,90].forEach(function(q){ kshf.Util.setTransform(this.DOM.quantile[distr+q][0][0],"translateX("+this.quantile_pos[distr+q]+"px)"); },this); [[10,90],[20,80],[30,70],[40,60]].forEach(function(qb){ kshf.Util.setTransform(this.DOM.quantile[distr+qb[0]+"_"+qb[1]][0][0], "translateX("+(this.quantile_pos[distr+qb[0]])+"px) "+ "scaleX("+(this.quantile_pos[distr+qb[1]]-this.quantile_pos[distr+qb[0]])+") "); },this); } }; for(var index in Summary_Interval_functions){ kshf.Summary_Interval.prototype[index] = Summary_Interval_functions[index]; } kshf.Summary_Set = function(){}; kshf.Summary_Set.prototype = new kshf.Summary_Base(); var Summary_Clique_functions = { initialize: function(browser,setListSummary,side){ kshf.Summary_Base.prototype.initialize.call(this,browser,"Relations in "+setListSummary.summaryName); var me = this; this.setListSummary = setListSummary; this.panel = this.setListSummary.panel; if(side) this.position = side; else{ this.position = (this.panel.name==="left") ? "right" : "left"; } this.pausePanning=false; this.gridPan_x=0; // Update sorting options of setListSummary (adding relatednesness metric...) this.setListSummary.catSortBy[0].name = this.browser.itemName+" #"; this.setListSummary.insertSortingOption({ name: "Relatedness", value: function(category){ return -category.MST.index; }, prep: function(){ me.updatePerceptualOrder(); } }); this.setListSummary.refreshSortOptions(); this.setListSummary.DOM.optionSelect.attr("dir","rtl"); // quick hack: right-align the sorting label this.setListSummary.cbFacetSort = function(){ me.refreshWindowSize(); me.refreshRow(); me.DOM.setPairGroup.attr("animate_position",false); me.refreshSetPair_Position(); setTimeout(function(){ me.DOM.setPairGroup.attr("animate_position",true); },1000); }; this.setListSummary.onCategoryCull = function(){ if(me.pausePanning) return; me.checkPan(); me.refreshSVGViewBox(); }; this.setListSummary.cbSetHeight = function(){ // update self me.updateWidthFromHeight(); me.updateSetPairScale(); // do not show number labels if the row height is small me.DOM.chartRoot.attr("showNumberLabels",me.getRowHeight()>=30); me.DOM.chartRoot.attr("show_gridlines",(me.getRowHeight()>15)); me.DOM.setPairGroup.attr("animate_position",false); me.refreshRow(); me.refreshSetPair_Background(); me.refreshSetPair_Position(); me.refreshViz_All(); me.refreshWindowSize(); me.refreshSetPair_Strength(); setTimeout(function(){ me.DOM.setPairGroup.attr("animate_position",true); },1000); }; this._setPairs = []; this._setPairs_ID = {}; this._sets = this.setListSummary._cats; // sorted already this._sets.forEach(function(set){ set.setPairs = []; }); this.createSetPairs(); // Inserts the DOM root under the setListSummary so that the matrix view is attached... this.DOM.root = this.setListSummary.DOM.root.insert("div",":first-child") .attr("class","kshfSummary setPairSummary") .attr("filtered",false) .attr("position",this.position); // Use keshif's standard header this.insertHeader(); this.DOM.headerGroup.style("height",(this.setListSummary.getHeight_Header())+"px"); this.DOM.chartRoot = this.DOM.wrapper.append("span") .attr("class","Summary_Set") .attr("noanim",false) .attr("show_gridlines",true); var body=d3.select("body"); this.DOM.chartRoot.append("span").attr("class","setMatrixWidthAdjust") .attr("title","Drag to adjust panel width") .on("mousedown", function (d, i) { if(d3.event.which !== 1) return; // only respond to left-click browser.DOM.root.style('cursor','ew-resize'); me.DOM.root.attr('noanim',true); me.DOM.setPairGroup.attr("animate_position",false); var mouseInit_x = d3.mouse(body[0][0])[0]; console.log("mouseInit_x: "+mouseInit_x); var initWidth = me.getWidth(); var myHeight = me.getHeight(); body.on("mousemove", function() { var mouseDif = d3.mouse(body[0][0])[0]-mouseInit_x; console.log("mouseNew_x: "+d3.mouse(body[0][0])[0]); var targetWidth = initWidth-mouseDif; var targetAngle_Rad = Math.atan(myHeight/targetWidth); var targetAngle_Deg = 90-(targetAngle_Rad*180)/Math.PI; targetAngle_Deg = Math.min(Math.max(targetAngle_Deg,30),60); me.noanim = true; me.summaryWidth = (me.position==="left") ? initWidth-mouseDif : initWidth+mouseDif; me.checkWidth(); me.refreshWindowSize(); me.refreshRow_LineWidths(); me.refreshSetPair_Position(); }).on("mouseup", function(){ browser.DOM.root.style('cursor','default'); me.DOM.setPairGroup.attr("animate_position",true); me.DOM.root.attr('noanim',false); me.noanim = false; // unregister mouse-move callbacks body.on("mousemove", null).on("mouseup", null); }); d3.event.preventDefault(); }) .on("click",function(){ d3.event.stopPropagation(); d3.event.preventDefault(); }); this.insertControls(); this.DOM.setMatrixSVG = this.DOM.chartRoot.append("svg").attr("xmlns","http://www.w3.org/2000/svg").attr("class","setMatrix"); /** BELOW THE MATRIX **/ this.DOM.belowMatrix = this.DOM.chartRoot.append("div").attr("class","belowMatrix"); this.DOM.belowMatrix.append("div").attr("class","border_line"); this.DOM.pairCount = this.DOM.belowMatrix.append("span").attr("class","pairCount matrixInfo"); this.DOM.pairCount.append("span").attr("class","circleeee"); this.DOM.pairCount_Text = this.DOM.pairCount.append("span").attr("class","pairCount_Text") .text(""+this._setPairs.length+" pairs ("+Math.round(100*this._setPairs.length/this.getSetPairCount_Total())+"%)"); this.DOM.subsetCount = this.DOM.belowMatrix.append("span").attr("class","subsetCount matrixInfo"); this.DOM.subsetCount.append("span").attr("class","circleeee borrderr"); this.DOM.subsetCount_Text = this.DOM.subsetCount.append("span").attr("class","subsetCount_Text"); // invisible background - Used for panning this.DOM.setMatrixBackground = this.DOM.setMatrixSVG.append("rect") .attr("x",0).attr("y",0) .style("fill-opacity","0") .on("mousedown",function(){ var background_dom = this.parentNode.parentNode.parentNode.parentNode; background_dom.style.cursor = "all-scroll"; me.browser.DOM.pointerBlock.attr("active",""); var mouseInitPos = d3.mouse(background_dom); var gridPan_x_init = me.gridPan_x; // scroll the setlist summary too... var scrollDom = me.setListSummary.DOM.aggrGroup[0][0]; var initScrollPos = scrollDom.scrollTop; var w=me.getWidth(); var h=me.getHeight(); var initT = me.setListSummary.scrollTop_cache; var initR = Math.min(-initT-me.gridPan_x,0); me.pausePanning = true; me.browser.DOM.root.on("mousemove", function() { var mouseMovePos = d3.mouse(background_dom); var difX = mouseMovePos[0]-mouseInitPos[0]; var difY = mouseMovePos[1]-mouseInitPos[1]; if(me.position==="right") { difX *= -1; } me.gridPan_x = Math.min(0,gridPan_x_init+difX+difY); me.checkPan(); var maxHeight = me.setListSummary.heightRow_category*me.setListSummary._cats.length - h; var t = initT-difY; t = Math.min(maxHeight,Math.max(0,t)); var r = initR-difX; r = Math.min(0,Math.max(r,-t)); if(me.position==="right") r = -r; me.DOM.setMatrixSVG.attr("viewBox",r+" "+t+" "+w+" "+h); scrollDom.scrollTop = Math.max(0,initScrollPos-difY); d3.event.preventDefault(); d3.event.stopPropagation(); }).on("mouseup", function(){ me.pausePanning = false; background_dom.style.cursor = "default"; me.browser.DOM.root.on("mousemove", null).on("mouseup", null); me.browser.DOM.pointerBlock.attr("active",null); me.refreshLabel_Vert_Show(); d3.event.preventDefault(); d3.event.stopPropagation(); }); d3.event.preventDefault(); d3.event.stopPropagation(); }) ; this.DOM.setMatrixSVG.append("g").attr("class","rows"); this.DOM.setPairGroup = this.DOM.setMatrixSVG.append("g").attr("class","aggrGroup setPairGroup").attr("animate_position",true); this.insertRows(); this.insertSetPairs(); this.updateWidthFromHeight(); this.updateSetPairScale(); this.refreshRow(); this.refreshSetPair_Background(); this.refreshSetPair_Position(); this.refreshSetPair_Containment(); this.refreshViz_Axis(); this.refreshViz_Active(); this.refreshWindowSize(); }, /** -- */ refreshHeight: function(){ // TODO: Added just because the browser calls this automatically }, /** -- */ isEmpty: function(){ return false; // TODO Temp? }, /** -- */ getHeight: function(){ return this.setListSummary.categoriesHeight; }, /** -- */ getWidth: function(){ return this.summaryWidth; }, /** -- */ getRowHeight: function(){ return this.setListSummary.heightRow_category; }, /** -- */ getSetPairCount_Total: function(){ return this._sets.length*(this._sets.length-1)/2; }, /** -- */ getSetPairCount_Empty: function(){ return this.getSetPairCount_Total()-this._setPairs.length; }, /** -- */ updateWidthFromHeight: function(){ this.summaryWidth = this.getHeight()+25; this.checkWidth(); }, /** -- */ updateSetPairScale: function(){ this.setPairDiameter = this.setListSummary.heightRow_category; this.setPairRadius = this.setPairDiameter/2; }, /** -- */ updateMaxAggr_Active: function(){ this._maxSetPairAggr_Active = d3.max(this._setPairs, function(aggr){ return aggr.measure('Active'); }); }, /** -- */ checkWidth: function(){ var minv=210; var maxv=Math.max(minv,this.getHeight())+40; this.summaryWidth = Math.min(maxv,Math.max(minv,this.summaryWidth)); }, /** -- */ checkPan: function(){ var maxV, minV; maxV = 0; minV = -this.setListSummary.scrollTop_cache; this.gridPan_x = Math.round(Math.min(maxV,Math.max(minV,this.gridPan_x))); }, /** -- */ insertControls: function(){ var me=this; this.DOM.summaryControls = this.DOM.chartRoot.append("div").attr("class","summaryControls") .style("height",(this.setListSummary.getHeight_Config())+"px"); // TODO: remove var buttonTop = (this.setListSummary.getHeight_Config()-18)/2; this.DOM.strengthControl = this.DOM.summaryControls.append("span").attr("class","strengthControl") .on("click",function(){ me.browser.setMeasureAxisMode(me.browser.ratioModeActive!==true); }) .style("margin-top",buttonTop+"px"); // ******************* STRENGTH CONFIG this.DOM.strengthControl.append("span").attr("class","strengthLabel").text("Weak"); this.DOM.strengthControl.append("span").attr("class","strengthText").text("Strength"); this.DOM.strengthControl.append("span").attr("class","strengthLabel").text("Strong"); this.DOM.scaleLegend_SVG = this.DOM.summaryControls.append("svg").attr("xmlns","http://www.w3.org/2000/svg") .attr("class","sizeLegend"); this.DOM.legendHeader = this.DOM.scaleLegend_SVG.append("text").attr("class","legendHeader").text("#"); this.DOM.legend_Group = this.DOM.scaleLegend_SVG.append("g"); // ******************* ROW HEIGHT CONFIG var domRowHeightControl = this.DOM.summaryControls.append("span").attr("class","configRowHeight configOpt"); var sdad = domRowHeightControl.append("span").attr("class","configOpt_label") domRowHeightControl.append("span").attr("class","configOpt_icon") .append("span").attr("class","fa fa-search-plus"); sdad.append("span").attr("class","sdsdssds").text("Zoom"); sdad.append("span").attr("class","fa fa-plus").on("mousedown",function(){ // TODO: Keep calling as long as the mouse is clicked - to a certain limit me.setListSummary.setHeight_Category(me.getRowHeight()+1); d3.event.stopPropagation(); }); sdad.append("span").attr("class","fa fa-minus").on("mousedown",function(){ // TODO: Keep calling as long as the mouse is clicked - to a certain limit me.setListSummary.setHeight_Category(me.getRowHeight()-1); d3.event.stopPropagation(); }); sdad.append("span").attr("class","fa fa-arrows-alt").on("mousedown",function(){ // TODO: Keep calling as long as the mouse is clicked - to a certain limit me.setListSummary.setHeight_Category(10); d3.event.stopPropagation(); }); }, /** -- */ insertRows: function(){ var me=this; var newRows = this.DOM.setMatrixSVG.select("g.rows").selectAll("g.row") .data(this._sets, function(d,i){ return d.id(); }) .enter().append("g").attr("class","row") .each(function(d){ d.DOM.matrixRow = this; }) .on("mouseenter",function(d){ me.setListSummary.onCatEnter(d); }) .on("mouseleave",function(d){ me.setListSummary.onCatLeave(d); }); // tmp is used to parse html text. TODO: delete the temporary DOM var tmp = document.createElement("div"); newRows.append("line").attr("class","line line_vert") .attr("x1",0).attr("y1",0).attr("y1",0).attr("y2",0); newRows.append("text").attr("class","label label_horz") .text(function(d){ tmp.innerHTML = me.setListSummary.catLabel_Func.call(d.data); return tmp.textContent || tmp.innerText || ""; }); newRows.append("line").attr("class","line line_horz") .attr("x1",0).attr("y1",0).attr("y2",0); newRows.append("text").attr("class","label label_vert") .text(function(d){ tmp.innerHTML = me.setListSummary.catLabel_Func.call(d.data); return tmp.textContent || tmp.innerText || ""; }) .attr("y",-4); this.DOM.setRows = this.DOM.setMatrixSVG.selectAll("g.rows > g.row"); this.DOM.line_vert = this.DOM.setMatrixSVG.selectAll("g.rows > g.row > line.line_vert"); this.DOM.line_horz = this.DOM.setMatrixSVG.selectAll("g.rows > g.row > line.line_horz"); this.DOM.line_horz_label = this.DOM.setMatrixSVG.selectAll("g.rows > g.row > text.label_horz"); this.DOM.line_vert_label = this.DOM.setMatrixSVG.selectAll("g.rows > g.row > text.label_vert"); }, /** -- */ onSetPairEnter: function(aggr){ aggr.set_1.DOM.matrixRow.setAttribute("selection","selected"); aggr.set_2.DOM.matrixRow.setAttribute("selection","selected"); aggr.set_1.DOM.aggrGlyph.setAttribute("selectType","and"); aggr.set_2.DOM.aggrGlyph.setAttribute("selectType","and"); aggr.set_1.DOM.aggrGlyph.setAttribute("selection","selected"); aggr.set_2.DOM.aggrGlyph.setAttribute("selection","selected"); this.browser.setSelect_Highlight(this,aggr); }, /** -- */ onSetPairLeave: function(aggr){ aggr.set_1.DOM.matrixRow.removeAttribute("selection"); aggr.set_2.DOM.matrixRow.removeAttribute("selection"); aggr.set_1.DOM.aggrGlyph.removeAttribute("selection"); aggr.set_2.DOM.aggrGlyph.removeAttribute("selection"); this.browser.clearSelect_Highlight(); }, /** -- */ insertSetPairs: function(){ var me=this; var newCliques = this.DOM.setMatrixSVG.select("g.setPairGroup").selectAll("g.setPairGlyph") .data(this._setPairs,function(d,i){ return i; }) .enter().append("g").attr("class","aggrGlyph setPairGlyph") .each(function(d){ d.DOM.aggrGlyph = this; }) .on("mouseenter",function(aggr){ if(me.browser.mouseSpeed<0.2) { me.onSetPairEnter(aggr); return; } this.highlightTimeout = window.setTimeout( function(){ me.onSetPairEnter(aggr) }, me.browser.mouseSpeed*500); }) .on("mouseleave",function(aggr){ if(this.highlightTimeout) window.clearTimeout(this.highlightTimeout); me.onSetPairLeave(aggr); }) .on("click",function(aggr){ if(d3.event.shiftKey){ me.browser.setSelect_Compare(me,aggr,false); return; } me.setListSummary.filterCategory(aggr.set_1,"AND"); me.setListSummary.filterCategory(aggr.set_2,"AND"); }); newCliques.append("rect").attr("class","setPairBackground").attr("rx",3).attr("ry",3); newCliques.append("circle").attr("class","measure_Active").attr("cx",0).attr("cy",0).attr("r",0); newCliques.append("path").attr("class","measure_Highlighted").each(function(aggr){ aggr.currentPreviewAngle=-Math.PI/2; }); newCliques.append("path").attr("class","measure_Compared_A"); newCliques.append("path").attr("class","measure_Compared_B"); newCliques.append("path").attr("class","measure_Compared_C"); this.DOM.aggrGlyphs = this.DOM.setPairGroup.selectAll("g.setPairGlyph"); this.DOM.setPairBackground = this.DOM.aggrGlyphs.selectAll(".setPairBackground"); this.DOM.measure_Active = this.DOM.aggrGlyphs.selectAll(".measure_Active"); this.DOM.measure_Highlighted = this.DOM.aggrGlyphs.selectAll(".measure_Highlighted"); this.DOM.measure_Compared_A = this.DOM.aggrGlyphs.selectAll(".measure_Compared_A"); this.DOM.measure_Compared_B = this.DOM.aggrGlyphs.selectAll(".measure_Compared_B"); this.DOM.measure_Compared_C = this.DOM.aggrGlyphs.selectAll(".measure_Compared_C"); }, /** -- */ printAggrSelection: function(aggr){ return this.setListSummary.printAggrSelection(aggr.set_1)+ " and "+ this.setListSummary.printAggrSelection(aggr.set_2); }, /** -- */ refreshLabel_Vert_Show: function(){ var me=this; var setListSummary=this.setListSummary; var totalWidth=this.getWidth(); var totalHeight = this.getHeight(); var w=this.getWidth(); var h=this.getHeight(); var t=this.setListSummary.scrollTop_cache; var r=(t)*-1; this.DOM.line_vert_label // points up/right .attr("show",function(d){ return !d.isVisible; }) .attr("transform",function(d){ var i=d.orderIndex; var x=totalWidth-((i+0.5)*me.setPairDiameter)-2; if(me.position==="right") x = totalWidth-x-4; var y=((me.setListSummary.catCount_Visible-i-1)*me.setPairDiameter); y-=setListSummary.getHeight_VisibleAttrib()-setListSummary.scrollTop_cache-totalHeight; return "translate("+x+" "+y+") rotate(-90)";//" rotate(45) "; }); }, /** --*/ updatePerceptualOrder: function(){ var me=this; // Edges are set-pairs with at least one element inside (based on the filtering state) var edges = this._setPairs.filter(function(setPair){ return setPair._measure.Active>0; }); // Nodes are the set-categories var nodes = this.setListSummary._cats; // Initialize per-node (per-set) data structures nodes.forEach(function(node){ node.MST = { tree: new Object(), // Some unqiue identifier, to check if two nodes are in the same tree. childNodes: [], parentNode: null }; }); // Compute the perceptual similarity metric (mst_distance) edges.forEach(function(edge){ var set_1 = edge.set_1; var set_2 = edge.set_2; edge.mst_distance = 0; // For every intersection of set_1 set_1.setPairs.forEach(function(setPair_1){ if(setPair_1===edge) return; var set_other = (setPair_1.set_1===set_1)?setPair_1.set_2:setPair_1.set_1; // find the set-pair of set_2 and set_other; var setPair_2 = undefined; if(set_2.id()>set_other.id()){ if(me._setPairs_ID[set_other.id()]) setPair_2 = me._setPairs_ID[set_other.id()][set_2.id()]; } else { if(me._setPairs_ID[set_2.id()]) setPair_2 = me._setPairs_ID[set_2.id()][set_other.id()]; } if(setPair_2===undefined){ // the other intersection size is zero, there is no link edge.mst_distance+=setPair_1._measure.Active; return; } edge.mst_distance += Math.abs(setPair_1._measure.Active-setPair_2._measure.Active); }); // For every intersection of set_2 set_2.setPairs.forEach(function(setPair_1){ if(setPair_1===edge) return; var set_other = (setPair_1.set_1===set_2)?setPair_1.set_2:setPair_1.set_1; // find the set-pair of set_1 and set_other; var setPair_2 = undefined; if(set_1.id()>set_other.id()){ if(me._setPairs_ID[set_other.id()]) setPair_2 = me._setPairs_ID[set_other.id()][set_1.id()]; } else { if(me._setPairs_ID[set_1.id()]) setPair_2 = me._setPairs_ID[set_1.id()][set_other.id()]; } if(setPair_2===undefined){ // the other intersection size is zero, there is no link edge.mst_distance+=setPair_1._measure.Active; return; } // If ther is setPair_2, it was already processed in the main loop above }); }); // Order the edges (setPairs) by their distance (lower score is better) edges.sort(function(e1, e2){ return e1.mst_distance-e2.mst_distance; }); // Run Kruskal's algorithm... edges.forEach(function(setPair){ var node_1 = setPair.set_1; var node_2 = setPair.set_2; // set_1 and set_2 are in the same tree if(node_1.MST.tree===node_2.MST.tree) return; // set_1 and set_2 are not in the same tree, connect set_2 under set_1 var set_above, set_below; if(node_1.setPairs.length<node_2.setPairs.length){ set_above = node_1; set_below = node_2; } else { set_above = node_2; set_below = node_1; } set_below.MST.tree = set_above.MST.tree; set_below.MST.parentNode = set_above; set_above.MST.childNodes.push(set_below); }); // Identify the root-nodes of resulting MSTs var treeRootNodes = nodes.filter(function(node){ return node.MST.parentNode===null; }); // We can have multiple trees (there can be sub-groups disconnected from each other) // Update tree size recursively by starting at the root nodes var updateTreeSize = function(node){ node.MST.treeSize=1; node.MST.childNodes.forEach(function(childNode){ node.MST.treeSize+=updateTreeSize(childNode); }); return node.MST.treeSize; }; treeRootNodes.forEach(function(rootNode){ updateTreeSize(rootNode); }); // Sort the root nodes by largest tree first treeRootNodes.sort(function(node1, node2){ return node1.MST.treeSize - node2.MST.treeSize; }); // For each MST, traverse the nodes and add the MST (perceptual) node index incrementally var mst_index = 0; var updateNodeIndex = function(node){ node.MST.childNodes.forEach(function(chileNode){ chileNode.MST.index = mst_index++; }); node.MST.childNodes.forEach(function(chileNode){ updateNodeIndex(chileNode); }); }; treeRootNodes.forEach(function(node){ node.MST.index = mst_index++; updateNodeIndex(node); }); }, /** -- */ refreshViz_Axis: function(){ var me=this; this.refreshSetPair_Strength(); if(this.browser.ratioModeActive){ this.DOM.scaleLegend_SVG.style("display","none"); return; } this.DOM.scaleLegend_SVG.style("display","block"); this.DOM.scaleLegend_SVG .attr("width",this.setPairDiameter+50) .attr("height",this.setPairDiameter+10) .attr("viewBox","0 0 "+(this.setPairDiameter+50)+" "+(this.setPairDiameter+10)); this.DOM.legend_Group.attr("transform", "translate("+(this.setPairRadius)+","+(this.setPairRadius+18)+")"); this.DOM.legendHeader.attr("transform", "translate("+(2*this.setPairRadius+3)+",6)"); var maxVal = this._maxSetPairAggr_Active; tickValues = [maxVal]; if(this.setPairRadius>8) tickValues.push(Math.round(maxVal/4)); this.DOM.legend_Group.selectAll("g.legendMark").remove(); var tickDoms = this.DOM.legend_Group.selectAll("g.legendMark").data(tickValues,function(i){return i;}); this.DOM.legendCircleMarks = tickDoms.enter().append("g").attr("class","legendMark"); this.DOM.legendCircleMarks.append("circle").attr("class","legendCircle") .attr("cx",0).attr("cy",0) .attr("r",function(d,i){ return me.setPairRadius*Math.sqrt(d/maxVal); }); this.DOM.legendCircleMarks.append("line").attr("class","legendLine") .each(function(d,i){ var rx=me.setPairRadius+3; var ry=me.setPairRadius*Math.sqrt(d/maxVal); var x2,y1; switch(i%4){ case 0: x2 = rx; y1 = -ry; break; case 1: x2 = rx; // -rx; y1 = ry; // -ry; break; case 2: x2 = rx; y1 = ry; break; case 3: x2 = -rx; y1 = ry; break; } this.setAttribute("x1",0); this.setAttribute("x2",x2); this.setAttribute("y1",y1); this.setAttribute("y2",y1); }); this.DOM.legendText = this.DOM.legendCircleMarks .append("text").attr("class","legendLabel"); this.DOM.legendText.each(function(d,i){ var rx=me.setPairRadius+3; var ry=me.setPairRadius*Math.sqrt(d/maxVal); var x2,y1; switch(i%4){ case 0: x2 = rx; y1 = -ry; break; case 1: x2 = rx; // -rx; y1 = ry; // -ry; break; case 2: x2 = rx; y1 = ry; break; case 3: x2 = -rx; y1 = ry; break; } this.setAttribute("transform","translate("+x2+","+y1+")"); this.style.textAnchor = (i%2===0||true)?"start":"end"; }); this.DOM.legendText.text(function(d){ return d3.format("s")(d); }); }, /** -- */ refreshWindowSize: function(){ var w=this.getWidth(); var h=this.getHeight(); this.DOM.wrapper.style("height",( this.setListSummary.getHeight()-this.setListSummary.getHeight_Header())+"px"); this.DOM.setMatrixBackground .attr("x",-w*24) .attr("y",-h*24) .attr("width",w*50) .attr("height",h*50); this.DOM.root .style(this.position,(-w)+"px") .style(this.position==="left"?"right":"left","initial"); ; if(!this.pausePanning) this.refreshSVGViewBox(); }, /** -- */ setPosition: function(p){ if(p===this.position) return; this.position = p; this.DOM.root.attr("position",this.position); this.refreshWindowSize(); this.refreshRow_LineWidths(); this.refreshSetPair_Position(); }, /** -- */ refreshSVGViewBox: function(){ var w=this.getWidth(); var h=this.getHeight(); var t=this.setListSummary.scrollTop_cache; var r; if(this.position==="left"){ r=Math.min(-t-this.gridPan_x,0); // r cannot be positive } if(this.position==="right"){ r=Math.max(t+this.gridPan_x,0); } this.DOM.setMatrixSVG.attr("width",w).attr("height",h).attr("viewBox",r+" "+t+" "+w+" "+h); this.refreshLabel_Vert_Show(); }, /** -- */ refreshSetPair_Background: function(){ this.DOM.setPairBackground .attr("x",-this.setPairRadius) .attr("y",-this.setPairRadius) .attr("width",this.setPairDiameter) .attr("height",this.setPairDiameter); }, /** - Call when measure.Active is updated - Does not work with Average aggregate */ updateSetPairSimilarity: function(){ this._setPairs.forEach(function(setPair){ var size_A = setPair.set_1._measure.Active; var size_B = setPair.set_2._measure.Active; var size_and = setPair._measure.Active; setPair.Similarity = (size_and===0 || (size_A===0&&size_B===0)) ? 0 : size_and/Math.min(size_A,size_B); }); this._maxSimilarity = d3.max(this._setPairs, function(d){ return d.Similarity; }); }, /** For each element in the given list, checks the set membership and adds setPairs */ createSetPairs: function(){ var me=this; var insertToClique = function(set_1,set_2,record){ // avoid self reference and adding the same data item twice (insert only A-B, not B-A or A-A/B-B) if(set_2.id()<=set_1.id()) return; if(me._setPairs_ID[set_1.id()]===undefined) me._setPairs_ID[set_1.id()] = {}; var targetClique = me._setPairs_ID[set_1.id()][set_2.id()]; if(targetClique===undefined){ targetClique = new kshf.Aggregate(); targetClique.init([me._setPairs.length],0); me.browser.allAggregates.push(targetClique); targetClique.set_1 = set_1; targetClique.set_2 = set_2; set_1.setPairs.push(targetClique); set_2.setPairs.push(targetClique); me._setPairs.push(targetClique); me._setPairs_ID[set_1.id()][set_2.id()] = targetClique; } targetClique.addRecord(record); }; // AND var filterID = this.setListSummary.summaryID; function getAggr(v){ return me.setListSummary.catTable_id[v]; }; this.setListSummary.records.forEach(function(record){ var values = record._valueCache[filterID]; if(values===null) return; // maps to no value values.forEach(function(v_1){ set_1 = getAggr(v_1); // make sure set_1 has an attrib on c display if(set_1.setPairs===undefined) return; values.forEach(function(v_2){ set_2 = getAggr(v_2); if(set_2.setPairs===undefined) return; insertToClique(set_1,set_2,record); }); }); }); this.updateMaxAggr_Active(); this.updateSetPairSimilarity(); }, /** -- */ refreshRow_LineWidths: function(){ var me=this; var setPairDiameter=this.setPairDiameter; var totalWidth=this.getWidth(); var totalHeight = this.getHeight(); // vertical this.DOM.line_vert.each(function(d){ var i=d.orderIndex; var height=((me.setListSummary.catCount_Visible-i-1)*setPairDiameter); var right=((i+0.5)*setPairDiameter); var m=totalWidth-right; if(me.position==="right") m = right; this.setAttribute("x1",m); this.setAttribute("x2",m); this.setAttribute("y2",height); }); // horizontal this.DOM.line_horz .attr("x2",(this.position==="left")?totalWidth : 0) .attr("x1",function(d){ var m = ((d.orderIndex+0.5)*setPairDiameter); return (me.position==="left") ? (totalWidth-m) : m; }); this.DOM.line_horz_label.attr("transform",function(d){ var m=((d.orderIndex+0.5)*setPairDiameter)+2; if(me.position==="left") m = totalWidth-m; return "translate("+m+" 0)"; }); }, /** -- */ refreshRow_Position: function(){ var rowHeight = this.setPairDiameter; this.DOM.setRows.attr("transform",function(set){ return "translate(0,"+((set.orderIndex+0.5)*rowHeight)+")"; }); }, /** -- */ refreshRow: function(){ this.refreshRow_Position(); this.refreshRow_LineWidths(); }, /** -- */ refreshSetPair_Position: function(){ var me=this; var w=this.getWidth(); this.DOM.aggrGlyphs.each(function(setPair){ var i1 = setPair.set_1.orderIndex; var i2 = setPair.set_2.orderIndex; var left = (Math.min(i1,i2)+0.5)*me.setPairDiameter; if(me.position==="left") left = w-left; var top = (Math.max(i1,i2)+0.5)*me.setPairDiameter; kshf.Util.setTransform(this,"translate("+left+"px,"+top+"px)"); }); }, /** -- */ getCliqueSizeRatio: function(setPair){ return Math.sqrt(setPair.measure('Active')/this._maxSetPairAggr_Active); }, /** Given a setPair, return the angle for preview Does not work with "Avg" measure **/ getAngleToActive_rad: function(setPair,m){ if(setPair._measure.Active===0) return 0; var ratio = setPair._measure[m] / setPair._measure.Active; if(this.browser.preview_not) ratio = 1-ratio; if(ratio===1) ratio=0.999; return ((360*ratio-90) * Math.PI) / 180; }, /** -- */ // http://stackoverflow.com/questions/5737975/circle-drawing-with-svgs-arc-path // http://stackoverflow.com/questions/15591614/svg-radial-wipe-animation-using-css3-js // http://jsfiddle.net/Matt_Coughlin/j3Bhz/5/ getPiePath: function(endAngleRad,sub,ratio){ var r = ratio*this.setPairRadius-sub; var endX = Math.cos(endAngleRad) * r; var endY = Math.sin(endAngleRad) * r; var largeArcFlag = (endAngleRad>Math.PI/2)?1:0; return "M 0,"+(-r)+" A "+r+","+r+" "+largeArcFlag+" "+largeArcFlag+" 1 "+endX+","+endY+" L0,0"; }, /** setPairGlyph do not have a total component */ refreshViz_Total: function(){ }, /** -- */ refreshViz_Active: function(){ var me=this; this.DOM.aggrGlyphs.attr("activesize",function(aggr){ return aggr.measure('Active'); }); this.DOM.measure_Active.transition().duration(this.noanim?0:700) .attr("r",this.browser.ratioModeActive ? function(setPair){ return (setPair.subset!=='') ? me.setPairRadius-1 : me.setPairRadius; } : function(setPair){ return me.getCliqueSizeRatio(setPair)*me.setPairRadius; } ); }, /** -- */ refreshViz_Highlight: function(){ var me=this; this.DOM.measure_Highlighted .transition().duration(500).attrTween("d",function(aggr) { var angleInterp = d3.interpolate(aggr.currentPreviewAngle, me.getAngleToActive_rad(aggr,"Highlighted")); var ratio=(me.browser.ratioModeActive)?1:me.getCliqueSizeRatio(aggr); return function(t) { var newAngle=angleInterp(t); aggr.currentPreviewAngle = newAngle; return me.getPiePath(newAngle,(aggr.subset!=='' && me.browser.ratioModeActive)?2:0,ratio); }; }); }, /** -- */ refreshViz_Compare: function(cT, curGroup, totalGroups){ var me=this; var strokeWidth = 1; if(this.browser.ratioModeActive){ strokeWidth = Math.ceil(this.getRowHeight()/18); } this.DOM["measure_Compared_"+cT].attr("d",function(setPair){ var ratio=(me.browser.ratioModeActive)?1:me.getCliqueSizeRatio(setPair); this.style.display = setPair.measure("Compared_"+cT)===0 ? "none" : "block"; this.style.strokeWidth = strokeWidth; return me.getPiePath( me.getAngleToActive_rad(setPair,"Compared_"+cT), curGroup*strokeWidth, ratio ); }); }, /** Does not work with Avg pair */ refreshSetPair_Containment: function(){ var me=this; var numOfSubsets = 0; this.DOM.measure_Active .each(function(setPair){ var setPair_itemCount = setPair._measure.Active; var set_1_itemCount = setPair.set_1._measure.Active; var set_2_itemCount = setPair.set_2._measure.Active; if(setPair_itemCount===set_1_itemCount || setPair_itemCount===set_2_itemCount){ numOfSubsets++; setPair.subset = (set_1_itemCount===set_2_itemCount)?'equal':'proper'; } else { setPair.subset = ''; } }) .attr("subset",function(setPair){ return (setPair.subset!=='')?true:null; }); this.DOM.subsetCount.style("display",(numOfSubsets===0)?"none":null); this.DOM.subsetCount_Text.text(numOfSubsets); this.refreshSetPair_Strength(); }, /** -- */ refreshSetPair_Strength: function(){ var me=this; var strengthColor = d3.interpolateHsl(d3.rgb(230, 230, 247),d3.rgb(159, 159, 223)); this.DOM.measure_Active.style("fill",function(setPair){ if(!me.browser.ratioModeActive) return null; return strengthColor(setPair.Similarity/me._maxSimilarity); }); if(this.browser.ratioModeActive){ this.DOM.measure_Active.each(function(setPair){ // border if(setPair.subset==='') return; if(setPair.subset==='equal'){ this.style.strokeDasharray = ""; this.style.strokeDashoffset = ""; return; } var halfCircle = (me.setPairRadius-1)*Math.PI; this.style.strokeDasharray = halfCircle+"px"; // rotate halfway var i1 = setPair.set_1.orderIndex; var i2 = setPair.set_2.orderIndex; var c1 = setPair.set_1._measure.Active; var c2 = setPair.set_2._measure.Active; if((i1<i2 && c1<c2) || (i1>i2 && c1>c2)) halfCircle = halfCircle/2; this.style.strokeDashoffset = halfCircle+"px"; }); } }, /** -- */ updateAfterFilter: function () { if(this.isEmpty() || this.collapsed || !this.inBrowser()) return; this.updateMaxAggr_Active(); this.refreshViz_All(); this.refreshViz_EmptyRecords(); this.DOM.setRows.style("opacity",function(setRow){ return (setRow._measure.Active>0)?1:0.3; }); this.updateSetPairSimilarity(); this.refreshSetPair_Containment(); }, }; for(var index in Summary_Clique_functions){ kshf.Summary_Set.prototype[index] = Summary_Clique_functions[index]; }
Allowing for shorter interval summaries...
keshif.js
Allowing for shorter interval summaries...
<ide><path>eshif.js <ide> <ide> // pixel width settings... <ide> this.height_hist = 1; // Initial width (will be updated later...) <del> this.height_hist_min = 15; // Minimum possible histogram height <add> this.height_hist_min = 10; // Minimum possible histogram height <ide> this.height_hist_max = 100; // Maximim possible histogram height <ide> this.height_slider = 12; // Slider height <ide> this.height_labels = 13; // Height for labels
JavaScript
mit
87b33cbec80be37de430fb447980ff339a640881
0
smanongga/smanongga.github.io,smanongga/smanongga.github.io,smanongga/smanongga.github.io
const path = require('path') const express = require('express') const bodyParser = require('body-parser') const hbs = require('express-handlebars') const index = require('./routes/index') const app = express() // Middleware app.engine('hbs', hbs({extname: 'hbs'})) app.set('view engine', 'hbs') app.set('views', path.join(__dirname, 'views')) app.use(express.static('public')) app.use(bodyParser.urlencoded({ extended: true })) // Routes app.use('/', index) module.exports = (connection) => { app.set('connection', connection) return app }
server.js
var path = require('path') var express = require('express') var bodyParser = require('body-parser') var hbs = require('express-handlebars') var index = require('./routes/index') var app = express() // Middleware app.engine('hbs', hbs({extname: 'hbs'})) app.set('view engine', 'hbs') app.set('views', path.join(__dirname, 'views')) app.use(bodyParser.urlencoded({ extended: true })) // Routes app.use('/', index) module.exports = (connection) => { app.set('connection', connection) return app }
Declare express public folder
server.js
Declare express public folder
<ide><path>erver.js <del>var path = require('path') <add>const path = require('path') <ide> <del>var express = require('express') <del>var bodyParser = require('body-parser') <del>var hbs = require('express-handlebars') <add>const express = require('express') <add>const bodyParser = require('body-parser') <add>const hbs = require('express-handlebars') <ide> <del>var index = require('./routes/index') <add>const index = require('./routes/index') <ide> <del>var app = express() <del> <add>const app = express() <ide> <ide> // Middleware <ide> <ide> app.engine('hbs', hbs({extname: 'hbs'})) <ide> app.set('view engine', 'hbs') <ide> app.set('views', path.join(__dirname, 'views')) <add>app.use(express.static('public')) <ide> app.use(bodyParser.urlencoded({ extended: true })) <ide> <ide> // Routes
Java
lgpl-2.1
f241dd6200f8836f9afe0512b36fc0eed851ebef
0
RockManJoe64/swingx,RockManJoe64/swingx
/* * $Id$ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx.border; import org.jdesktop.swingx.graphics.GraphicsUtilities; import javax.swing.border.Border; import java.awt.*; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.awt.image.ConvolveOp; import java.awt.image.Kernel; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /** * Implements a DropShadow for components. In general, the DropShadowBorder will * work with any rectangular components that do not have a default border installed * as part of the look and feel, or otherwise. For example, DropShadowBorder works * wonderfully with JPanel, but horribly with JComboBox. * * @author rbair */ public class DropShadowBorder implements Border, Serializable { private static enum Position {TOP, TOP_LEFT, LEFT, BOTTOM_LEFT, BOTTOM, BOTTOM_RIGHT, RIGHT, TOP_RIGHT} private static final Map<Double,Map<Position,BufferedImage>> CACHE = new HashMap<Double,Map<Position,BufferedImage>>(); private final Color shadowColor; private final int shadowSize; private final float shadowOpacity; private final int cornerSize; private final boolean showTopShadow; private final boolean showLeftShadow; private final boolean showBottomShadow; private final boolean showRightShadow; public DropShadowBorder() { this(Color.BLACK, 5); } public DropShadowBorder(Color shadowColor, int shadowSize) { this(shadowColor, shadowSize, .5f, 12, false, false, true, true); } public DropShadowBorder(boolean showLeftShadow) { this(Color.BLACK, 5, .5f, 12, false, showLeftShadow, true, true); } public DropShadowBorder(Color shadowColor, int shadowSize, float shadowOpacity, int cornerSize, boolean showTopShadow, boolean showLeftShadow, boolean showBottomShadow, boolean showRightShadow) { this.shadowColor = shadowColor; this.shadowSize = shadowSize; this.shadowOpacity = shadowOpacity; this.cornerSize = cornerSize; this.showTopShadow = showTopShadow; this.showLeftShadow = showLeftShadow; this.showBottomShadow = showBottomShadow; this.showRightShadow = showRightShadow; } /** * @inheritDoc */ public void paintBorder(Component c, Graphics graphics, int x, int y, int width, int height) { /* * 1) Get images for this border * 2) Paint the images for each side of the border that should be painted */ Map<Position,BufferedImage> images = getImages((Graphics2D)graphics); Graphics2D g2 = (Graphics2D)graphics.create(); //The location and size of the shadows depends on which shadows are being //drawn. For instance, if the left & bottom shadows are being drawn, then //the left shadow extends all the way down to the corner, a corner is drawn, //and then the bottom shadow begins at the corner. If, however, only the //bottom shadow is drawn, then the bottom-left corner is drawn to the //right of the corner, and the bottom shadow is somewhat shorter than before. int shadowOffset = 2; //the distance between the shadow and the edge Point topLeftShadowPoint = null; if (showLeftShadow || showTopShadow) { topLeftShadowPoint = new Point(); if (showLeftShadow && !showTopShadow) { topLeftShadowPoint.setLocation(x, y + shadowOffset); } else if (showLeftShadow && showTopShadow) { topLeftShadowPoint.setLocation(x, y); } else if (!showLeftShadow && showTopShadow) { topLeftShadowPoint.setLocation(x + shadowSize, y); } } Point bottomLeftShadowPoint = null; if (showLeftShadow || showBottomShadow) { bottomLeftShadowPoint = new Point(); if (showLeftShadow && !showBottomShadow) { bottomLeftShadowPoint.setLocation(x, y + height - shadowSize - shadowSize); } else if (showLeftShadow && showBottomShadow) { bottomLeftShadowPoint.setLocation(x, y + height - shadowSize); } else if (!showLeftShadow && showBottomShadow) { bottomLeftShadowPoint.setLocation(x + shadowSize, y + height - shadowSize); } } Point bottomRightShadowPoint = null; if (showRightShadow || showBottomShadow) { bottomRightShadowPoint = new Point(); if (showRightShadow && !showBottomShadow) { bottomRightShadowPoint.setLocation(x + width - shadowSize, y + height - shadowSize - shadowSize); } else if (showRightShadow && showBottomShadow) { bottomRightShadowPoint.setLocation(x + width - shadowSize, y + height - shadowSize); } else if (!showRightShadow && showBottomShadow) { bottomRightShadowPoint.setLocation(x + width - shadowSize - shadowSize, y + height - shadowSize); } } Point topRightShadowPoint = null; if (showRightShadow || showTopShadow) { topRightShadowPoint = new Point(); if (showRightShadow && !showTopShadow) { topRightShadowPoint.setLocation(x + width - shadowSize, y + shadowOffset); } else if (showRightShadow && showTopShadow) { topRightShadowPoint.setLocation(x + width - shadowSize, y); } else if (!showRightShadow && showTopShadow) { topRightShadowPoint.setLocation(x + width - shadowSize - shadowSize, y); } } g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED); if (showLeftShadow) { Rectangle leftShadowRect = new Rectangle(x, topLeftShadowPoint.y + shadowSize, shadowSize, bottomLeftShadowPoint.y - topLeftShadowPoint.y - shadowSize); g2.drawImage(images.get(Position.LEFT), leftShadowRect.x, leftShadowRect.y, leftShadowRect.width, leftShadowRect.height, null); } if (showBottomShadow) { Rectangle bottomShadowRect = new Rectangle(bottomLeftShadowPoint.x + shadowSize, y + height - shadowSize, bottomRightShadowPoint.x - bottomLeftShadowPoint.x - shadowSize, shadowSize); g2.drawImage(images.get(Position.BOTTOM), bottomShadowRect.x, bottomShadowRect.y, bottomShadowRect.width, bottomShadowRect.height, null); } if (showRightShadow) { Rectangle rightShadowRect = new Rectangle(x + width - shadowSize, topRightShadowPoint.y + shadowSize, shadowSize, bottomRightShadowPoint.y - topRightShadowPoint.y - shadowSize); g2.drawImage(images.get(Position.RIGHT), rightShadowRect.x, rightShadowRect.y, rightShadowRect.width, rightShadowRect.height, null); } if (showTopShadow) { Rectangle topShadowRect = new Rectangle(topLeftShadowPoint.x + shadowSize, y, topRightShadowPoint.x - topLeftShadowPoint.x - shadowSize, shadowSize); g2.drawImage(images.get(Position.TOP), topShadowRect.x, topShadowRect.y, topShadowRect.width, topShadowRect.height, null); } if (showLeftShadow || showTopShadow) { g2.drawImage(images.get(Position.TOP_LEFT), topLeftShadowPoint.x, topLeftShadowPoint.y, null); } if (showLeftShadow || showBottomShadow) { g2.drawImage(images.get(Position.BOTTOM_LEFT), bottomLeftShadowPoint.x, bottomLeftShadowPoint.y, null); } if (showRightShadow || showBottomShadow) { g2.drawImage(images.get(Position.BOTTOM_RIGHT), bottomRightShadowPoint.x, bottomRightShadowPoint.y, null); } if (showRightShadow || showTopShadow) { g2.drawImage(images.get(Position.TOP_RIGHT), topRightShadowPoint.x, topRightShadowPoint.y, null); } g2.dispose(); } private Map<Position,BufferedImage> getImages(Graphics2D g2) { //first, check to see if an image for this size has already been rendered //if so, use the cache. Else, draw and save Map<Position,BufferedImage> images = CACHE.get(shadowSize + (shadowColor.hashCode() * .3) + (shadowOpacity * .12));//TODO do a real hash if (images == null) { images = new HashMap<Position,BufferedImage>(); /* * To draw a drop shadow, I have to: * 1) Create a rounded rectangle * 2) Create a BufferedImage to draw the rounded rect in * 3) Translate the graphics for the image, so that the rectangle * is centered in the drawn space. The border around the rectangle * needs to be shadowWidth wide, so that there is space for the * shadow to be drawn. * 4) Draw the rounded rect as shadowColor, with an opacity of shadowOpacity * 5) Create the BLUR_KERNEL * 6) Blur the image * 7) copy off the corners, sides, etc into images to be used for * drawing the Border */ int rectWidth = cornerSize + 1; RoundRectangle2D rect = new RoundRectangle2D.Double(0, 0, rectWidth, rectWidth, cornerSize, cornerSize); int imageWidth = rectWidth + shadowSize * 2; BufferedImage image = GraphicsUtilities.createCompatibleTranslucentImage(imageWidth, imageWidth); Graphics2D buffer = (Graphics2D)image.getGraphics(); buffer.setPaint(new Color(shadowColor.getRed(), shadowColor.getGreen(), shadowColor.getBlue(), (int)(shadowOpacity * 255))); // buffer.setColor(new Color(0.0f, 0.0f, 0.0f, shadowOpacity)); buffer.translate(shadowSize, shadowSize); buffer.fill(rect); buffer.dispose(); float blurry = 1.0f / (float)(shadowSize * shadowSize); float[] blurKernel = new float[shadowSize * shadowSize]; for (int i=0; i<blurKernel.length; i++) { blurKernel[i] = blurry; } ConvolveOp blur = new ConvolveOp(new Kernel(shadowSize, shadowSize, blurKernel)); BufferedImage targetImage = GraphicsUtilities.createCompatibleTranslucentImage(imageWidth, imageWidth); ((Graphics2D)targetImage.getGraphics()).drawImage(image, blur, -(shadowSize/2), -(shadowSize/2)); int x = 1; int y = 1; int w = shadowSize; int h = shadowSize; images.put(Position.TOP_LEFT, getSubImage(targetImage, x, y, w, h)); x = 1; y = h; w = shadowSize; h = 1; images.put(Position.LEFT, getSubImage(targetImage, x, y, w, h)); x = 1; y = rectWidth; w = shadowSize; h = shadowSize; images.put(Position.BOTTOM_LEFT, getSubImage(targetImage, x, y, w, h)); x = cornerSize + 1; y = rectWidth; w = 1; h = shadowSize; images.put(Position.BOTTOM, getSubImage(targetImage, x, y, w, h)); x = rectWidth; y = x; w = shadowSize; h = shadowSize; images.put(Position.BOTTOM_RIGHT, getSubImage(targetImage, x, y, w, h)); x = rectWidth; y = cornerSize + 1; w = shadowSize; h = 1; images.put(Position.RIGHT, getSubImage(targetImage, x, y, w, h)); x = rectWidth; y = 1; w = shadowSize; h = shadowSize; images.put(Position.TOP_RIGHT, getSubImage(targetImage, x, y, w, h)); x = shadowSize; y = 1; w = 1; h = shadowSize; images.put(Position.TOP, getSubImage(targetImage, x, y, w, h)); image.flush(); CACHE.put(shadowSize + (shadowColor.hashCode() * .3) + (shadowOpacity * .12), images); //TODO do a real hash } return images; } /** * Returns a new BufferedImage that represents a subregion of the given * BufferedImage. (Note that this method does not use * BufferedImage.getSubimage(), which will defeat image acceleration * strategies on later JDKs.) */ private BufferedImage getSubImage(BufferedImage img, int x, int y, int w, int h) { BufferedImage ret = GraphicsUtilities.createCompatibleTranslucentImage(w, h); Graphics2D g2 = ret.createGraphics(); g2.drawImage(img, 0, 0, w, h, x, y, x+w, y+h, null); g2.dispose(); return ret; } /** * @inheritDoc */ public Insets getBorderInsets(Component c) { int top = showTopShadow ? shadowSize : 0; int left = showLeftShadow ? shadowSize : 0; int bottom = showBottomShadow ? shadowSize : 0; int right = showRightShadow ? shadowSize : 0; return new Insets(top, left, bottom, right); } /** * @inheritDoc */ public boolean isBorderOpaque() { return false; } public boolean isShowTopShadow() { return showTopShadow; } public boolean isShowLeftShadow() { return showLeftShadow; } public boolean isShowRightShadow() { return showRightShadow; } public boolean isShowBottomShadow() { return showBottomShadow; } public int getShadowSize() { return shadowSize; } public Color getShadowColor() { return shadowColor; } public float getShadowOpacity() { return shadowOpacity; } public int getCornerSize() { return cornerSize; } }
src/java/org/jdesktop/swingx/border/DropShadowBorder.java
/* * $Id$ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx.border; import org.jdesktop.swingx.graphics.GraphicsUtilities; import javax.swing.border.Border; import java.awt.*; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.awt.image.ConvolveOp; import java.awt.image.Kernel; import java.util.HashMap; import java.util.Map; /** * Implements a DropShadow for components. In general, the DropShadowBorder will * work with any rectangular components that do not have a default border installed * as part of the look and feel, or otherwise. For example, DropShadowBorder works * wonderfully with JPanel, but horribly with JComboBox. * * @author rbair */ public class DropShadowBorder implements Border { private static enum Position {TOP, TOP_LEFT, LEFT, BOTTOM_LEFT, BOTTOM, BOTTOM_RIGHT, RIGHT, TOP_RIGHT} private static final Map<Double,Map<Position,BufferedImage>> CACHE = new HashMap<Double,Map<Position,BufferedImage>>(); private final Color shadowColor; private final int shadowSize; private final float shadowOpacity; private final int cornerSize; private final boolean showTopShadow; private final boolean showLeftShadow; private final boolean showBottomShadow; private final boolean showRightShadow; public DropShadowBorder() { this(Color.BLACK, 5); } public DropShadowBorder(Color shadowColor, int shadowSize) { this(shadowColor, shadowSize, .5f, 12, false, false, true, true); } public DropShadowBorder(boolean showLeftShadow) { this(Color.BLACK, 5, .5f, 12, false, showLeftShadow, true, true); } public DropShadowBorder(Color shadowColor, int shadowSize, float shadowOpacity, int cornerSize, boolean showTopShadow, boolean showLeftShadow, boolean showBottomShadow, boolean showRightShadow) { this.shadowColor = shadowColor; this.shadowSize = shadowSize; this.shadowOpacity = shadowOpacity; this.cornerSize = cornerSize; this.showTopShadow = showTopShadow; this.showLeftShadow = showLeftShadow; this.showBottomShadow = showBottomShadow; this.showRightShadow = showRightShadow; } /** * @inheritDoc */ public void paintBorder(Component c, Graphics graphics, int x, int y, int width, int height) { /* * 1) Get images for this border * 2) Paint the images for each side of the border that should be painted */ Map<Position,BufferedImage> images = getImages((Graphics2D)graphics); Graphics2D g2 = (Graphics2D)graphics.create(); //The location and size of the shadows depends on which shadows are being //drawn. For instance, if the left & bottom shadows are being drawn, then //the left shadow extends all the way down to the corner, a corner is drawn, //and then the bottom shadow begins at the corner. If, however, only the //bottom shadow is drawn, then the bottom-left corner is drawn to the //right of the corner, and the bottom shadow is somewhat shorter than before. int shadowOffset = 2; //the distance between the shadow and the edge Point topLeftShadowPoint = null; if (showLeftShadow || showTopShadow) { topLeftShadowPoint = new Point(); if (showLeftShadow && !showTopShadow) { topLeftShadowPoint.setLocation(x, y + shadowOffset); } else if (showLeftShadow && showTopShadow) { topLeftShadowPoint.setLocation(x, y); } else if (!showLeftShadow && showTopShadow) { topLeftShadowPoint.setLocation(x + shadowSize, y); } } Point bottomLeftShadowPoint = null; if (showLeftShadow || showBottomShadow) { bottomLeftShadowPoint = new Point(); if (showLeftShadow && !showBottomShadow) { bottomLeftShadowPoint.setLocation(x, y + height - shadowSize - shadowSize); } else if (showLeftShadow && showBottomShadow) { bottomLeftShadowPoint.setLocation(x, y + height - shadowSize); } else if (!showLeftShadow && showBottomShadow) { bottomLeftShadowPoint.setLocation(x + shadowSize, y + height - shadowSize); } } Point bottomRightShadowPoint = null; if (showRightShadow || showBottomShadow) { bottomRightShadowPoint = new Point(); if (showRightShadow && !showBottomShadow) { bottomRightShadowPoint.setLocation(x + width - shadowSize, y + height - shadowSize - shadowSize); } else if (showRightShadow && showBottomShadow) { bottomRightShadowPoint.setLocation(x + width - shadowSize, y + height - shadowSize); } else if (!showRightShadow && showBottomShadow) { bottomRightShadowPoint.setLocation(x + width - shadowSize - shadowSize, y + height - shadowSize); } } Point topRightShadowPoint = null; if (showRightShadow || showTopShadow) { topRightShadowPoint = new Point(); if (showRightShadow && !showTopShadow) { topRightShadowPoint.setLocation(x + width - shadowSize, y + shadowOffset); } else if (showRightShadow && showTopShadow) { topRightShadowPoint.setLocation(x + width - shadowSize, y); } else if (!showRightShadow && showTopShadow) { topRightShadowPoint.setLocation(x + width - shadowSize - shadowSize, y); } } g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED); if (showLeftShadow) { Rectangle leftShadowRect = new Rectangle(x, topLeftShadowPoint.y + shadowSize, shadowSize, bottomLeftShadowPoint.y - topLeftShadowPoint.y - shadowSize); g2.drawImage(images.get(Position.LEFT), leftShadowRect.x, leftShadowRect.y, leftShadowRect.width, leftShadowRect.height, null); } if (showBottomShadow) { Rectangle bottomShadowRect = new Rectangle(bottomLeftShadowPoint.x + shadowSize, y + height - shadowSize, bottomRightShadowPoint.x - bottomLeftShadowPoint.x - shadowSize, shadowSize); g2.drawImage(images.get(Position.BOTTOM), bottomShadowRect.x, bottomShadowRect.y, bottomShadowRect.width, bottomShadowRect.height, null); } if (showRightShadow) { Rectangle rightShadowRect = new Rectangle(x + width - shadowSize, topRightShadowPoint.y + shadowSize, shadowSize, bottomRightShadowPoint.y - topRightShadowPoint.y - shadowSize); g2.drawImage(images.get(Position.RIGHT), rightShadowRect.x, rightShadowRect.y, rightShadowRect.width, rightShadowRect.height, null); } if (showTopShadow) { Rectangle topShadowRect = new Rectangle(topLeftShadowPoint.x + shadowSize, y, topRightShadowPoint.x - topLeftShadowPoint.x - shadowSize, shadowSize); g2.drawImage(images.get(Position.TOP), topShadowRect.x, topShadowRect.y, topShadowRect.width, topShadowRect.height, null); } if (showLeftShadow || showTopShadow) { g2.drawImage(images.get(Position.TOP_LEFT), topLeftShadowPoint.x, topLeftShadowPoint.y, null); } if (showLeftShadow || showBottomShadow) { g2.drawImage(images.get(Position.BOTTOM_LEFT), bottomLeftShadowPoint.x, bottomLeftShadowPoint.y, null); } if (showRightShadow || showBottomShadow) { g2.drawImage(images.get(Position.BOTTOM_RIGHT), bottomRightShadowPoint.x, bottomRightShadowPoint.y, null); } if (showRightShadow || showTopShadow) { g2.drawImage(images.get(Position.TOP_RIGHT), topRightShadowPoint.x, topRightShadowPoint.y, null); } g2.dispose(); } private Map<Position,BufferedImage> getImages(Graphics2D g2) { //first, check to see if an image for this size has already been rendered //if so, use the cache. Else, draw and save Map<Position,BufferedImage> images = CACHE.get(shadowSize + (shadowColor.hashCode() * .3) + (shadowOpacity * .12));//TODO do a real hash if (images == null) { images = new HashMap<Position,BufferedImage>(); /* * To draw a drop shadow, I have to: * 1) Create a rounded rectangle * 2) Create a BufferedImage to draw the rounded rect in * 3) Translate the graphics for the image, so that the rectangle * is centered in the drawn space. The border around the rectangle * needs to be shadowWidth wide, so that there is space for the * shadow to be drawn. * 4) Draw the rounded rect as shadowColor, with an opacity of shadowOpacity * 5) Create the BLUR_KERNEL * 6) Blur the image * 7) copy off the corners, sides, etc into images to be used for * drawing the Border */ int rectWidth = cornerSize + 1; RoundRectangle2D rect = new RoundRectangle2D.Double(0, 0, rectWidth, rectWidth, cornerSize, cornerSize); int imageWidth = rectWidth + shadowSize * 2; BufferedImage image = GraphicsUtilities.createCompatibleTranslucentImage(imageWidth, imageWidth); Graphics2D buffer = (Graphics2D)image.getGraphics(); buffer.setPaint(new Color(shadowColor.getRed(), shadowColor.getGreen(), shadowColor.getBlue(), (int)(shadowOpacity * 255))); // buffer.setColor(new Color(0.0f, 0.0f, 0.0f, shadowOpacity)); buffer.translate(shadowSize, shadowSize); buffer.fill(rect); buffer.dispose(); float blurry = 1.0f / (float)(shadowSize * shadowSize); float[] blurKernel = new float[shadowSize * shadowSize]; for (int i=0; i<blurKernel.length; i++) { blurKernel[i] = blurry; } ConvolveOp blur = new ConvolveOp(new Kernel(shadowSize, shadowSize, blurKernel)); BufferedImage targetImage = GraphicsUtilities.createCompatibleTranslucentImage(imageWidth, imageWidth); ((Graphics2D)targetImage.getGraphics()).drawImage(image, blur, -(shadowSize/2), -(shadowSize/2)); int x = 1; int y = 1; int w = shadowSize; int h = shadowSize; images.put(Position.TOP_LEFT, getSubImage(targetImage, x, y, w, h)); x = 1; y = h; w = shadowSize; h = 1; images.put(Position.LEFT, getSubImage(targetImage, x, y, w, h)); x = 1; y = rectWidth; w = shadowSize; h = shadowSize; images.put(Position.BOTTOM_LEFT, getSubImage(targetImage, x, y, w, h)); x = cornerSize + 1; y = rectWidth; w = 1; h = shadowSize; images.put(Position.BOTTOM, getSubImage(targetImage, x, y, w, h)); x = rectWidth; y = x; w = shadowSize; h = shadowSize; images.put(Position.BOTTOM_RIGHT, getSubImage(targetImage, x, y, w, h)); x = rectWidth; y = cornerSize + 1; w = shadowSize; h = 1; images.put(Position.RIGHT, getSubImage(targetImage, x, y, w, h)); x = rectWidth; y = 1; w = shadowSize; h = shadowSize; images.put(Position.TOP_RIGHT, getSubImage(targetImage, x, y, w, h)); x = shadowSize; y = 1; w = 1; h = shadowSize; images.put(Position.TOP, getSubImage(targetImage, x, y, w, h)); image.flush(); CACHE.put(shadowSize + (shadowColor.hashCode() * .3) + (shadowOpacity * .12), images); //TODO do a real hash } return images; } /** * Returns a new BufferedImage that represents a subregion of the given * BufferedImage. (Note that this method does not use * BufferedImage.getSubimage(), which will defeat image acceleration * strategies on later JDKs.) */ private BufferedImage getSubImage(BufferedImage img, int x, int y, int w, int h) { BufferedImage ret = GraphicsUtilities.createCompatibleTranslucentImage(w, h); Graphics2D g2 = ret.createGraphics(); g2.drawImage(img, 0, 0, w, h, x, y, x+w, y+h, null); g2.dispose(); return ret; } /** * @inheritDoc */ public Insets getBorderInsets(Component c) { int top = showTopShadow ? shadowSize : 0; int left = showLeftShadow ? shadowSize : 0; int bottom = showBottomShadow ? shadowSize : 0; int right = showRightShadow ? shadowSize : 0; return new Insets(top, left, bottom, right); } /** * @inheritDoc */ public boolean isBorderOpaque() { return false; } public boolean isShowTopShadow() { return showTopShadow; } public boolean isShowLeftShadow() { return showLeftShadow; } public boolean isShowRightShadow() { return showRightShadow; } public boolean isShowBottomShadow() { return showBottomShadow; } public int getShadowSize() { return shadowSize; } public Color getShadowColor() { return shadowColor; } public float getShadowOpacity() { return shadowOpacity; } public int getCornerSize() { return cornerSize; } }
Making DropShadowBorder serializable.
src/java/org/jdesktop/swingx/border/DropShadowBorder.java
Making DropShadowBorder serializable.
<ide><path>rc/java/org/jdesktop/swingx/border/DropShadowBorder.java <ide> import java.awt.image.BufferedImage; <ide> import java.awt.image.ConvolveOp; <ide> import java.awt.image.Kernel; <add>import java.io.Serializable; <ide> import java.util.HashMap; <ide> import java.util.Map; <ide> <ide> * <ide> * @author rbair <ide> */ <del>public class DropShadowBorder implements Border { <add>public class DropShadowBorder implements Border, Serializable { <ide> private static enum Position {TOP, TOP_LEFT, LEFT, BOTTOM_LEFT, <ide> BOTTOM, BOTTOM_RIGHT, RIGHT, TOP_RIGHT} <ide>
Java
apache-2.0
0723d5e6c15d994f137aed441379e0674cf245bd
0
folio-org/raml-module-builder,folio-org/raml-module-builder,folio-org/raml-module-builder
package org.folio.rest.persist; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.vertx.core.AsyncResult; import io.vertx.core.Context; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.http.HttpHeaders; import io.vertx.core.http.HttpServerResponse; import io.vertx.core.json.Json; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.ext.web.RoutingContext; import io.vertx.sqlclient.Row; import io.vertx.sqlclient.RowIterator; import io.vertx.sqlclient.RowSet; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.concurrent.atomic.AtomicBoolean; import java.util.Map; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.ws.rs.core.Response; import org.apache.commons.lang.StringEscapeUtils; import org.folio.rest.tools.utils.ObjectMapperTool; import org.folio.rest.tools.utils.OutStream; import org.folio.rest.tools.utils.TenantTool; import org.folio.rest.tools.utils.ValidationHelper; import org.folio.util.UuidUtil; import org.folio.cql2pgjson.CQL2PgJSON; import org.folio.cql2pgjson.exception.FieldException; import org.folio.cql2pgjson.exception.QueryValidationException; import org.folio.rest.persist.cql.CQLWrapper; import org.folio.rest.jaxrs.model.Errors; import org.folio.rest.jaxrs.resource.support.ResponseDelegate; import org.folio.rest.jaxrs.model.Diagnostic; import org.folio.rest.persist.facets.FacetField; import org.folio.rest.persist.facets.FacetManager; import org.folio.rest.jaxrs.model.ResultInfo; import org.z3950.zing.cql.CQLDefaultNodeVisitor; import org.z3950.zing.cql.CQLNode; import org.z3950.zing.cql.CQLParseException; import org.z3950.zing.cql.CQLParser; import org.z3950.zing.cql.CQLSortNode; import org.z3950.zing.cql.Modifier; import org.z3950.zing.cql.ModifierSet; /** * Helper methods for using PostgresClient. */ public final class PgUtil { private static final Logger logger = LoggerFactory.getLogger(PgUtil.class); private static final String RESPOND_200_WITH_APPLICATION_JSON = "respond200WithApplicationJson"; private static final String RESPOND_201_WITH_APPLICATION_JSON = "respond201WithApplicationJson"; private static final String RESPOND_204 = "respond204"; private static final String RESPOND_400_WITH_TEXT_PLAIN = "respond400WithTextPlain"; private static final String RESPOND_404_WITH_TEXT_PLAIN = "respond404WithTextPlain"; private static final String RESPOND_422_WITH_APPLICATION_JSON = "respond422WithApplicationJson"; private static final String RESPOND_500_WITH_TEXT_PLAIN = "respond500WithTextPlain"; private static final String NOT_FOUND = "Not found"; private static final String INVALID_UUID = "Invalid UUID format of id, should be " + "xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx where M is 1-5 and N is 8, 9, a, b, A or B and " + "x is 0-9, a-f or A-F."; /** This is the name of the column used by all modules to store actual data */ private static final String JSON_COLUMN = "jsonb"; /** mapper between JSON and Java instance (POJO) */ private static final ObjectMapper OBJECT_MAPPER = ObjectMapperTool.getMapper(); /** * Assume this String: * <p> * <code>Key (((jsonb -> 'x'::text) ->> 'barcode'::text))=(=() already exists.</code> * <p> * The pattern will match and return these substrings: * <p> * 1 = <code>((jsonb -> 'x'::text) ->> 'barcode'::text)</code> * <p> * 2 = <code>=(</code> */ private static final Pattern KEY_ALREADY_EXISTS_PATTERN = Pattern.compile( "^Key \\(([^=]+)\\)=\\((.*)\\) already exists.$"); /** * Assume this String: * <p> * <code>Key (userid)=(82666c63-ef00-4ca6-afb5-e069bac767fa) is not present in table "users".</code> * <p> * The pattern will match and return these substrings: * <p> * 1 = <code>userid</code> * <p> * 2 = <code>82666c63-ef00-4ca6-afb5-e069bac767fa</code> * <p> * 3 = <code>users</code> */ private static final Pattern KEY_NOT_PRESENT_PATTERN = Pattern.compile( "^Key \\(([^=]+)\\)=\\((.*)\\) is not present in table \"(.*)\".$"); /** * Assume this String: * <p> * <code>Key (id)=(64f55fa2-50f4-40e5-978a-bbad17dc644d) is still referenced from table "referencing".</code> * <p> * The pattern will match and return these substrings: * <p> * 1 = <code>id</code> * <p> * 2 = <code>64f55fa2-50f4-40e5-978a-bbad17dc644d</code> * <p> * 3 = <code>referencing</code> */ private static final Pattern KEY_STILL_REFERENCED_PATTERN = Pattern.compile( "^Key \\(([^=]+)\\)=\\((.*)\\) is still referenced from table \"(.*)\".$"); /** Number of records to read from the sort index in getWithOptimizedSql and generateOptimizedSql method */ private static int optimizedSqlSize = 10000; private PgUtil() { throw new UnsupportedOperationException("Cannot instantiate utility class."); } /** * Create a Response using okMethod(entity, headersMethod().withLocationMethod(location)). * On exception create a Response using failResponseMethod. * * <p>All exceptions are caught and reported via the returned Future. */ static <T> Future<Response> response(T entity, String location, Method headersMethod, Method withLocationMethod, Method okResponseMethod, Method failResponseMethod) { try { OutStream stream = new OutStream(); stream.setData(entity); Object headers = headersMethod.invoke(null); withLocationMethod.invoke(headers, location); Response response = (Response) okResponseMethod.invoke(null, entity, headers); return Future.succeededFuture(response); } catch (Exception e) { logger.error(e.getMessage(), e); try { Response response = (Response) failResponseMethod.invoke(null, e.getMessage()); return Future.succeededFuture(response); } catch (Exception innerException) { logger.error(innerException.getMessage(), innerException); return Future.failedFuture(innerException); } } } /** * Message of t or t.getCause(). Useful for InvocationTargetException. * @return The first non-null value of these: t.getMessage(), t.getCause().getMessage(). * Null if both are null. */ static String message(Throwable t) { String message = t.getMessage(); if (message != null) { return message; } Throwable inner = t.getCause(); if (inner == null) { return null; } return inner.getMessage(); } /** * Create a Response for the Exception e using failResponseMethod. */ private static Future<Response> response(Exception e, Method failResponseMethod) { String message = message(e); logger.error(message, e); try { if (failResponseMethod == null) { return Future.failedFuture(e); } Response response = (Response) failResponseMethod.invoke(null, message); return Future.succeededFuture(response); } catch (Exception innerException) { message = message(innerException); logger.error(message, innerException); return Future.failedFuture(innerException); } } /** * Create a Response using valueMethod(T). * On exception create a Response using failResponseMethod(String exceptionMessage). * If that also throws an exception create a failed future. * * <p>All exceptions are caught and reported via the returned Future. */ static <T> Future<Response> response(T value, Method valueMethod, Method failResponseMethod) { try { if (valueMethod == null) { throw new NullPointerException("valueMethod must not be null (" + value + ")"); } // this null check is redundant but avoids several sonarlint warnings if (failResponseMethod == null) { throw new NullPointerException("failResponseMethod must not be null (" + value + ")"); } Response response = (Response) valueMethod.invoke(null, value); return Future.succeededFuture(response); } catch (Exception e) { return response(e, failResponseMethod); } } /** * Return a Response using responseMethod() wrapped in a succeeded future. * * <p>On exception create a Response using failResponseMethod(String exceptionMessage) * wrapped in a succeeded future. * * <p>If that also throws an exception create a failed future. * * <p>All exceptions are caught and reported via the returned Future. */ static Future<Response> response(Method responseMethod, Method failResponseMethod) { try { // the null check is redundant but avoids several sonarlint warnings if (responseMethod == null) { throw new NullPointerException("responseMethod must not be null"); } if (failResponseMethod == null) { throw new NullPointerException("failResponseMethod must not be null"); } Response response = (Response) responseMethod.invoke(null); return Future.succeededFuture(response); } catch (Exception e) { return response(e, failResponseMethod); } } static Future<Response> respond422(Method response422Method, String key, String value, String message) { try { Errors errors = ValidationHelper.createValidationErrorMessage(key, value, message); Response response = (Response) response422Method.invoke(null, errors); return Future.succeededFuture(response); } catch (IllegalAccessException | InvocationTargetException | NullPointerException e) { throw new IllegalArgumentException(e); } } /** * Return the <code>respond422WithApplicationJson(Errors entity)</code> method. * @param clazz class to search in * @return the found method, or null if not found */ static Method respond422method(Class<? extends ResponseDelegate> clazz) { // this loop is 20 times faster than getMethod(...) if the method doesn't exist // because it avoids the Exception that getMethod(...) throws. for (Method method : clazz.getMethods()) { if (method.getName().equals(RESPOND_422_WITH_APPLICATION_JSON) && method.getParameterCount() == 1 && method.getParameters()[0].getType().equals(Errors.class)) { return method; } } return null; } /** * Create a Response about the invalid uuid. Use clazz' respond422WithApplicationJson(Errors) * if exists, otherwise use valueMethod. * On exception create a Response using failResponseMethod(String exceptionMessage). * If that also throws an exception create a failed future. * * <p>All exceptions are caught and reported via the returned Future. */ static Future<Response> responseInvalidUuid(String field, String uuid, Class<? extends ResponseDelegate> clazz, Method valueMethod, Method failResponseMethod) { try { Method respond422 = respond422method(clazz); if (respond422 == null) { return response(INVALID_UUID, valueMethod, failResponseMethod); } return respond422(respond422, field, uuid, INVALID_UUID); } catch (Exception e) { return response(e, failResponseMethod); } } static Future<Response> responseForeignKeyViolation(String table, String id, PgExceptionFacade pgException, Method response422method, Method valueMethod, Method failResponseMethod) { try { String detail = pgException.getDetail(); Matcher matcher = KEY_NOT_PRESENT_PATTERN.matcher(detail); if (matcher.find()) { String field = matcher.group(1); String value = matcher.group(2); String refTable = matcher.group(3); String message = "Cannot set " + table + "." + field + " = " + value + " because it does not exist in " + refTable + ".id."; if (response422method == null) { return response(message, valueMethod, failResponseMethod); } return respond422(response422method, table + "." + field, value, message); } matcher = KEY_STILL_REFERENCED_PATTERN.matcher(detail); if (matcher.find()) { String field = matcher.group(1); String value = matcher.group(2); String refTable = matcher.group(3); String message = "Cannot delete " + table + "." + field + " = " + value + " because id is still referenced from table " + refTable + "."; if (response422method == null) { return response(message, valueMethod, failResponseMethod); } return respond422(response422method, table + "." + field, value, message); } String message = pgException.getMessage() + " " + detail; if (response422method == null) { return response(message, valueMethod, failResponseMethod); } return respond422(response422method, table, id, message); } catch (Exception e) { return response(e, failResponseMethod); } } static Future<Response> responseUniqueViolation(String table, String id, PgExceptionFacade pgException, Method response422method, Method valueMethod, Method failResponseMethod) { try { String detail = pgException.getDetail(); Matcher matcher = KEY_ALREADY_EXISTS_PATTERN.matcher(detail); if (! matcher.find()) { detail = pgException.getMessage() + " " + detail; if (response422method == null) { return response(detail, valueMethod, failResponseMethod); } return respond422(response422method, table, id, detail); } String key = matcher.group(1); String value = matcher.group(2); String message = key + " value already exists in table " + table + ": " + value; if (response422method == null) { return response(message, valueMethod, failResponseMethod); } return respond422(response422method, key, value, message); } catch (Exception e) { return response(e, failResponseMethod); } } /** * Create a Response about the cause. Use clazz' respond422WithApplicationJson(Errors) * if exists, otherwise use valueMethod. * On exception create a Response using failResponseMethod(String exceptionMessage). * If that also throws an exception create a failed future. * * <p>All exceptions are caught and reported via the returned Future. */ static Future<Response> response(String table, String id, Throwable cause, Class<? extends ResponseDelegate> clazz, Method valueMethod, Method failResponseMethod) { try { PgExceptionFacade pgException = new PgExceptionFacade(cause); if (pgException.isForeignKeyViolation()) { return responseForeignKeyViolation(table, id, pgException, respond422method(clazz), valueMethod, failResponseMethod); } if (pgException.isUniqueViolation()) { return responseUniqueViolation(table, id, pgException, respond422method(clazz), valueMethod, failResponseMethod); } return response(cause.getMessage(), failResponseMethod, failResponseMethod); } catch (Exception e) { return response(e, failResponseMethod); } } /** * Delete a record from a table. * * <p>All exceptions are caught and reported via the asyncResultHandler. * * @param table where to delete * @param id the primary key of the record to delete * @param okapiHeaders http headers provided by okapi * @param vertxContext the current context * @param clazz the ResponseDelegate class created from the RAML file with these methods: * respond204(), respond400WithTextPlain(Object), respond404WithTextPlain(Object), * respond500WithTextPlain(Object). * @param asyncResultHandler where to return the result created by clazz */ public static void deleteById(String table, String id, Map<String, String> okapiHeaders, Context vertxContext, Class<? extends ResponseDelegate> clazz, Handler<AsyncResult<Response>> asyncResultHandler) { final Method respond500; try { respond500 = clazz.getMethod(RESPOND_500_WITH_TEXT_PLAIN, Object.class); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), null, null)); return; } try { Method respond204 = clazz.getMethod(RESPOND_204); Method respond400 = clazz.getMethod(RESPOND_400_WITH_TEXT_PLAIN, Object.class); Method respond404 = clazz.getMethod(RESPOND_404_WITH_TEXT_PLAIN, Object.class); if (! UuidUtil.isUuid(id)) { asyncResultHandler.handle(responseInvalidUuid(table + ".id", id, clazz, respond400, respond500)); return; } PostgresClient postgresClient = PgUtil.postgresClient(vertxContext, okapiHeaders); postgresClient.delete(table, id, reply -> { if (reply.failed()) { asyncResultHandler.handle(response(table, id, reply.cause(), clazz, respond400, respond500)); return; } int deleted = reply.result().rowCount(); if (deleted == 0) { asyncResultHandler.handle(response(NOT_FOUND, respond404, respond500)); return; } if (deleted != 1) { String message = "Deleted " + deleted + " records in " + table + " for id: " + id; logger.fatal(message); asyncResultHandler.handle(response(message, respond500, respond500)); return; } asyncResultHandler.handle(response(respond204, respond500)); }); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), respond500, respond500)); } } /** * Return the first method whose name starts with <code>set</code> and that takes a List as parameter, * for example {@code setUser(List<User>)}. * @param collectionClass where to search for the method * @return the method * @throws NoSuchMethodException if not found */ static <C> Method getListSetter(Class<C> collectionClass) throws NoSuchMethodException { for (Method method : collectionClass.getMethods()) { Class<?> [] parameterTypes = method.getParameterTypes(); if (method.getName().startsWith("set") && parameterTypes.length == 1 && parameterTypes[0].equals(List.class)) { return method; } } throw new NoSuchMethodException(collectionClass.getName() + " must have a set...(java.util.List<>) method."); } private static <T, C> C collection(Class<C> collectionClazz, List<T> list, int totalRecords) throws ReflectiveOperationException { Method setList = getListSetter(collectionClazz); Method setTotalRecords = collectionClazz.getMethod("setTotalRecords", Integer.class); C collection = collectionClazz.newInstance(); setList.invoke(collection, list); setTotalRecords.invoke(collection, totalRecords); return collection; } private static void streamTrailer(HttpServerResponse response, ResultInfo resultInfo) { response.write(String.format("],%n \"totalRecords\": %d,%n", resultInfo.getTotalRecords())); response.end(String.format(" \"resultInfo\": %s%n}", Json.encode(resultInfo))); } private static <T> void streamGetResult(PostgresClientStreamResult<T> result, String element, HttpServerResponse response) { response.setStatusCode(200); response.setChunked(true); response.putHeader(HttpHeaders.CONTENT_TYPE, "application/json"); response.write("{\n"); response.write(String.format(" \"%s\": [%n", element)); AtomicBoolean first = new AtomicBoolean(true); result.exceptionHandler(res -> { String message = res.getMessage(); List<Diagnostic> diag = new ArrayList<>(); diag.add(new Diagnostic().withCode("500").withMessage(message)); result.resultInto().setDiagnostics(diag); streamTrailer(response, result.resultInto()); }); result.endHandler(res -> streamTrailer(response, result.resultInto())); result.handler(res -> { String itemString = null; try { itemString = OBJECT_MAPPER.writeValueAsString(res); } catch (JsonProcessingException ex) { logger.error(ex.getMessage(), ex); throw new IllegalArgumentException(ex.getCause()); } if (first.get()) { first.set(false); } else { response.write(String.format(",%n")); } response.write(itemString); }); } /** * Streaming GET with query. This produces a HTTP with JSON content with * properties {@code totalRecords}, {@code resultInfo} and custom element. * The custom element is array type which POJO that is of type clazz. * The JSON schema looks as follows: * * <pre>{@code * "properties": { * "element": { * "description": "the custom element array wrapper", * "type": "array", * "items": { * "description": "The clazz", * "type": "object", * "$ref": "clazz.schema" * } * }, * "totalRecords": { * "type": "integer" * }, * "resultInfo": { * "$ref": "raml-util/schemas/resultInfo.schema", * "readonly": true * } * }, * "required": [ * "instances", * "totalRecords" * ] *</pre> * @param <T> Class for each item returned * @param table SQL table * @param clazz The item class * @param cql CQL query * @param offset offset >= 0; < 0 for no offset * @param limit limit >= 0 ; <0 for no limit * @param facets facets (empty or null for no facets) * @param element wrapper JSON element for list of items (eg books / users) * @param routingContext routing context from which a HTTP response is made * @param okapiHeaders * @param vertxContext */ @SuppressWarnings({"unchecked", "squid:S107"}) // Method has >7 parameters public static <T> void streamGet(String table, Class<T> clazz, String cql, int offset, int limit, List<String> facets, String element, RoutingContext routingContext, Map<String, String> okapiHeaders, Context vertxContext) { HttpServerResponse response = routingContext.response(); try { List<FacetField> facetList = FacetManager.convertFacetStrings2FacetFields(facets, JSON_COLUMN); CQLWrapper wrapper = new CQLWrapper(new CQL2PgJSON(table + "." + JSON_COLUMN), cql, limit, offset); streamGet(table, clazz, wrapper, facetList, element, routingContext, okapiHeaders, vertxContext); } catch (Exception e) { logger.error(e.getMessage(), e); response.setStatusCode(500); response.putHeader(HttpHeaders.CONTENT_TYPE, "text/plain"); response.end(e.toString()); } } /** * streamGet that takes CQLWrapper and FacetField List * @param <T> * @param table * @param clazz * @param filter * @param facetList * @param element * @param routingContext * @param okapiHeaders * @param vertxContext */ @SuppressWarnings({"unchecked", "squid:S107"}) // Method has >7 parameters public static <T> void streamGet(String table, Class<T> clazz, CQLWrapper filter, List<FacetField> facetList, String element, RoutingContext routingContext, Map<String, String> okapiHeaders, Context vertxContext) { HttpServerResponse response = routingContext.response(); PostgresClient postgresClient = PgUtil.postgresClient(vertxContext, okapiHeaders); postgresClient.streamGet(table, clazz, JSON_COLUMN, filter, true, null, facetList, reply -> { if (reply.failed()) { String message = PgExceptionUtil.badRequestMessage(reply.cause()); if (message == null) { message = reply.cause().getMessage(); } logger.error(message, reply.cause()); response.setStatusCode(400); response.putHeader(HttpHeaders.CONTENT_TYPE, "text/plain"); response.end(message); return; } streamGetResult(reply.result(), element, response); }); } /** * Get records by CQL. * @param table the table that contains the records * @param clazz the class of the record type T * @param collectionClazz the class of the collection type C containing records of type T * @param cql the CQL query for filtering and sorting the records * @param offset number of records to skip, use 0 or negative number for not skipping * @param limit maximum number of records to return, use a negative number for no limit * @param okapiHeaders http headers provided by okapi * @param vertxContext the current context * @param responseDelegateClass the ResponseDelegate class generated as defined by the RAML file, * must have these methods: respond200(C), respond400WithTextPlain(Object), respond500WithTextPlain(Object). * @param asyncResultHandler where to return the result created by the responseDelegateClass */ public static <T, C> void get(String table, Class<T> clazz, Class<C> collectionClazz, String cql, int offset, int limit, Map<String, String> okapiHeaders, Context vertxContext, Class<? extends ResponseDelegate> responseDelegateClass, Handler<AsyncResult<Response>> asyncResultHandler) { final Method respond500; final Method respond400; try { respond500 = responseDelegateClass.getMethod(RESPOND_500_WITH_TEXT_PLAIN, Object.class); respond400 = responseDelegateClass.getMethod(RESPOND_400_WITH_TEXT_PLAIN, Object.class); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), null, null)); return; } try { CQL2PgJSON cql2pgJson = new CQL2PgJSON(table + "." + JSON_COLUMN); CQLWrapper cqlWrapper = new CQLWrapper(cql2pgJson, cql, limit, offset); PreparedCQL preparedCql = new PreparedCQL(table, cqlWrapper, okapiHeaders); get(preparedCql, clazz, collectionClazz, okapiHeaders, vertxContext, responseDelegateClass, asyncResultHandler); } catch (FieldException e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), respond400, respond500)); } } static <T, C> void get(PreparedCQL preparedCql, Class<T> clazz, Class<C> collectionClazz, Map<String, String> okapiHeaders, Context vertxContext, Class<? extends ResponseDelegate> responseDelegateClass, Handler<AsyncResult<Response>> asyncResultHandler) { final Method respond500; try { respond500 = responseDelegateClass.getMethod(RESPOND_500_WITH_TEXT_PLAIN, Object.class); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), null, null)); return; } try { Method respond200 = responseDelegateClass.getMethod(RESPOND_200_WITH_APPLICATION_JSON, collectionClazz); Method respond400 = responseDelegateClass.getMethod(RESPOND_400_WITH_TEXT_PLAIN, Object.class); PostgresClient postgresClient = PgUtil.postgresClient(vertxContext, okapiHeaders); postgresClient.get(preparedCql.getTableName(), clazz, preparedCql.getCqlWrapper(), true, reply -> { try { if (reply.failed()) { String message = PgExceptionUtil.badRequestMessage(reply.cause()); if (message == null) { message = reply.cause().getMessage(); } logger.error(message, reply.cause()); asyncResultHandler.handle(response(message, respond400, respond500)); return; } List<T> list = reply.result().getResults(); C collection = collection(collectionClazz, list, reply.result().getResultInfo().getTotalRecords()); asyncResultHandler.handle(response(collection, respond200, respond500)); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), respond500, respond500)); } }); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), respond500, respond500)); } } /** * Get a record by id. * * <p>All exceptions are caught and reported via the asyncResultHandler. * * @param table the table that contains the record * @param clazz the class of the response type T * @param id the primary key of the record to get * @param okapiHeaders http headers provided by okapi * @param vertxContext the current context * @param responseDelegateClass the ResponseDelegate class generated as defined by the RAML file, * must have these methods: respond200(T), respond404WithTextPlain(Object), respond500WithTextPlain(Object). * @param asyncResultHandler where to return the result created by the responseDelegateClass */ public static <T> void getById(String table, Class<T> clazz, String id, Map<String, String> okapiHeaders, Context vertxContext, Class<? extends ResponseDelegate> responseDelegateClass, Handler<AsyncResult<Response>> asyncResultHandler) { final Method respond500; try { respond500 = responseDelegateClass.getMethod(RESPOND_500_WITH_TEXT_PLAIN, Object.class); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), null, null)); return; } try { Method respond200 = responseDelegateClass.getMethod(RESPOND_200_WITH_APPLICATION_JSON, clazz); Method respond404 = responseDelegateClass.getMethod(RESPOND_404_WITH_TEXT_PLAIN, Object.class); if (! UuidUtil.isUuid(id)) { asyncResultHandler.handle(responseInvalidUuid(table + ".id", id, responseDelegateClass, respond404, respond500)); return; } PostgresClient postgresClient = postgresClient(vertxContext, okapiHeaders); postgresClient.getById(table, id, clazz, reply -> { if (reply.failed()) { asyncResultHandler.handle(response(reply.cause().getMessage(), respond500, respond500)); return; } if (reply.result() == null) { asyncResultHandler.handle(response(NOT_FOUND, respond404, respond500)); return; } asyncResultHandler.handle(response(reply.result(), respond200, respond500)); }); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), respond500, respond500)); } } /** * Return entity's id. * * <p>Use reflection, the POJOs don't have a interface/superclass in common. */ private static <T> Object getId(T entity) throws ReflectiveOperationException { return entity.getClass().getDeclaredMethod("getId").invoke(entity); } /** * Set entity's id. * * <p>Use reflection, the POJOs don't have a interface/superclass in common. * @param entity where to set the id field * @param id the new id value */ private static <T> void setId(T entity, String id) throws ReflectiveOperationException { entity.getClass().getDeclaredMethod("setId", String.class).invoke(entity, id); } /** * If entity's id field is null then initialize it with a random UUID. * @param entity entity with id field * @return the value of the id field at the end * @throws ReflectiveOperationException if entity.getId() or entity.setId(String) fails. */ private static <T> String initId(T entity) throws ReflectiveOperationException { Object id = getId(entity); if (id != null) { return id.toString(); } String idString = UUID.randomUUID().toString(); setId(entity, idString); return idString; } /** * Return the method respond201WithApplicationJson(entity, headers) where the type of entity * is assignable from entityClass and the type of headers is assignable from headersFor201Class. * * <p>Depending on the .raml file entity is either of type Object or of the POJO type (for example of type User). * * @throws NoSuchMethodException if not found */ private static <T> Method getResponse201Method(Class<? extends ResponseDelegate> clazz, Class<T> entityClass, Class<?> headersFor201Class) throws NoSuchMethodException { for (Method method : clazz.getMethods()) { if (! method.getName().equals(RESPOND_201_WITH_APPLICATION_JSON)) { continue; } Class<?> [] parameterType = method.getParameterTypes(); if (parameterType.length == 2 && parameterType[0].isAssignableFrom(entityClass) && parameterType[1].isAssignableFrom(headersFor201Class)) { return method; } } throw new NoSuchMethodException(RESPOND_201_WITH_APPLICATION_JSON + "(" + entityClass.getName() + ", " + headersFor201Class.getName() + ") not found in " + clazz.getCanonicalName()); } /** * Post entity to table. * * <p>Create a random UUID for id if entity doesn't contain one. * * <p>All exceptions are caught and reported via the asyncResultHandler. * * @param table table name * @param entity the entity to post. If the id field is missing or null it is set to a random UUID. * @param okapiHeaders http headers provided by okapi * @param vertxContext the current context * @param clazz the ResponseDelegate class generated as defined by the RAML file, must have these methods: * headersFor201(), respond201WithApplicationJson(T, HeadersFor201), * respond400WithTextPlain(Object), respond500WithTextPlain(Object). * @param asyncResultHandler where to return the result created by clazz */ @SuppressWarnings("squid:S1523") // suppress "Dynamically executing code is security-sensitive" // we use only hard-coded names public static <T> void post(String table, T entity, Map<String, String> okapiHeaders, Context vertxContext, Class<? extends ResponseDelegate> clazz, Handler<AsyncResult<Response>> asyncResultHandler) { final Method respond500; try { respond500 = clazz.getMethod(RESPOND_500_WITH_TEXT_PLAIN, Object.class); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(Future.failedFuture(e)); return; } try { Method headersFor201Method = clazz.getMethod("headersFor201"); Class<?> headersFor201Class = null; for (Class<?> declaredClass : clazz.getClasses()) { if (declaredClass.getName().endsWith("$HeadersFor201")) { headersFor201Class = declaredClass; break; } } if (headersFor201Class == null) { throw new ClassNotFoundException("Class HeadersFor201 not found in " + clazz.getCanonicalName()); } Method withLocation = headersFor201Class.getMethod("withLocation", String.class); Method respond201 = getResponse201Method(clazz, entity.getClass(), headersFor201Class); Method respond400 = clazz.getMethod(RESPOND_400_WITH_TEXT_PLAIN, Object.class); String id = initId(entity); if (! UuidUtil.isUuid(id)) { asyncResultHandler.handle(responseInvalidUuid(table + ".id", id, clazz, respond400, respond500)); return; } PostgresClient postgresClient = postgresClient(vertxContext, okapiHeaders); postgresClient.saveAndReturnUpdatedEntity(table, id, entity, reply -> { if (reply.failed()) { asyncResultHandler.handle(response(table, id, reply.cause(), clazz, respond400, respond500)); return; } asyncResultHandler.handle(response(reply.result(), id, headersFor201Method, withLocation, respond201, respond500)); }); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), respond500, respond500)); } } /** * Put entity to table. * * <p>All exceptions are caught and reported via the asyncResultHandler. * * @param table table name * @param entity the new entity to store. The id field is set to the id value. * @param id the id value to use for entity * @param okapiHeaders http headers provided by okapi * @param vertxContext the current context * @param clazz the ResponseDelegate class created from the RAML file with these methods: * respond204(), respond400WithTextPlain(Object), respond404WithTextPlain(Object), * respond500WithTextPlain(Object). * @param asyncResultHandler where to return the result created by clazz */ public static <T> void put(String table, T entity, String id, Map<String, String> okapiHeaders, Context vertxContext, Class<? extends ResponseDelegate> clazz, Handler<AsyncResult<Response>> asyncResultHandler) { final Method respond500; try { respond500 = clazz.getMethod(RESPOND_500_WITH_TEXT_PLAIN, Object.class); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), null, null)); return; } try { Method respond204 = clazz.getMethod(RESPOND_204); Method respond400 = clazz.getMethod(RESPOND_400_WITH_TEXT_PLAIN, Object.class); Method respond404 = clazz.getMethod(RESPOND_404_WITH_TEXT_PLAIN, Object.class); if (! UuidUtil.isUuid(id)) { asyncResultHandler.handle(responseInvalidUuid(table + ".id", id, clazz, respond400, respond500)); return; } setId(entity, id); PostgresClient postgresClient = postgresClient(vertxContext, okapiHeaders); postgresClient.update(table, entity, id, reply -> { if (reply.failed()) { asyncResultHandler.handle(response(table, id, reply.cause(), clazz, respond400, respond500)); return; } int updated = reply.result().rowCount(); if (updated == 0) { asyncResultHandler.handle(response(NOT_FOUND, respond404, respond500)); return; } if (updated != 1) { String message = "Updated " + updated + " records in " + table + " for id: " + id; logger.fatal(message); asyncResultHandler.handle(response(message, respond500, respond500)); return; } asyncResultHandler.handle(response(respond204, respond500)); }); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), respond500, respond500)); } } /** * Return the sort node from the sortBy clause of the cql query, or null if no * sortBy clause exists or cql is invalid. * @param cql the CQL query to parse * @return sort node, or null */ static CQLSortNode getSortNode(String cql) { try { CQLParser parser = new CQLParser(); CQLNode node = parser.parse(cql); return getSortNode(node); } catch (IOException|CQLParseException|NullPointerException e) { return null; } } private static CQLSortNode getSortNode(CQLNode node) { CqlSortNodeVisitor visitor = new CqlSortNodeVisitor(); node.traverse(visitor); return visitor.sortNode; } private static class CqlSortNodeVisitor extends CQLDefaultNodeVisitor { CQLSortNode sortNode = null; @Override public void onSortNode(CQLSortNode cqlSortNode) { sortNode = cqlSortNode; } } private static String getAscDesc(ModifierSet modifierSet) { String ascDesc = ""; for (Modifier modifier : modifierSet.getModifiers()) { switch (modifier.getType()) { case "sort.ascending": ascDesc = "ASC"; break; case "sort.descending": ascDesc = "DESC"; break; default: // ignore } } return ascDesc; } /** * Return a PostgresClient. * @param vertxContext Where to get a Vertx from. * @param okapiHeaders Where to get the tenantId from. * @return the PostgresClient for the vertx and the tenantId */ public static PostgresClient postgresClient(Context vertxContext, Map<String, String> okapiHeaders) { String tenantId = TenantTool.tenantId(okapiHeaders); if (PostgresClient.DEFAULT_SCHEMA.equals(tenantId)) { return PostgresClient.getInstance(vertxContext.owner()); } return PostgresClient.getInstance(vertxContext.owner(), TenantTool.tenantId(okapiHeaders)); } /** Number of records to read from the sort index in getWithOptimizedSql method */ public static int getOptimizedSqlSize() { return optimizedSqlSize; } /** * Set the number of records the getWithOptimizedSql methode uses from the sort index. * @param size the new size */ public static void setOptimizedSqlSize(int size) { optimizedSqlSize = size; } /** * Run the cql query using optimized SQL (if possible) or standard SQL. * <p> * PostgreSQL has no statistics about a field within a JSONB resulting in bad performance. * <p> * This method requires that the sortField has a b-tree index (non-unique) and caseSensitive=false * and removeAccents=true, and that the cql query is supported by a full text index. * <p> * This method starts a full table scan until getOptimizedSqlSize() records have been scanned. * Then it assumes that there are only a few result records and uses the full text match. * If the requested number of records have been found it stops immediately. * * @param table * @param clazz * @param cql * @param okapiHeaders * @param vertxContext * @param responseDelegateClass * @param asyncResultHandler */ public static <T, C> void getWithOptimizedSql(String table, Class<T> clazz, Class<C> collectionClazz, String sortField, String cql, int offset, int limit, Map<String, String> okapiHeaders, Context vertxContext, Class<? extends ResponseDelegate> responseDelegateClass, Handler<AsyncResult<Response>> asyncResultHandler) { final Method respond500; try { respond500 = responseDelegateClass.getMethod(RESPOND_500_WITH_TEXT_PLAIN, Object.class); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), null, null)); return; } final Method respond200; final Method respond400; try { respond200 = responseDelegateClass.getMethod(RESPOND_200_WITH_APPLICATION_JSON, collectionClazz); respond400 = responseDelegateClass.getMethod(RESPOND_400_WITH_TEXT_PLAIN, Object.class); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), respond500, respond500)); return; } try { CQL2PgJSON cql2pgJson = new CQL2PgJSON(table + "." + JSON_COLUMN); CQLWrapper cqlWrapper = new CQLWrapper(cql2pgJson, cql, limit, offset); PreparedCQL preparedCql = new PreparedCQL(table, cqlWrapper, okapiHeaders); String sql = generateOptimizedSql(sortField, preparedCql, offset, limit); if (sql == null) { // the cql is not suitable for optimization, generate simple sql get(preparedCql, clazz, collectionClazz, okapiHeaders, vertxContext, responseDelegateClass, asyncResultHandler); return; } logger.info("Optimized SQL generated. Source CQL: " + cql); PostgresClient postgresClient = postgresClient(vertxContext, okapiHeaders); postgresClient.select(sql, reply -> { try { if (reply.failed()) { Throwable cause = reply.cause(); logger.error("Optimized SQL failed: " + cause.getMessage() + ": " + sql, cause); asyncResultHandler.handle(response(cause.getMessage(), respond500, respond500)); return; } C collection = collection(clazz, collectionClazz, reply.result(), offset, limit); asyncResultHandler.handle(response(collection, respond200, respond500)); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), respond500, respond500)); return; } }); } catch (FieldException | QueryValidationException e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), respond400, respond500)); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), respond500, respond500)); } } private static <T, C> C collection(Class<T> clazz, Class<C> collectionClazz, RowSet<Row> resultSet, int offset, int limit) throws ReflectiveOperationException, IOException { int totalRecords = 0; int resultSize = resultSet.size(); List<T> recordList = new ArrayList<>(resultSize); RowIterator<Row> iterator = resultSet.iterator(); while (iterator.hasNext()) { Row row = iterator.next(); String jsonb = row.getValue(JSON_COLUMN).toString(); recordList.add(OBJECT_MAPPER.readValue(jsonb, clazz)); totalRecords = row.getInteger("count"); } totalRecords = PostgresClient.getTotalRecords(resultSize, totalRecords, offset, limit); return collection(collectionClazz, recordList, totalRecords); } /** * Anticipate whether {@link #getWithOptimizedSql} will optimize for query * @param cql CQL query string * @param column sorting criteria to check for (eg "title") * @return null if not eligible; CQL sort node it would be optimized */ public static CQLSortNode checkOptimizedCQL(String cql, String column) { CQLSortNode cqlSortNode = getSortNode(cql); if (cqlSortNode == null) { return null; } List<ModifierSet> sortIndexes = cqlSortNode.getSortIndexes(); if (sortIndexes.size() != 1) { return null; } ModifierSet modifierSet = sortIndexes.get(0); if (! modifierSet.getBase().equals(column)) { return null; } return cqlSortNode; } /** * Generate optimized sql given a specific cql query, tenant, index column name hint and configurable size to hinge the optimization on. * * @param column the column that has an index to be used for sorting * @param preparedCql the cql query * @param offset start index of objects to return * @param limit max number of objects to return * @throws QueryValidationException * @return the generated SQL string, or null if the CQL query is not suitable for optimization. */ static String generateOptimizedSql(String column, PreparedCQL preparedCql, int offset, int limit) throws QueryValidationException { String cql = preparedCql.getCqlWrapper().getQuery(); CQLSortNode cqlSortNode = checkOptimizedCQL(cql, column); if (cqlSortNode == null) { return null; } List<ModifierSet> sortIndexes = cqlSortNode.getSortIndexes(); ModifierSet modifierSet = sortIndexes.get(0); String ascDesc = getAscDesc(modifierSet); cql = cqlSortNode.getSubtree().toCQL(); String lessGreater = ""; if (ascDesc.equals("DESC")) { lessGreater = ">" ; } else { lessGreater = "<"; } String tableName = preparedCql.getFullTableName(); String where = preparedCql.getCqlWrapper().getField().toSql(cql).getWhere(); // If there are many matches use a full table scan in data_column sort order // using the data_column index, but stop this scan after OPTIMIZED_SQL_SIZE index entries. // Otherwise use full text matching because there are only a few matches. // // "headrecords" are the matching records found within the first OPTIMIZED_SQL_SIZE records // by stopping at the data_column from "OFFSET OPTIMIZED_SQL_SIZE LIMIT 1". // If "headrecords" are enough to return the requested "LIMIT" number of records we are done. // Otherwise use the full text index to create "allrecords" with all matching // records and do sorting and LIMIT afterwards. String wrappedColumn = "lower(f_unaccent(jsonb->>'" + column + "')) "; String cutWrappedColumn = "left(" + wrappedColumn + ",600) "; String countSql = "(" + preparedCql.getSchemaName() + ".count_estimate('" + " SELECT " + StringEscapeUtils.escapeSql(wrappedColumn) + " AS data_column " + " FROM " + tableName + " " + " WHERE " + StringEscapeUtils.escapeSql(where) + "')) AS count"; String sql = " WITH " + " headrecords AS (" + " SELECT jsonb, (" + wrappedColumn + ") AS data_column FROM " + tableName + " WHERE (" + where + ")" + " AND " + cutWrappedColumn + lessGreater + " ( SELECT " + cutWrappedColumn + " FROM " + tableName + " ORDER BY " + cutWrappedColumn + ascDesc + " OFFSET " + optimizedSqlSize + " LIMIT 1" + " )" + " ORDER BY " + cutWrappedColumn + ascDesc + " LIMIT " + limit + " OFFSET " + offset + " ), " + " allrecords AS (" + " SELECT jsonb, " + wrappedColumn + " AS data_column FROM " + tableName + " WHERE (" + where + ")" + " AND (SELECT COUNT(*) FROM headrecords) < " + limit + " )" + " SELECT jsonb, data_column, " + countSql + " FROM headrecords" + " WHERE (SELECT COUNT(*) FROM headrecords) >= " + limit + " UNION" + " (SELECT jsonb, data_column, " + countSql + " FROM allrecords" + " ORDER BY data_column " + ascDesc + " LIMIT " + limit + " OFFSET " + offset + " )" + " ORDER BY data_column " + ascDesc; logger.info("optimized SQL generated from CQL: " + sql); return sql; } static class PreparedCQL { private final String tableName; private final String fullTableName; private final CQLWrapper cqlWrapper; private final String schemaName; public PreparedCQL(String tableName, CQLWrapper cqlWrapper, Map<String, String> okapiHeaders) { String tenantId = TenantTool.tenantId(okapiHeaders); this.tableName = tableName; this.cqlWrapper = cqlWrapper; schemaName = PostgresClient.convertToPsqlStandard(tenantId); fullTableName = schemaName + "." + tableName; } public String getTableName() { return tableName; } public String getSchemaName() { return schemaName; } /** * @return full table name including schema, for example * tenant_mymodule.users */ public String getFullTableName() { return fullTableName; } public CQLWrapper getCqlWrapper() { return cqlWrapper; } } }
domain-models-runtime/src/main/java/org/folio/rest/persist/PgUtil.java
package org.folio.rest.persist; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.vertx.core.AsyncResult; import io.vertx.core.Context; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.http.HttpHeaders; import io.vertx.core.http.HttpServerResponse; import io.vertx.core.json.Json; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.ext.web.RoutingContext; import io.vertx.sqlclient.Row; import io.vertx.sqlclient.RowIterator; import io.vertx.sqlclient.RowSet; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.concurrent.atomic.AtomicBoolean; import java.util.Map; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.ws.rs.core.Response; import org.apache.commons.lang.StringEscapeUtils; import org.folio.rest.tools.utils.ObjectMapperTool; import org.folio.rest.tools.utils.OutStream; import org.folio.rest.tools.utils.TenantTool; import org.folio.rest.tools.utils.ValidationHelper; import org.folio.util.UuidUtil; import org.folio.cql2pgjson.CQL2PgJSON; import org.folio.cql2pgjson.exception.FieldException; import org.folio.cql2pgjson.exception.QueryValidationException; import org.folio.rest.persist.cql.CQLWrapper; import org.folio.rest.jaxrs.model.Errors; import org.folio.rest.jaxrs.resource.support.ResponseDelegate; import org.folio.rest.jaxrs.model.Diagnostic; import org.folio.rest.persist.facets.FacetField; import org.folio.rest.persist.facets.FacetManager; import org.folio.rest.jaxrs.model.ResultInfo; import org.z3950.zing.cql.CQLDefaultNodeVisitor; import org.z3950.zing.cql.CQLNode; import org.z3950.zing.cql.CQLParseException; import org.z3950.zing.cql.CQLParser; import org.z3950.zing.cql.CQLSortNode; import org.z3950.zing.cql.Modifier; import org.z3950.zing.cql.ModifierSet; /** * Helper methods for using PostgresClient. */ public final class PgUtil { private static final Logger logger = LoggerFactory.getLogger(PgUtil.class); private static final String RESPOND_200_WITH_APPLICATION_JSON = "respond200WithApplicationJson"; private static final String RESPOND_201_WITH_APPLICATION_JSON = "respond201WithApplicationJson"; private static final String RESPOND_204 = "respond204"; private static final String RESPOND_400_WITH_TEXT_PLAIN = "respond400WithTextPlain"; private static final String RESPOND_404_WITH_TEXT_PLAIN = "respond404WithTextPlain"; private static final String RESPOND_422_WITH_APPLICATION_JSON = "respond422WithApplicationJson"; private static final String RESPOND_500_WITH_TEXT_PLAIN = "respond500WithTextPlain"; private static final String NOT_FOUND = "Not found"; private static final String INVALID_UUID = "Invalid UUID format of id, should be " + "xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx where M is 1-5 and N is 8, 9, a, b, A or B and " + "x is 0-9, a-f or A-F."; /** This is the name of the column used by all modules to store actual data */ private static final String JSON_COLUMN = "jsonb"; /** mapper between JSON and Java instance (POJO) */ private static final ObjectMapper OBJECT_MAPPER = ObjectMapperTool.getMapper(); /** * Assume this String: * <p> * <code>Key (((jsonb -> 'x'::text) ->> 'barcode'::text))=(=() already exists.</code> * <p> * The pattern will match and return these substrings: * <p> * 1 = <code>((jsonb -> 'x'::text) ->> 'barcode'::text)</code> * <p> * 2 = <code>=(</code> */ private static final Pattern KEY_ALREADY_EXISTS_PATTERN = Pattern.compile( "^Key \\(([^=]+)\\)=\\((.*)\\) already exists.$"); /** * Assume this String: * <p> * <code>Key (userid)=(82666c63-ef00-4ca6-afb5-e069bac767fa) is not present in table "users".</code> * <p> * The pattern will match and return these substrings: * <p> * 1 = <code>userid</code> * <p> * 2 = <code>82666c63-ef00-4ca6-afb5-e069bac767fa</code> * <p> * 3 = <code>users</code> */ private static final Pattern KEY_NOT_PRESENT_PATTERN = Pattern.compile( "^Key \\(([^=]+)\\)=\\((.*)\\) is not present in table \"(.*)\".$"); /** * Assume this String: * <p> * <code>Key (id)=(64f55fa2-50f4-40e5-978a-bbad17dc644d) is still referenced from table "referencing".</code> * <p> * The pattern will match and return these substrings: * <p> * 1 = <code>id</code> * <p> * 2 = <code>64f55fa2-50f4-40e5-978a-bbad17dc644d</code> * <p> * 3 = <code>referencing</code> */ private static final Pattern KEY_STILL_REFERENCED_PATTERN = Pattern.compile( "^Key \\(([^=]+)\\)=\\((.*)\\) is still referenced from table \"(.*)\".$"); /** Number of records to read from the sort index in getWithOptimizedSql and generateOptimizedSql method */ private static int optimizedSqlSize = 10000; private PgUtil() { throw new UnsupportedOperationException("Cannot instantiate utility class."); } /** * Create a Response using okMethod(entity, headersMethod().withLocationMethod(location)). * On exception create a Response using failResponseMethod. * * <p>All exceptions are caught and reported via the returned Future. */ static <T> Future<Response> response(T entity, String location, Method headersMethod, Method withLocationMethod, Method okResponseMethod, Method failResponseMethod) { try { OutStream stream = new OutStream(); stream.setData(entity); Object headers = headersMethod.invoke(null); withLocationMethod.invoke(headers, location); Response response = (Response) okResponseMethod.invoke(null, entity, headers); return Future.succeededFuture(response); } catch (Exception e) { logger.error(e.getMessage(), e); try { Response response = (Response) failResponseMethod.invoke(null, e.getMessage()); return Future.succeededFuture(response); } catch (Exception innerException) { logger.error(innerException.getMessage(), innerException); return Future.failedFuture(innerException); } } } /** * Message of t or t.getCause(). Useful for InvocationTargetException. * @return The first non-null value of these: t.getMessage(), t.getCause().getMessage(). * Null if both are null. */ static String message(Throwable t) { String message = t.getMessage(); if (message != null) { return message; } Throwable inner = t.getCause(); if (inner == null) { return null; } return inner.getMessage(); } /** * Create a Response for the Exception e using failResponseMethod. */ private static Future<Response> response(Exception e, Method failResponseMethod) { String message = message(e); logger.error(message, e); try { if (failResponseMethod == null) { return Future.failedFuture(e); } Response response = (Response) failResponseMethod.invoke(null, message); return Future.succeededFuture(response); } catch (Exception innerException) { message = message(innerException); logger.error(message, innerException); return Future.failedFuture(innerException); } } /** * Create a Response using valueMethod(T). * On exception create a Response using failResponseMethod(String exceptionMessage). * If that also throws an exception create a failed future. * * <p>All exceptions are caught and reported via the returned Future. */ static <T> Future<Response> response(T value, Method valueMethod, Method failResponseMethod) { try { if (valueMethod == null) { throw new NullPointerException("valueMethod must not be null (" + value + ")"); } // this null check is redundant but avoids several sonarlint warnings if (failResponseMethod == null) { throw new NullPointerException("failResponseMethod must not be null (" + value + ")"); } Response response = (Response) valueMethod.invoke(null, value); return Future.succeededFuture(response); } catch (Exception e) { return response(e, failResponseMethod); } } /** * Return a Response using responseMethod() wrapped in a succeeded future. * * <p>On exception create a Response using failResponseMethod(String exceptionMessage) * wrapped in a succeeded future. * * <p>If that also throws an exception create a failed future. * * <p>All exceptions are caught and reported via the returned Future. */ static Future<Response> response(Method responseMethod, Method failResponseMethod) { try { // the null check is redundant but avoids several sonarlint warnings if (responseMethod == null) { throw new NullPointerException("responseMethod must not be null"); } if (failResponseMethod == null) { throw new NullPointerException("failResponseMethod must not be null"); } Response response = (Response) responseMethod.invoke(null); return Future.succeededFuture(response); } catch (Exception e) { return response(e, failResponseMethod); } } static Future<Response> respond422(Method response422Method, String key, String value, String message) { try { Errors errors = ValidationHelper.createValidationErrorMessage(key, value, message); Response response = (Response) response422Method.invoke(null, errors); return Future.succeededFuture(response); } catch (IllegalAccessException | InvocationTargetException | NullPointerException e) { throw new IllegalArgumentException(e); } } /** * Return the <code>respond422WithApplicationJson(Errors entity)</code> method. * @param clazz class to search in * @return the found method, or null if not found */ static Method respond422method(Class<? extends ResponseDelegate> clazz) { // this loop is 20 times faster than getMethod(...) if the method doesn't exist // because it avoids the Exception that getMethod(...) throws. for (Method method : clazz.getMethods()) { if (method.getName().equals(RESPOND_422_WITH_APPLICATION_JSON) && method.getParameterCount() == 1 && method.getParameters()[0].getType().equals(Errors.class)) { return method; } } return null; } /** * Create a Response about the invalid uuid. Use clazz' respond422WithApplicationJson(Errors) * if exists, otherwise use valueMethod. * On exception create a Response using failResponseMethod(String exceptionMessage). * If that also throws an exception create a failed future. * * <p>All exceptions are caught and reported via the returned Future. */ static Future<Response> responseInvalidUuid(String field, String uuid, Class<? extends ResponseDelegate> clazz, Method valueMethod, Method failResponseMethod) { try { Method respond422 = respond422method(clazz); if (respond422 == null) { return response(INVALID_UUID, valueMethod, failResponseMethod); } return respond422(respond422, field, uuid, INVALID_UUID); } catch (Exception e) { return response(e, failResponseMethod); } } static Future<Response> responseForeignKeyViolation(String table, String id, PgExceptionFacade pgException, Method response422method, Method valueMethod, Method failResponseMethod) { try { String detail = pgException.getDetail(); Matcher matcher = KEY_NOT_PRESENT_PATTERN.matcher(detail); if (matcher.find()) { String field = matcher.group(1); String value = matcher.group(2); String refTable = matcher.group(3); String message = "Cannot set " + table + "." + field + " = " + value + " because it does not exist in " + refTable + ".id."; if (response422method == null) { return response(message, valueMethod, failResponseMethod); } return respond422(response422method, table + "." + field, value, message); } matcher = KEY_STILL_REFERENCED_PATTERN.matcher(detail); if (matcher.find()) { String field = matcher.group(1); String value = matcher.group(2); String refTable = matcher.group(3); String message = "Cannot delete " + table + "." + field + " = " + value + " because id is still referenced from table " + refTable + "."; if (response422method == null) { return response(message, valueMethod, failResponseMethod); } return respond422(response422method, table + "." + field, value, message); } String message = pgException.getMessage() + " " + detail; if (response422method == null) { return response(message, valueMethod, failResponseMethod); } return respond422(response422method, table, id, message); } catch (Exception e) { return response(e, failResponseMethod); } } static Future<Response> responseUniqueViolation(String table, String id, PgExceptionFacade pgException, Method response422method, Method valueMethod, Method failResponseMethod) { try { String detail = pgException.getDetail(); Matcher matcher = KEY_ALREADY_EXISTS_PATTERN.matcher(detail); if (! matcher.find()) { detail = pgException.getMessage() + " " + detail; if (response422method == null) { return response(detail, valueMethod, failResponseMethod); } return respond422(response422method, table, id, detail); } String key = matcher.group(1); String value = matcher.group(2); String message = key + " value already exists in table " + table + ": " + value; if (response422method == null) { return response(message, valueMethod, failResponseMethod); } return respond422(response422method, key, value, message); } catch (Exception e) { return response(e, failResponseMethod); } } /** * Create a Response about the cause. Use clazz' respond422WithApplicationJson(Errors) * if exists, otherwise use valueMethod. * On exception create a Response using failResponseMethod(String exceptionMessage). * If that also throws an exception create a failed future. * * <p>All exceptions are caught and reported via the returned Future. */ static Future<Response> response(String table, String id, Throwable cause, Class<? extends ResponseDelegate> clazz, Method valueMethod, Method failResponseMethod) { try { PgExceptionFacade pgException = new PgExceptionFacade(cause); if (pgException.isForeignKeyViolation()) { return responseForeignKeyViolation(table, id, pgException, respond422method(clazz), valueMethod, failResponseMethod); } if (pgException.isUniqueViolation()) { return responseUniqueViolation(table, id, pgException, respond422method(clazz), valueMethod, failResponseMethod); } return response(cause.getMessage(), failResponseMethod, failResponseMethod); } catch (Exception e) { return response(e, failResponseMethod); } } /** * Delete a record from a table. * * <p>All exceptions are caught and reported via the asyncResultHandler. * * @param table where to delete * @param id the primary key of the record to delete * @param okapiHeaders http headers provided by okapi * @param vertxContext the current context * @param clazz the ResponseDelegate class created from the RAML file with these methods: * respond204(), respond400WithTextPlain(Object), respond404WithTextPlain(Object), * respond500WithTextPlain(Object). * @param asyncResultHandler where to return the result created by clazz */ public static void deleteById(String table, String id, Map<String, String> okapiHeaders, Context vertxContext, Class<? extends ResponseDelegate> clazz, Handler<AsyncResult<Response>> asyncResultHandler) { final Method respond500; try { respond500 = clazz.getMethod(RESPOND_500_WITH_TEXT_PLAIN, Object.class); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), null, null)); return; } try { Method respond204 = clazz.getMethod(RESPOND_204); Method respond400 = clazz.getMethod(RESPOND_400_WITH_TEXT_PLAIN, Object.class); Method respond404 = clazz.getMethod(RESPOND_404_WITH_TEXT_PLAIN, Object.class); if (! UuidUtil.isUuid(id)) { asyncResultHandler.handle(responseInvalidUuid(table + ".id", id, clazz, respond400, respond500)); return; } PostgresClient postgresClient = PgUtil.postgresClient(vertxContext, okapiHeaders); postgresClient.delete(table, id, reply -> { if (reply.failed()) { asyncResultHandler.handle(response(table, id, reply.cause(), clazz, respond400, respond500)); return; } int deleted = reply.result().rowCount(); if (deleted == 0) { asyncResultHandler.handle(response(NOT_FOUND, respond404, respond500)); return; } if (deleted != 1) { String message = "Deleted " + deleted + " records in " + table + " for id: " + id; logger.fatal(message); asyncResultHandler.handle(response(message, respond500, respond500)); return; } asyncResultHandler.handle(response(respond204, respond500)); }); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), respond500, respond500)); } } /** * Return the first method whose name starts with <code>set</code> and that takes a List as parameter, * for example {@code setUser(List<User>)}. * @param collectionClass where to search for the method * @return the method * @throws NoSuchMethodException if not found */ static <C> Method getListSetter(Class<C> collectionClass) throws NoSuchMethodException { for (Method method : collectionClass.getMethods()) { Class<?> [] parameterTypes = method.getParameterTypes(); if (method.getName().startsWith("set") && parameterTypes.length == 1 && parameterTypes[0].equals(List.class)) { return method; } } throw new NoSuchMethodException(collectionClass.getName() + " must have a set...(java.util.List<>) method."); } private static <T, C> C collection(Class<C> collectionClazz, List<T> list, int totalRecords) throws ReflectiveOperationException { Method setList = getListSetter(collectionClazz); Method setTotalRecords = collectionClazz.getMethod("setTotalRecords", Integer.class); C collection = collectionClazz.newInstance(); setList.invoke(collection, list); setTotalRecords.invoke(collection, totalRecords); return collection; } private static void streamTrailer(HttpServerResponse response, ResultInfo resultInfo) { response.write(String.format("],%n \"totalRecords\": %d,%n", resultInfo.getTotalRecords())); response.end(String.format(" \"resultInfo\": %s%n}", Json.encode(resultInfo))); } private static <T> void streamGetResult(PostgresClientStreamResult<T> result, String element, HttpServerResponse response) { response.setStatusCode(200); response.setChunked(true); response.putHeader(HttpHeaders.CONTENT_TYPE, "application/json"); response.write("{\n"); response.write(String.format(" \"%s\": [%n", element)); AtomicBoolean first = new AtomicBoolean(true); result.exceptionHandler(res -> { String message = res.getMessage(); List<Diagnostic> diag = new ArrayList<>(); diag.add(new Diagnostic().withCode("500").withMessage(message)); result.resultInto().setDiagnostics(diag); streamTrailer(response, result.resultInto()); }); result.endHandler(res -> streamTrailer(response, result.resultInto())); result.handler(res -> { String itemString = null; try { itemString = OBJECT_MAPPER.writeValueAsString(res); } catch (JsonProcessingException ex) { logger.error(ex.getMessage(), ex); logger.error(ex.getMessage(), ex); throw new IllegalArgumentException(ex.getCause()); } if (first.get()) { first.set(false); } else { response.write(String.format(",%n")); } response.write(itemString); }); } /** * Streaming GET with query. This produces a HTTP with JSON content with * properties {@code totalRecords}, {@code resultInfo} and custom element. * The custom element is array type which POJO that is of type clazz. * The JSON schema looks as follows: * * <pre>{@code * "properties": { * "element": { * "description": "the custom element array wrapper", * "type": "array", * "items": { * "description": "The clazz", * "type": "object", * "$ref": "clazz.schema" * } * }, * "totalRecords": { * "type": "integer" * }, * "resultInfo": { * "$ref": "raml-util/schemas/resultInfo.schema", * "readonly": true * } * }, * "required": [ * "instances", * "totalRecords" * ] *</pre> * @param <T> Class for each item returned * @param table SQL table * @param clazz The item class * @param cql CQL query * @param offset offset >= 0; < 0 for no offset * @param limit limit >= 0 ; <0 for no limit * @param facets facets (empty or null for no facets) * @param element wrapper JSON element for list of items (eg books / users) * @param routingContext routing context from which a HTTP response is made * @param okapiHeaders * @param vertxContext */ @SuppressWarnings({"unchecked", "squid:S107"}) // Method has >7 parameters public static <T> void streamGet(String table, Class<T> clazz, String cql, int offset, int limit, List<String> facets, String element, RoutingContext routingContext, Map<String, String> okapiHeaders, Context vertxContext) { HttpServerResponse response = routingContext.response(); try { List<FacetField> facetList = FacetManager.convertFacetStrings2FacetFields(facets, JSON_COLUMN); CQLWrapper wrapper = new CQLWrapper(new CQL2PgJSON(table + "." + JSON_COLUMN), cql, limit, offset); streamGet(table, clazz, wrapper, facetList, element, routingContext, okapiHeaders, vertxContext); } catch (Exception e) { logger.error(e.getMessage(), e); response.setStatusCode(500); response.putHeader(HttpHeaders.CONTENT_TYPE, "text/plain"); response.end(e.toString()); } } /** * streamGet that takes CQLWrapper and FacetField List * @param <T> * @param table * @param clazz * @param filter * @param facetList * @param element * @param routingContext * @param okapiHeaders * @param vertxContext */ @SuppressWarnings({"unchecked", "squid:S107"}) // Method has >7 parameters public static <T> void streamGet(String table, Class<T> clazz, CQLWrapper filter, List<FacetField> facetList, String element, RoutingContext routingContext, Map<String, String> okapiHeaders, Context vertxContext) { HttpServerResponse response = routingContext.response(); PostgresClient postgresClient = PgUtil.postgresClient(vertxContext, okapiHeaders); postgresClient.streamGet(table, clazz, JSON_COLUMN, filter, true, null, facetList, reply -> { if (reply.failed()) { String message = PgExceptionUtil.badRequestMessage(reply.cause()); if (message == null) { message = reply.cause().getMessage(); } logger.error(message, reply.cause()); response.setStatusCode(400); response.putHeader(HttpHeaders.CONTENT_TYPE, "text/plain"); response.end(message); return; } streamGetResult(reply.result(), element, response); }); } /** * Get records by CQL. * @param table the table that contains the records * @param clazz the class of the record type T * @param collectionClazz the class of the collection type C containing records of type T * @param cql the CQL query for filtering and sorting the records * @param offset number of records to skip, use 0 or negative number for not skipping * @param limit maximum number of records to return, use a negative number for no limit * @param okapiHeaders http headers provided by okapi * @param vertxContext the current context * @param responseDelegateClass the ResponseDelegate class generated as defined by the RAML file, * must have these methods: respond200(C), respond400WithTextPlain(Object), respond500WithTextPlain(Object). * @param asyncResultHandler where to return the result created by the responseDelegateClass */ public static <T, C> void get(String table, Class<T> clazz, Class<C> collectionClazz, String cql, int offset, int limit, Map<String, String> okapiHeaders, Context vertxContext, Class<? extends ResponseDelegate> responseDelegateClass, Handler<AsyncResult<Response>> asyncResultHandler) { final Method respond500; final Method respond400; try { respond500 = responseDelegateClass.getMethod(RESPOND_500_WITH_TEXT_PLAIN, Object.class); respond400 = responseDelegateClass.getMethod(RESPOND_400_WITH_TEXT_PLAIN, Object.class); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), null, null)); return; } try { CQL2PgJSON cql2pgJson = new CQL2PgJSON(table + "." + JSON_COLUMN); CQLWrapper cqlWrapper = new CQLWrapper(cql2pgJson, cql, limit, offset); PreparedCQL preparedCql = new PreparedCQL(table, cqlWrapper, okapiHeaders); get(preparedCql, clazz, collectionClazz, okapiHeaders, vertxContext, responseDelegateClass, asyncResultHandler); } catch (FieldException e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), respond400, respond500)); } } static <T, C> void get(PreparedCQL preparedCql, Class<T> clazz, Class<C> collectionClazz, Map<String, String> okapiHeaders, Context vertxContext, Class<? extends ResponseDelegate> responseDelegateClass, Handler<AsyncResult<Response>> asyncResultHandler) { final Method respond500; try { respond500 = responseDelegateClass.getMethod(RESPOND_500_WITH_TEXT_PLAIN, Object.class); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), null, null)); return; } try { Method respond200 = responseDelegateClass.getMethod(RESPOND_200_WITH_APPLICATION_JSON, collectionClazz); Method respond400 = responseDelegateClass.getMethod(RESPOND_400_WITH_TEXT_PLAIN, Object.class); PostgresClient postgresClient = PgUtil.postgresClient(vertxContext, okapiHeaders); postgresClient.get(preparedCql.getTableName(), clazz, preparedCql.getCqlWrapper(), true, reply -> { try { if (reply.failed()) { String message = PgExceptionUtil.badRequestMessage(reply.cause()); if (message == null) { message = reply.cause().getMessage(); } logger.error(message, reply.cause()); asyncResultHandler.handle(response(message, respond400, respond500)); return; } List<T> list = reply.result().getResults(); C collection = collection(collectionClazz, list, reply.result().getResultInfo().getTotalRecords()); asyncResultHandler.handle(response(collection, respond200, respond500)); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), respond500, respond500)); } }); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), respond500, respond500)); } } /** * Get a record by id. * * <p>All exceptions are caught and reported via the asyncResultHandler. * * @param table the table that contains the record * @param clazz the class of the response type T * @param id the primary key of the record to get * @param okapiHeaders http headers provided by okapi * @param vertxContext the current context * @param responseDelegateClass the ResponseDelegate class generated as defined by the RAML file, * must have these methods: respond200(T), respond404WithTextPlain(Object), respond500WithTextPlain(Object). * @param asyncResultHandler where to return the result created by the responseDelegateClass */ public static <T> void getById(String table, Class<T> clazz, String id, Map<String, String> okapiHeaders, Context vertxContext, Class<? extends ResponseDelegate> responseDelegateClass, Handler<AsyncResult<Response>> asyncResultHandler) { final Method respond500; try { respond500 = responseDelegateClass.getMethod(RESPOND_500_WITH_TEXT_PLAIN, Object.class); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), null, null)); return; } try { Method respond200 = responseDelegateClass.getMethod(RESPOND_200_WITH_APPLICATION_JSON, clazz); Method respond404 = responseDelegateClass.getMethod(RESPOND_404_WITH_TEXT_PLAIN, Object.class); if (! UuidUtil.isUuid(id)) { asyncResultHandler.handle(responseInvalidUuid(table + ".id", id, responseDelegateClass, respond404, respond500)); return; } PostgresClient postgresClient = postgresClient(vertxContext, okapiHeaders); postgresClient.getById(table, id, clazz, reply -> { if (reply.failed()) { asyncResultHandler.handle(response(reply.cause().getMessage(), respond500, respond500)); return; } if (reply.result() == null) { asyncResultHandler.handle(response(NOT_FOUND, respond404, respond500)); return; } asyncResultHandler.handle(response(reply.result(), respond200, respond500)); }); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), respond500, respond500)); } } /** * Return entity's id. * * <p>Use reflection, the POJOs don't have a interface/superclass in common. */ private static <T> Object getId(T entity) throws ReflectiveOperationException { return entity.getClass().getDeclaredMethod("getId").invoke(entity); } /** * Set entity's id. * * <p>Use reflection, the POJOs don't have a interface/superclass in common. * @param entity where to set the id field * @param id the new id value */ private static <T> void setId(T entity, String id) throws ReflectiveOperationException { entity.getClass().getDeclaredMethod("setId", String.class).invoke(entity, id); } /** * If entity's id field is null then initialize it with a random UUID. * @param entity entity with id field * @return the value of the id field at the end * @throws ReflectiveOperationException if entity.getId() or entity.setId(String) fails. */ private static <T> String initId(T entity) throws ReflectiveOperationException { Object id = getId(entity); if (id != null) { return id.toString(); } String idString = UUID.randomUUID().toString(); setId(entity, idString); return idString; } /** * Return the method respond201WithApplicationJson(entity, headers) where the type of entity * is assignable from entityClass and the type of headers is assignable from headersFor201Class. * * <p>Depending on the .raml file entity is either of type Object or of the POJO type (for example of type User). * * @throws NoSuchMethodException if not found */ private static <T> Method getResponse201Method(Class<? extends ResponseDelegate> clazz, Class<T> entityClass, Class<?> headersFor201Class) throws NoSuchMethodException { for (Method method : clazz.getMethods()) { if (! method.getName().equals(RESPOND_201_WITH_APPLICATION_JSON)) { continue; } Class<?> [] parameterType = method.getParameterTypes(); if (parameterType.length == 2 && parameterType[0].isAssignableFrom(entityClass) && parameterType[1].isAssignableFrom(headersFor201Class)) { return method; } } throw new NoSuchMethodException(RESPOND_201_WITH_APPLICATION_JSON + "(" + entityClass.getName() + ", " + headersFor201Class.getName() + ") not found in " + clazz.getCanonicalName()); } /** * Post entity to table. * * <p>Create a random UUID for id if entity doesn't contain one. * * <p>All exceptions are caught and reported via the asyncResultHandler. * * @param table table name * @param entity the entity to post. If the id field is missing or null it is set to a random UUID. * @param okapiHeaders http headers provided by okapi * @param vertxContext the current context * @param clazz the ResponseDelegate class generated as defined by the RAML file, must have these methods: * headersFor201(), respond201WithApplicationJson(T, HeadersFor201), * respond400WithTextPlain(Object), respond500WithTextPlain(Object). * @param asyncResultHandler where to return the result created by clazz */ @SuppressWarnings("squid:S1523") // suppress "Dynamically executing code is security-sensitive" // we use only hard-coded names public static <T> void post(String table, T entity, Map<String, String> okapiHeaders, Context vertxContext, Class<? extends ResponseDelegate> clazz, Handler<AsyncResult<Response>> asyncResultHandler) { final Method respond500; try { respond500 = clazz.getMethod(RESPOND_500_WITH_TEXT_PLAIN, Object.class); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(Future.failedFuture(e)); return; } try { Method headersFor201Method = clazz.getMethod("headersFor201"); Class<?> headersFor201Class = null; for (Class<?> declaredClass : clazz.getClasses()) { if (declaredClass.getName().endsWith("$HeadersFor201")) { headersFor201Class = declaredClass; break; } } if (headersFor201Class == null) { throw new ClassNotFoundException("Class HeadersFor201 not found in " + clazz.getCanonicalName()); } Method withLocation = headersFor201Class.getMethod("withLocation", String.class); Method respond201 = getResponse201Method(clazz, entity.getClass(), headersFor201Class); Method respond400 = clazz.getMethod(RESPOND_400_WITH_TEXT_PLAIN, Object.class); String id = initId(entity); if (! UuidUtil.isUuid(id)) { asyncResultHandler.handle(responseInvalidUuid(table + ".id", id, clazz, respond400, respond500)); return; } PostgresClient postgresClient = postgresClient(vertxContext, okapiHeaders); postgresClient.saveAndReturnUpdatedEntity(table, id, entity, reply -> { if (reply.failed()) { asyncResultHandler.handle(response(table, id, reply.cause(), clazz, respond400, respond500)); return; } asyncResultHandler.handle(response(reply.result(), id, headersFor201Method, withLocation, respond201, respond500)); }); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), respond500, respond500)); } } /** * Put entity to table. * * <p>All exceptions are caught and reported via the asyncResultHandler. * * @param table table name * @param entity the new entity to store. The id field is set to the id value. * @param id the id value to use for entity * @param okapiHeaders http headers provided by okapi * @param vertxContext the current context * @param clazz the ResponseDelegate class created from the RAML file with these methods: * respond204(), respond400WithTextPlain(Object), respond404WithTextPlain(Object), * respond500WithTextPlain(Object). * @param asyncResultHandler where to return the result created by clazz */ public static <T> void put(String table, T entity, String id, Map<String, String> okapiHeaders, Context vertxContext, Class<? extends ResponseDelegate> clazz, Handler<AsyncResult<Response>> asyncResultHandler) { final Method respond500; try { respond500 = clazz.getMethod(RESPOND_500_WITH_TEXT_PLAIN, Object.class); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), null, null)); return; } try { Method respond204 = clazz.getMethod(RESPOND_204); Method respond400 = clazz.getMethod(RESPOND_400_WITH_TEXT_PLAIN, Object.class); Method respond404 = clazz.getMethod(RESPOND_404_WITH_TEXT_PLAIN, Object.class); if (! UuidUtil.isUuid(id)) { asyncResultHandler.handle(responseInvalidUuid(table + ".id", id, clazz, respond400, respond500)); return; } setId(entity, id); PostgresClient postgresClient = postgresClient(vertxContext, okapiHeaders); postgresClient.update(table, entity, id, reply -> { if (reply.failed()) { asyncResultHandler.handle(response(table, id, reply.cause(), clazz, respond400, respond500)); return; } int updated = reply.result().rowCount(); if (updated == 0) { asyncResultHandler.handle(response(NOT_FOUND, respond404, respond500)); return; } if (updated != 1) { String message = "Updated " + updated + " records in " + table + " for id: " + id; logger.fatal(message); asyncResultHandler.handle(response(message, respond500, respond500)); return; } asyncResultHandler.handle(response(respond204, respond500)); }); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), respond500, respond500)); } } /** * Return the sort node from the sortBy clause of the cql query, or null if no * sortBy clause exists or cql is invalid. * @param cql the CQL query to parse * @return sort node, or null */ static CQLSortNode getSortNode(String cql) { try { CQLParser parser = new CQLParser(); CQLNode node = parser.parse(cql); return getSortNode(node); } catch (IOException|CQLParseException|NullPointerException e) { return null; } } private static CQLSortNode getSortNode(CQLNode node) { CqlSortNodeVisitor visitor = new CqlSortNodeVisitor(); node.traverse(visitor); return visitor.sortNode; } private static class CqlSortNodeVisitor extends CQLDefaultNodeVisitor { CQLSortNode sortNode = null; @Override public void onSortNode(CQLSortNode cqlSortNode) { sortNode = cqlSortNode; } } private static String getAscDesc(ModifierSet modifierSet) { String ascDesc = ""; for (Modifier modifier : modifierSet.getModifiers()) { switch (modifier.getType()) { case "sort.ascending": ascDesc = "ASC"; break; case "sort.descending": ascDesc = "DESC"; break; default: // ignore } } return ascDesc; } /** * Return a PostgresClient. * @param vertxContext Where to get a Vertx from. * @param okapiHeaders Where to get the tenantId from. * @return the PostgresClient for the vertx and the tenantId */ public static PostgresClient postgresClient(Context vertxContext, Map<String, String> okapiHeaders) { String tenantId = TenantTool.tenantId(okapiHeaders); if (PostgresClient.DEFAULT_SCHEMA.equals(tenantId)) { return PostgresClient.getInstance(vertxContext.owner()); } return PostgresClient.getInstance(vertxContext.owner(), TenantTool.tenantId(okapiHeaders)); } /** Number of records to read from the sort index in getWithOptimizedSql method */ public static int getOptimizedSqlSize() { return optimizedSqlSize; } /** * Set the number of records the getWithOptimizedSql methode uses from the sort index. * @param size the new size */ public static void setOptimizedSqlSize(int size) { optimizedSqlSize = size; } /** * Run the cql query using optimized SQL (if possible) or standard SQL. * <p> * PostgreSQL has no statistics about a field within a JSONB resulting in bad performance. * <p> * This method requires that the sortField has a b-tree index (non-unique) and caseSensitive=false * and removeAccents=true, and that the cql query is supported by a full text index. * <p> * This method starts a full table scan until getOptimizedSqlSize() records have been scanned. * Then it assumes that there are only a few result records and uses the full text match. * If the requested number of records have been found it stops immediately. * * @param table * @param clazz * @param cql * @param okapiHeaders * @param vertxContext * @param responseDelegateClass * @param asyncResultHandler */ public static <T, C> void getWithOptimizedSql(String table, Class<T> clazz, Class<C> collectionClazz, String sortField, String cql, int offset, int limit, Map<String, String> okapiHeaders, Context vertxContext, Class<? extends ResponseDelegate> responseDelegateClass, Handler<AsyncResult<Response>> asyncResultHandler) { final Method respond500; try { respond500 = responseDelegateClass.getMethod(RESPOND_500_WITH_TEXT_PLAIN, Object.class); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), null, null)); return; } final Method respond200; final Method respond400; try { respond200 = responseDelegateClass.getMethod(RESPOND_200_WITH_APPLICATION_JSON, collectionClazz); respond400 = responseDelegateClass.getMethod(RESPOND_400_WITH_TEXT_PLAIN, Object.class); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), respond500, respond500)); return; } try { CQL2PgJSON cql2pgJson = new CQL2PgJSON(table + "." + JSON_COLUMN); CQLWrapper cqlWrapper = new CQLWrapper(cql2pgJson, cql, limit, offset); PreparedCQL preparedCql = new PreparedCQL(table, cqlWrapper, okapiHeaders); String sql = generateOptimizedSql(sortField, preparedCql, offset, limit); if (sql == null) { // the cql is not suitable for optimization, generate simple sql get(preparedCql, clazz, collectionClazz, okapiHeaders, vertxContext, responseDelegateClass, asyncResultHandler); return; } logger.info("Optimized SQL generated. Source CQL: " + cql); PostgresClient postgresClient = postgresClient(vertxContext, okapiHeaders); postgresClient.select(sql, reply -> { try { if (reply.failed()) { Throwable cause = reply.cause(); logger.error("Optimized SQL failed: " + cause.getMessage() + ": " + sql, cause); asyncResultHandler.handle(response(cause.getMessage(), respond500, respond500)); return; } C collection = collection(clazz, collectionClazz, reply.result(), offset, limit); asyncResultHandler.handle(response(collection, respond200, respond500)); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), respond500, respond500)); return; } }); } catch (FieldException | QueryValidationException e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), respond400, respond500)); } catch (Exception e) { logger.error(e.getMessage(), e); asyncResultHandler.handle(response(e.getMessage(), respond500, respond500)); } } private static <T, C> C collection(Class<T> clazz, Class<C> collectionClazz, RowSet<Row> resultSet, int offset, int limit) throws ReflectiveOperationException, IOException { int totalRecords = 0; int resultSize = resultSet.size(); List<T> recordList = new ArrayList<>(resultSize); RowIterator<Row> iterator = resultSet.iterator(); while (iterator.hasNext()) { Row row = iterator.next(); String jsonb = row.getValue(JSON_COLUMN).toString(); recordList.add(OBJECT_MAPPER.readValue(jsonb, clazz)); totalRecords = row.getInteger("count"); } totalRecords = PostgresClient.getTotalRecords(resultSize, totalRecords, offset, limit); return collection(collectionClazz, recordList, totalRecords); } /** * Anticipate whether {@link #getWithOptimizedSql} will optimize for query * @param cql CQL query string * @param column sorting criteria to check for (eg "title") * @return null if not eligible; CQL sort node it would be optimized */ public static CQLSortNode checkOptimizedCQL(String cql, String column) { CQLSortNode cqlSortNode = getSortNode(cql); if (cqlSortNode == null) { return null; } List<ModifierSet> sortIndexes = cqlSortNode.getSortIndexes(); if (sortIndexes.size() != 1) { return null; } ModifierSet modifierSet = sortIndexes.get(0); if (! modifierSet.getBase().equals(column)) { return null; } return cqlSortNode; } /** * Generate optimized sql given a specific cql query, tenant, index column name hint and configurable size to hinge the optimization on. * * @param column the column that has an index to be used for sorting * @param preparedCql the cql query * @param offset start index of objects to return * @param limit max number of objects to return * @throws QueryValidationException * @return the generated SQL string, or null if the CQL query is not suitable for optimization. */ static String generateOptimizedSql(String column, PreparedCQL preparedCql, int offset, int limit) throws QueryValidationException { String cql = preparedCql.getCqlWrapper().getQuery(); CQLSortNode cqlSortNode = checkOptimizedCQL(cql, column); if (cqlSortNode == null) { return null; } List<ModifierSet> sortIndexes = cqlSortNode.getSortIndexes(); ModifierSet modifierSet = sortIndexes.get(0); String ascDesc = getAscDesc(modifierSet); cql = cqlSortNode.getSubtree().toCQL(); String lessGreater = ""; if (ascDesc.equals("DESC")) { lessGreater = ">" ; } else { lessGreater = "<"; } String tableName = preparedCql.getFullTableName(); String where = preparedCql.getCqlWrapper().getField().toSql(cql).getWhere(); // If there are many matches use a full table scan in data_column sort order // using the data_column index, but stop this scan after OPTIMIZED_SQL_SIZE index entries. // Otherwise use full text matching because there are only a few matches. // // "headrecords" are the matching records found within the first OPTIMIZED_SQL_SIZE records // by stopping at the data_column from "OFFSET OPTIMIZED_SQL_SIZE LIMIT 1". // If "headrecords" are enough to return the requested "LIMIT" number of records we are done. // Otherwise use the full text index to create "allrecords" with all matching // records and do sorting and LIMIT afterwards. String wrappedColumn = "lower(f_unaccent(jsonb->>'" + column + "')) "; String cutWrappedColumn = "left(" + wrappedColumn + ",600) "; String countSql = "(" + preparedCql.getSchemaName() + ".count_estimate('" + " SELECT " + StringEscapeUtils.escapeSql(wrappedColumn) + " AS data_column " + " FROM " + tableName + " " + " WHERE " + StringEscapeUtils.escapeSql(where) + "')) AS count"; String sql = " WITH " + " headrecords AS (" + " SELECT jsonb, (" + wrappedColumn + ") AS data_column FROM " + tableName + " WHERE (" + where + ")" + " AND " + cutWrappedColumn + lessGreater + " ( SELECT " + cutWrappedColumn + " FROM " + tableName + " ORDER BY " + cutWrappedColumn + ascDesc + " OFFSET " + optimizedSqlSize + " LIMIT 1" + " )" + " ORDER BY " + cutWrappedColumn + ascDesc + " LIMIT " + limit + " OFFSET " + offset + " ), " + " allrecords AS (" + " SELECT jsonb, " + wrappedColumn + " AS data_column FROM " + tableName + " WHERE (" + where + ")" + " AND (SELECT COUNT(*) FROM headrecords) < " + limit + " )" + " SELECT jsonb, data_column, " + countSql + " FROM headrecords" + " WHERE (SELECT COUNT(*) FROM headrecords) >= " + limit + " UNION" + " (SELECT jsonb, data_column, " + countSql + " FROM allrecords" + " ORDER BY data_column " + ascDesc + " LIMIT " + limit + " OFFSET " + offset + " )" + " ORDER BY data_column " + ascDesc; logger.info("optimized SQL generated from CQL: " + sql); return sql; } static class PreparedCQL { private final String tableName; private final String fullTableName; private final CQLWrapper cqlWrapper; private final String schemaName; public PreparedCQL(String tableName, CQLWrapper cqlWrapper, Map<String, String> okapiHeaders) { String tenantId = TenantTool.tenantId(okapiHeaders); this.tableName = tableName; this.cqlWrapper = cqlWrapper; schemaName = PostgresClient.convertToPsqlStandard(tenantId); fullTableName = schemaName + "." + tableName; } public String getTableName() { return tableName; } public String getSchemaName() { return schemaName; } /** * @return full table name including schema, for example * tenant_mymodule.users */ public String getFullTableName() { return fullTableName; } public CQLWrapper getCqlWrapper() { return cqlWrapper; } } }
Remove extra log stmt
domain-models-runtime/src/main/java/org/folio/rest/persist/PgUtil.java
Remove extra log stmt
<ide><path>omain-models-runtime/src/main/java/org/folio/rest/persist/PgUtil.java <ide> itemString = OBJECT_MAPPER.writeValueAsString(res); <ide> } catch (JsonProcessingException ex) { <ide> logger.error(ex.getMessage(), ex); <del> logger.error(ex.getMessage(), ex); <ide> throw new IllegalArgumentException(ex.getCause()); <ide> } <ide> if (first.get()) {
Java
bsd-3-clause
aa19d96034a08513be13f8967d81d5cb9ae0fecf
0
NCIP/iso21090
package gov.nih.nci.iso21090.grid.dto.transform; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import java.io.StringReader; import java.io.StringWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.namespace.QName; import javax.xml.transform.stream.StreamSource; import org.junit.Before; import org.junit.Test; /** * To write a converter test, extend this class and follow public method pairs to generate data, and verify the * converted value. The methods are paired by their name patters: - makeXmlZZZ and verifyDtoZZZ, or - makeDtoZZZ and * verifyXmlZZZ. * * @author gax */ @SuppressWarnings("unchecked") public abstract class AbstractTransformerTestBase<T extends Transformer<XML, DTO>, XML, DTO> { private final int NUM_OBJ_TO_CONVERT = 10; protected final Class<T> tClass; protected final Class<XML> xmlClass; protected final Class<DTO> dtoClass; { ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass(); final Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); if (actualTypeArguments[0] instanceof Class) { tClass = (Class<T>) actualTypeArguments[0]; } else { tClass = (Class<T>) ((ParameterizedType) actualTypeArguments[0]).getRawType(); } xmlClass = (Class<XML>) actualTypeArguments[1]; if (actualTypeArguments[2] instanceof Class) { dtoClass = (Class<DTO>) actualTypeArguments[2]; } else { dtoClass = (Class<DTO>) ((ParameterizedType) actualTypeArguments[2]).getActualTypeArguments()[0]; } } protected T transformer; private Method[] makers; private Method[] verifiers; private void setUpTests() { Method[] methods = getClass().getMethods(); Hashtable<String, Method> makerMap = new Hashtable<String, Method>(); Hashtable<String, Method> verifierMap = new Hashtable<String, Method>(); for (Method m : methods) { String n = m.getName(); if (n.startsWith("make")) { makerMap.put(n.substring("make".length()), m); } else if (n.startsWith("verify")) { verifierMap.put(n.substring("verify".length()), m); } } makers = new Method[makerMap.size()]; verifiers = new Method[makers.length]; int i = 0; for (Map.Entry<String, Method> e : makerMap.entrySet()) { makers[i] = e.getValue(); String vn = null; if (e.getKey().startsWith("Xml")) { vn = "Dto" + e.getKey().substring(3); } else if (e.getKey().startsWith("Dto")) { vn = "Xml" + e.getKey().substring(3); } else { fail("method name should be makeXml* or makeDto*, but was make" + e.getKey()); } verifiers[i] = verifierMap.remove(vn); assertNotNull("make" + e.getKey() + "() needs a matching verify" + vn + "()", verifiers[i]); // System.out.println("matched "+makers[i]+" to "+verifiers[i]); i++; } if (!verifierMap.isEmpty()) { fail(" found verifier(s) w/o matching makers : " + verifierMap.toString()); } } public abstract XML makeXmlSimple() throws DtoTransformException; public abstract DTO makeDtoSimple() throws DtoTransformException; public abstract void verifyXmlSimple(XML x) throws DtoTransformException; public abstract void verifyDtoSimple(DTO x) throws DtoTransformException; public void testXmlConvert() throws DtoTransformException { // create list of XML objects XML[] arr = transformer.createXmlArray(NUM_OBJ_TO_CONVERT); for (int i = 0 ; i < NUM_OBJ_TO_CONVERT ; i++) { arr[i] = makeXmlSimple(); } //test null XML[] nullArr = null; assertNull(transformer.convert(nullArr)); List<DTO> dtos = transformer.convert(arr); for (DTO dto : dtos) { verifyDtoSimple(dto); } } public void testDtoConvert() throws DtoTransformException { // create list of DTO objects List<DTO> dtos = new ArrayList<DTO>(); for (int i = 0 ; i < NUM_OBJ_TO_CONVERT ; i++) { dtos.add(makeDtoSimple()); } //test null List<DTO> nullList = null; assertNull(transformer.convert(nullList)); XML[] isos = transformer.convert(dtos); for (int i = 0 ; i < NUM_OBJ_TO_CONVERT ; i++) { verifyXmlSimple(isos[i]); } } public XML makeXmlNull() { return null; } public DTO makeDtoNull() { return null; } public void verifyXmlNull(XML x) { assertNull(x); } public void verifyDtoNull(DTO x) { assertNull(x); } @Before public void initTransformer() { try { transformer = (T) tClass.getField("INSTANCE").get(null); } catch (Exception ex) { throw new Error(ex); } } @Test public void testAll() throws DtoTransformException { setUpTests(); for (int i = 0; i < makers.length; i++) { testOne(makers[i], verifiers[i]); } testDtoConvert(); testXmlConvert(); } private void testOne(Method make, Method verify) { testConversion(make, verify); if (make.getName().startsWith("makeXml")) { testRoundTripXml(make, verify); } else { testRoundTripDto(make, verify); } } private void testConversion(Method make, Method verify) { try { Object o = make.invoke(this); Object converted; if (make.getName().startsWith("makeXml")) { converted = transformer.toDto((XML) o); } else { converted = transformer.toXml((DTO) o); } verify.invoke(this, converted); } catch (InvocationTargetException ex) { if (ex.getTargetException() instanceof Error) { throw (Error) ex.getTargetException(); } throw new RuntimeException(make.getName(), ex.getTargetException()); } catch (Exception ex) { throw new RuntimeException(make.getName(), ex); } } private void testRoundTripXml(Method make, Method verify) { try { XML x = (XML) make.invoke(this); JAXBContext jaxbContext = JAXBContext.newInstance(xmlClass.getPackage().getName()); StringWriter sw = new StringWriter(); jaxbContext.createMarshaller().marshal(new JAXBElement(new QName("foo"), xmlClass, x), sw); String xml = sw.getBuffer().toString(); StreamSource s = new StreamSource(new StringReader(xml)); XML x2 = jaxbContext.createUnmarshaller().unmarshal(s, xmlClass).getValue(); DTO d = transformer.toDto(x2); verify.invoke(this, d); } catch (InvocationTargetException ex) { if (ex.getTargetException() instanceof Error) { throw (Error) ex.getTargetException(); } throw new RuntimeException(make.getName(), ex.getTargetException()); } catch (Exception ex) { throw new RuntimeException(make.getName(), ex); } } private void testRoundTripDto(Method make, Method verify) { try { DTO d = (DTO) make.invoke(this); XML x = transformer.toXml(d); JAXBContext jaxbContext = JAXBContext.newInstance(xmlClass.getPackage().getName()); StringWriter sw = new StringWriter(); jaxbContext.createMarshaller().marshal(new JAXBElement(new QName("foo"), xmlClass, x), sw); String xml = sw.getBuffer().toString(); StreamSource s = new StreamSource(new StringReader(xml)); XML x2 = jaxbContext.createUnmarshaller().unmarshal(s, xmlClass).getValue(); verify.invoke(this, x2); } catch (InvocationTargetException ex) { if (ex.getTargetException() instanceof Error) { throw (Error) ex.getTargetException(); } throw new RuntimeException(make.getName(), ex.getTargetException()); } catch (Exception ex) { throw new RuntimeException(make.getName(), ex); } } }
code/extensions/src/test/java/gov/nih/nci/iso21090/grid/dto/transform/AbstractTransformerTestBase.java
package gov.nih.nci.iso21090.grid.dto.transform; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import java.io.StringReader; import java.io.StringWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.namespace.QName; import javax.xml.transform.stream.StreamSource; import org.junit.Before; import org.junit.Test; /** * To write a converter test, extend this class and follow public method pairs to generate data, and verify the * converted value. The methods are paired by their name patters: - makeXmlZZZ and verifyDtoZZZ, or - makeDtoZZZ and * verifyXmlZZZ. * * @author gax */ @SuppressWarnings("unchecked") public abstract class AbstractTransformerTestBase<T extends Transformer<XML, DTO>, XML, DTO> { private final int NUM_OBJ_TO_CONVERT = 10; protected final Class<T> tClass; protected final Class<XML> xmlClass; protected final Class<DTO> dtoClass; { ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass(); final Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); if (actualTypeArguments[0] instanceof Class) { tClass = (Class<T>) actualTypeArguments[0]; } else { tClass = (Class<T>) ((ParameterizedType) actualTypeArguments[0]).getRawType(); } xmlClass = (Class<XML>) actualTypeArguments[1]; if (actualTypeArguments[2] instanceof Class) { dtoClass = (Class<DTO>) actualTypeArguments[2]; } else { dtoClass = (Class<DTO>) ((ParameterizedType) actualTypeArguments[2]).getActualTypeArguments()[0]; } } protected T transformer; private Method[] makers; private Method[] verifiers; private void setUpTests() { Method[] methods = getClass().getMethods(); Hashtable<String, Method> makerMap = new Hashtable<String, Method>(); Hashtable<String, Method> verifierMap = new Hashtable<String, Method>(); for (Method m : methods) { String n = m.getName(); if (n.startsWith("make")) { makerMap.put(n.substring("make".length()), m); } else if (n.startsWith("verify")) { verifierMap.put(n.substring("verify".length()), m); } } makers = new Method[makerMap.size()]; verifiers = new Method[makers.length]; int i = 0; for (Map.Entry<String, Method> e : makerMap.entrySet()) { makers[i] = e.getValue(); String vn = null; if (e.getKey().startsWith("Xml")) { vn = "Dto" + e.getKey().substring(3); } else if (e.getKey().startsWith("Dto")) { vn = "Xml" + e.getKey().substring(3); } else { fail("method name should be makeXml* or makeDto*, but was make" + e.getKey()); } verifiers[i] = verifierMap.remove(vn); assertNotNull("make" + e.getKey() + "() needs a matching verify" + vn + "()", verifiers[i]); // System.out.println("matched "+makers[i]+" to "+verifiers[i]); i++; } if (!verifierMap.isEmpty()) { fail(" found verifier(s) w/o matching makers : " + verifierMap.toString()); } } public abstract XML makeXmlSimple() throws DtoTransformException; public abstract DTO makeDtoSimple() throws DtoTransformException; public abstract void verifyXmlSimple(XML x) throws DtoTransformException; public abstract void verifyDtoSimple(DTO x) throws DtoTransformException; public void testXmlConvert() throws DtoTransformException { // create list of XML objects XML[] arr = transformer.createXmlArray(NUM_OBJ_TO_CONVERT); for (int i = 0 ; i < NUM_OBJ_TO_CONVERT ; i++) { arr[i] = makeXmlSimple(); } //test null XML[] nullArr = null; assertNull(transformer.convert(nullArr)); List<DTO> dtos = transformer.convert(arr); for (DTO dto : dtos) { verifyDtoSimple(dto); } } public void testDtoConvert() throws DtoTransformException { // create list of DTO objects List<DTO> dtos = new ArrayList<DTO>(); for (int i = 0 ; i < NUM_OBJ_TO_CONVERT ; i++) { dtos.add(makeDtoSimple()); } //test null List<DTO> nullList = null; assertNull(transformer.convert(nullList)); XML[] isos = transformer.convert(dtos); for (int i = 0 ; i < NUM_OBJ_TO_CONVERT ; i++) { verifyXmlSimple(isos[i]); } } public XML makeXmlNull() { return null; } public DTO makeDtoNull() { return null; } public void verifyXmlNull(XML x) { assertNull(x); } public void verifyDtoNull(DTO x) { assertNull(x); } @Before public void initTransformer() { try { transformer = (T) tClass.getField("INSTANCE").get(null); } catch (Exception ex) { throw new Error(ex); } } @Test public void testAll() throws DtoTransformException { setUpTests(); for (int i = 0; i < makers.length; i++) { testOne(makers[i], verifiers[i]); } testDtoConvert(); testXmlConvert(); } private void testOne(Method make, Method verify) { testConversion(make, verify); if (make.getName().startsWith("makeXml")) { testRoudTripXml(make, verify); } else { testRoundTripDto(make, verify); } } private void testConversion(Method make, Method verify) { try { Object o = make.invoke(this); Object converted; if (make.getName().startsWith("makeXml")) { converted = transformer.toDto((XML) o); } else { converted = transformer.toXml((DTO) o); } verify.invoke(this, converted); } catch (InvocationTargetException ex) { if (ex.getTargetException() instanceof Error) { throw (Error) ex.getTargetException(); } throw new RuntimeException(make.getName(), ex.getTargetException()); } catch (Exception ex) { throw new RuntimeException(make.getName(), ex); } } private void testRoudTripXml(Method make, Method verify) { try { XML x = (XML) make.invoke(this); JAXBContext jaxbContext = JAXBContext.newInstance(xmlClass.getPackage().getName()); StringWriter sw = new StringWriter(); jaxbContext.createMarshaller().marshal(new JAXBElement(new QName("foo"), xmlClass, x), sw); String xml = sw.getBuffer().toString(); StreamSource s = new StreamSource(new StringReader(xml)); XML x2 = jaxbContext.createUnmarshaller().unmarshal(s, xmlClass).getValue(); DTO d = transformer.toDto(x2); verify.invoke(this, d); } catch (InvocationTargetException ex) { if (ex.getTargetException() instanceof Error) { throw (Error) ex.getTargetException(); } throw new RuntimeException(make.getName(), ex.getTargetException()); } catch (Exception ex) { throw new RuntimeException(make.getName(), ex); } } private void testRoundTripDto(Method make, Method verify) { try { DTO d = (DTO) make.invoke(this); XML x = transformer.toXml(d); JAXBContext jaxbContext = JAXBContext.newInstance(xmlClass.getPackage().getName()); StringWriter sw = new StringWriter(); jaxbContext.createMarshaller().marshal(new JAXBElement(new QName("foo"), xmlClass, x), sw); String xml = sw.getBuffer().toString(); StreamSource s = new StreamSource(new StringReader(xml)); XML x2 = jaxbContext.createUnmarshaller().unmarshal(s, xmlClass).getValue(); verify.invoke(this, x2); } catch (InvocationTargetException ex) { if (ex.getTargetException() instanceof Error) { throw (Error) ex.getTargetException(); } throw new RuntimeException(make.getName(), ex.getTargetException()); } catch (Exception ex) { throw new RuntimeException(make.getName(), ex); } } }
minor: correct method spelling SVN-Revision: 318
code/extensions/src/test/java/gov/nih/nci/iso21090/grid/dto/transform/AbstractTransformerTestBase.java
minor: correct method spelling
<ide><path>ode/extensions/src/test/java/gov/nih/nci/iso21090/grid/dto/transform/AbstractTransformerTestBase.java <ide> private void testOne(Method make, Method verify) { <ide> testConversion(make, verify); <ide> if (make.getName().startsWith("makeXml")) { <del> testRoudTripXml(make, verify); <add> testRoundTripXml(make, verify); <ide> } else { <ide> testRoundTripDto(make, verify); <ide> } <ide> <ide> } <ide> <del> private void testRoudTripXml(Method make, Method verify) { <add> private void testRoundTripXml(Method make, Method verify) { <ide> try { <ide> XML x = (XML) make.invoke(this); <ide>
JavaScript
mit
b05af84f190e7958fd02b2e69dfa8190424b24cb
0
dmarcelino/sails-redis,camel-chased/sails-redis,balderdashy/sails-redis,jpwilliams/sails-aerospike,aradnom/sails-redis,apowers313/sails-redis
/** * `Transaction` dependencies */ var redis = require('redis'), utils = require('./utils'); /** * Expose `Transaction` */ module.exports = Transaction; /** * A container object for executing redis commands * * @param {Object} config */ function Transaction(config) { this.connection = null; this.definitions = {}; } /** * Overwrite config object with a new config object. * * @param {Object} config */ Transaction.prototype.configure = function(config) { this.config = utils.extend(this.config, config); }; /** * Return the key name for a record * * @param {String} collection * @param {Number|String} key */ Transaction.prototype.retrieveKey = function(collection, key) { var k = key ? ':' + key : '', pk = this.retrieve(collection); return 'waterline:' + collection + ':' + pk + k; }; /** * Register primary key in `this.definitions` * * @param {Object} collection */ Transaction.prototype.register = function(collection) { var pk; // Retrieve primary key from schema definition if(typeof collection.definition.id !== 'undefined' && collection.definition.id.primaryKey) { pk = 'id'; } else { for(var attr in collection.definition) { if(collection.definition[attr].primaryKey) { pk = attr; break; } } } this.definitions[collection.identity] = pk; }; /** * Retrieve registered primary key * * @param {String} collection */ Transaction.prototype.retrieve = function(collection) { var def = this.definitions[collection]; if(typeof def === 'undefined') throw new Error(collection + ' not registered.'); return def; }; /** * Connect to the redis instance * * @param {Function} callback */ Transaction.prototype.connect = function(callback) { var config = this.config; if(this.connection !== null) return callback(); this.connection = config.password !== null ? redis.createClient(config.port, config.host, config.options).auth(config.password) : redis.createClient(config.port, config.host, config.options); this.connection.once('ready', callback); }; /** * Disconnect from the redis instance */ Transaction.prototype.disconnect = function(callback) { this.connection.quit(); this.connection = null; if(typeof callback === 'function') { callback.apply(null, Array.prototype.slice.call(arguments, 1)); } }; /** * Execute `callback` in the context of `this.connection` * * @param {Function} callback */ Transaction.prototype.exec = function(callback) { var self = this; this.connect(function() { // On ready execute callback in the context of `this.connection`, // if there are arguments in the callback, pass disconnect to be called at the end. if(callback.length) return callback.call(self, self.disconnect.bind(self)); // Otherwise just call the function, and disconnect. callback.call(self.connection); self.disconnect(); }); };
lib/transaction.js
/** * `Transaction` dependencies */ var redis = require('redis'), utils = require('./utils'); /** * Expose `Transaction` */ module.exports = Transaction; /** * A container object for executing redis commands * * @param {Object} config */ function Transaction(config) { this.config = config; } /** * Connect to the redis instance */ Transaction.prototype.connect = function() { this.connection = utils.connect(this.config); }; /** * Disconnect from the redis instance */ Transaction.prototype.disconnect = function() { this.connection.quit(); this.connection = null; }; /** * Execute `callback` in the context of `this.connection` * * @param {Function} callback */ Transaction.prototype.exec = function(callback) { var self = this; this.connect(); this.connection.once('ready', function() { callback.call(self.connection); // Execute transaction block self.disconnect(); }); };
expand on transaction object
lib/transaction.js
expand on transaction object
<ide><path>ib/transaction.js <ide> */ <ide> <ide> function Transaction(config) { <del> this.config = config; <add> this.connection = null; <add> this.definitions = {}; <ide> } <ide> <ide> /** <del> * Connect to the redis instance <add> * Overwrite config object with a new config object. <add> * <add> * @param {Object} config <ide> */ <ide> <del>Transaction.prototype.connect = function() { <del> this.connection = utils.connect(this.config); <add>Transaction.prototype.configure = function(config) { <add> this.config = utils.extend(this.config, config); <add>}; <add> <add>/** <add> * Return the key name for a record <add> * <add> * @param {String} collection <add> * @param {Number|String} key <add> */ <add> <add>Transaction.prototype.retrieveKey = function(collection, key) { <add> var k = key ? ':' + key : '', <add> pk = this.retrieve(collection); <add> <add> return 'waterline:' + collection + ':' + pk + k; <add>}; <add> <add>/** <add> * Register primary key in `this.definitions` <add> * <add> * @param {Object} collection <add> */ <add> <add>Transaction.prototype.register = function(collection) { <add> var pk; <add> <add> // Retrieve primary key from schema definition <add> if(typeof collection.definition.id !== 'undefined' && <add> collection.definition.id.primaryKey) { <add> pk = 'id'; <add> } else { <add> for(var attr in collection.definition) { <add> if(collection.definition[attr].primaryKey) { <add> pk = attr; <add> break; <add> } <add> } <add> } <add> <add> this.definitions[collection.identity] = pk; <add>}; <add> <add>/** <add> * Retrieve registered primary key <add> * <add> * @param {String} collection <add> */ <add> <add>Transaction.prototype.retrieve = function(collection) { <add> var def = this.definitions[collection]; <add> <add> if(typeof def === 'undefined') throw new Error(collection + ' not registered.'); <add> return def; <add>}; <add> <add>/** <add> * Connect to the redis instance <add> * <add> * @param {Function} callback <add> */ <add> <add>Transaction.prototype.connect = function(callback) { <add> var config = this.config; <add> <add> if(this.connection !== null) return callback(); <add> this.connection = config.password !== null ? <add> redis.createClient(config.port, config.host, config.options).auth(config.password) : <add> redis.createClient(config.port, config.host, config.options); <add> <add> this.connection.once('ready', callback); <ide> }; <ide> <ide> /** <ide> * Disconnect from the redis instance <ide> */ <ide> <del>Transaction.prototype.disconnect = function() { <add>Transaction.prototype.disconnect = function(callback) { <ide> this.connection.quit(); <ide> this.connection = null; <add> if(typeof callback === 'function') { <add> callback.apply(null, Array.prototype.slice.call(arguments, 1)); <add> } <ide> }; <ide> <ide> /** <ide> Transaction.prototype.exec = function(callback) { <ide> var self = this; <ide> <del> this.connect(); <del> this.connection.once('ready', function() { <del> callback.call(self.connection); // Execute transaction block <add> this.connect(function() { <add> // On ready execute callback in the context of `this.connection`, <add> // if there are arguments in the callback, pass disconnect to be called at the end. <add> if(callback.length) return callback.call(self, self.disconnect.bind(self)); <add> <add> // Otherwise just call the function, and disconnect. <add> callback.call(self.connection); <ide> self.disconnect(); <ide> }); <ide> };
JavaScript
apache-2.0
3dbda674ffdd2d3bcb84137d8e71502aaa5a824a
0
ajnsit/dreamwriter,manesiotise/dreamwriter,makyo/dreamwriter,Softsapiens/dreamwriter,rtfeldman/dreamwriter,manesiotise/dreamwriter,Softsapiens/dreamwriter,jlongster/dreamwriter,makyo/dreamwriter,ajnsit/dreamwriter,jlongster/dreamwriter,Iced-Tea/dreamwriter,Iced-Tea/dreamwriter,rtfeldman/dreamwriter,zztczcx/dreamwriter,zztczcx/dreamwriter
// Generated by CoffeeScript 1.3.3 (function() { var IdbAdapter, Vault, VaultStore, applyDefaults, debug, defaultOptions, getTransactionMode, root, _ref, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; Vault = (function() { Vault.prototype.stores = {}; function Vault(options) { var db, storeName, storeOptions, _i, _len, _ref, _ref1, _ref2, _ref3, _this = this; if (options == null) { options = {}; } applyDefaults(options, defaultOptions); _ref = options.stores; for (storeName in _ref) { storeOptions = _ref[storeName]; applyDefaults(storeOptions, options.storeDefaults); storeOptions.name = (_ref1 = storeOptions.name) != null ? _ref1 : storeName; } db = new IdbAdapter(options); if (options.stores instanceof Array) { _ref2 = options.stores; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { storeName = _ref2[_i]; storeOptions = applyDefaults({ name: storeName }, options.storeDefaults); this.stores[storeName] = new VaultStore(db, storeOptions); } } else { _ref3 = options.stores; for (storeName in _ref3) { storeOptions = _ref3[storeName]; this.stores[storeName] = new VaultStore(db, storeOptions); } } db.on('load', function() { if (options.onready) { return options.onready(_this.stores); } }); } return Vault; })(); defaultOptions = { name: 'vault', stores: {}, storeDefaults: { keyName: 'key' } }; applyDefaults = function(object, defaults) { var key, value; for (key in defaults) { value = defaults[key]; if (object[key] == null) { object[key] = defaults[key]; } } return object; }; if (typeof module !== "undefined" && module !== null) { module.exports = Vault; } if (typeof window !== "undefined" && window !== null) { window.Vault = Vault; } root = (_ref = typeof window !== "undefined" && window !== null ? window : exports) != null ? _ref : this; IdbAdapter = (function() { function IdbAdapter(options) { this.openCursor = __bind(this.openCursor, this); this.dbDo = __bind(this.dbDo, this); this.getStore = __bind(this.getStore, this); this.doWhenReady = __bind(this.doWhenReady, this); this.fireEvent = __bind(this.fireEvent, this); this.off = __bind(this.off, this); this.on = __bind(this.on, this); var onload, problem, problems, request, upgrade, _i, _len, _ref1, _ref2, _ref3, _ref4, _ref5, _this = this; applyDefaults(options, defaultOptions); this.eventListeners = {}; this.deferredUntilLoad = []; this.loaded = false; root.indexedDB = root.indexedDB || root.webkitIndexedDB || root.mozIndexedDB || root.msIndexedDB; root.IDBTransaction = (_ref1 = root.IDBTransaction) != null ? _ref1 : root.webkitIDBTransaction; root.IDBKeyRange = (_ref2 = root.IDBKeyRange) != null ? _ref2 : root.webkitIDBKeyRange; problems = []; if (!root.indexedDB) { problems.push("Could not initialize IndexedDB - no indexedDB present"); } if (!root.IDBTransaction) { problems.push("Could not initialize IndexedDB - no IDBTransaction present"); } if (!root.IDBKeyRange) { problems.push("Could not initialize IndexedDB - no IDBKeyRange present"); } if (!!problems.length) { for (_i = 0, _len = problems.length; _i < _len; _i++) { problem = problems[_i]; console.error(problem); } return; } //if (navigator.webkitTemporaryStorage != null) { // requestQuota((_ref5 = root.storageInfo) != null ? navigator.webkitTemporaryStorage : void 0, options.desiredQuotaBytes); //} upgrade = function(event) { var store, storeName, _j, _len1, _ref6, _ref7; _this.fireEvent('upgrade'); debug(function() { return "Creating database..."; }); if (options.stores instanceof Array) { _ref6 = options.stores; for (_j = 0, _len1 = _ref6.length; _j < _len1; _j++) { storeName = _ref6[_j]; _this.db.createObjectStore(storeName, { keyPath: 'id' }); } } else { _ref7 = options.stores; for (storeName in _ref7) { store = _ref7[storeName]; _this.db.createObjectStore(storeName, { keyPath: store.keyName }); } } return debug(function() { return "Success. Database now at version \"" + options.version + "\""; }); }; onload = function(event) { var deferred, _j, _len1, _ref6; _ref6 = _this.deferredUntilLoad; for (_j = 0, _len1 = _ref6.length; _j < _len1; _j++) { deferred = _ref6[_j]; deferred(); } _this.loaded = true; return _this.fireEvent('load'); }; debug(function() { return "Attempting to open db version " + options.version; }); request = root.indexedDB.open(options.name, options.version); request.onupgradeneeded = function(event) { _this.db = event.target.result; return upgrade(event); }; request.onerror = this.onerror; request.onsuccess = function(e) { var setVersionRequest; _this.db = e.target.result; if (_this.db.version) { debug(function() { return "Opened db ver " + _this.db.version; }); } else { debug(function() { return "Opened new db"; }); } _this.db.onerror = _this.onerror; _this.db.onversionchange = function(event) { _this.db.close(); throw "An unexpected database version change occurred."; }; if ((_this.db.setVersion != null) && _this.db.version !== options.version) { setVersionRequest = _this.db.setVersion(options.version); setVersionRequest.onerror = _this.onerror; return setVersionRequest.onsuccess = function(event) { upgrade(event); return setVersionRequest.result.oncomplete = onload; }; } else { return onload(); } }; } IdbAdapter.prototype.onerror = function(event) { var msg, _ref1, _ref2; console.error(event); msg = (_ref1 = event != null ? (_ref2 = event.target) != null ? _ref2.webkitErrorMessage : void 0 : void 0) != null ? _ref1 : 'see console log for details'; throw "IndexedDB Error Code " + event.target.errorCode + " - " + msg; }; IdbAdapter.prototype.on = function(event, handler) { var listeners; if (typeof handler !== 'function') { throw "Invalid handler function for event " + event + ": " + handler; } listeners = this.eventListeners[event]; if (listeners) { return listeners.unshift(handler); } else { return this.eventListeners[event] = [handler]; } }; IdbAdapter.prototype.off = function(event, handler) { var currentHandler, listener, value, _i, _len, _ref1, _ref2, _results, _results1; if (handler) { _ref1 = this.eventListeners[event]; _results = []; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { currentHandler = _ref1[_i]; if (handler === currentHandler) { throw "unsupported"; } else { _results.push(void 0); } } return _results; } else if (event) { return this.eventListeners[event] = []; } else { _ref2 = this.eventListeners; _results1 = []; for (listener in _ref2) { value = _ref2[listener]; _results1.push(this.eventListeners[listener] = []); } return _results1; } }; IdbAdapter.prototype.fireEvent = function(eventName, event) { var closure, listeners, _i, _len, _results; listeners = this.eventListeners[eventName]; if (listeners) { _results = []; for (_i = 0, _len = listeners.length; _i < _len; _i++) { closure = listeners[_i]; if (closure) { _results.push(closure(event)); } else { _results.push(void 0); } } return _results; } }; IdbAdapter.prototype.doWhenReady = function(closure) { if (!this.loaded) { return this.deferredUntilLoad.unshift(closure); } else { return closure(); } }; IdbAdapter.prototype.getStore = function(storeName, mode, onTransactionComplete, onError) { var transaction; if (onError == null) { onError = this.onerror; } try { transaction = this.db.transaction([storeName], mode); transaction.onerror = onError; transaction.oncomplete = onTransactionComplete; return transaction.objectStore(storeName); } catch (err) { console.error("Could not get store " + storeName + " in mode " + mode); throw err; } }; IdbAdapter.prototype.dbDo = function(storeName, method, value, onSuccess, onError, onTransactionComplete, mode) { var _this = this; if (onError == null) { onError = this.onerror; } if (mode == null) { mode = getTransactionMode(method); } return this.doWhenReady(function() { var request, store; store = _this.getStore(storeName, mode, onTransactionComplete, onError); if (!store[method]) { throw "Store " + store + " does not have a method " + method; } debug(function() { return "" + storeName + "." + method + "(" + (value != null ? value : '') + ")"; }); try { if (!(value != null)) { request = store[method].call(store); } else if (value instanceof Array) { request = store[method].apply(store, value); } else { request = store[method].call(store, value); } } catch (err) { console.error("Could not execute " + storeName + "." + method + " with value:"); console.error(err); console.error(value); } request.onsuccess = onSuccess; request.onerror = onError; return _this.fireEvent(method, value); }); }; IdbAdapter.prototype.openCursor = function(storeName, onSuccess, onError, readOnly) { var method; if (readOnly == null) { readOnly = true; } method = readOnly ? "readonly" : "readwrite"; return this.dbDo(storeName, 'openCursor', void 0, onSuccess, onError, void 0, method); }; return IdbAdapter; })(); getTransactionMode = function(method) { if (method === 'put' || method === 'add' || method === 'delete' || method === 'clear') { return "readwrite"; } else { return "readonly"; } }; debug = function(getMessage) { var _ref1; if (root != null ? root.debug : void 0) { return root != null ? (_ref1 = root.console) != null ? _ref1.debug(getMessage()) : void 0 : void 0; } }; defaultOptions = { name: 'vault', version: '1', desiredQuotaBytes: 1024 * 1024 * 1024 * 1024, stores: {} }; if (typeof module !== "undefined" && module !== null) { module.exports = IdbAdapter; } if (typeof window !== "undefined" && window !== null) { window.IdbAdapter = IdbAdapter; } VaultStore = (function() { VaultStore.prototype.cache = {}; function VaultStore(db, options) { var key, _i, _len, _ref1; this.db = db; this.deleteEach = __bind(this.deleteEach, this); this.each = __bind(this.each, this); this.count = __bind(this.count, this); this.clear = __bind(this.clear, this); this["delete"] = __bind(this["delete"], this); this.add = __bind(this.add, this); this.put = __bind(this.put, this); this.get = __bind(this.get, this); this["do"] = __bind(this["do"], this); _ref1 = ['name', 'keyName']; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { key = _ref1[_i]; this[key] = options[key]; } if (!this.name) { throw "Cannot create a store with name " + this.name; } } VaultStore.prototype["do"] = function(method, args, success, error, cache) { var convertedSuccess, _this = this; convertedSuccess = function(response) { var _ref1; if (success) { return success(response != null ? (_ref1 = response.target) != null ? _ref1.result : void 0 : void 0); } }; return this.db.dbDo(this.name, method, args, convertedSuccess, error); }; VaultStore.prototype.get = function(id, success, error, cache) { if (id == null) { throw "Cannot get " + id + " from " + this.name; } return this["do"]('get', id, success, error, cache); }; VaultStore.prototype.put = function(obj, success, error, cache) { if (obj == null) { throw "Cannot put " + obj + " into " + this.name; } return this["do"]('put', obj, success, error, cache); }; VaultStore.prototype.add = function(obj, success, error, cache) { if (obj == null) { throw "Cannot add " + obj + " to " + this.name; } return this["do"]('add', obj, success, error, cache); }; VaultStore.prototype["delete"] = function(id, success, error, cache) { if (id == null) { throw "Cannot delete " + id + " from " + this.name; } return this["do"]('delete', id, success, error, cache); }; VaultStore.prototype.clear = function(success, error) { var _this = this; return this["do"]('clear', void 0, (function(response) { _this.cache = {}; if (success) { return success(response); } }), error); }; VaultStore.prototype.count = function(success, error, cache) { var count; count = 0; return this.each((function() { return count++; }), (function() { if (success) { return success(count); } }), error, cache); }; VaultStore.prototype.each = function(iterator, success, error, cache) { var cursorIterator, key, stopFunction, stopper, value, _ref1; if (cache) { _ref1 = this.db.cache[this.name]; for (key in _ref1) { value = _ref1[key]; stopper = {}; stopFunction = function() { return stopper.stop = true; }; iterator(key, value, stopFunction); if (stopper.stop) { if (success) { success(); } return; } } if (success) { return success(); } } else { cursorIterator = function(event) { var cursor, halt; cursor = event.target.result; if (cursor) { halt = false; iterator(cursor.key, cursor.value, (function() { return halt = true; })); if (halt) { if (success) { return success(); } } else { return cursor["continue"](); } } else { if (success) { return success(); } } }; return this.db.openCursor(this.name, cursorIterator, error); } }; VaultStore.prototype.deleteEach = function(iterator, success, error) { var cursorIterator; cursorIterator = function(event) { var cursor, halt, shouldDelete; cursor = event.target.result; if (cursor) { halt = false; shouldDelete = iterator(cursor.key, cursor.value, (function() { return halt = true; })); if (halt) { if (success) { return success(); } } else { try { if (shouldDelete) { cursor["delete"](); } } catch (err) { console.error(err); } return cursor["continue"](); } } else { if (success) { return success(); } } }; return this.db.openCursor(this.name, cursorIterator, error, false); }; return VaultStore; })(); if (typeof module !== "undefined" && module !== null) { module.exports = VaultStore; } if (typeof window !== "undefined" && window !== null) { window.VaultStore = VaultStore; } }).call(this);
vendor/vault-0.3.js
// Generated by CoffeeScript 1.3.3 (function() { var IdbAdapter, Vault, VaultStore, applyDefaults, debug, defaultOptions, getTransactionMode, root, _ref, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; Vault = (function() { Vault.prototype.stores = {}; function Vault(options) { var db, storeName, storeOptions, _i, _len, _ref, _ref1, _ref2, _ref3, _this = this; if (options == null) { options = {}; } applyDefaults(options, defaultOptions); _ref = options.stores; for (storeName in _ref) { storeOptions = _ref[storeName]; applyDefaults(storeOptions, options.storeDefaults); storeOptions.name = (_ref1 = storeOptions.name) != null ? _ref1 : storeName; } db = new IdbAdapter(options); if (options.stores instanceof Array) { _ref2 = options.stores; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { storeName = _ref2[_i]; storeOptions = applyDefaults({ name: storeName }, options.storeDefaults); this.stores[storeName] = new VaultStore(db, storeOptions); } } else { _ref3 = options.stores; for (storeName in _ref3) { storeOptions = _ref3[storeName]; this.stores[storeName] = new VaultStore(db, storeOptions); } } db.on('load', function() { if (options.onready) { return options.onready(_this.stores); } }); } return Vault; })(); defaultOptions = { name: 'vault', stores: {}, storeDefaults: { keyName: 'key' } }; applyDefaults = function(object, defaults) { var key, value; for (key in defaults) { value = defaults[key]; if (object[key] == null) { object[key] = defaults[key]; } } return object; }; if (typeof module !== "undefined" && module !== null) { module.exports = Vault; } if (typeof window !== "undefined" && window !== null) { window.Vault = Vault; } root = (_ref = typeof window !== "undefined" && window !== null ? window : exports) != null ? _ref : this; IdbAdapter = (function() { function IdbAdapter(options) { this.openCursor = __bind(this.openCursor, this); this.dbDo = __bind(this.dbDo, this); this.getStore = __bind(this.getStore, this); this.doWhenReady = __bind(this.doWhenReady, this); this.fireEvent = __bind(this.fireEvent, this); this.off = __bind(this.off, this); this.on = __bind(this.on, this); var onload, problem, problems, request, upgrade, _i, _len, _ref1, _ref2, _ref3, _ref4, _ref5, _this = this; applyDefaults(options, defaultOptions); this.eventListeners = {}; this.deferredUntilLoad = []; this.loaded = false; root.indexedDB = root.indexedDB || root.webkitIndexedDB || root.mozIndexedDB || root.msIndexedDB; root.IDBTransaction = (_ref1 = root.IDBTransaction) != null ? _ref1 : root.webkitIDBTransaction; root.IDBKeyRange = (_ref2 = root.IDBKeyRange) != null ? _ref2 : root.webkitIDBKeyRange; root.storageInfo = (_ref3 = root.storageInfo) != null ? _ref3 : root.webkitStorageInfo; problems = []; if (!root.indexedDB) { problems.push("Could not initialize IndexedDB - no indexedDB present"); } if (!root.IDBTransaction) { problems.push("Could not initialize IndexedDB - no IDBTransaction present"); } if (!root.IDBKeyRange) { problems.push("Could not initialize IndexedDB - no IDBKeyRange present"); } if (!!problems.length) { for (_i = 0, _len = problems.length; _i < _len; _i++) { problem = problems[_i]; console.error(problem); } return; } if ((_ref4 = root.storageInfo) != null) { _ref4.requestQuota((_ref5 = root.storageInfo) != null ? _ref5.TEMPORARY : void 0, options.desiredQuotaBytes); } upgrade = function(event) { var store, storeName, _j, _len1, _ref6, _ref7; _this.fireEvent('upgrade'); debug(function() { return "Creating database..."; }); if (options.stores instanceof Array) { _ref6 = options.stores; for (_j = 0, _len1 = _ref6.length; _j < _len1; _j++) { storeName = _ref6[_j]; _this.db.createObjectStore(storeName, { keyPath: 'id' }); } } else { _ref7 = options.stores; for (storeName in _ref7) { store = _ref7[storeName]; _this.db.createObjectStore(storeName, { keyPath: store.keyName }); } } return debug(function() { return "Success. Database now at version \"" + options.version + "\""; }); }; onload = function(event) { var deferred, _j, _len1, _ref6; _ref6 = _this.deferredUntilLoad; for (_j = 0, _len1 = _ref6.length; _j < _len1; _j++) { deferred = _ref6[_j]; deferred(); } _this.loaded = true; return _this.fireEvent('load'); }; debug(function() { return "Attempting to open db version " + options.version; }); request = root.indexedDB.open(options.name, options.version); request.onupgradeneeded = function(event) { _this.db = event.target.result; return upgrade(event); }; request.onerror = this.onerror; request.onsuccess = function(e) { var setVersionRequest; _this.db = e.target.result; if (_this.db.version) { debug(function() { return "Opened db ver " + _this.db.version; }); } else { debug(function() { return "Opened new db"; }); } _this.db.onerror = _this.onerror; _this.db.onversionchange = function(event) { _this.db.close(); throw "An unexpected database version change occurred."; }; if ((_this.db.setVersion != null) && _this.db.version !== options.version) { setVersionRequest = _this.db.setVersion(options.version); setVersionRequest.onerror = _this.onerror; return setVersionRequest.onsuccess = function(event) { upgrade(event); return setVersionRequest.result.oncomplete = onload; }; } else { return onload(); } }; } IdbAdapter.prototype.onerror = function(event) { var msg, _ref1, _ref2; console.error(event); msg = (_ref1 = event != null ? (_ref2 = event.target) != null ? _ref2.webkitErrorMessage : void 0 : void 0) != null ? _ref1 : 'see console log for details'; throw "IndexedDB Error Code " + event.target.errorCode + " - " + msg; }; IdbAdapter.prototype.on = function(event, handler) { var listeners; if (typeof handler !== 'function') { throw "Invalid handler function for event " + event + ": " + handler; } listeners = this.eventListeners[event]; if (listeners) { return listeners.unshift(handler); } else { return this.eventListeners[event] = [handler]; } }; IdbAdapter.prototype.off = function(event, handler) { var currentHandler, listener, value, _i, _len, _ref1, _ref2, _results, _results1; if (handler) { _ref1 = this.eventListeners[event]; _results = []; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { currentHandler = _ref1[_i]; if (handler === currentHandler) { throw "unsupported"; } else { _results.push(void 0); } } return _results; } else if (event) { return this.eventListeners[event] = []; } else { _ref2 = this.eventListeners; _results1 = []; for (listener in _ref2) { value = _ref2[listener]; _results1.push(this.eventListeners[listener] = []); } return _results1; } }; IdbAdapter.prototype.fireEvent = function(eventName, event) { var closure, listeners, _i, _len, _results; listeners = this.eventListeners[eventName]; if (listeners) { _results = []; for (_i = 0, _len = listeners.length; _i < _len; _i++) { closure = listeners[_i]; if (closure) { _results.push(closure(event)); } else { _results.push(void 0); } } return _results; } }; IdbAdapter.prototype.doWhenReady = function(closure) { if (!this.loaded) { return this.deferredUntilLoad.unshift(closure); } else { return closure(); } }; IdbAdapter.prototype.getStore = function(storeName, mode, onTransactionComplete, onError) { var transaction; if (onError == null) { onError = this.onerror; } try { transaction = this.db.transaction([storeName], mode); transaction.onerror = onError; transaction.oncomplete = onTransactionComplete; return transaction.objectStore(storeName); } catch (err) { console.error("Could not get store " + storeName + " in mode " + mode); throw err; } }; IdbAdapter.prototype.dbDo = function(storeName, method, value, onSuccess, onError, onTransactionComplete, mode) { var _this = this; if (onError == null) { onError = this.onerror; } if (mode == null) { mode = getTransactionMode(method); } return this.doWhenReady(function() { var request, store; store = _this.getStore(storeName, mode, onTransactionComplete, onError); if (!store[method]) { throw "Store " + store + " does not have a method " + method; } debug(function() { return "" + storeName + "." + method + "(" + (value != null ? value : '') + ")"; }); try { if (!(value != null)) { request = store[method].call(store); } else if (value instanceof Array) { request = store[method].apply(store, value); } else { request = store[method].call(store, value); } } catch (err) { console.error("Could not execute " + storeName + "." + method + " with value:"); console.error(err); console.error(value); } request.onsuccess = onSuccess; request.onerror = onError; return _this.fireEvent(method, value); }); }; IdbAdapter.prototype.openCursor = function(storeName, onSuccess, onError, readOnly) { var method; if (readOnly == null) { readOnly = true; } method = readOnly ? "readonly" : "readwrite"; return this.dbDo(storeName, 'openCursor', void 0, onSuccess, onError, void 0, method); }; return IdbAdapter; })(); getTransactionMode = function(method) { if (method === 'put' || method === 'add' || method === 'delete' || method === 'clear') { return "readwrite"; } else { return "readonly"; } }; debug = function(getMessage) { var _ref1; if (root != null ? root.debug : void 0) { return root != null ? (_ref1 = root.console) != null ? _ref1.debug(getMessage()) : void 0 : void 0; } }; defaultOptions = { name: 'vault', version: '1', desiredQuotaBytes: 1024 * 1024 * 1024 * 1024, stores: {} }; if (typeof module !== "undefined" && module !== null) { module.exports = IdbAdapter; } if (typeof window !== "undefined" && window !== null) { window.IdbAdapter = IdbAdapter; } VaultStore = (function() { VaultStore.prototype.cache = {}; function VaultStore(db, options) { var key, _i, _len, _ref1; this.db = db; this.deleteEach = __bind(this.deleteEach, this); this.each = __bind(this.each, this); this.count = __bind(this.count, this); this.clear = __bind(this.clear, this); this["delete"] = __bind(this["delete"], this); this.add = __bind(this.add, this); this.put = __bind(this.put, this); this.get = __bind(this.get, this); this["do"] = __bind(this["do"], this); _ref1 = ['name', 'keyName']; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { key = _ref1[_i]; this[key] = options[key]; } if (!this.name) { throw "Cannot create a store with name " + this.name; } } VaultStore.prototype["do"] = function(method, args, success, error, cache) { var convertedSuccess, _this = this; convertedSuccess = function(response) { var _ref1; if (success) { return success(response != null ? (_ref1 = response.target) != null ? _ref1.result : void 0 : void 0); } }; return this.db.dbDo(this.name, method, args, convertedSuccess, error); }; VaultStore.prototype.get = function(id, success, error, cache) { if (id == null) { throw "Cannot get " + id + " from " + this.name; } return this["do"]('get', id, success, error, cache); }; VaultStore.prototype.put = function(obj, success, error, cache) { if (obj == null) { throw "Cannot put " + obj + " into " + this.name; } return this["do"]('put', obj, success, error, cache); }; VaultStore.prototype.add = function(obj, success, error, cache) { if (obj == null) { throw "Cannot add " + obj + " to " + this.name; } return this["do"]('add', obj, success, error, cache); }; VaultStore.prototype["delete"] = function(id, success, error, cache) { if (id == null) { throw "Cannot delete " + id + " from " + this.name; } return this["do"]('delete', id, success, error, cache); }; VaultStore.prototype.clear = function(success, error) { var _this = this; return this["do"]('clear', void 0, (function(response) { _this.cache = {}; if (success) { return success(response); } }), error); }; VaultStore.prototype.count = function(success, error, cache) { var count; count = 0; return this.each((function() { return count++; }), (function() { if (success) { return success(count); } }), error, cache); }; VaultStore.prototype.each = function(iterator, success, error, cache) { var cursorIterator, key, stopFunction, stopper, value, _ref1; if (cache) { _ref1 = this.db.cache[this.name]; for (key in _ref1) { value = _ref1[key]; stopper = {}; stopFunction = function() { return stopper.stop = true; }; iterator(key, value, stopFunction); if (stopper.stop) { if (success) { success(); } return; } } if (success) { return success(); } } else { cursorIterator = function(event) { var cursor, halt; cursor = event.target.result; if (cursor) { halt = false; iterator(cursor.key, cursor.value, (function() { return halt = true; })); if (halt) { if (success) { return success(); } } else { return cursor["continue"](); } } else { if (success) { return success(); } } }; return this.db.openCursor(this.name, cursorIterator, error); } }; VaultStore.prototype.deleteEach = function(iterator, success, error) { var cursorIterator; cursorIterator = function(event) { var cursor, halt, shouldDelete; cursor = event.target.result; if (cursor) { halt = false; shouldDelete = iterator(cursor.key, cursor.value, (function() { return halt = true; })); if (halt) { if (success) { return success(); } } else { try { if (shouldDelete) { cursor["delete"](); } } catch (err) { console.error(err); } return cursor["continue"](); } } else { if (success) { return success(); } } }; return this.db.openCursor(this.name, cursorIterator, error, false); }; return VaultStore; })(); if (typeof module !== "undefined" && module !== null) { module.exports = VaultStore; } if (typeof window !== "undefined" && window !== null) { window.VaultStore = VaultStore; } }).call(this);
Hack vault.js to avoid a warning.
vendor/vault-0.3.js
Hack vault.js to avoid a warning.
<ide><path>endor/vault-0.3.js <ide> root.indexedDB = root.indexedDB || root.webkitIndexedDB || root.mozIndexedDB || root.msIndexedDB; <ide> root.IDBTransaction = (_ref1 = root.IDBTransaction) != null ? _ref1 : root.webkitIDBTransaction; <ide> root.IDBKeyRange = (_ref2 = root.IDBKeyRange) != null ? _ref2 : root.webkitIDBKeyRange; <del> root.storageInfo = (_ref3 = root.storageInfo) != null ? _ref3 : root.webkitStorageInfo; <ide> problems = []; <ide> if (!root.indexedDB) { <ide> problems.push("Could not initialize IndexedDB - no indexedDB present"); <ide> } <ide> return; <ide> } <del> if ((_ref4 = root.storageInfo) != null) { <del> _ref4.requestQuota((_ref5 = root.storageInfo) != null ? _ref5.TEMPORARY : void 0, options.desiredQuotaBytes); <del> } <add> //if (navigator.webkitTemporaryStorage != null) { <add> // requestQuota((_ref5 = root.storageInfo) != null ? navigator.webkitTemporaryStorage : void 0, options.desiredQuotaBytes); <add> //} <ide> upgrade = function(event) { <ide> var store, storeName, _j, _len1, _ref6, _ref7; <ide> _this.fireEvent('upgrade');
Java
mpl-2.0
3b97dd848db4f1691ef5b860d43e241b81e4da3e
0
etomica/etomica,etomica/etomica,ajschult/etomica,etomica/etomica,ajschult/etomica,ajschult/etomica
//This class includes a main method to demonstrate its use package etomica.graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JTextField; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import etomica.Controller; import etomica.EtomicaElement; import etomica.EtomicaInfo; import etomica.Modifier; import etomica.event.ChangeEventManager; import etomica.modifier.ModifierGeneral; import etomica.modifier.ModifyAction; import etomica.units.Unit; import etomica.utility.DecimalSlider; import etomica.utility.StringUtility; /** * Device the changes a property using a graphical slider, via a Modifier. * * @see ModifierGeneral */ /* History * 10/08/02 (SKK) modified for DecimalSlider, textBox * 10/12/02 (DAK) added init method * 10/13/02 (DAK) restored nMajor and its accessor/mutator methods * changed graphic method to always return panel, never just slider * always adding slider to panel */ public class DeviceSlider extends Device implements EtomicaElement { /** * Descriptive text label to be displayed with the value * No longer used -- instead apply label via a title border on the slider itself */ private String label; /** * Modifier connecting the slider to the property */ protected ModifyAction modifier; /** * Subclass of Swing slider displayed to screen * located in utility package */ protected DecimalSlider slider; /** * Object with property being modulated */ protected Object component; /** * Property being modulated */ protected String property; /** * Values for maximum and minimum values of slider in double form */ private double minimum, maximum; /** * boolean showValues for showing values on textfield * boolean editvalus for editing the values in textfield, which change slider tip */ private boolean showValues, editValues; /* * To show slider with value in one */ private JPanel panel; /** * To show the values of slider */ private JTextField textField; /** * column of textfield to show the value of slider correctly with horizontal view * default value is five and affected if precision is greater than 5 */ private int column; /** * Layout instance to show slider and textfield */ private GridBagLayout gbLayout; private GridBagConstraints gbConst; private boolean showBorder = false; private int nMajor = 3; protected final ChangeEventManager changeEventManager = new ChangeEventManager(this); public DeviceSlider(Controller controller) { super(controller); init(); } /** * Constructs a slider connected to the given property of the given object */ public DeviceSlider(Controller controller, Object object, String property) { this(controller, new ModifierGeneral(object, property)); component = object; this.property = property; } /** * Constructs a slider connected to the get/set Value methods of the given Modifier */ public DeviceSlider(Controller controller, Modifier m) { this(controller); //set component and property in some way setModifier(m); } private void init() { textField = new JTextField(""); textField.setFont(new java.awt.Font("",0,15)); textField.setHorizontalAlignment(JTextField.CENTER); gbLayout = new GridBagLayout(); gbConst = new GridBagConstraints(); panel = new JPanel(); // panel.setBorder(new javax.swing.border.TitledBorder("JPST")); //JPanel of Slider and TextField setLabel(""); panel.setLayout(gbLayout); column = 5; slider = new DecimalSlider(); slider.setSize(200,40); slider.setPaintTicks(true); slider.setPaintLabels(true); slider.setDecimalSliderValue(300); setMinimum(100); setMaximum(500); slider.setDecimalSliderMajorTickSpacing(100); slider.setDecimalSliderMinorTickSpacing(50); slider.addChangeListener(new SliderListener()); //SliderListener is an inner class defined below gbConst.gridx = 0; gbConst.gridy = 0; gbLayout.setConstraints(getSlider(), gbConst); panel.add(getSlider()); setShowValues(false); // default is false to show values of slider setEditValues(false); // default is false to edit values of slider thru textField } public static EtomicaInfo getEtomicaInfo() { EtomicaInfo info = new EtomicaInfo(); info.setDescription("Slider-type device for changing a property"); return info; } /** * Override superclass setUnit method to update label when unit is changed */ public void setUnit(Unit u) { super.setUnit(u); setLabelDefault(); } public final void setModifier(Modifier m) { if(m == null) throw new NullPointerException(); modifier = null; if (unit == null) { setUnit(m.getDimension().defaultIOUnit()); } slider.setDecimalSliderValue(unit.fromSim(m.getValue())); modifier = new ModifyAction(m); targetAction = modifier; setLabelDefault(); setMinimum(getMinimum()); setMaximum(getMaximum()); } public final Modifier getModifier() {return modifier.getWrappedModifier();} public String getProperty() {return property;} public void setProperty(String s) { property = s; if(component != null) setModifier(new ModifierGeneral(component, property)); } public Object getComponent() {return component;} public void setComponent(Object obj) { component = obj; if(property != null) setModifier(new ModifierGeneral(component,property)); } public double getMinimum() {return minimum;} /** * Sets minimum value of slider; should be called after * any calls to setPrecision. */ public void setMinimum(double min) { minimum = min; ModifyAction tmpModifier = modifier; modifier = null; slider.setDecimalSliderMinimum(min); slider.setInverted(maximum < minimum); setTicks(); modifier = tmpModifier; } public double getMaximum() {return maximum;} /** * Sets maximum value of slider; should be called after * any calls to setPrecision. */ public void setMaximum(double max) { maximum = max; ModifyAction tmpModifier = modifier; modifier = null; slider.setDecimalSliderMaximum(max); slider.setInverted(maximum < minimum); setTicks(); modifier = tmpModifier; } private boolean showMinorValues = false; public void setShowMinorValues(boolean b){ showMinorValues = b; } public void setNMajor(int n) { nMajor = n; setTicks(); } public int getNMajor() {return nMajor;} private void setTicks() { double minorTick = 1.0 ; if(showMinorValues){ minorTick = 2;} double spacing = (getMaximum()-getMinimum())/nMajor; if(spacing <= 0) return; slider.setDecimalSliderMajorTickSpacing(spacing); slider.setDecimalSliderMinorTickSpacing(spacing/2.0); //need to do the following because JSlider does not automatically //reset labels if they have been set before slider.setDecimalSliderLabelTable(slider.createDecimalSliderStandardLabels(Math.max(spacing/minorTick,1))); } public boolean getShowValues(){ return showValues;} public void setShowValues(boolean b){ showValues = b; if(showValues){ setSliderValueShape("VERTICAL"); textField.addActionListener(new ActionListener(){ public void actionPerformed( ActionEvent e){ //sets value of slider, which then fires event to modifier, taking care of units setValue((Double.parseDouble(e.getActionCommand()))); // setValue(unit.toSim(Double.parseDouble(e.getActionCommand()))); }});} } public void setSliderValueShape(String s){ panel.removeAll(); textField.setColumns(column); gbConst.gridx = 0; gbConst.gridy = 0; gbLayout.setConstraints(getSlider(), gbConst); panel.add(getSlider()); if(s=="HORIZONTAL") { gbConst.gridx = 1; gbConst.gridy = 0; gbLayout.setConstraints(textField, gbConst); panel.add(textField);} if(s=="VERTICAL") { gbConst.fill = GridBagConstraints.HORIZONTAL; gbConst.gridx = 0; gbConst.gridy = 1; gbLayout.setConstraints(textField, gbConst); panel.add(textField); } } public void setSliderVerticalOrientation(boolean b){ if(b){getSlider().setOrientation(DecimalSlider.VERTICAL);} } public boolean getEditValues(){ return editValues;} public void setEditValues(boolean b){ editValues = b; textField.setEditable(editValues); } public int getPrecision(){return slider.getPrecision();} public void setPrecision(int n) { if(n>5){column = n;} slider.setPrecision(n); } public double getValue(){return slider.getDecimalSliderValue();} public void setValue(double d){ slider.setDecimalSliderValue(d); } /** * Returns the GUI element for display in the simulation. */ public java.awt.Component graphic(Object obj) { // if(showValues){ return panel; // } else {return slider;} return panel; } /** * Sets the value of a descriptive label using the meter's label and the unit's symbol (abbreviation). */ private void setLabelDefault() { String suffix = (unit.symbol().length() > 0) ? " ("+unit.symbol()+")" : ""; if(modifier != null) setLabel(StringUtility.capitalize(modifier.getLabel())+suffix); } /** * Sets the value of a descriptive label using the given string. */ public void setLabel(String s){ label = s; if(s == null || s.equals("") || !showBorder) panel.setBorder(new javax.swing.border.EmptyBorder(0,0,0,0)); else panel.setBorder(new javax.swing.border.TitledBorder(s)); } /** * @return the current instance of the descriptive label. */ public String getLabel() {return label;} public void setShowBorder(boolean b) { showBorder = b; setLabel(label); } public boolean isShowBorder() {return showBorder;} /** * @return a handle to the DecimalSlider instance used by this slider device */ public DecimalSlider getSlider() {return slider;} /** * @return a handle to the JTextField instance used by this slider device */ public JTextField getTextField() {return textField;} /** * @return a handle to the JPanel instance used by this slider device */ public JPanel getPanel() { return panel; } /** * Performs no action (slider can not be accessed for setting). * Method exists so that slider and its properties (which can be set) will * show up on the property sheet. */ public void setSlider(JSlider s) {} public void addChangeListener(ChangeListener l) {changeEventManager.addChangeListener(l);} public void removeChangeListener(ChangeListener l) {changeEventManager.removeChangeListener(l);} /** * Slider listener, which relays the slider change events to the modifier */ private class SliderListener implements ChangeListener { public void stateChanged(ChangeEvent evt) { if(modifier!=null) { modifier.setValue(unit.toSim(slider.getDecimalSliderValue())); textField.setText(String.valueOf(slider.getDecimalSliderValue())); doAction(); changeEventManager.fireChangeEvent(evt); } } } /** * Method to demonstrate and test the use of this class. * Slider is used to control the diameter of a hard-sphere in MD simulation */ // public static void main(String[] args) { // //// inner class of Modifier that works with Slider************************************************************* // class DiameterModifier extends etomica.ModifierAbstract { // // public double fullDiameter; // public double currentValue; // public etomica.graphics.DisplayPhase display; // private etomica.P2SquareWell p2SquareWell; // private etomica.SpeciesSpheresMono speciesSpheres01; // private JPanel valuePanel; // // public DiameterModifier(etomica.P2SquareWell pot, etomica.SpeciesSpheresMono ssm){ // p2SquareWell = pot; // speciesSpheres01 = ssm; // fullDiameter = pot.getCoreDiameter(); // } // public etomica.units.Dimension getDimension() { // return etomica.units.Dimension.LENGTH; // } // public double getValue() { // return p2SquareWell.getCoreDiameter(); // } // public void setValue(double d) { // p2SquareWell.setCoreDiameter(d); // speciesSpheres01.setDiameter(d); // display.repaint(); // } // public void setDisplay(etomica.graphics.DisplayPhase display){ // this.display = display; // } // } ////end of DiameterModifier class********************************************************************* // // Simulation.instance = new etomica.graphics.SimulationGraphic(); // // Phase phase0 = new Phase(); // phase0.setLrcEnabled(false); // IntegratorHard integrator = new IntegratorHard(); // P2SquareWell p2SquareWell = new P2SquareWell(); // Controller controller0 = new Controller(); // SpeciesSpheresMono speciesSpheres0 = new SpeciesSpheresMono(); // DisplayPhase displayPhase0 = new DisplayPhase(); // DeviceTrioControllerButton button = new DeviceTrioControllerButton(); //// button.setTrioControllerButtonShape("VERTICAL"); // // DiameterModifier diaModifier= new DiameterModifier(p2SquareWell, speciesSpheres0); // diaModifier.setDisplay(displayPhase0); // // DeviceSlider mySlider = new DeviceSlider(); //// mySlider.setShowMinorValues(true); // mySlider.setPrecision(3); // default "0" - working with integer without setting precision, better higher precesion than minimum and maximum // mySlider.setMinimum(0); // possible to give double value // mySlider.setMaximum(6.2); // possible to give double value // mySlider.setModifier(diaModifier); // call modifier instance after setting precision, minimum, and maximum //// mySlider.setValue(2*Default.ATOM_SIZE);// if modifier instance is called first then setValue method should be called to set slider value //// mySlider.setLabel(" "); // without this, shows modifier demension // mySlider.setShowValues(true); // default "false" - true makes panel to put Slider and TextField, which shows the values of slider // mySlider.setEditValues(true); // defaulst " false" - decide to edit the values after true setShowValues // mySlider.setLabel("Diameter"); ///* mySlider.getJPanel().setBorder(new javax.swing.border.TitledBorder( // default border is null // new javax.swing.border.EtchedBorder( // javax.swing.border.EtchedBorder.RAISED, java.awt.Color.black, java.awt.Color.gray) // ,"" // ,javax.swing.border.TitledBorder.LEFT // ,javax.swing.border.TitledBorder.TOP // ,new java.awt.Font(null,java.awt.Font.BOLD,15) // ,java.awt.Color.black)); */ //// mySlider.setSliderValueShape("HORIZONTAL"); // default "VERTICAL" //// mySlider.setSliderVerticalOrientation(true); // true is for vertically standing slider //// mySlider.getTextField().setHorizontalAlignment(mySlider.getTextField().LEFT); // default "CENTER" // // Simulation.instance.elementCoordinator.go(); // SimulationGraphic.makeAndDisplayFrame(Simulation.instance); // // } }
etomica/graphics/DeviceSlider.java
//This class includes a main method to demonstrate its use package etomica.graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JTextField; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import etomica.Controller; import etomica.EtomicaElement; import etomica.EtomicaInfo; import etomica.Modifier; import etomica.event.ChangeEventManager; import etomica.modifier.ModifierGeneral; import etomica.modifier.ModifyAction; import etomica.units.Unit; import etomica.utility.DecimalSlider; import etomica.utility.StringUtility; /** * Device the changes a property using a graphical slider, via a Modifier. * * @see ModifierGeneral */ /* History * 10/08/02 (SKK) modified for DecimalSlider, textBox * 10/12/02 (DAK) added init method * 10/13/02 (DAK) restored nMajor and its accessor/mutator methods * changed graphic method to always return panel, never just slider * always adding slider to panel */ public class DeviceSlider extends Device implements EtomicaElement { /** * Descriptive text label to be displayed with the value * No longer used -- instead apply label via a title border on the slider itself */ private String label; /** * Modifier connecting the slider to the property */ protected ModifyAction modifier; /** * Subclass of Swing slider displayed to screen * located in utility package */ protected DecimalSlider slider; /** * Object with property being modulated */ protected Object component; /** * Property being modulated */ protected String property; /** * Values for maximum and minimum values of slider in double form */ private double minimum, maximum; /** * boolean showValues for showing values on textfield * boolean editvalus for editing the values in textfield, which change slider tip */ private boolean showValues, editValues; /* * To show slider with value in one */ private JPanel panel; /** * To show the values of slider */ private JTextField textField; /** * column of textfield to show the value of slider correctly with horizontal view * default value is five and affected if precision is greater than 5 */ private int column; /** * Layout instance to show slider and textfield */ private GridBagLayout gbLayout; private GridBagConstraints gbConst; private boolean showBorder = false; private int nMajor = 3; protected final ChangeEventManager changeEventManager = new ChangeEventManager(this); public DeviceSlider(Controller controller) { super(controller); init(); } /** * Constructs a slider connected to the given property of the given object */ public DeviceSlider(Controller controller, Object object, String property) { this(controller, new ModifierGeneral(object, property)); component = object; this.property = property; } /** * Constructs a slider connected to the get/set Value methods of the given Modifier */ public DeviceSlider(Controller controller, Modifier m) { this(controller); //set component and property in some way setModifier(m); } private void init() { textField = new JTextField(""); textField.setFont(new java.awt.Font("",0,15)); textField.setHorizontalAlignment(JTextField.CENTER); gbLayout = new GridBagLayout(); gbConst = new GridBagConstraints(); panel = new JPanel(); // panel.setBorder(new javax.swing.border.TitledBorder("JPST")); //JPanel of Slider and TextField setLabel(""); panel.setLayout(gbLayout); column = 5; slider = new DecimalSlider(); slider.setSize(200,40); slider.setPaintTicks(true); slider.setPaintLabels(true); slider.setDecimalSliderValue(300); setMinimum(100); setMaximum(500); slider.setDecimalSliderMajorTickSpacing(100); slider.setDecimalSliderMinorTickSpacing(50); slider.addChangeListener(new SliderListener()); //SliderListener is an inner class defined below gbConst.gridx = 0; gbConst.gridy = 0; gbLayout.setConstraints(getSlider(), gbConst); panel.add(getSlider()); setShowValues(false); // default is false to show values of slider setEditValues(false); // default is false to edit values of slider thru textField } public static EtomicaInfo getEtomicaInfo() { EtomicaInfo info = new EtomicaInfo(); info.setDescription("Slider-type device for changing a property"); return info; } /** * Override superclass setUnit method to update label when unit is changed */ public void setUnit(Unit u) { super.setUnit(u); setLabelDefault(); } public final void setModifier(Modifier m) { if(m == null) throw new NullPointerException(); modifier = null; unit = m.getDimension().defaultIOUnit(); slider.setDecimalSliderValue(unit.fromSim(m.getValue())); modifier = new ModifyAction(m); targetAction = modifier; setLabelDefault(); setMinimum(getMinimum()); setMaximum(getMaximum()); } public final Modifier getModifier() {return modifier.getWrappedModifier();} public String getProperty() {return property;} public void setProperty(String s) { property = s; if(component != null) setModifier(new ModifierGeneral(component, property)); } public Object getComponent() {return component;} public void setComponent(Object obj) { component = obj; if(property != null) setModifier(new ModifierGeneral(component,property)); } public double getMinimum() {return minimum;} /** * Sets minimum value of slider; should be called after * any calls to setPrecision. */ public void setMinimum(double min) { minimum = min; slider.setDecimalSliderMinimum(min); slider.setInverted(maximum < minimum); setTicks(); } public double getMaximum() {return maximum;} /** * Sets maximum value of slider; should be called after * any calls to setPrecision. */ public void setMaximum(double max) { maximum = max; slider.setDecimalSliderMaximum(max); slider.setInverted(maximum < minimum); setTicks(); } private boolean showMinorValues = false; public void setShowMinorValues(boolean b){ showMinorValues = b; } public void setNMajor(int n) { nMajor = n; setTicks(); } public int getNMajor() {return nMajor;} private void setTicks() { double minorTick = 1.0 ; if(showMinorValues){ minorTick = 2;} double spacing = (getMaximum()-getMinimum())/(double)nMajor; if(spacing <= 0) return; slider.setDecimalSliderMajorTickSpacing(spacing); slider.setDecimalSliderMinorTickSpacing(spacing/2.0); //need to do the following because JSlider does not automatically //reset labels if they have been set before slider.setDecimalSliderLabelTable(slider.createDecimalSliderStandardLabels(Math.max(spacing/minorTick,1))); } public boolean getShowValues(){ return showValues;} public void setShowValues(boolean b){ showValues = b; if(showValues){ setSliderValueShape("VERTICAL"); textField.addActionListener(new ActionListener(){ public void actionPerformed( ActionEvent e){ //sets value of slider, which then fires event to modifier, taking care of units setValue((Double.parseDouble(e.getActionCommand()))); // setValue(unit.toSim(Double.parseDouble(e.getActionCommand()))); }});} } public void setSliderValueShape(String s){ panel.removeAll(); textField.setColumns(column); gbConst.gridx = 0; gbConst.gridy = 0; gbLayout.setConstraints(getSlider(), gbConst); panel.add(getSlider()); if(s=="HORIZONTAL") { gbConst.gridx = 1; gbConst.gridy = 0; gbLayout.setConstraints(textField, gbConst); panel.add(textField);} if(s=="VERTICAL") { gbConst.fill = GridBagConstraints.HORIZONTAL; gbConst.gridx = 0; gbConst.gridy = 1; gbLayout.setConstraints(textField, gbConst); panel.add(textField); } } public void setSliderVerticalOrientation(boolean b){ if(b){getSlider().setOrientation(DecimalSlider.VERTICAL);} } public boolean getEditValues(){ return editValues;} public void setEditValues(boolean b){ editValues = b; textField.setEditable(editValues); } public int getPrecision(){return slider.getPrecision();} public void setPrecision(int n) { if(n>5){column = n;} slider.setPrecision(n); } public double getValue(){return slider.getDecimalSliderValue();} public void setValue(double d){ slider.setDecimalSliderValue(d); } /** * Returns the GUI element for display in the simulation. */ public java.awt.Component graphic(Object obj) { // if(showValues){ return panel; // } else {return slider;} return panel; } /** * Sets the value of a descriptive label using the meter's label and the unit's symbol (abbreviation). */ private void setLabelDefault() { String suffix = (unit.symbol().length() > 0) ? " ("+unit.symbol()+")" : ""; if(modifier != null) setLabel(StringUtility.capitalize(modifier.getLabel())+suffix); } /** * Sets the value of a descriptive label using the given string. */ public void setLabel(String s){ label = s; if(s == null || s.equals("") || !showBorder) panel.setBorder(new javax.swing.border.EmptyBorder(0,0,0,0)); else panel.setBorder(new javax.swing.border.TitledBorder(s)); } /** * @return the current instance of the descriptive label. */ public String getLabel() {return label;} public void setShowBorder(boolean b) { showBorder = b; setLabel(label); } public boolean isShowBorder() {return showBorder;} /** * @return a handle to the DecimalSlider instance used by this slider device */ public DecimalSlider getSlider() {return slider;} /** * @return a handle to the JTextField instance used by this slider device */ public JTextField getTextField() {return textField;} /** * @return a handle to the JPanel instance used by this slider device */ public JPanel getPanel() { return panel; } /** * Performs no action (slider can not be accessed for setting). * Method exists so that slider and its properties (which can be set) will * show up on the property sheet. */ public void setSlider(JSlider s) {} public void addChangeListener(ChangeListener l) {changeEventManager.addChangeListener(l);} public void removeChangeListener(ChangeListener l) {changeEventManager.removeChangeListener(l);} /** * Slider listener, which relays the slider change events to the modifier */ private class SliderListener implements ChangeListener { public void stateChanged(ChangeEvent evt) { if(modifier!=null) { modifier.setValue(unit.toSim(slider.getDecimalSliderValue())); textField.setText(String.valueOf(slider.getDecimalSliderValue())); doAction(); changeEventManager.fireChangeEvent(evt); } } } /** * Method to demonstrate and test the use of this class. * Slider is used to control the diameter of a hard-sphere in MD simulation */ // public static void main(String[] args) { // //// inner class of Modifier that works with Slider************************************************************* // class DiameterModifier extends etomica.ModifierAbstract { // // public double fullDiameter; // public double currentValue; // public etomica.graphics.DisplayPhase display; // private etomica.P2SquareWell p2SquareWell; // private etomica.SpeciesSpheresMono speciesSpheres01; // private JPanel valuePanel; // // public DiameterModifier(etomica.P2SquareWell pot, etomica.SpeciesSpheresMono ssm){ // p2SquareWell = pot; // speciesSpheres01 = ssm; // fullDiameter = pot.getCoreDiameter(); // } // public etomica.units.Dimension getDimension() { // return etomica.units.Dimension.LENGTH; // } // public double getValue() { // return p2SquareWell.getCoreDiameter(); // } // public void setValue(double d) { // p2SquareWell.setCoreDiameter(d); // speciesSpheres01.setDiameter(d); // display.repaint(); // } // public void setDisplay(etomica.graphics.DisplayPhase display){ // this.display = display; // } // } ////end of DiameterModifier class********************************************************************* // // Simulation.instance = new etomica.graphics.SimulationGraphic(); // // Phase phase0 = new Phase(); // phase0.setLrcEnabled(false); // IntegratorHard integrator = new IntegratorHard(); // P2SquareWell p2SquareWell = new P2SquareWell(); // Controller controller0 = new Controller(); // SpeciesSpheresMono speciesSpheres0 = new SpeciesSpheresMono(); // DisplayPhase displayPhase0 = new DisplayPhase(); // DeviceTrioControllerButton button = new DeviceTrioControllerButton(); //// button.setTrioControllerButtonShape("VERTICAL"); // // DiameterModifier diaModifier= new DiameterModifier(p2SquareWell, speciesSpheres0); // diaModifier.setDisplay(displayPhase0); // // DeviceSlider mySlider = new DeviceSlider(); //// mySlider.setShowMinorValues(true); // mySlider.setPrecision(3); // default "0" - working with integer without setting precision, better higher precesion than minimum and maximum // mySlider.setMinimum(0); // possible to give double value // mySlider.setMaximum(6.2); // possible to give double value // mySlider.setModifier(diaModifier); // call modifier instance after setting precision, minimum, and maximum //// mySlider.setValue(2*Default.ATOM_SIZE);// if modifier instance is called first then setValue method should be called to set slider value //// mySlider.setLabel(" "); // without this, shows modifier demension // mySlider.setShowValues(true); // default "false" - true makes panel to put Slider and TextField, which shows the values of slider // mySlider.setEditValues(true); // defaulst " false" - decide to edit the values after true setShowValues // mySlider.setLabel("Diameter"); ///* mySlider.getJPanel().setBorder(new javax.swing.border.TitledBorder( // default border is null // new javax.swing.border.EtchedBorder( // javax.swing.border.EtchedBorder.RAISED, java.awt.Color.black, java.awt.Color.gray) // ,"" // ,javax.swing.border.TitledBorder.LEFT // ,javax.swing.border.TitledBorder.TOP // ,new java.awt.Font(null,java.awt.Font.BOLD,15) // ,java.awt.Color.black)); */ //// mySlider.setSliderValueShape("HORIZONTAL"); // default "VERTICAL" //// mySlider.setSliderVerticalOrientation(true); // true is for vertically standing slider //// mySlider.getTextField().setHorizontalAlignment(mySlider.getTextField().LEFT); // default "CENTER" // // Simulation.instance.elementCoordinator.go(); // SimulationGraphic.makeAndDisplayFrame(Simulation.instance); // // } }
don't override previously-set unit in setModifier avoid triggering action in setMax/Min
etomica/graphics/DeviceSlider.java
don't override previously-set unit in setModifier avoid triggering action in setMax/Min
<ide><path>tomica/graphics/DeviceSlider.java <ide> public final void setModifier(Modifier m) { <ide> if(m == null) throw new NullPointerException(); <ide> modifier = null; <del> unit = m.getDimension().defaultIOUnit(); <del> slider.setDecimalSliderValue(unit.fromSim(m.getValue())); <add> if (unit == null) { <add> setUnit(m.getDimension().defaultIOUnit()); <add> } <add> slider.setDecimalSliderValue(unit.fromSim(m.getValue())); <ide> modifier = new ModifyAction(m); <ide> targetAction = modifier; <ide> setLabelDefault(); <ide> */ <ide> public void setMinimum(double min) { <ide> minimum = min; <add> ModifyAction tmpModifier = modifier; <add> modifier = null; <ide> slider.setDecimalSliderMinimum(min); <ide> slider.setInverted(maximum < minimum); <ide> setTicks(); <add> modifier = tmpModifier; <ide> } <ide> <ide> public double getMaximum() {return maximum;} <ide> */ <ide> public void setMaximum(double max) { <ide> maximum = max; <add> ModifyAction tmpModifier = modifier; <add> modifier = null; <ide> slider.setDecimalSliderMaximum(max); <ide> slider.setInverted(maximum < minimum); <ide> setTicks(); <add> modifier = tmpModifier; <ide> } <ide> <ide> private boolean showMinorValues = false; <ide> private void setTicks() { <ide> double minorTick = 1.0 ; <ide> if(showMinorValues){ minorTick = 2;} <del> double spacing = (getMaximum()-getMinimum())/(double)nMajor; <add> double spacing = (getMaximum()-getMinimum())/nMajor; <ide> if(spacing <= 0) return; <ide> slider.setDecimalSliderMajorTickSpacing(spacing); <ide> slider.setDecimalSliderMinorTickSpacing(spacing/2.0);
Java
mit
fcd2fb601ce170e2d9463473d38b0165ac0bcb52
0
markusfisch/ShaderEditor,markusfisch/ShaderEditor
package de.markusfisch.android.shadereditor; import android.content.SharedPreferences; import android.database.Cursor; import android.preference.PreferenceManager; import android.service.wallpaper.WallpaperService; import android.view.MotionEvent; import android.view.SurfaceHolder; public class ShaderWallpaperService extends WallpaperService { @Override public final Engine onCreateEngine() { return new ShaderWallpaperEngine(); } private class ShaderWallpaperEngine extends Engine implements SharedPreferences.OnSharedPreferenceChangeListener { private ShaderWallpaperView view = null; private String fragmentShader = null; public ShaderWallpaperEngine() { super(); PreferenceManager.setDefaultValues( ShaderWallpaperService.this, R.xml.preferences, false ); SharedPreferences p = ShaderWallpaperService.this.getSharedPreferences( ShaderPreferenceActivity.SHARED_PREFERENCES_NAME, 0 ); p.registerOnSharedPreferenceChangeListener( this ); onSharedPreferenceChanged( p, null ); setTouchEventsEnabled( true ); } @Override public void onSharedPreferenceChanged( SharedPreferences p, String key ) { ShaderDataSource dataSource = new ShaderDataSource( ShaderWallpaperService.this ); dataSource.open(); final long id = Long.parseLong( p.getString( ShaderPreferenceActivity.SHADER, "1" ) ); if( (fragmentShader = dataSource.getShader( id )) == null ) { Cursor c = dataSource.getRandomShader(); if( c != null ) { fragmentShader = c.getString( c.getColumnIndex( ShaderDataSource.COLUMN_SHADER ) ); ShaderListPreference.saveShader( p, c.getLong( c.getColumnIndex( ShaderDataSource.COLUMN_ID ) ) ); } } if( view != null ) view.renderer.fragmentShader = fragmentShader; dataSource.close(); } @Override public void onCreate( SurfaceHolder holder ) { super.onCreate( holder ); view = new ShaderWallpaperView(); view.renderer.fragmentShader = fragmentShader; } @Override public void onDestroy() { super.onDestroy(); view.destroy(); view = null; } @Override public void onVisibilityChanged( boolean visible ) { super.onVisibilityChanged( visible ); if( visible ) { view.onResume(); view.requestRender(); } else view.onPause(); } @Override public void onTouchEvent( MotionEvent e ) { super.onTouchEvent( e ); view.renderer.onTouch( e.getX(), e.getY() ); } @Override public void onOffsetsChanged( float xOffset, float yOffset, float xStep, float yStep, int xPixels, int yPixels ) { view.renderer.offset[0] = xOffset; view.renderer.offset[1] = yOffset; } private class ShaderWallpaperView extends ShaderView { public ShaderWallpaperView() { super( ShaderWallpaperService.this ); } @Override public final SurfaceHolder getHolder() { return ShaderWallpaperEngine.this.getSurfaceHolder(); } public void destroy() { super.onDetachedFromWindow(); } } } }
src/de/markusfisch/android/shadereditor/ShaderWallpaperService.java
package de.markusfisch.android.shadereditor; import android.content.SharedPreferences; import android.database.Cursor; import android.preference.PreferenceManager; import android.service.wallpaper.WallpaperService; import android.view.MotionEvent; import android.view.SurfaceHolder; public class ShaderWallpaperService extends WallpaperService { @Override public final Engine onCreateEngine() { return new ShaderWallpaperEngine(); } private class ShaderWallpaperEngine extends Engine implements SharedPreferences.OnSharedPreferenceChangeListener { private ShaderWallpaperView view = null; private String fragmentShader = null; public ShaderWallpaperEngine() { super(); PreferenceManager.setDefaultValues( ShaderWallpaperService.this, R.xml.preferences, false ); SharedPreferences p = ShaderWallpaperService.this.getSharedPreferences( ShaderPreferenceActivity.SHARED_PREFERENCES_NAME, 0 ); p.registerOnSharedPreferenceChangeListener( this ); onSharedPreferenceChanged( p, null ); setTouchEventsEnabled( true ); } @Override public void onSharedPreferenceChanged( SharedPreferences p, String key ) { ShaderDataSource dataSource = new ShaderDataSource( ShaderWallpaperService.this ); dataSource.open(); final long id = Long.parseLong( p.getString( ShaderPreferenceActivity.SHADER, "1" ) ); if( (fragmentShader = dataSource.getShader( id )) == null ) { Cursor c = dataSource.getRandomShader(); if( c != null ) { fragmentShader = c.getString( c.getColumnIndex( ShaderDataSource.COLUMN_SHADER ) ); ShaderListPreference.saveShader( p, c.getLong( c.getColumnIndex( ShaderDataSource.COLUMN_ID ) ) ); } } if( view != null ) view.renderer.fragmentShader = fragmentShader; dataSource.close(); } @Override public void onCreate( SurfaceHolder holder ) { super.onCreate( holder ); view = new ShaderWallpaperView(); view.renderer.fragmentShader = fragmentShader; } @Override public void onDestroy() { super.onDestroy(); view.destroy(); view = null; } @Override public void onVisibilityChanged( boolean visible ) { super.onVisibilityChanged( visible ); if( visible ) { view.onResume(); view.requestRender(); } else view.onPause(); } @Override public void onTouchEvent( MotionEvent e ) { super.onTouchEvent( e ); view.renderer.onTouch( e.getX(), e.getY() ); } @Override public void onOffsetsChanged( float xOffset, float yOffset, float xStep, float yStep, int xPixels, int yPixels ) { view.renderer.offset[0] = xOffset; view.renderer.offset[1] = yOffset; } private class ShaderWallpaperView extends ShaderView { public ShaderWallpaperView() { super( ShaderWallpaperService.this ); } @Override public final SurfaceHolder getHolder() { return ShaderWallpaperEngine.this.getSurfaceHolder(); } public void destroy() { super.onDetachedFromWindow(); } } } }
Removed white space
src/de/markusfisch/android/shadereditor/ShaderWallpaperService.java
Removed white space
<ide><path>rc/de/markusfisch/android/shadereditor/ShaderWallpaperService.java <ide> public ShaderWallpaperView() <ide> { <ide> super( ShaderWallpaperService.this ); <del> <ide> } <ide> <ide> @Override
Java
cc0-1.0
18440f0195ec39211bed6e65a5dced679cd2ef30
0
brueesch/paraglider,brueesch/paraglider
src/ch/zhaw/paraglider/physics/test.java
package ch.zhaw.paraglider.physics; import ch.zhaw.paraglider.controller.RunGame; /** * This Class handles the physics and the position of the pilot. In addition it * includes a method which animates the pilot. * * @author Christian Bresch * */ public final class Pilot { /** * Variable that defines the Weight of the Pilot in kg. */ private int weightOfPilot = 85; /** * Constant to convert pixel into meter. */ private final double CONVERT_METER_AND_PIXEL = 20; /** * Constant to konvert km/h into m/s. */ private final double CONVERT_KMH_AND_MS = 3.6; /** * Constant to konvert secounds into milisecounds. */ private final double CONVERT_S_AND_MS = 1000; /** * Constant which defines the Lenght of the paraglider cord in m. */ private final double LENGTH_OF_CORD = 7.68; /** * Constant for the Gravitational Force in m per second squared. */ private final double GRAVITATIONAL_FORCE = 9.81; /** * Period time of the "pilot pendulum". */ private final double TIME_OF_PERIOD = (2 * Math.PI * Math .sqrt(LENGTH_OF_CORD / GRAVITATIONAL_FORCE)); /** * Start position of the pilot in the x-axis. */ private final double ZERO_X_POSITION = 310; /** * Start position of the pilot in the y-axis. */ private final double ZERO_Y_POSITION = 394; /** * Start position of the pilot in the z-axis. */ private final double ZERO_Z_POSITION = 910; /** * Position of the Zero Point. In the middle of the paraglider, where the * line starts. */ private final double[] ZERO_POINT = { 310, 240 }; /** * The current position of the pilot x-axis. */ private double currentPositionX = ZERO_X_POSITION; /** * The current position of the pilot y-axis. */ private double currentPositionY = ZERO_Y_POSITION; /** * The current position of the pilot z-axis. */ private double currentPositionZ = ZERO_Z_POSITION; /** * Boolean which defines in which direction the movement is. */ private boolean movesForward = true; /** * Pilot instance for the Singleton pattern. */ private static Pilot instance; /** * Constant with the current Forward Force. */ double fForward; /** * Private constructor - Singleton Pattern. */ private Pilot() { super(); } /** * Method returns the instance of the Pilot. If there is no Pilot initiated * yet, it will be done. * * @return Pilot */ public static Pilot getInstance() { if (instance == null) { instance = new Pilot(); } return instance; } /** * Returns the current position of the pilot on the x-axis. * * @return double */ public double getCurrentXPosition() { return currentPositionX; } /** * Returns the current position of the pilot on the y-axis. * * @return double */ public double getCurrentYPosition() { return currentPositionY; } /** * Returns the current position of the pilot on the z-axis. * * @return double */ public double getCurrentZPosition() { return currentPositionZ; } /** * Sets the new speed change. * * @param speed */ public void setChangeInSpeed(double speed) { fForward += (speed * CONVERT_KMH_AND_MS / (RunGame.REFRESHRATE / CONVERT_S_AND_MS)) * weightOfPilot; } /** * Returns the weight of the pilot. * * @return int */ public int getWeightOfPilot() { return weightOfPilot; } /** * Sets the new weight of the pilot. * * @param weight */ public void setWeightOfPilot(int weight) { weightOfPilot = weight; } public void reset() { currentPositionX = ZERO_X_POSITION; currentPositionY = ZERO_Y_POSITION; currentPositionZ = ZERO_Z_POSITION; fForward = 0; } /** * Calculates the next step of the animation of the pilot and sets the * current position of the x and y - axis to the calculated values. */ public void makeNextStep() { calculateForces(); calculateXChange(); calculateYChange(); calculateZChange(); } /** * Calculates the different Forces. */ private void calculateForces() { double fg = weightOfPilot * GRAVITATIONAL_FORCE; double fCord = fg * Math.cos(getCurrentAngle()); double fBackwards = Math.sqrt(Math.pow(fg, 2) - Math.pow(fCord, 2)); if (movesForward) { fForward += fBackwards; } else { fForward -= fBackwards; } if (fForward > 0) { fForward -= getDamping(); } else { fForward += getDamping(); } } /** * Returns the damping of the pendel. * * @return double in Newton */ private double getDamping() { // TODO Formel korrigieren, nicht ganz richtig. return weightOfPilot / (Math.pow((TIME_OF_PERIOD / (2 * Math.PI)), 2)); } /** * Returns the current Angle, between the current positon of the pilot and * his position in flight without speed change. * * @return double with the angle in radian. */ private double getCurrentAngle() { double[] u = { ZERO_X_POSITION - ZERO_POINT[0], ZERO_Y_POSITION - ZERO_POINT[1] }; double[] v = { currentPositionX - ZERO_POINT[0], currentPositionY - ZERO_POINT[1] }; double upperFormula = ((u[0] * u[1]) + (v[0] * v[1])); double lowerFormula = (Math.sqrt(Math.pow(u[0], 2) + Math.pow(u[1], 2))) * (Math.sqrt(Math.pow(v[0], 2) + Math.pow(v[1], 2))); double cosAngle = upperFormula / lowerFormula; if (cosAngle < 0) { cosAngle = 1 + cosAngle; movesForward = false; } else { cosAngle = 1 - cosAngle; movesForward = true; } return Math.acos(cosAngle); } /** * calculates the change in the y axis. */ private void calculateYChange() { double x = (currentPositionX - ZERO_X_POSITION) / CONVERT_METER_AND_PIXEL; double y = Math.sqrt(Math.pow(LENGTH_OF_CORD, 2) - Math.pow(x, 2)); currentPositionY = (y * CONVERT_METER_AND_PIXEL) + ZERO_POINT[1]; } /** * Calculates the change in the x-axis. */ private void calculateXChange() { double acceleration = (fForward) / weightOfPilot; double change = (acceleration * Math.pow(RunGame.REFRESHRATE / CONVERT_S_AND_MS, 2)) / 2; currentPositionX -= change * CONVERT_METER_AND_PIXEL; } /** * Calculates the change in the z-axis. */ private void calculateZChange() { Glider glider = Glider.getInstance(); double angle = glider.getAngleOfTheGlider(); double change = Math.sin(angle) * LENGTH_OF_CORD; currentPositionZ = ZERO_Z_POSITION+(change * CONVERT_METER_AND_PIXEL); } }
Remove Testclass
src/ch/zhaw/paraglider/physics/test.java
Remove Testclass
<ide><path>rc/ch/zhaw/paraglider/physics/test.java <del>package ch.zhaw.paraglider.physics; <del> <del>import ch.zhaw.paraglider.controller.RunGame; <del> <del>/** <del> * This Class handles the physics and the position of the pilot. In addition it <del> * includes a method which animates the pilot. <del> * <del> * @author Christian Bresch <del> * <del> */ <del>public final class Pilot { <del> <del> /** <del> * Variable that defines the Weight of the Pilot in kg. <del> */ <del> private int weightOfPilot = 85; <del> /** <del> * Constant to convert pixel into meter. <del> */ <del> private final double CONVERT_METER_AND_PIXEL = 20; <del> /** <del> * Constant to konvert km/h into m/s. <del> */ <del> private final double CONVERT_KMH_AND_MS = 3.6; <del> /** <del> * Constant to konvert secounds into milisecounds. <del> */ <del> private final double CONVERT_S_AND_MS = 1000; <del> /** <del> * Constant which defines the Lenght of the paraglider cord in m. <del> */ <del> private final double LENGTH_OF_CORD = 7.68; <del> /** <del> * Constant for the Gravitational Force in m per second squared. <del> */ <del> private final double GRAVITATIONAL_FORCE = 9.81; <del> <del> /** <del> * Period time of the "pilot pendulum". <del> */ <del> private final double TIME_OF_PERIOD = (2 * Math.PI * Math <del> .sqrt(LENGTH_OF_CORD / GRAVITATIONAL_FORCE)); <del> /** <del> * Start position of the pilot in the x-axis. <del> */ <del> private final double ZERO_X_POSITION = 310; <del> /** <del> * Start position of the pilot in the y-axis. <del> */ <del> private final double ZERO_Y_POSITION = 394; <del> /** <del> * Start position of the pilot in the z-axis. <del> */ <del> private final double ZERO_Z_POSITION = 910; <del> /** <del> * Position of the Zero Point. In the middle of the paraglider, where the <del> * line starts. <del> */ <del> private final double[] ZERO_POINT = { 310, 240 }; <del> /** <del> * The current position of the pilot x-axis. <del> */ <del> private double currentPositionX = ZERO_X_POSITION; <del> /** <del> * The current position of the pilot y-axis. <del> */ <del> private double currentPositionY = ZERO_Y_POSITION; <del> /** <del> * The current position of the pilot z-axis. <del> */ <del> private double currentPositionZ = ZERO_Z_POSITION; <del> /** <del> * Boolean which defines in which direction the movement is. <del> */ <del> private boolean movesForward = true; <del> /** <del> * Pilot instance for the Singleton pattern. <del> */ <del> private static Pilot instance; <del> /** <del> * Constant with the current Forward Force. <del> */ <del> double fForward; <del> <del> /** <del> * Private constructor - Singleton Pattern. <del> */ <del> private Pilot() { <del> super(); <del> } <del> <del> /** <del> * Method returns the instance of the Pilot. If there is no Pilot initiated <del> * yet, it will be done. <del> * <del> * @return Pilot <del> */ <del> public static Pilot getInstance() { <del> if (instance == null) { <del> instance = new Pilot(); <del> } <del> <del> return instance; <del> } <del> <del> /** <del> * Returns the current position of the pilot on the x-axis. <del> * <del> * @return double <del> */ <del> public double getCurrentXPosition() { <del> return currentPositionX; <del> } <del> <del> /** <del> * Returns the current position of the pilot on the y-axis. <del> * <del> * @return double <del> */ <del> public double getCurrentYPosition() { <del> return currentPositionY; <del> } <del> /** <del> * Returns the current position of the pilot on the z-axis. <del> * <del> * @return double <del> */ <del> public double getCurrentZPosition() { <del> return currentPositionZ; <del> } <del> <del> /** <del> * Sets the new speed change. <del> * <del> * @param speed <del> */ <del> public void setChangeInSpeed(double speed) { <del> <del> fForward += (speed * CONVERT_KMH_AND_MS / (RunGame.REFRESHRATE / CONVERT_S_AND_MS)) <del> * weightOfPilot; <del> } <del> <del> /** <del> * Returns the weight of the pilot. <del> * <del> * @return int <del> */ <del> public int getWeightOfPilot() { <del> return weightOfPilot; <del> } <del> <del> /** <del> * Sets the new weight of the pilot. <del> * <del> * @param weight <del> */ <del> public void setWeightOfPilot(int weight) { <del> weightOfPilot = weight; <del> } <del> <del> public void reset() { <del> currentPositionX = ZERO_X_POSITION; <del> currentPositionY = ZERO_Y_POSITION; <del> currentPositionZ = ZERO_Z_POSITION; <del> fForward = 0; <del> } <del> <del> /** <del> * Calculates the next step of the animation of the pilot and sets the <del> * current position of the x and y - axis to the calculated values. <del> */ <del> public void makeNextStep() { <del> calculateForces(); <del> calculateXChange(); <del> calculateYChange(); <del> calculateZChange(); <del> } <del> <del> /** <del> * Calculates the different Forces. <del> */ <del> private void calculateForces() { <del> double fg = weightOfPilot * GRAVITATIONAL_FORCE; <del> double fCord = fg * Math.cos(getCurrentAngle()); <del> double fBackwards = Math.sqrt(Math.pow(fg, 2) - Math.pow(fCord, 2)); <del> <del> if (movesForward) { <del> fForward += fBackwards; <del> } else { <del> fForward -= fBackwards; <del> } <del> <del> if (fForward > 0) { <del> fForward -= getDamping(); <del> } else { <del> fForward += getDamping(); <del> } <del> } <del> <del> /** <del> * Returns the damping of the pendel. <del> * <del> * @return double in Newton <del> */ <del> private double getDamping() { <del> // TODO Formel korrigieren, nicht ganz richtig. <del> return weightOfPilot / (Math.pow((TIME_OF_PERIOD / (2 * Math.PI)), 2)); <del> } <del> <del> /** <del> * Returns the current Angle, between the current positon of the pilot and <del> * his position in flight without speed change. <del> * <del> * @return double with the angle in radian. <del> */ <del> private double getCurrentAngle() { <del> double[] u = { ZERO_X_POSITION - ZERO_POINT[0], <del> ZERO_Y_POSITION - ZERO_POINT[1] }; <del> double[] v = { currentPositionX - ZERO_POINT[0], <del> currentPositionY - ZERO_POINT[1] }; <del> <del> double upperFormula = ((u[0] * u[1]) + (v[0] * v[1])); <del> double lowerFormula = (Math.sqrt(Math.pow(u[0], 2) + Math.pow(u[1], 2))) <del> * (Math.sqrt(Math.pow(v[0], 2) + Math.pow(v[1], 2))); <del> double cosAngle = upperFormula / lowerFormula; <del> <del> if (cosAngle < 0) { <del> cosAngle = 1 + cosAngle; <del> movesForward = false; <del> } else { <del> cosAngle = 1 - cosAngle; <del> movesForward = true; <del> } <del> return Math.acos(cosAngle); <del> } <del> <del> /** <del> * calculates the change in the y axis. <del> */ <del> private void calculateYChange() { <del> double x = (currentPositionX - ZERO_X_POSITION) <del> / CONVERT_METER_AND_PIXEL; <del> double y = Math.sqrt(Math.pow(LENGTH_OF_CORD, 2) - Math.pow(x, 2)); <del> currentPositionY = (y * CONVERT_METER_AND_PIXEL) + ZERO_POINT[1]; <del> } <del> <del> /** <del> * Calculates the change in the x-axis. <del> */ <del> private void calculateXChange() { <del> double acceleration = (fForward) / weightOfPilot; <del> double change = (acceleration * Math.pow(RunGame.REFRESHRATE <del> / CONVERT_S_AND_MS, 2)) / 2; <del> currentPositionX -= change * CONVERT_METER_AND_PIXEL; <del> } <del> <del> /** <del> * Calculates the change in the z-axis. <del> */ <del> private void calculateZChange() { <del> Glider glider = Glider.getInstance(); <del> <del> double angle = glider.getAngleOfTheGlider(); <del> <del> double change = Math.sin(angle) * LENGTH_OF_CORD; <del> <del> currentPositionZ = ZERO_Z_POSITION+(change * CONVERT_METER_AND_PIXEL); <del> <del> } <del> <del>}
Java
epl-1.0
c21be2f3a0abeb82ba4cb56756807bedcf7f73f8
0
elexis/elexis-3-core,elexis/elexis-3-core,sazgin/elexis-3-core,elexis/elexis-3-core,elexis/elexis-3-core,sazgin/elexis-3-core,sazgin/elexis-3-core,sazgin/elexis-3-core
/******************************************************************************* * Copyright (c) 2006-2010, G. Weirich and Elexis * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * G. Weirich - initial implementation * *******************************************************************************/ package ch.elexis.core.ui.views; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.InputDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ColumnLabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerComparator; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.ui.ISaveablePart2; import org.eclipse.ui.PartInitException; import org.eclipse.ui.forms.widgets.Form; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.part.ViewPart; import ch.elexis.core.constants.Preferences; import ch.elexis.core.data.activator.CoreHub; import ch.elexis.core.data.events.ElexisEvent; import ch.elexis.core.data.events.ElexisEventDispatcher; import ch.elexis.core.ui.UiDesk; import ch.elexis.core.ui.actions.GlobalActions; import ch.elexis.core.ui.actions.GlobalEventDispatcher; import ch.elexis.core.ui.actions.IActivationListener; import ch.elexis.core.ui.dialogs.DocumentSelectDialog; import ch.elexis.core.ui.dialogs.SelectFallDialog; import ch.elexis.core.ui.icons.Images; import ch.elexis.core.ui.util.SWTHelper; import ch.elexis.core.ui.util.ViewMenus; import ch.elexis.core.ui.util.viewers.CommonViewer; import ch.elexis.core.ui.util.viewers.CommonViewer.DoubleClickListener; import ch.elexis.core.ui.util.viewers.DefaultContentProvider; import ch.elexis.core.ui.util.viewers.DefaultControlFieldProvider; import ch.elexis.core.ui.util.viewers.DefaultLabelProvider; import ch.elexis.core.ui.util.viewers.SimpleWidgetProvider; import ch.elexis.core.ui.util.viewers.ViewerConfigurer; import ch.elexis.data.Brief; import ch.elexis.data.Fall; import ch.elexis.data.Konsultation; import ch.elexis.data.Kontakt; import ch.elexis.data.Patient; import ch.elexis.data.PersistentObject; import ch.elexis.data.Query; import ch.rgw.tools.ExHandler; import ch.rgw.tools.TimeTool; public class BriefAuswahl extends ViewPart implements ch.elexis.core.data.events.ElexisEventListener, IActivationListener, ISaveablePart2 { public final static String ID = "ch.elexis.BriefAuswahlView"; //$NON-NLS-1$ private final FormToolkit tk; private Form form; private Action briefNeuAction, briefLadenAction, editNameAction; private Action deleteAction; private ViewMenus menus; private ArrayList<sPage> pages = new ArrayList<sPage>(); CTabFolder ctab; // private ViewMenus menu; // private IAction delBriefAction; public BriefAuswahl(){ tk = UiDesk.getToolkit(); } @Override public void createPartControl(final Composite parent){ StringBuilder sb = new StringBuilder(); sb.append(Messages.BriefAuswahlAllLetters).append(Brief.UNKNOWN) .append(",").append(Brief.AUZ) //$NON-NLS-1$ .append(",").append(Brief.RP).append(",").append(Brief.LABOR); String cats = CoreHub.globalCfg.get(Preferences.DOC_CATEGORY, sb.toString()); parent.setLayout(new GridLayout()); form = tk.createForm(parent); form.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true)); form.setBackground(parent.getBackground()); // Grid layout with zero margins GridLayout slimLayout = new GridLayout(); slimLayout.marginHeight = 0; slimLayout.marginWidth = 0; Composite body = form.getBody(); body.setLayout(slimLayout); body.setBackground(parent.getBackground()); ctab = new CTabFolder(body, SWT.BOTTOM); ctab.setLayout(slimLayout); ctab.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true)); ctab.setBackground(parent.getBackground()); makeActions(); menus = new ViewMenus(getViewSite()); for (String cat : cats.split(",")) { CTabItem ct = new CTabItem(ctab, SWT.NONE); ct.setText(cat); sPage page = new sPage(ctab, cat); pages.add(page); menus.createViewerContextMenu(page.cv.getViewerWidget(), editNameAction, deleteAction); ct.setData(page.cv); ct.setControl(page); page.cv.addDoubleClickListener(new DoubleClickListener() { @Override public void doubleClicked(PersistentObject obj, CommonViewer cv){ briefLadenAction.run(); } }); } ctab.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e){ relabel(); } }); GlobalEventDispatcher.addActivationListener(this, this); menus.createMenu(briefNeuAction, briefLadenAction, editNameAction, deleteAction); menus.createToolbar(briefNeuAction, briefLadenAction, deleteAction); ctab.setSelection(0); relabel(); } @Override public void dispose(){ ElexisEventDispatcher.getInstance().removeListeners(this); GlobalEventDispatcher.removeActivationListener(this, this); for (sPage page : pages) { page.getCommonViewer().getConfigurer().getContentProvider().stopListening(); } } @Override public void setFocus(){ } public void relabel(){ UiDesk.asyncExec(new Runnable() { public void run(){ Patient pat = (Patient) ElexisEventDispatcher.getSelected(Patient.class); if (pat == null) { form.setText(Messages.BriefAuswahlNoPatientSelected); //$NON-NLS-1$ } else { form.setText(pat.getLabel()); CTabItem sel = ctab.getSelection(); if (sel != null) { CommonViewer cv = (CommonViewer) sel.getData(); cv.notify(CommonViewer.Message.update); } } } }); } class sPage extends Composite { private TableViewer tableViewer; private LetterViewerComparator comparator; private final CommonViewer cv; private final ViewerConfigurer vc; public CommonViewer getCommonViewer(){ return cv; } sPage(final Composite parent, final String cat){ super(parent, SWT.NONE); setLayout(new GridLayout()); cv = new CommonViewer(); vc = new ViewerConfigurer(new DefaultContentProvider(cv, Brief.class, new String[] { Brief.FLD_DATE }, true) { @Override public Object[] getElements(final Object inputElement){ Patient actPat = (Patient) ElexisEventDispatcher.getSelected(Patient.class); if (actPat != null) { Query<Brief> qbe = new Query<Brief>(Brief.class); qbe.add(Brief.FLD_PATIENT_ID, Query.EQUALS, actPat.getId()); if (cat.equals(Messages.BriefAuswahlAllLetters2)) { //$NON-NLS-1$ qbe.add(Brief.FLD_TYPE, Query.NOT_EQUAL, Brief.TEMPLATE); } else { qbe.add(Brief.FLD_TYPE, Query.EQUALS, cat); } cv.getConfigurer().getControlFieldProvider().setQuery(qbe); List<Brief> list = qbe.execute(); return list.toArray(); } else { return new Brief[0]; } } }, new DefaultLabelProvider(), new DefaultControlFieldProvider(cv, new String[] { "Betreff=Titel" }), new ViewerConfigurer.DefaultButtonProvider(), new SimpleWidgetProvider( SimpleWidgetProvider.TYPE_TABLE, SWT.V_SCROLL | SWT.FULL_SELECTION, cv)); cv.create(vc, this, SWT.NONE, getViewSite()); tableViewer = (TableViewer) cv.getViewerWidget(); tableViewer.getTable().setHeaderVisible(true); createColumns(); comparator = new LetterViewerComparator(); tableViewer.setComparator(comparator); vc.getContentProvider().startListening(); Button bLoad = tk.createButton(this, Messages.BriefAuswahlLoadButtonText, SWT.PUSH); //$NON-NLS-1$ bLoad.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e){ try { TextView tv = (TextView) getViewSite().getPage().showView(TextView.ID); Object[] o = cv.getSelection(); if ((o != null) && (o.length > 0)) { Brief brief = (Brief) o[0]; if (tv.openDocument(brief) == false) { SWTHelper.alert(Messages.BriefAuswahlErrorHeading, //$NON-NLS-1$ Messages.BriefAuswahlCouldNotLoadText); //$NON-NLS-1$ } } else { tv.createDocument(null, null); } } catch (Throwable ex) { ExHandler.handle(ex); } } }); bLoad.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false)); } // create the columns for the table private void createColumns(){ // first column - date TableViewerColumn col = new TableViewerColumn(tableViewer, SWT.NONE); col.getColumn().setText(Messages.BriefAuswahlColumnDate); col.getColumn().setWidth(100); col.getColumn().addSelectionListener(getSelectionAdapter(col.getColumn(), 0)); col.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element){ Brief b = (Brief) element; return b.getDatum(); } }); // second column - title col = new TableViewerColumn(tableViewer, SWT.NONE); col.getColumn().setText(Messages.BriefAuswahlColumnTitle); col.getColumn().setWidth(300); col.getColumn().addSelectionListener(getSelectionAdapter(col.getColumn(), 1)); col.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element){ Brief b = (Brief) element; return b.getBetreff(); } }); } private SelectionAdapter getSelectionAdapter(final TableColumn column, final int index){ SelectionAdapter selectionAdapter = new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ comparator.setColumn(index); tableViewer.getTable().setSortDirection(comparator.getDirection()); tableViewer.getTable().setSortColumn(column); tableViewer.refresh(); } }; return selectionAdapter; } class LetterViewerComparator extends ViewerComparator { private int propertyIndex; private boolean direction = true; private TimeTool time1; private TimeTool time2; public LetterViewerComparator(){ this.propertyIndex = 0; time1 = new TimeTool(); time2 = new TimeTool(); } /** * for sort direction * * @return SWT.DOWN or SWT.UP */ public int getDirection(){ return direction ? SWT.DOWN : SWT.UP; } public void setColumn(int column){ if (column == this.propertyIndex) { // Same column as last sort; toggle the direction direction = !direction; } else { // New column; do an ascending sort this.propertyIndex = column; direction = true; } } @Override public int compare(Viewer viewer, Object e1, Object e2){ if (e1 instanceof Brief && e2 instanceof Brief) { Brief b1 = (Brief) e1; Brief b2 = (Brief) e2; int rc = 0; switch (propertyIndex) { case 0: time1.set((b1).getDatum()); time2.set((b2).getDatum()); rc = time1.compareTo(time2); break; case 1: rc = b1.getBetreff().compareTo(b2.getBetreff()); break; default: rc = 0; } // If descending order, flip the direction if (direction) { rc = -rc; } return rc; } return 0; } } } private void makeActions(){ briefNeuAction = new Action(Messages.BriefAuswahlNewButtonText) { //$NON-NLS-1$ @Override public void run(){ Patient pat = ElexisEventDispatcher.getSelectedPatient(); if (pat == null) { MessageDialog.openInformation(UiDesk.getTopShell(), Messages.BriefAuswahlNoPatientSelected, Messages.BriefAuswahlNoPatientSelected); return; } Fall selectedFall = (Fall) ElexisEventDispatcher.getSelected(Fall.class); if (selectedFall == null) { SelectFallDialog sfd = new SelectFallDialog(UiDesk.getTopShell()); sfd.open(); if (sfd.result != null) { ElexisEventDispatcher.fireSelectionEvent(sfd.result); } else { MessageDialog.openInformation(UiDesk.getTopShell(), Messages.TextView_NoCaseSelected, //$NON-NLS-1$ Messages.TextView_SaveNotPossibleNoCaseAndKonsSelected); //$NON-NLS-1$ return; } } Konsultation selectedKonsultation = (Konsultation) ElexisEventDispatcher.getSelected(Konsultation.class); if (selectedKonsultation == null) { Konsultation k = pat.getLetzteKons(false); if (k == null) { k = ((Fall) ElexisEventDispatcher.getSelected(Fall.class)) .neueKonsultation(); k.setMandant(CoreHub.actMandant); } ElexisEventDispatcher.fireSelectionEvent(k); } TextView tv = null; try { tv = (TextView) getSite().getPage().showView(TextView.ID /* * ,StringTool.unique * ("textView") * ,IWorkbenchPage * .VIEW_ACTIVATE */); DocumentSelectDialog bs = new DocumentSelectDialog(getViewSite().getShell(), CoreHub.actMandant, DocumentSelectDialog.TYPE_CREATE_DOC_WITH_TEMPLATE); if (bs.open() == Dialog.OK) { // trick: just supply a dummy address for creating the doc Kontakt address = null; if (DocumentSelectDialog.getDontAskForAddresseeForThisTemplate(bs .getSelectedDocument())) address = Kontakt.load("-1"); tv.createDocument(bs.getSelectedDocument(), bs.getBetreff(), address); tv.setName(); CTabItem sel = ctab.getSelection(); if (sel != null) { CommonViewer cv = (CommonViewer) sel.getData(); cv.notify(CommonViewer.Message.update_keeplabels); } } } catch (Exception ex) { ExHandler.handle(ex); } } }; briefLadenAction = new Action(Messages.BriefAuswahlOpenButtonText) { //$NON-NLS-1$ @Override public void run(){ try { TextView tv = (TextView) getViewSite().getPage().showView(TextView.ID); CTabItem sel = ctab.getSelection(); if (sel != null) { CommonViewer cv = (CommonViewer) sel.getData(); Object[] o = cv.getSelection(); if ((o != null) && (o.length > 0)) { Brief brief = (Brief) o[0]; if (tv.openDocument(brief) == false) { SWTHelper.alert(Messages.BriefAuswahlErrorHeading, //$NON-NLS-1$ Messages.BriefAuswahlCouldNotLoadText); //$NON-NLS-1$ } } else { tv.createDocument(null, null); } cv.notify(CommonViewer.Message.update); } } catch (PartInitException e) { ExHandler.handle(e); } } }; deleteAction = new Action(Messages.BriefAuswahlDeleteButtonText) { //$NON-NLS-1$ @Override public void run(){ CTabItem sel = ctab.getSelection(); if ((sel != null) && SWTHelper.askYesNo(Messages.BriefAuswahlDeleteConfirmHeading, //$NON-NLS-1$ Messages.BriefAuswahlDeleteConfirmText)) { //$NON-NLS-1$ CommonViewer cv = (CommonViewer) sel.getData(); Object[] o = cv.getSelection(); if ((o != null) && (o.length > 0)) { Brief brief = (Brief) o[0]; brief.delete(); } cv.notify(CommonViewer.Message.update); } } }; editNameAction = new Action(Messages.BriefAuswahlRenameButtonText) { //$NON-NLS-1$ @Override public void run(){ CTabItem sel = ctab.getSelection(); if (sel != null) { CommonViewer cv = (CommonViewer) sel.getData(); Object[] o = cv.getSelection(); if ((o != null) && (o.length > 0)) { Brief brief = (Brief) o[0]; InputDialog id = new InputDialog(getViewSite().getShell(), Messages.BriefAuswahlNewSubjectHeading, //$NON-NLS-1$ Messages.BriefAuswahlNewSubjectText, //$NON-NLS-1$ brief.getBetreff(), null); if (id.open() == Dialog.OK) { brief.setBetreff(id.getValue()); } } cv.notify(CommonViewer.Message.update); } } }; /* * importAction=new Action("Importieren..."){ public void run(){ * * } }; */ briefLadenAction.setImageDescriptor(Images.IMG_DOCUMENT_TEXT.getImageDescriptor()); briefLadenAction.setToolTipText(Messages.BriefAuswahlOpenLetterForEdit); //$NON-NLS-1$ briefNeuAction.setImageDescriptor(Images.IMG_DOCUMENT_ADD.getImageDescriptor()); briefNeuAction.setToolTipText(Messages.BriefAuswahlCreateNewDocument); //$NON-NLS-1$ editNameAction.setImageDescriptor(Images.IMG_DOCUMENT_WRITE.getImageDescriptor()); editNameAction.setToolTipText(Messages.BriefAuswahlRenameDocument); //$NON-NLS-1$ deleteAction.setImageDescriptor(Images.IMG_DOCUMENT_REMOVE.getImageDescriptor()); deleteAction.setToolTipText(Messages.BriefAuswahlDeleteDocument); //$NON-NLS-1$ } public void activation(final boolean mode){ // TODO Auto-generated method stub } public void visible(final boolean mode){ if (mode == true) { ElexisEventDispatcher.getInstance().addListeners(this); relabel(); } else { ElexisEventDispatcher.getInstance().removeListeners(this); } } /* * Die folgenden 6 Methoden implementieren das Interface ISaveablePart2 Wir benötigen das * Interface nur, um das Schliessen einer View zu verhindern, wenn die Perspektive fixiert ist. * Gibt es da keine einfachere Methode? */ public int promptToSaveOnClose(){ return GlobalActions.fixLayoutAction.isChecked() ? ISaveablePart2.CANCEL : ISaveablePart2.NO; } public void doSave(final IProgressMonitor monitor){ /* leer */ } public void doSaveAs(){ /* leer */ } public boolean isDirty(){ return true; } public boolean isSaveAsAllowed(){ return false; } public boolean isSaveOnCloseNeeded(){ return true; } public void catchElexisEvent(ElexisEvent ev){ relabel(); } private static ElexisEvent template = new ElexisEvent(null, Patient.class, ElexisEvent.EVENT_SELECTED | ElexisEvent.EVENT_DESELECTED); public ElexisEvent getElexisEventFilter(){ return template; } }
ch.elexis.core.ui/src/ch/elexis/core/ui/views/BriefAuswahl.java
/******************************************************************************* * Copyright (c) 2006-2010, G. Weirich and Elexis * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * G. Weirich - initial implementation * *******************************************************************************/ package ch.elexis.core.ui.views; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.InputDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ColumnLabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerComparator; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.ui.ISaveablePart2; import org.eclipse.ui.PartInitException; import org.eclipse.ui.forms.widgets.Form; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.part.ViewPart; import ch.elexis.core.constants.Preferences; import ch.elexis.core.data.activator.CoreHub; import ch.elexis.core.data.events.ElexisEvent; import ch.elexis.core.data.events.ElexisEventDispatcher; import ch.elexis.core.ui.UiDesk; import ch.elexis.core.ui.actions.GlobalActions; import ch.elexis.core.ui.actions.GlobalEventDispatcher; import ch.elexis.core.ui.actions.IActivationListener; import ch.elexis.core.ui.dialogs.DocumentSelectDialog; import ch.elexis.core.ui.dialogs.SelectFallDialog; import ch.elexis.core.ui.icons.Images; import ch.elexis.core.ui.util.SWTHelper; import ch.elexis.core.ui.util.ViewMenus; import ch.elexis.core.ui.util.viewers.CommonViewer; import ch.elexis.core.ui.util.viewers.CommonViewer.DoubleClickListener; import ch.elexis.core.ui.util.viewers.DefaultContentProvider; import ch.elexis.core.ui.util.viewers.DefaultControlFieldProvider; import ch.elexis.core.ui.util.viewers.DefaultLabelProvider; import ch.elexis.core.ui.util.viewers.SimpleWidgetProvider; import ch.elexis.core.ui.util.viewers.ViewerConfigurer; import ch.elexis.data.Brief; import ch.elexis.data.Fall; import ch.elexis.data.Konsultation; import ch.elexis.data.Kontakt; import ch.elexis.data.Patient; import ch.elexis.data.PersistentObject; import ch.elexis.data.Query; import ch.rgw.tools.ExHandler; import ch.rgw.tools.TimeTool; public class BriefAuswahl extends ViewPart implements ch.elexis.core.data.events.ElexisEventListener, IActivationListener, ISaveablePart2 { public final static String ID = "ch.elexis.BriefAuswahlView"; //$NON-NLS-1$ private final FormToolkit tk; private Form form; private Action briefNeuAction, briefLadenAction, editNameAction; private Action deleteAction; private ViewMenus menus; private ArrayList<sPage> pages = new ArrayList<sPage>(); CTabFolder ctab; // private ViewMenus menu; // private IAction delBriefAction; public BriefAuswahl(){ tk = UiDesk.getToolkit(); } @Override public void createPartControl(final Composite parent){ StringBuilder sb = new StringBuilder(); sb.append(Messages.BriefAuswahlAllLetters).append(Brief.UNKNOWN) .append(",").append(Brief.AUZ) //$NON-NLS-1$ .append(",").append(Brief.RP).append(",").append(Brief.LABOR); String cats = CoreHub.globalCfg.get(Preferences.DOC_CATEGORY, sb.toString()); parent.setLayout(new GridLayout()); form = tk.createForm(parent); form.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true)); form.setBackground(parent.getBackground()); // Grid layout with zero margins GridLayout slimLayout = new GridLayout(); slimLayout.marginHeight = 0; slimLayout.marginWidth = 0; Composite body = form.getBody(); body.setLayout(slimLayout); body.setBackground(parent.getBackground()); ctab = new CTabFolder(body, SWT.BOTTOM); ctab.setLayout(slimLayout); ctab.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true)); ctab.setBackground(parent.getBackground()); makeActions(); menus = new ViewMenus(getViewSite()); for (String cat : cats.split(",")) { CTabItem ct = new CTabItem(ctab, SWT.NONE); ct.setText(cat); sPage page = new sPage(ctab, cat); pages.add(page); menus.createViewerContextMenu(page.cv.getViewerWidget(), editNameAction, deleteAction); ct.setData(page.cv); ct.setControl(page); page.cv.addDoubleClickListener(new DoubleClickListener() { @Override public void doubleClicked(PersistentObject obj, CommonViewer cv){ briefLadenAction.run(); } }); } ctab.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e){ relabel(); } }); GlobalEventDispatcher.addActivationListener(this, this); menus.createMenu(briefNeuAction, briefLadenAction, editNameAction, deleteAction); menus.createToolbar(briefNeuAction, briefLadenAction, deleteAction); ctab.setSelection(0); relabel(); } @Override public void dispose(){ ElexisEventDispatcher.getInstance().removeListeners(this); GlobalEventDispatcher.removeActivationListener(this, this); for (sPage page : pages) { page.getCommonViewer().getConfigurer().getContentProvider().stopListening(); } } @Override public void setFocus(){ } public void relabel(){ UiDesk.asyncExec(new Runnable() { public void run(){ Patient pat = (Patient) ElexisEventDispatcher.getSelected(Patient.class); if (pat == null) { form.setText(Messages.BriefAuswahlNoPatientSelected); //$NON-NLS-1$ } else { form.setText(pat.getLabel()); CTabItem sel = ctab.getSelection(); if (sel != null) { CommonViewer cv = (CommonViewer) sel.getData(); cv.notify(CommonViewer.Message.update); } } } }); } class sPage extends Composite { private TableViewer tableViewer; private LetterViewerComparator comparator; private final CommonViewer cv; private final ViewerConfigurer vc; public CommonViewer getCommonViewer(){ return cv; } sPage(final Composite parent, final String cat){ super(parent, SWT.NONE); setLayout(new GridLayout()); cv = new CommonViewer(); vc = new ViewerConfigurer(new DefaultContentProvider(cv, Brief.class, new String[] { Brief.FLD_DATE }, true) { @Override public Object[] getElements(final Object inputElement){ Patient actPat = (Patient) ElexisEventDispatcher.getSelected(Patient.class); if (actPat != null) { Query<Brief> qbe = new Query<Brief>(Brief.class); qbe.add(Brief.FLD_PATIENT_ID, Query.EQUALS, actPat.getId()); if (cat.equals(Messages.BriefAuswahlAllLetters2)) { //$NON-NLS-1$ qbe.add(Brief.FLD_TYPE, Query.NOT_EQUAL, Brief.TEMPLATE); } else { qbe.add(Brief.FLD_TYPE, Query.EQUALS, cat); } cv.getConfigurer().getControlFieldProvider().setQuery(qbe); List<Brief> list = qbe.execute(); return list.toArray(); } else { return new Brief[0]; } } }, new DefaultLabelProvider(), new DefaultControlFieldProvider(cv, new String[] { "Betreff=Titel" }), new ViewerConfigurer.DefaultButtonProvider(), new SimpleWidgetProvider( SimpleWidgetProvider.TYPE_TABLE, SWT.V_SCROLL | SWT.FULL_SELECTION, cv)); cv.create(vc, this, SWT.NONE, getViewSite()); tableViewer = (TableViewer) cv.getViewerWidget(); tableViewer.getTable().setHeaderVisible(true); createColumns(); comparator = new LetterViewerComparator(); tableViewer.setComparator(comparator); vc.getContentProvider().startListening(); Button bLoad = tk.createButton(this, Messages.BriefAuswahlLoadButtonText, SWT.PUSH); //$NON-NLS-1$ bLoad.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e){ try { TextView tv = (TextView) getViewSite().getPage().showView(TextView.ID); Object[] o = cv.getSelection(); if ((o != null) && (o.length > 0)) { Brief brief = (Brief) o[0]; if (tv.openDocument(brief) == false) { SWTHelper.alert(Messages.BriefAuswahlErrorHeading, //$NON-NLS-1$ Messages.BriefAuswahlCouldNotLoadText); //$NON-NLS-1$ } } else { tv.createDocument(null, null); } } catch (Throwable ex) { ExHandler.handle(ex); } } }); bLoad.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false)); } // create the columns for the table private void createColumns(){ // first column - date TableViewerColumn col = new TableViewerColumn(tableViewer, SWT.NONE); col.getColumn().setText(Messages.BriefAuswahlColumnDate); col.getColumn().setWidth(100); col.getColumn().addSelectionListener(getSelectionAdapter(col.getColumn(), 0)); col.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element){ Brief b = (Brief) element; return b.getDatum(); } }); // second column - title col = new TableViewerColumn(tableViewer, SWT.NONE); col.getColumn().setText(Messages.BriefAuswahlColumnTitle); col.getColumn().setWidth(300); col.getColumn().addSelectionListener(getSelectionAdapter(col.getColumn(), 1)); col.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element){ Brief b = (Brief) element; return b.getBetreff(); } }); } private SelectionAdapter getSelectionAdapter(final TableColumn column, final int index){ SelectionAdapter selectionAdapter = new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ comparator.setColumn(index); int dir = comparator.getDirection(); tableViewer.getTable().setSortDirection(dir); tableViewer.getTable().setSortColumn(column); tableViewer.refresh(); } }; return selectionAdapter; } class LetterViewerComparator extends ViewerComparator { private int propertyIndex; private static final int DESCENDING = 1; private int direction = DESCENDING; public LetterViewerComparator(){ this.propertyIndex = 0; direction = DESCENDING; } public int getDirection(){ return direction == 1 ? SWT.DOWN : SWT.UP; } public void setColumn(int column){ if (column == this.propertyIndex) { // Same column as last sort; toggle the direction direction = 1 - direction; } else { // New column; do an ascending sort this.propertyIndex = column; direction = DESCENDING; } } @Override public int compare(Viewer viewer, Object e1, Object e2){ Brief b1 = (Brief) e1; Brief b2 = (Brief) e2; int rc = 0; switch (propertyIndex) { case 0: TimeTool time1 = new TimeTool(((Brief) e1).getDatum()); TimeTool time2 = new TimeTool(((Brief) e2).getDatum()); rc = time1.compareTo(time2); break; case 1: rc = b1.getBetreff().compareTo(b2.getBetreff()); break; default: rc = 0; } // If descending order, flip the direction if (direction == DESCENDING) { rc = -rc; } return rc; } } } private void makeActions(){ briefNeuAction = new Action(Messages.BriefAuswahlNewButtonText) { //$NON-NLS-1$ @Override public void run(){ Patient pat = ElexisEventDispatcher.getSelectedPatient(); if (pat == null) { MessageDialog.openInformation(UiDesk.getTopShell(), Messages.BriefAuswahlNoPatientSelected, Messages.BriefAuswahlNoPatientSelected); return; } Fall selectedFall = (Fall) ElexisEventDispatcher.getSelected(Fall.class); if (selectedFall == null) { SelectFallDialog sfd = new SelectFallDialog(UiDesk.getTopShell()); sfd.open(); if (sfd.result != null) { ElexisEventDispatcher.fireSelectionEvent(sfd.result); } else { MessageDialog.openInformation(UiDesk.getTopShell(), Messages.TextView_NoCaseSelected, //$NON-NLS-1$ Messages.TextView_SaveNotPossibleNoCaseAndKonsSelected); //$NON-NLS-1$ return; } } Konsultation selectedKonsultation = (Konsultation) ElexisEventDispatcher.getSelected(Konsultation.class); if (selectedKonsultation == null) { Konsultation k = pat.getLetzteKons(false); if (k == null) { k = ((Fall) ElexisEventDispatcher.getSelected(Fall.class)) .neueKonsultation(); k.setMandant(CoreHub.actMandant); } ElexisEventDispatcher.fireSelectionEvent(k); } TextView tv = null; try { tv = (TextView) getSite().getPage().showView(TextView.ID /* * ,StringTool.unique * ("textView") * ,IWorkbenchPage * .VIEW_ACTIVATE */); DocumentSelectDialog bs = new DocumentSelectDialog(getViewSite().getShell(), CoreHub.actMandant, DocumentSelectDialog.TYPE_CREATE_DOC_WITH_TEMPLATE); if (bs.open() == Dialog.OK) { // trick: just supply a dummy address for creating the doc Kontakt address = null; if (DocumentSelectDialog.getDontAskForAddresseeForThisTemplate(bs .getSelectedDocument())) address = Kontakt.load("-1"); tv.createDocument(bs.getSelectedDocument(), bs.getBetreff(), address); tv.setName(); CTabItem sel = ctab.getSelection(); if (sel != null) { CommonViewer cv = (CommonViewer) sel.getData(); cv.notify(CommonViewer.Message.update_keeplabels); } } } catch (Exception ex) { ExHandler.handle(ex); } } }; briefLadenAction = new Action(Messages.BriefAuswahlOpenButtonText) { //$NON-NLS-1$ @Override public void run(){ try { TextView tv = (TextView) getViewSite().getPage().showView(TextView.ID); CTabItem sel = ctab.getSelection(); if (sel != null) { CommonViewer cv = (CommonViewer) sel.getData(); Object[] o = cv.getSelection(); if ((o != null) && (o.length > 0)) { Brief brief = (Brief) o[0]; if (tv.openDocument(brief) == false) { SWTHelper.alert(Messages.BriefAuswahlErrorHeading, //$NON-NLS-1$ Messages.BriefAuswahlCouldNotLoadText); //$NON-NLS-1$ } } else { tv.createDocument(null, null); } cv.notify(CommonViewer.Message.update); } } catch (PartInitException e) { ExHandler.handle(e); } } }; deleteAction = new Action(Messages.BriefAuswahlDeleteButtonText) { //$NON-NLS-1$ @Override public void run(){ CTabItem sel = ctab.getSelection(); if ((sel != null) && SWTHelper.askYesNo(Messages.BriefAuswahlDeleteConfirmHeading, //$NON-NLS-1$ Messages.BriefAuswahlDeleteConfirmText)) { //$NON-NLS-1$ CommonViewer cv = (CommonViewer) sel.getData(); Object[] o = cv.getSelection(); if ((o != null) && (o.length > 0)) { Brief brief = (Brief) o[0]; brief.delete(); } cv.notify(CommonViewer.Message.update); } } }; editNameAction = new Action(Messages.BriefAuswahlRenameButtonText) { //$NON-NLS-1$ @Override public void run(){ CTabItem sel = ctab.getSelection(); if (sel != null) { CommonViewer cv = (CommonViewer) sel.getData(); Object[] o = cv.getSelection(); if ((o != null) && (o.length > 0)) { Brief brief = (Brief) o[0]; InputDialog id = new InputDialog(getViewSite().getShell(), Messages.BriefAuswahlNewSubjectHeading, //$NON-NLS-1$ Messages.BriefAuswahlNewSubjectText, //$NON-NLS-1$ brief.getBetreff(), null); if (id.open() == Dialog.OK) { brief.setBetreff(id.getValue()); } } cv.notify(CommonViewer.Message.update); } } }; /* * importAction=new Action("Importieren..."){ public void run(){ * * } }; */ briefLadenAction.setImageDescriptor(Images.IMG_DOCUMENT_TEXT.getImageDescriptor()); briefLadenAction.setToolTipText(Messages.BriefAuswahlOpenLetterForEdit); //$NON-NLS-1$ briefNeuAction.setImageDescriptor(Images.IMG_DOCUMENT_ADD.getImageDescriptor()); briefNeuAction.setToolTipText(Messages.BriefAuswahlCreateNewDocument); //$NON-NLS-1$ editNameAction.setImageDescriptor(Images.IMG_DOCUMENT_WRITE.getImageDescriptor()); editNameAction.setToolTipText(Messages.BriefAuswahlRenameDocument); //$NON-NLS-1$ deleteAction.setImageDescriptor(Images.IMG_DOCUMENT_REMOVE.getImageDescriptor()); deleteAction.setToolTipText(Messages.BriefAuswahlDeleteDocument); //$NON-NLS-1$ } public void activation(final boolean mode){ // TODO Auto-generated method stub } public void visible(final boolean mode){ if (mode == true) { ElexisEventDispatcher.getInstance().addListeners(this); relabel(); } else { ElexisEventDispatcher.getInstance().removeListeners(this); } } /* * Die folgenden 6 Methoden implementieren das Interface ISaveablePart2 Wir benötigen das * Interface nur, um das Schliessen einer View zu verhindern, wenn die Perspektive fixiert ist. * Gibt es da keine einfachere Methode? */ public int promptToSaveOnClose(){ return GlobalActions.fixLayoutAction.isChecked() ? ISaveablePart2.CANCEL : ISaveablePart2.NO; } public void doSave(final IProgressMonitor monitor){ /* leer */ } public void doSaveAs(){ /* leer */ } public boolean isDirty(){ return true; } public boolean isSaveAsAllowed(){ return false; } public boolean isSaveOnCloseNeeded(){ return true; } public void catchElexisEvent(ElexisEvent ev){ relabel(); } private static ElexisEvent template = new ElexisEvent(null, Patient.class, ElexisEvent.EVENT_SELECTED | ElexisEvent.EVENT_DESELECTED); public ElexisEvent getElexisEventFilter(){ return template; } }
[1386] save 'Brief' access
ch.elexis.core.ui/src/ch/elexis/core/ui/views/BriefAuswahl.java
[1386] save 'Brief' access
<ide><path>h.elexis.core.ui/src/ch/elexis/core/ui/views/BriefAuswahl.java <ide> @Override <ide> public void widgetSelected(SelectionEvent e){ <ide> comparator.setColumn(index); <del> int dir = comparator.getDirection(); <del> tableViewer.getTable().setSortDirection(dir); <add> tableViewer.getTable().setSortDirection(comparator.getDirection()); <ide> tableViewer.getTable().setSortColumn(column); <ide> tableViewer.refresh(); <ide> } <ide> <ide> class LetterViewerComparator extends ViewerComparator { <ide> private int propertyIndex; <del> private static final int DESCENDING = 1; <del> private int direction = DESCENDING; <add> private boolean direction = true; <add> private TimeTool time1; <add> private TimeTool time2; <ide> <ide> public LetterViewerComparator(){ <ide> this.propertyIndex = 0; <del> direction = DESCENDING; <add> time1 = new TimeTool(); <add> time2 = new TimeTool(); <ide> } <ide> <add> /** <add> * for sort direction <add> * <add> * @return SWT.DOWN or SWT.UP <add> */ <ide> public int getDirection(){ <del> return direction == 1 ? SWT.DOWN : SWT.UP; <add> return direction ? SWT.DOWN : SWT.UP; <ide> } <ide> <ide> public void setColumn(int column){ <ide> if (column == this.propertyIndex) { <ide> // Same column as last sort; toggle the direction <del> direction = 1 - direction; <add> direction = !direction; <ide> } else { <ide> // New column; do an ascending sort <ide> this.propertyIndex = column; <del> direction = DESCENDING; <add> direction = true; <ide> } <ide> } <ide> <ide> @Override <ide> public int compare(Viewer viewer, Object e1, Object e2){ <del> Brief b1 = (Brief) e1; <del> Brief b2 = (Brief) e2; <del> int rc = 0; <del> switch (propertyIndex) { <del> case 0: <del> TimeTool time1 = new TimeTool(((Brief) e1).getDatum()); <del> TimeTool time2 = new TimeTool(((Brief) e2).getDatum()); <del> rc = time1.compareTo(time2); <del> break; <del> case 1: <del> rc = b1.getBetreff().compareTo(b2.getBetreff()); <del> break; <del> default: <del> rc = 0; <del> } <del> // If descending order, flip the direction <del> if (direction == DESCENDING) { <del> rc = -rc; <del> } <del> return rc; <add> if (e1 instanceof Brief && e2 instanceof Brief) { <add> Brief b1 = (Brief) e1; <add> Brief b2 = (Brief) e2; <add> int rc = 0; <add> switch (propertyIndex) { <add> case 0: <add> time1.set((b1).getDatum()); <add> time2.set((b2).getDatum()); <add> rc = time1.compareTo(time2); <add> break; <add> case 1: <add> rc = b1.getBetreff().compareTo(b2.getBetreff()); <add> break; <add> default: <add> rc = 0; <add> } <add> // If descending order, flip the direction <add> if (direction) { <add> rc = -rc; <add> } <add> return rc; <add> } <add> return 0; <ide> } <ide> } <ide> }
Java
mit
ae2b66e42653af7c6ea4baaaaf9b4732f49a282d
0
jenkinsci/plasticscm-plugin,jenkinsci/plasticscm-plugin
package com.codicesoftware.plugins.hudson.actions; import com.codicesoftware.plugins.hudson.PlasticTool; import com.codicesoftware.plugins.hudson.WorkspaceManager; import com.codicesoftware.plugins.hudson.commands.CommandRunner; import com.codicesoftware.plugins.hudson.commands.GetSelectorSpecCommand; import com.codicesoftware.plugins.hudson.model.Workspace; import com.codicesoftware.plugins.hudson.model.WorkspaceInfo; import hudson.FilePath; import org.apache.commons.io.FilenameUtils; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CheckoutAction { private static final Logger LOGGER = Logger.getLogger(CheckoutAction.class.getName()); private static final Pattern WINDOWS_PATH_PATTERN = Pattern.compile("^[a-zA-Z]:/.*$"); private CheckoutAction() { } public static Workspace checkout( PlasticTool tool, FilePath workspacePath, String selector, boolean useUpdate) throws IOException, InterruptedException, ParseException { List<Workspace> workspaces = WorkspaceManager.loadWorkspaces(tool); cleanOldWorkspacesIfNeeded(tool, workspacePath, useUpdate, workspaces); if (!useUpdate && workspacePath.exists()) { workspacePath.deleteContents(); } return checkoutWorkspace(tool, workspacePath, selector, workspaces); } private static Workspace checkoutWorkspace( PlasticTool tool, FilePath workspacePath, String selector, List<Workspace> workspaces) throws IOException, InterruptedException, ParseException { Workspace workspace = findWorkspaceByPath(workspaces, workspacePath); if (workspace != null) { LOGGER.fine("Reusing existing workspace"); WorkspaceManager.cleanWorkspace(tool, workspace.getPath()); if (mustUpdateSelector(tool, workspace.getName(), selector)) { WorkspaceManager.setWorkspaceSelector(tool, workspacePath, selector); return workspace; } if (isBranchSelector(tool, selector)) { WorkspaceManager.updateWorkspace(tool, workspace.getPath()); } return workspace; } LOGGER.fine("Creating new workspace"); String uniqueWorkspaceName = WorkspaceManager.generateUniqueWorkspaceName(); workspace = WorkspaceManager.newWorkspace(tool, workspacePath, uniqueWorkspaceName, selector); WorkspaceManager.cleanWorkspace(tool, workspace.getPath()); WorkspaceManager.updateWorkspace(tool, workspace.getPath()); return workspace; } private static boolean mustUpdateSelector(PlasticTool tool, String name, String selector) { String wkSelector = removeNewLinesFromSelector(WorkspaceManager.loadSelector(tool, name)); String currentSelector = removeNewLinesFromSelector(selector); return !wkSelector.equals(currentSelector); } private static String removeNewLinesFromSelector(String selector) { return selector.trim().replace("\r\n", "").replace("\n", "").replace("\r", ""); } private static boolean isBranchSelector(PlasticTool tool, String selector) { Path selectorFilePath = null; try { selectorFilePath = Files.createTempFile("selector_", ".txt"); Files.write( selectorFilePath, selector.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE); GetSelectorSpecCommand getSelectorSpecCommand = new GetSelectorSpecCommand( selectorFilePath.toString()); WorkspaceInfo wkInfo = CommandRunner.executeAndRead( tool, getSelectorSpecCommand, getSelectorSpecCommand); if (wkInfo == null) { LOGGER.info(String.format( "Invalid selector:%s%s", System.lineSeparator(), selector)); return false; } String branchSpec = wkInfo.getBranch(); return branchSpec != null && !branchSpec.equals(""); } catch (Exception e) { LOGGER.log( Level.SEVERE, "Unable to determine whether selector is a branch selector", e); LOGGER.log( Level.INFO, String.format("Selector:%s%s", System.lineSeparator(), selector)); return false; } finally { try { if (selectorFilePath != null) { Files.deleteIfExists(selectorFilePath); } } catch (IOException e) { LOGGER.log( Level.WARNING, String.format("Delete tmp selector file '%s' failed", selectorFilePath), e); } } } private static void cleanOldWorkspacesIfNeeded( PlasticTool tool, FilePath workspacePath, boolean shouldUseUpdate, List<Workspace> workspaces) throws IOException, InterruptedException { // handle situation where workspace exists in parent path Workspace parentWorkspace = findWorkspaceByPath(workspaces, workspacePath.getParent()); if (parentWorkspace != null) { deleteWorkspace(tool, parentWorkspace, workspaces); } // handle situation where workspace exists in child path List<Workspace> nestedWorkspaces = findWorkspacesInsidePath(workspaces, workspacePath); for (Workspace workspace : nestedWorkspaces) { deleteWorkspace(tool, workspace, workspaces); } if (shouldUseUpdate) { return; } Workspace workspace = findWorkspaceByPath(workspaces, workspacePath); if (workspace != null) { deleteWorkspace(tool, workspace, workspaces); } } private static boolean isSameWorkspacePath(String actual, String expected) { String actualFixed = actual.replaceAll("\\\\", "/"); String expectedFixed = expected.replaceAll("\\\\", "/"); Matcher windowsPathMatcher = WINDOWS_PATH_PATTERN.matcher(expectedFixed); if (windowsPathMatcher.matches()) { return actualFixed.equalsIgnoreCase(expectedFixed); } return actualFixed.equals(expectedFixed); } private static void deleteWorkspace( PlasticTool tool, Workspace workspace, List<Workspace> workspaces) throws IOException, InterruptedException { WorkspaceManager.deleteWorkspace(tool, workspace.getPath()); workspace.getPath().deleteContents(); workspaces.remove(workspace); } @Deprecated private static Workspace findWorkspaceByName(List<Workspace> workspaces, String workspaceName) { for (Workspace workspace : workspaces) { if (workspace.getName().equals(workspaceName)) { return workspace; } } return null; } private static Workspace findWorkspaceByPath(List<Workspace> workspaces, FilePath workspacePath) { for (Workspace workspace : workspaces) { if (isSameWorkspacePath(workspace.getPath().getRemote(), workspacePath.getRemote())) { return workspace; } } return null; } private static List<Workspace> findWorkspacesInsidePath(List<Workspace> workspaces, FilePath workspacePath) { List<Workspace> result = new ArrayList<>(); for (Workspace workspace : workspaces) { String parentPath = FilenameUtils.getFullPathNoEndSeparator(workspace.getPath().getRemote()); if (isSameWorkspacePath(parentPath, workspacePath.getRemote())) { result.add(workspace); } } return result; } }
src/main/java/com/codicesoftware/plugins/hudson/actions/CheckoutAction.java
package com.codicesoftware.plugins.hudson.actions; import com.codicesoftware.plugins.hudson.PlasticTool; import com.codicesoftware.plugins.hudson.WorkspaceManager; import com.codicesoftware.plugins.hudson.model.Workspace; import hudson.FilePath; import org.apache.commons.io.FilenameUtils; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CheckoutAction { private static final Logger LOGGER = Logger.getLogger(CheckoutAction.class.getName()); private static final Pattern WINDOWS_PATH_PATTERN = Pattern.compile("^[a-zA-Z]:/.*$"); private CheckoutAction() { } public static Workspace checkout( PlasticTool tool, FilePath workspacePath, String selector, boolean useUpdate) throws IOException, InterruptedException, ParseException { List<Workspace> workspaces = WorkspaceManager.loadWorkspaces(tool); cleanOldWorkspacesIfNeeded(tool, workspacePath, useUpdate, workspaces); if (!useUpdate && workspacePath.exists()) { workspacePath.deleteContents(); } return checkoutWorkspace(tool, workspacePath, selector, workspaces); } private static Workspace checkoutWorkspace( PlasticTool tool, FilePath workspacePath, String selector, List<Workspace> workspaces) throws IOException, InterruptedException, ParseException { Workspace workspace = findWorkspaceByPath(workspaces, workspacePath); if (workspace != null) { LOGGER.fine("Reusing existing workspace"); WorkspaceManager.cleanWorkspace(tool, workspace.getPath()); if (mustUpdateSelector(tool, workspace.getName(), selector)) { WorkspaceManager.setWorkspaceSelector(tool, workspacePath, selector); return workspace; } if (!isChangesetOrLabelSelector(selector)) { WorkspaceManager.updateWorkspace(tool, workspace.getPath()); } return workspace; } LOGGER.fine("Creating new workspace"); String uniqueWorkspaceName = WorkspaceManager.generateUniqueWorkspaceName(); workspace = WorkspaceManager.newWorkspace(tool, workspacePath, uniqueWorkspaceName, selector); WorkspaceManager.cleanWorkspace(tool, workspace.getPath()); WorkspaceManager.updateWorkspace(tool, workspace.getPath()); return workspace; } private static boolean mustUpdateSelector(PlasticTool tool, String name, String selector) { String wkSelector = removeNewLinesFromSelector(WorkspaceManager.loadSelector(tool, name)); String currentSelector = removeNewLinesFromSelector(selector); return !wkSelector.equals(currentSelector); } private static String removeNewLinesFromSelector(String selector) { return selector.trim().replace("\r\n", "").replace("\n", "").replace("\r", ""); } private static boolean isChangesetOrLabelSelector(String selector) { return selector.contains("changeset") || selector.contains("label"); } private static void cleanOldWorkspacesIfNeeded( PlasticTool tool, FilePath workspacePath, boolean shouldUseUpdate, List<Workspace> workspaces) throws IOException, InterruptedException { // handle situation where workspace exists in parent path Workspace parentWorkspace = findWorkspaceByPath(workspaces, workspacePath.getParent()); if (parentWorkspace != null) { deleteWorkspace(tool, parentWorkspace, workspaces); } // handle situation where workspace exists in child path List<Workspace> nestedWorkspaces = findWorkspacesInsidePath(workspaces, workspacePath); for (Workspace workspace : nestedWorkspaces) { deleteWorkspace(tool, workspace, workspaces); } if (shouldUseUpdate) { return; } Workspace workspace = findWorkspaceByPath(workspaces, workspacePath); if (workspace != null) { deleteWorkspace(tool, workspace, workspaces); } } private static boolean isSameWorkspacePath(String actual, String expected) { String actualFixed = actual.replaceAll("\\\\", "/"); String expectedFixed = expected.replaceAll("\\\\", "/"); Matcher windowsPathMatcher = WINDOWS_PATH_PATTERN.matcher(expectedFixed); if (windowsPathMatcher.matches()) { return actualFixed.equalsIgnoreCase(expectedFixed); } return actualFixed.equals(expectedFixed); } private static void deleteWorkspace( PlasticTool tool, Workspace workspace, List<Workspace> workspaces) throws IOException, InterruptedException { WorkspaceManager.deleteWorkspace(tool, workspace.getPath()); workspace.getPath().deleteContents(); workspaces.remove(workspace); } @Deprecated private static Workspace findWorkspaceByName(List<Workspace> workspaces, String workspaceName) { for (Workspace workspace : workspaces) { if (workspace.getName().equals(workspaceName)) { return workspace; } } return null; } private static Workspace findWorkspaceByPath(List<Workspace> workspaces, FilePath workspacePath) { for (Workspace workspace : workspaces) { if (isSameWorkspacePath(workspace.getPath().getRemote(), workspacePath.getRemote())) { return workspace; } } return null; } private static List<Workspace> findWorkspacesInsidePath(List<Workspace> workspaces, FilePath workspacePath) { List<Workspace> result = new ArrayList<>(); for (Workspace workspace : workspaces) { String parentPath = FilenameUtils.getFullPathNoEndSeparator(workspace.getPath().getRemote()); if (isSameWorkspacePath(parentPath, workspacePath.getRemote())) { result.add(workspace); } } return result; } }
Improve the selector type detection Instead of simply checking the selector string, perform a CLI command to determine the selector type. This avoids issues if e.g. the branch name contains the word "changeset" or "label". Signed-off-by: Miguel González <[email protected]>
src/main/java/com/codicesoftware/plugins/hudson/actions/CheckoutAction.java
Improve the selector type detection
<ide><path>rc/main/java/com/codicesoftware/plugins/hudson/actions/CheckoutAction.java <ide> <ide> import com.codicesoftware.plugins.hudson.PlasticTool; <ide> import com.codicesoftware.plugins.hudson.WorkspaceManager; <add>import com.codicesoftware.plugins.hudson.commands.CommandRunner; <add>import com.codicesoftware.plugins.hudson.commands.GetSelectorSpecCommand; <ide> import com.codicesoftware.plugins.hudson.model.Workspace; <add>import com.codicesoftware.plugins.hudson.model.WorkspaceInfo; <ide> import hudson.FilePath; <ide> import org.apache.commons.io.FilenameUtils; <ide> <ide> import java.io.IOException; <add>import java.nio.charset.StandardCharsets; <add>import java.nio.file.Files; <add>import java.nio.file.Path; <add>import java.nio.file.StandardOpenOption; <ide> import java.text.ParseException; <ide> import java.util.ArrayList; <ide> import java.util.List; <add>import java.util.logging.Level; <ide> import java.util.logging.Logger; <ide> import java.util.regex.Matcher; <ide> import java.util.regex.Pattern; <ide> return workspace; <ide> } <ide> <del> if (!isChangesetOrLabelSelector(selector)) { <add> if (isBranchSelector(tool, selector)) { <ide> WorkspaceManager.updateWorkspace(tool, workspace.getPath()); <ide> } <ide> return workspace; <ide> return selector.trim().replace("\r\n", "").replace("\n", "").replace("\r", ""); <ide> } <ide> <del> private static boolean isChangesetOrLabelSelector(String selector) { <del> return selector.contains("changeset") || selector.contains("label"); <add> private static boolean isBranchSelector(PlasticTool tool, String selector) { <add> Path selectorFilePath = null; <add> try { <add> selectorFilePath = Files.createTempFile("selector_", ".txt"); <add> Files.write( <add> selectorFilePath, <add> selector.getBytes(StandardCharsets.UTF_8), <add> StandardOpenOption.CREATE); <add> <add> GetSelectorSpecCommand getSelectorSpecCommand = new GetSelectorSpecCommand( <add> selectorFilePath.toString()); <add> <add> WorkspaceInfo wkInfo = CommandRunner.executeAndRead( <add> tool, getSelectorSpecCommand, getSelectorSpecCommand); <add> <add> if (wkInfo == null) { <add> LOGGER.info(String.format( <add> "Invalid selector:%s%s", System.lineSeparator(), selector)); <add> return false; <add> } <add> <add> String branchSpec = wkInfo.getBranch(); <add> return branchSpec != null && !branchSpec.equals(""); <add> } catch (Exception e) { <add> LOGGER.log( <add> Level.SEVERE, <add> "Unable to determine whether selector is a branch selector", e); <add> LOGGER.log( <add> Level.INFO, <add> String.format("Selector:%s%s", System.lineSeparator(), selector)); <add> <add> return false; <add> } finally { <add> try { <add> if (selectorFilePath != null) { <add> Files.deleteIfExists(selectorFilePath); <add> } <add> } catch (IOException e) { <add> LOGGER.log( <add> Level.WARNING, <add> String.format("Delete tmp selector file '%s' failed", selectorFilePath), <add> e); <add> } <add> } <ide> } <ide> <ide> private static void cleanOldWorkspacesIfNeeded(
Java
mit
error: pathspec 'app/jsondto/JSONDTORepresentable.java' did not match any file(s) known to git
c7d755b809496cdc3e8c2b4bb3df45723b52d72a
1
jareware/JSON-DTO
package jsondto; /** * Model objects marked with this interface are able to represent themselves as * a JSON-DTO, and vice-versa (that is, able to set their state according to a * given DTO). * * @author Jarno Rantanen <[email protected]> */ public interface JSONDTORepresentable<DTO extends JSONDTO> { /** * Copies any state in the given JSON-DTO to this model object. * */ public void merge(DTO dto); /** * Returns a JSON-DTO-representation of this model object. * */ public DTO toDTO(); }
app/jsondto/JSONDTORepresentable.java
Added an interface that marks Models JSON-representable.
app/jsondto/JSONDTORepresentable.java
Added an interface that marks Models JSON-representable.
<ide><path>pp/jsondto/JSONDTORepresentable.java <add>package jsondto; <add> <add>/** <add> * Model objects marked with this interface are able to represent themselves as <add> * a JSON-DTO, and vice-versa (that is, able to set their state according to a <add> * given DTO). <add> * <add> * @author Jarno Rantanen <[email protected]> <add> */ <add>public interface JSONDTORepresentable<DTO extends JSONDTO> { <add> <add> /** <add> * Copies any state in the given JSON-DTO to this model object. <add> * <add> */ <add> public void merge(DTO dto); <add> <add> /** <add> * Returns a JSON-DTO-representation of this model object. <add> * <add> */ <add> public DTO toDTO(); <add> <add>}
Java
apache-2.0
81f6ec5d5bac83e97af0b2377226d660b349cdaf
0
SerCeMan/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,vladmm/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,ryano144/intellij-community,ernestp/consulo,fnouama/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,caot/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,caot/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,kdwink/intellij-community,consulo/consulo,caot/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,samthor/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,consulo/consulo,robovm/robovm-studio,alphafoobar/intellij-community,clumsy/intellij-community,dslomov/intellij-community,asedunov/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,allotria/intellij-community,hurricup/intellij-community,slisson/intellij-community,samthor/intellij-community,hurricup/intellij-community,adedayo/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,holmes/intellij-community,ibinti/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,apixandru/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,jagguli/intellij-community,semonte/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,semonte/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,caot/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,amith01994/intellij-community,samthor/intellij-community,fnouama/intellij-community,jagguli/intellij-community,signed/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,allotria/intellij-community,petteyg/intellij-community,adedayo/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,da1z/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,diorcety/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,semonte/intellij-community,kdwink/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,wreckJ/intellij-community,caot/intellij-community,signed/intellij-community,jagguli/intellij-community,supersven/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,allotria/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,samthor/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,ernestp/consulo,allotria/intellij-community,alphafoobar/intellij-community,ernestp/consulo,hurricup/intellij-community,ibinti/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,ryano144/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,kdwink/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,allotria/intellij-community,kdwink/intellij-community,izonder/intellij-community,slisson/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,kdwink/intellij-community,hurricup/intellij-community,holmes/intellij-community,adedayo/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,consulo/consulo,youdonghai/intellij-community,petteyg/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,apixandru/intellij-community,holmes/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,kool79/intellij-community,vladmm/intellij-community,kdwink/intellij-community,dslomov/intellij-community,amith01994/intellij-community,slisson/intellij-community,kdwink/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,hurricup/intellij-community,blademainer/intellij-community,izonder/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,allotria/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,ryano144/intellij-community,supersven/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,semonte/intellij-community,izonder/intellij-community,orekyuu/intellij-community,allotria/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,ryano144/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,supersven/intellij-community,apixandru/intellij-community,xfournet/intellij-community,slisson/intellij-community,da1z/intellij-community,retomerz/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,petteyg/intellij-community,da1z/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,da1z/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,slisson/intellij-community,samthor/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,supersven/intellij-community,orekyuu/intellij-community,kool79/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,fitermay/intellij-community,asedunov/intellij-community,robovm/robovm-studio,izonder/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,caot/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,blademainer/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,samthor/intellij-community,signed/intellij-community,ahb0327/intellij-community,supersven/intellij-community,retomerz/intellij-community,ernestp/consulo,muntasirsyed/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,ftomassetti/intellij-community,signed/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,samthor/intellij-community,signed/intellij-community,FHannes/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,supersven/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,fnouama/intellij-community,hurricup/intellij-community,supersven/intellij-community,jagguli/intellij-community,signed/intellij-community,caot/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,signed/intellij-community,samthor/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,consulo/consulo,asedunov/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,caot/intellij-community,signed/intellij-community,signed/intellij-community,fitermay/intellij-community,fitermay/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,vladmm/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,jagguli/intellij-community,ernestp/consulo,diorcety/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,holmes/intellij-community,izonder/intellij-community,izonder/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,allotria/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,ibinti/intellij-community,jagguli/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,kool79/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,diorcety/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,izonder/intellij-community,semonte/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,slisson/intellij-community,suncycheng/intellij-community,holmes/intellij-community,slisson/intellij-community,asedunov/intellij-community,retomerz/intellij-community,robovm/robovm-studio,fnouama/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,kool79/intellij-community,clumsy/intellij-community,allotria/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,amith01994/intellij-community,diorcety/intellij-community,consulo/consulo,allotria/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,caot/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,slisson/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,amith01994/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,fitermay/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,ryano144/intellij-community,kool79/intellij-community,kool79/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,ibinti/intellij-community,fnouama/intellij-community,ibinti/intellij-community,fitermay/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,FHannes/intellij-community,hurricup/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,FHannes/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,samthor/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,da1z/intellij-community,allotria/intellij-community,jagguli/intellij-community,xfournet/intellij-community,ernestp/consulo,xfournet/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,FHannes/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,holmes/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,apixandru/intellij-community,holmes/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,da1z/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,jagguli/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,supersven/intellij-community,allotria/intellij-community,caot/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,kool79/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,consulo/consulo,izonder/intellij-community
package org.jetbrains.plugins.gradle.manage; import com.intellij.ide.util.projectWizard.WizardContext; import com.intellij.openapi.module.ModifiableModuleModel; import com.intellij.openapi.module.Module; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.projectRoots.JavaSdk; import com.intellij.openapi.projectRoots.SdkTypeId; import com.intellij.openapi.roots.LanguageLevelProjectExtension; import com.intellij.openapi.roots.ui.configuration.ModulesProvider; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.packaging.artifacts.ModifiableArtifactModel; import com.intellij.pom.java.LanguageLevel; import com.intellij.projectImport.ProjectImportBuilder; import icons.GradleIcons; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.gradle.config.GradleConfigurable; import org.jetbrains.plugins.gradle.config.GradleSettings; import org.jetbrains.plugins.gradle.model.gradle.GradleEntity; import org.jetbrains.plugins.gradle.model.gradle.GradleModule; import org.jetbrains.plugins.gradle.model.gradle.GradleProject; import org.jetbrains.plugins.gradle.util.GradleBundle; import org.jetbrains.plugins.gradle.util.GradleConstants; import org.jetbrains.plugins.gradle.util.GradleLog; import org.jetbrains.plugins.gradle.util.GradleUtil; import javax.swing.*; import java.io.File; import java.util.*; /** * GoF builder for gradle-backed projects. * * @author Denis Zhdanov * @since 8/1/11 1:29 PM */ @SuppressWarnings("MethodMayBeStatic") public class GradleProjectImportBuilder extends ProjectImportBuilder<GradleProject> { /** @see #setModuleMappings(Map) */ private final Map<GradleModule/*origin*/, GradleModule/*adjusted*/> myModuleMappings = new HashMap<GradleModule, GradleModule>(); private GradleProject myGradleProject; private GradleConfigurable myConfigurable; @NotNull @Override public String getName() { return GradleBundle.message("gradle.name"); } @Override public Icon getIcon() { return GradleIcons.Gradle; } @Override public List<GradleProject> getList() { return Arrays.asList(myGradleProject); } @Override public boolean isMarked(GradleProject element) { return true; } @Override public void setList(List<GradleProject> gradleProjects) { } @Override public void setOpenProjectSettingsAfter(boolean on) { } public GradleConfigurable getConfigurable() { return myConfigurable; } public void prepare(@NotNull WizardContext context) { if (myConfigurable == null) { myConfigurable = new GradleConfigurable(getProject(context)); myConfigurable.setAlwaysShowLinkedProjectControls(true); } myConfigurable.reset(); String pathToUse = context.getProjectFileDirectory(); if (!pathToUse.endsWith(GradleConstants.DEFAULT_SCRIPT_NAME)) { pathToUse = new File(pathToUse, GradleConstants.DEFAULT_SCRIPT_NAME).getAbsolutePath(); } myConfigurable.setLinkedGradleProjectPath(pathToUse); } @Override public List<Module> commit(final Project project, ModifiableModuleModel model, ModulesProvider modulesProvider, ModifiableArtifactModel artifactModel) { System.setProperty(GradleConstants.NEWLY_IMPORTED_PROJECT, Boolean.TRUE.toString()); final GradleProject gradleProject = getGradleProject(); if (gradleProject != null) { final LanguageLevel gradleLanguageLevel = gradleProject.getLanguageLevel(); final LanguageLevelProjectExtension languageLevelExtension = LanguageLevelProjectExtension.getInstance(project); if (gradleLanguageLevel != languageLevelExtension.getLanguageLevel()) { languageLevelExtension.setLanguageLevel(gradleLanguageLevel); } } StartupManager.getInstance(project).runWhenProjectIsInitialized(new Runnable() { @Override public void run() { GradleSettings.applyLinkedProjectPath(myConfigurable.getLinkedProjectPath(), project); GradleSettings.applyPreferLocalInstallationToWrapper(myConfigurable.isPreferLocalInstallationToWrapper(), project); GradleSettings.applyGradleHome(myConfigurable.getGradleHomePath(), project); } }); GradleModulesImporter importer = new GradleModulesImporter(); File projectFile = getProjectFile(); assert projectFile != null; Map<GradleModule, Module> mappings = importer.importModules(myModuleMappings.values(), project, model, projectFile.getAbsolutePath()); return new ArrayList<Module>(mappings.values()); } @Nullable private File getProjectFile() { String path = myConfigurable.getLinkedProjectPath(); return path == null ? null : new File(path); } /** * Is called to indicate that user changed path to the gradle project to import. * * @param path new directory path */ public void setCurrentProjectPath(@NotNull String path) { myConfigurable.setLinkedGradleProjectPath(path); } /** * Asks current builder to ensure that target gradle project is defined. * * @param wizardContext current wizard context * @throws ConfigurationException if gradle project is not defined and can't be constructed */ public void ensureProjectIsDefined(@NotNull WizardContext wizardContext) throws ConfigurationException { File projectFile = getProjectFile(); if (projectFile == null) { throw new ConfigurationException(GradleBundle.message("gradle.import.text.error.project.undefined")); } if (projectFile.isDirectory()) { throw new ConfigurationException(GradleBundle.message("gradle.import.text.error.directory.instead.file")); } final Ref<String> errorReason = new Ref<String>(); final Ref<String> errorDetails = new Ref<String>(); try { final Project project = getProject(wizardContext); myGradleProject = GradleUtil.refreshProject(project, projectFile.getAbsolutePath(), errorReason, errorDetails, false, true); } catch (IllegalArgumentException e) { throw new ConfigurationException(e.getMessage(), GradleBundle.message("gradle.import.text.error.cannot.parse.project")); } if (myGradleProject == null) { final String details = errorDetails.get(); if (!StringUtil.isEmpty(details)) { GradleLog.LOG.warn(details); } String errorMessage; String reason = errorReason.get(); if (reason == null) { errorMessage = GradleBundle.message("gradle.import.text.error.resolve.generic.without.reason", projectFile.getPath()); } else { errorMessage = GradleBundle.message("gradle.import.text.error.resolve.with.reason", reason); } throw new ConfigurationException(errorMessage, GradleBundle.message("gradle.import.title.error.resolve.generic")); } } @Nullable public GradleProject getGradleProject() { return myGradleProject; } @Override public boolean isSuitableSdkType(SdkTypeId sdk) { return sdk == JavaSdk.getInstance(); } /** * Applies gradle-plugin-specific settings like project files location etc to the given context. * * @param context storage for the project/module settings. */ public void applyProjectSettings(@NotNull WizardContext context) { if (myGradleProject == null) { assert false; return; } context.setProjectName(myGradleProject.getName()); context.setProjectFileDirectory(myGradleProject.getProjectFileDirectoryPath()); context.setCompilerOutputDirectory(myGradleProject.getCompileOutputPath()); context.setProjectJdk(myGradleProject.getSdk()); } /** * The whole import sequence looks like below: * <p/> * <pre> * <ol> * <li>Get project view from the gradle tooling api without resolving dependencies (downloading libraries);</li> * <li>Allow to adjust project settings before importing;</li> * <li>Create IJ project and modules;</li> * <li>Ask gradle tooling api to resolve library dependencies (download the if necessary);</li> * <li>Configure modules dependencies;</li> * </ol> * </pre> * <p/> * {@link GradleEntity} guarantees correct {@link #equals(Object)}/{@link #hashCode()} implementation, so, we expect * to get {@link GradleModule modules} that are the same in terms of {@link #equals(Object)} on subsequent calls. However, * end-user is allowed to change their settings before the importing (e.g. module name), so, we need to map modules with * resolved libraries to the modules from project 'view'. That's why end-user adjusts settings of the cloned modules. * Given collection holds mappings between them. * * @param mappings origin-adjusted modules mappings */ public void setModuleMappings(@NotNull Map<GradleModule/*origin module*/, GradleModule/*adjusted module*/> mappings) { myModuleMappings.clear(); myModuleMappings.putAll(mappings); } /** * Allows to get {@link Project} instance to use. Basically, there are two alternatives - * {@link WizardContext#getProject() project from the current wizard context} and * {@link ProjectManager#getDefaultProject() default project}. * * @param wizardContext current wizard context * @return {@link Project} instance to use */ @NotNull public Project getProject(@NotNull WizardContext wizardContext) { Project result = wizardContext.getProject(); if (result == null) { result = ProjectManager.getInstance().getDefaultProject(); } return result; } }
plugins/gradle/src/org/jetbrains/plugins/gradle/manage/GradleProjectImportBuilder.java
package org.jetbrains.plugins.gradle.manage; import com.intellij.ide.util.projectWizard.WizardContext; import com.intellij.openapi.module.ModifiableModuleModel; import com.intellij.openapi.module.Module; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.projectRoots.JavaSdk; import com.intellij.openapi.projectRoots.SdkTypeId; import com.intellij.openapi.roots.LanguageLevelProjectExtension; import com.intellij.openapi.roots.ui.configuration.ModulesProvider; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.packaging.artifacts.ModifiableArtifactModel; import com.intellij.pom.java.LanguageLevel; import com.intellij.projectImport.ProjectImportBuilder; import icons.GradleIcons; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.gradle.config.GradleConfigurable; import org.jetbrains.plugins.gradle.config.GradleSettings; import org.jetbrains.plugins.gradle.model.gradle.GradleEntity; import org.jetbrains.plugins.gradle.model.gradle.GradleModule; import org.jetbrains.plugins.gradle.model.gradle.GradleProject; import org.jetbrains.plugins.gradle.util.GradleBundle; import org.jetbrains.plugins.gradle.util.GradleConstants; import org.jetbrains.plugins.gradle.util.GradleLog; import org.jetbrains.plugins.gradle.util.GradleUtil; import javax.swing.*; import java.io.File; import java.util.*; /** * GoF builder for gradle-backed projects. * * @author Denis Zhdanov * @since 8/1/11 1:29 PM */ @SuppressWarnings("MethodMayBeStatic") public class GradleProjectImportBuilder extends ProjectImportBuilder<GradleProject> { /** @see #setModuleMappings(Map) */ private final Map<GradleModule/*origin*/, GradleModule/*adjusted*/> myModuleMappings = new HashMap<GradleModule, GradleModule>(); private GradleProject myGradleProject; private GradleConfigurable myConfigurable; @NotNull @Override public String getName() { return GradleBundle.message("gradle.name"); } @Override public Icon getIcon() { return GradleIcons.Gradle; } @Override public List<GradleProject> getList() { return Arrays.asList(myGradleProject); } @Override public boolean isMarked(GradleProject element) { return true; } @Override public void setList(List<GradleProject> gradleProjects) { } @Override public void setOpenProjectSettingsAfter(boolean on) { } public GradleConfigurable getConfigurable() { return myConfigurable; } public void prepare(@NotNull WizardContext context) { if (myConfigurable == null) { myConfigurable = new GradleConfigurable(getProject(context)); myConfigurable.setAlwaysShowLinkedProjectControls(true); } myConfigurable.reset(); myConfigurable.setLinkedGradleProjectPath(new File(context.getProjectFileDirectory(), GradleConstants.DEFAULT_SCRIPT_NAME).getAbsolutePath()); } @Override public List<Module> commit(final Project project, ModifiableModuleModel model, ModulesProvider modulesProvider, ModifiableArtifactModel artifactModel) { System.setProperty(GradleConstants.NEWLY_IMPORTED_PROJECT, Boolean.TRUE.toString()); final GradleProject gradleProject = getGradleProject(); if (gradleProject != null) { final LanguageLevel gradleLanguageLevel = gradleProject.getLanguageLevel(); final LanguageLevelProjectExtension languageLevelExtension = LanguageLevelProjectExtension.getInstance(project); if (gradleLanguageLevel != languageLevelExtension.getLanguageLevel()) { languageLevelExtension.setLanguageLevel(gradleLanguageLevel); } } StartupManager.getInstance(project).runWhenProjectIsInitialized(new Runnable() { @Override public void run() { GradleSettings.applyLinkedProjectPath(myConfigurable.getLinkedProjectPath(), project); GradleSettings.applyPreferLocalInstallationToWrapper(myConfigurable.isPreferLocalInstallationToWrapper(), project); GradleSettings.applyGradleHome(myConfigurable.getGradleHomePath(), project); } }); GradleModulesImporter importer = new GradleModulesImporter(); File projectFile = getProjectFile(); assert projectFile != null; Map<GradleModule, Module> mappings = importer.importModules(myModuleMappings.values(), project, model, projectFile.getAbsolutePath()); return new ArrayList<Module>(mappings.values()); } @Nullable private File getProjectFile() { String path = myConfigurable.getLinkedProjectPath(); return path == null ? null : new File(path); } /** * Is called to indicate that user changed path to the gradle project to import. * * @param path new directory path */ public void setCurrentProjectPath(@NotNull String path) { myConfigurable.setLinkedGradleProjectPath(path); } /** * Asks current builder to ensure that target gradle project is defined. * * @param wizardContext current wizard context * @throws ConfigurationException if gradle project is not defined and can't be constructed */ public void ensureProjectIsDefined(@NotNull WizardContext wizardContext) throws ConfigurationException { File projectFile = getProjectFile(); if (projectFile == null) { throw new ConfigurationException(GradleBundle.message("gradle.import.text.error.project.undefined")); } if (projectFile.isDirectory()) { throw new ConfigurationException(GradleBundle.message("gradle.import.text.error.directory.instead.file")); } final Ref<String> errorReason = new Ref<String>(); final Ref<String> errorDetails = new Ref<String>(); try { final Project project = getProject(wizardContext); myGradleProject = GradleUtil.refreshProject(project, projectFile.getAbsolutePath(), errorReason, errorDetails, false, true); } catch (IllegalArgumentException e) { throw new ConfigurationException(e.getMessage(), GradleBundle.message("gradle.import.text.error.cannot.parse.project")); } if (myGradleProject == null) { final String details = errorDetails.get(); if (!StringUtil.isEmpty(details)) { GradleLog.LOG.warn(details); } String errorMessage; String reason = errorReason.get(); if (reason == null) { errorMessage = GradleBundle.message("gradle.import.text.error.resolve.generic.without.reason", projectFile.getPath()); } else { errorMessage = GradleBundle.message("gradle.import.text.error.resolve.with.reason", reason); } throw new ConfigurationException(errorMessage, GradleBundle.message("gradle.import.title.error.resolve.generic")); } } @Nullable public GradleProject getGradleProject() { return myGradleProject; } @Override public boolean isSuitableSdkType(SdkTypeId sdk) { return sdk == JavaSdk.getInstance(); } /** * Applies gradle-plugin-specific settings like project files location etc to the given context. * * @param context storage for the project/module settings. */ public void applyProjectSettings(@NotNull WizardContext context) { if (myGradleProject == null) { assert false; return; } context.setProjectName(myGradleProject.getName()); context.setProjectFileDirectory(myGradleProject.getProjectFileDirectoryPath()); context.setCompilerOutputDirectory(myGradleProject.getCompileOutputPath()); context.setProjectJdk(myGradleProject.getSdk()); } /** * The whole import sequence looks like below: * <p/> * <pre> * <ol> * <li>Get project view from the gradle tooling api without resolving dependencies (downloading libraries);</li> * <li>Allow to adjust project settings before importing;</li> * <li>Create IJ project and modules;</li> * <li>Ask gradle tooling api to resolve library dependencies (download the if necessary);</li> * <li>Configure modules dependencies;</li> * </ol> * </pre> * <p/> * {@link GradleEntity} guarantees correct {@link #equals(Object)}/{@link #hashCode()} implementation, so, we expect * to get {@link GradleModule modules} that are the same in terms of {@link #equals(Object)} on subsequent calls. However, * end-user is allowed to change their settings before the importing (e.g. module name), so, we need to map modules with * resolved libraries to the modules from project 'view'. That's why end-user adjusts settings of the cloned modules. * Given collection holds mappings between them. * * @param mappings origin-adjusted modules mappings */ public void setModuleMappings(@NotNull Map<GradleModule/*origin module*/, GradleModule/*adjusted module*/> mappings) { myModuleMappings.clear(); myModuleMappings.putAll(mappings); } /** * Allows to get {@link Project} instance to use. Basically, there are two alternatives - * {@link WizardContext#getProject() project from the current wizard context} and * {@link ProjectManager#getDefaultProject() default project}. * * @param wizardContext current wizard context * @return {@link Project} instance to use */ @NotNull public Project getProject(@NotNull WizardContext wizardContext) { Project result = wizardContext.getProject(); if (result == null) { result = ProjectManager.getInstance().getDefaultProject(); } return result; } }
IDEA-77127 Gradle: Support gradle wrapper on importing Correct gradle project path processing (different behavior of our 'import project' and 'open project' wizards)
plugins/gradle/src/org/jetbrains/plugins/gradle/manage/GradleProjectImportBuilder.java
IDEA-77127 Gradle: Support gradle wrapper on importing
<ide><path>lugins/gradle/src/org/jetbrains/plugins/gradle/manage/GradleProjectImportBuilder.java <ide> myConfigurable.setAlwaysShowLinkedProjectControls(true); <ide> } <ide> myConfigurable.reset(); <del> myConfigurable.setLinkedGradleProjectPath(new File(context.getProjectFileDirectory(), GradleConstants.DEFAULT_SCRIPT_NAME).getAbsolutePath()); <add> String pathToUse = context.getProjectFileDirectory(); <add> if (!pathToUse.endsWith(GradleConstants.DEFAULT_SCRIPT_NAME)) { <add> pathToUse = new File(pathToUse, GradleConstants.DEFAULT_SCRIPT_NAME).getAbsolutePath(); <add> } <add> myConfigurable.setLinkedGradleProjectPath(pathToUse); <ide> } <ide> <ide> @Override
Java
apache-2.0
601e69924657fa223f2f6d32356b6901a01cdd29
0
dke-knu/i2am,dke-knu/i2am,dke-knu/i2am,dke-knu/i2am,dke-knu/i2am,dke-knu/i2am,dke-knu/i2am,dke-knu/i2am
package i2am.benchmark.storm.systematic; import java.net.InetSocketAddress; import java.util.HashSet; import java.util.Properties; import java.util.Set; import java.util.UUID; import org.apache.storm.Config; import org.apache.storm.StormSubmitter; import org.apache.storm.generated.AlreadyAliveException; import org.apache.storm.generated.AuthorizationException; import org.apache.storm.generated.InvalidTopologyException; import org.apache.storm.kafka.KafkaSpout; import org.apache.storm.kafka.SpoutConfig; import org.apache.storm.kafka.StringScheme; import org.apache.storm.kafka.ZkHosts; import org.apache.storm.kafka.bolt.KafkaBolt; import org.apache.storm.kafka.bolt.mapper.FieldNameBasedTupleToKafkaMapper; import org.apache.storm.kafka.bolt.selector.DefaultTopicSelector; import org.apache.storm.redis.common.config.JedisClusterConfig; import org.apache.storm.spout.SchemeAsMultiScheme; import org.apache.storm.topology.TopologyBuilder; import redis.clients.jedis.Protocol; public class PerformanceTestTopology { // private static fina Logger LOG = LoggerFactory.getLoggerFactory.getLogger(PerformanceTestTopology.class); public static void main(String[] args) throws AlreadyAliveException, InvalidTopologyException, AuthorizationException{ String[] zookeepers = args[0].split(","); //KAFAK ZOOKEEPER short zkPort = Short.parseShort(args[1]); /* Kafka -> Storm Config */ StringBuilder sb = new StringBuilder(); for(String zookeeper: zookeepers){ sb.append(zookeeper + ":" + zkPort + ","); } String zkUrl = sb.substring(0, sb.length()-1); String input_topic = args[2]; String output_topic = args[3]; ZkHosts hosts = new ZkHosts(zkUrl); SpoutConfig kafkaSpoutConfig = new SpoutConfig(hosts, input_topic, "/" + input_topic, UUID.randomUUID().toString()); kafkaSpoutConfig.scheme = new SchemeAsMultiScheme(new StringScheme()); /* Storm -> Kafka Configs */ sb = new StringBuilder(); for(String zookeeper : zookeepers){ sb.append(zookeeper + ":9092,"); } String kafkaUrl = sb.substring(0, sb.length()-1); Properties props = new Properties(); props.put("bootstrap.servers", kafkaUrl); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("acks", "1"); /* Redis Configurations */ String redisKey = args[4]; Set<InetSocketAddress> redisNodes = new HashSet<InetSocketAddress>(); redisNodes.add(new InetSocketAddress("192.168.1.100", 17000)); redisNodes.add(new InetSocketAddress("192.168.1.101", 17001)); redisNodes.add(new InetSocketAddress("192.168.1.102", 17002)); redisNodes.add(new InetSocketAddress("192.168.1.103", 17003)); redisNodes.add(new InetSocketAddress("192.168.1.104", 17004)); redisNodes.add(new InetSocketAddress("192.168.1.105", 17005)); redisNodes.add(new InetSocketAddress("192.168.1.106", 17006)); redisNodes.add(new InetSocketAddress("192.168.1.107", 17007)); redisNodes.add(new InetSocketAddress("192.168.1.108", 17008)); /* Jedis */ JedisClusterConfig jedisClusterConfig = new JedisClusterConfig(redisNodes, Protocol.DEFAULT_TIMEOUT, 5); /* Topology */ KafkaBolt<String, Integer> kafkaBolt = new KafkaBolt<String, Integer>() .withProducerProperties(props) .withTopicSelector(new DefaultTopicSelector(output_topic)) .withTupleToKafkaMapper(new FieldNameBasedTupleToKafkaMapper()); TopologyBuilder builder = new TopologyBuilder(); builder.setSpout("kafka-spout", new KafkaSpout(kafkaSpoutConfig), 1) .setNumTasks(1); builder.setBolt("declare-field-bolt", new DeclareFieldBolt(), 1) .shuffleGrouping("kafka-spout") .setNumTasks(1); builder.setBolt("systematic-sampling-bolt", new SystematicSamplingBolt(redisKey, jedisClusterConfig), 1) .shuffleGrouping("declare-field-bolt") .setNumTasks(1); builder.setBolt("pass-bolt", new PassBolt(), 1) .shuffleGrouping("systematic-sampling-bolt") .setNumTasks(1); builder.setBolt("kafka-bolt", kafkaBolt, 1) .shuffleGrouping("pass-bolt") .setNumTasks(1); Config conf = new Config(); conf.setDebug(true); conf.setNumWorkers(5); StormSubmitter.submitTopology("performance-systematicsampling-topology", conf, builder.createTopology()); } }
i2am-performance-test/benchmark-storm-and-spark/benchmark-storm/src/main/java/i2am/benchmark/storm/systematic/PerformanceTestTopology.java
package i2am.benchmark.storm.systematic; import java.net.InetSocketAddress; import java.util.HashSet; import java.util.Properties; import java.util.Set; import java.util.UUID; import org.apache.storm.Config; import org.apache.storm.StormSubmitter; import org.apache.storm.generated.AlreadyAliveException; import org.apache.storm.generated.AuthorizationException; import org.apache.storm.generated.InvalidTopologyException; import org.apache.storm.kafka.KafkaSpout; import org.apache.storm.kafka.SpoutConfig; import org.apache.storm.kafka.StringScheme; import org.apache.storm.kafka.ZkHosts; import org.apache.storm.kafka.bolt.KafkaBolt; import org.apache.storm.kafka.bolt.mapper.FieldNameBasedTupleToKafkaMapper; import org.apache.storm.kafka.bolt.selector.DefaultTopicSelector; import org.apache.storm.redis.common.config.JedisClusterConfig; import org.apache.storm.spout.SchemeAsMultiScheme; import org.apache.storm.topology.TopologyBuilder; import redis.clients.jedis.Protocol; public class PerformanceTestTopology { // private static fina Logger LOG = LoggerFactory.getLoggerFactory.getLogger(PerformanceTestTopology.class); public static void main(String[] args) throws AlreadyAliveException, InvalidTopologyException, AuthorizationException{ String[] zookeepers = args[0].split(","); //KAFAK ZOOKEEPER short zkPort = Short.parseShort(args[1]); /* Kafka -> Storm Config */ StringBuilder sb = new StringBuilder(); for(String zookeeper: zookeepers){ sb.append(zookeeper + ":" + zkPort + ","); } String zkUrl = sb.substring(0, sb.length()-1); String input_topic = args[2]; String output_topic = args[3]; ZkHosts hosts = new ZkHosts(zkUrl); SpoutConfig kafkaSpoutConfig = new SpoutConfig(hosts, input_topic, "/" + input_topic, UUID.randomUUID().toString()); kafkaSpoutConfig.scheme = new SchemeAsMultiScheme(new StringScheme()); /* Storm -> Kafka Configs */ sb = new StringBuilder(); for(String zookeeper : zookeepers){ sb.append(zookeeper + ":9092,"); } String kafkaUrl = sb.substring(0, sb.length()-1); Properties props = new Properties(); props.put("bootstrap.servers", kafkaUrl); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("acks", "1"); /* Redis Configurations */ String redisKey = args[4]; Set<InetSocketAddress> redisNodes = new HashSet<InetSocketAddress>(); redisNodes.add(new InetSocketAddress("192.168.1.100", 17000)); redisNodes.add(new InetSocketAddress("192.168.1.101", 17001)); redisNodes.add(new InetSocketAddress("192.168.1.102", 17002)); redisNodes.add(new InetSocketAddress("192.168.1.103", 17003)); redisNodes.add(new InetSocketAddress("192.168.1.104", 17004)); redisNodes.add(new InetSocketAddress("192.168.1.105", 17005)); redisNodes.add(new InetSocketAddress("192.168.1.106", 17006)); redisNodes.add(new InetSocketAddress("192.168.1.107", 17007)); redisNodes.add(new InetSocketAddress("192.168.1.108", 17008)); /* Jedis */ JedisClusterConfig jedisClusterConfig = new JedisClusterConfig(redisNodes, Protocol.DEFAULT_TIMEOUT, 5); /* Topology */ KafkaBolt<String, Integer> kafkaBolt = new KafkaBolt<String, Integer>() .withProducerProperties(props) .withTopicSelector(new DefaultTopicSelector(output_topic)) .withTupleToKafkaMapper(new FieldNameBasedTupleToKafkaMapper()); TopologyBuilder builder = new TopologyBuilder(); builder.setSpout("kafka-spout", new KafkaSpout(kafkaSpoutConfig), 1) .setNumTasks(1); builder.setBolt("declare-field-bolt", new DeclareFieldBolt(), 1) .shuffleGrouping("kafka-spout") .setNumTasks(1); builder.setBolt("systematic-sampling-bolt", new SystematicSamplingBolt(redisKey, jedisClusterConfig), 1) .shuffleGrouping("declare-field-bolt") .setNumTasks(1); builder.setBolt("pass-bolt", new PassBolt(), 1) .shuffleGrouping("systematic-sampling-bolt") .setNumTasks(1); builder.setBolt("kafka-bolt", kafkaBolt, 1) .shuffleGrouping("pass-bolt") .setNumTasks(1); Config conf = new Config(); conf.setDebug(true); conf.setNumWorkers(5); StormSubmitter.submitTopology("performance-reservoirsampling-topology", conf, builder.createTopology()); } }
108줄 파라미터 수정
i2am-performance-test/benchmark-storm-and-spark/benchmark-storm/src/main/java/i2am/benchmark/storm/systematic/PerformanceTestTopology.java
108줄 파라미터 수정
<ide><path>2am-performance-test/benchmark-storm-and-spark/benchmark-storm/src/main/java/i2am/benchmark/storm/systematic/PerformanceTestTopology.java <ide> <ide> conf.setNumWorkers(5); <ide> <del> StormSubmitter.submitTopology("performance-reservoirsampling-topology", conf, builder.createTopology()); <add> StormSubmitter.submitTopology("performance-systematicsampling-topology", conf, builder.createTopology()); <ide> } <ide> }
JavaScript
agpl-3.0
1345b2d6dc6bc848c58b8233a573ac0823a93e03
0
ComPlat/chemotion_ELN,ComPlat/chemotion_ELN,ComPlat/chemotion_ELN,ComPlat/chemotion_ELN
import React from 'react'; import {ButtonGroup} from 'react-bootstrap'; import ShareButton from './ShareButton'; import MoveButton from './MoveButton'; import AssignButton from './AssignButton'; import RemoveButton from './RemoveButton'; import DeleteButton from './DeleteButton'; import ExportButton from './ExportButton'; import ImportButton from './ImportButton'; import UIStore from './../stores/UIStore'; import UserStore from './../stores/UserStore'; import UserActions from './../actions/UserActions'; import PermissionStore from './../stores/PermissionStore'; import PermissionActions from './../actions/PermissionActions'; import ManagingModal from './ManagingModal'; import ManagingModalSharing from './ManagingModalSharing'; import ManagingModalCollectionActions from './ManagingModalCollectionActions'; import ManagingModalDelete from './ManagingModalDelete'; import ManagingModalImport from './ManagingModalImport'; import ManagingModalRemove from './ManagingModalRemove'; import ManagingModalTopSecret from './ManagingModalTopSecret'; import ElementActions from '../actions/ElementActions'; export default class ManagingActions extends React.Component { constructor(props) { super(props); let {currentUser} = UserStore.getState(); this.state = { currentUser: currentUser, currentCollection: {id: 0}, sharing_allowed: false, deletion_allowed: false, is_top_secret: false, modalProps: { show: false, title: "", component: "", action: null } } } componentDidMount() { UserStore.listen(this.onUserChange.bind(this)); UIStore.listen(this.onChange.bind(this)); PermissionStore.listen(this.onPermissionChange.bind(this)); UserActions.fetchCurrentUser(); } componentWillUnmount() { UserStore.unlisten(this.onUserChange.bind(this)); UIStore.unlisten(this.onChange.bind(this)); PermissionStore.unlisten(this.onPermissionChange.bind(this)); } onChange(state) { let elementsFilter = this.filterParamsFromUIState(state); let params = { elements_filter: elementsFilter } PermissionActions.fetchSharingAllowedStatus(params); PermissionActions.fetchDeletionAllowedStatus(params); PermissionActions.fetchTopSecretStatus(params); this.setState({ currentCollection: state.currentCollection }) } onUserChange(state) { this.setState({ currentUser: state.currentUser }) } onPermissionChange(state) { this.setState({ sharing_allowed: state.sharing_allowed, deletion_allowed: state.deletion_allowed, is_top_secret: state.is_top_secret }) } filterParamsFromUIState(uiState) { let collectionId = uiState.currentCollection && uiState.currentCollection.id; let filterParams = { sample: { all: uiState.sample.checkedAll, included_ids: uiState.sample.checkedIds, excluded_ids: uiState.sample.uncheckedIds, collection_id: collectionId }, reaction: { all: uiState.reaction.checkedAll, included_ids: uiState.reaction.checkedIds, excluded_ids: uiState.reaction.uncheckedIds, collection_id: collectionId }, wellplate: { all: uiState.wellplate.checkedAll, included_ids: uiState.wellplate.checkedIds, excluded_ids: uiState.wellplate.uncheckedIds, collection_id: collectionId }, screen: { all: uiState.screen.checkedAll, included_ids: uiState.screen.checkedIds, excluded_ids: uiState.screen.uncheckedIds, collection_id: collectionId } }; return filterParams; } isDisabled() { const {currentCollection} = this.state; if(currentCollection) { return currentCollection.id == 'all' || currentCollection.is_shared == true; } } isShareButtonDisabled() { const {currentCollection} = this.state; let in_all_collection = (currentCollection) ? currentCollection.id == 'all' : false return in_all_collection || this.state.sharing_allowed == false; } isDeleteButtonDisabled() { return this.state.deletion_allowed == false; } isRemoteDisabled() { if(this.state.currentCollection) { let currentCollection = this.state.currentCollection; return currentCollection.id == 'all' || (currentCollection.is_shared == true && currentCollection.shared_by_id != this.state.currentUser.id); } } handleModalHide() { this.setState({ modalProps: { show: false, title: "", component: "", action: null } }); // https://github.com/react-bootstrap/react-bootstrap/issues/1137 document.body.className = document.body.className.replace('modal-open', ''); } handleButtonClick(type) { let title, component, action = ""; switch(type) { case 'share': if(!this.state.is_top_secret) { title = "Sharing"; component = ManagingModalSharing; } else { title = "Sharing not allowed"; component = ManagingModalTopSecret; } break; case 'move': title = "Move to Collection"; component = ManagingModalCollectionActions; action = ElementActions.updateElementsCollection; break; case 'remove': title = "Remove selected elements from this Collection?"; component = ManagingModalRemove; action = ElementActions.removeElementsCollection; break; case 'assign': title = "Assign to Collection"; component = ManagingModalCollectionActions; action = ElementActions.assignElementsCollection; break; case 'delete': title = "Delete from all Collections?"; component = ManagingModalDelete; action = ElementActions.deleteElements; break; case 'import': title = "Import Elements from File"; component = ManagingModalImport; action = ElementActions.importSamplesFromFile; break; } this.setState({ modalProps: { show: true, title, component, action } }); } render() { const {modalProps} = this.state; return ( <div style={{display: 'inline', float: 'left', marginRight: 10}}> <ButtonGroup> <MoveButton isDisabled={this.isDisabled()} onClick={() => this.handleButtonClick('move')}/> <AssignButton isDisabled={this.isDisabled()} onClick={() => this.handleButtonClick('assign')}/> <RemoveButton isDisabled={this.isRemoteDisabled()} onClick={() => this.handleButtonClick('remove')}/> <DeleteButton isDisabled={this.isDeleteButtonDisabled()} onClick={() => this.handleButtonClick('delete')}/> <ShareButton isDisabled={this.isShareButtonDisabled()} onClick={() => this.handleButtonClick('share')}/> <ImportButton isDisabled={this.isDisabled()} onClick={() => this.handleButtonClick('import')}/> <ExportButton isDisabled={this.isDisabled()}/> </ButtonGroup> <ManagingModal show={modalProps.show} title={modalProps.title} Component={modalProps.component} action={modalProps.action} onHide={() => this.handleModalHide()} /> </div> ) } }
app/assets/javascripts/components/managing_actions/ManagingActions.js
import React from 'react'; import {ButtonGroup} from 'react-bootstrap'; import ShareButton from './ShareButton'; import MoveButton from './MoveButton'; import AssignButton from './AssignButton'; import RemoveButton from './RemoveButton'; import DeleteButton from './DeleteButton'; import ExportButton from './ExportButton'; import ImportButton from './ImportButton'; import UIStore from './../stores/UIStore'; import UserStore from './../stores/UserStore'; import UserActions from './../actions/UserActions'; import PermissionStore from './../stores/PermissionStore'; import PermissionActions from './../actions/PermissionActions'; import ManagingModal from './ManagingModal'; import ManagingModalSharing from './ManagingModalSharing'; import ManagingModalCollectionActions from './ManagingModalCollectionActions'; import ManagingModalDelete from './ManagingModalDelete'; import ManagingModalImport from './ManagingModalImport'; import ManagingModalRemove from './ManagingModalRemove'; import ManagingModalTopSecret from './ManagingModalTopSecret'; import ElementActions from '../actions/ElementActions'; export default class ManagingActions extends React.Component { constructor(props) { super(props); let {currentUser} = UserStore.getState(); this.state = { currentUser: currentUser, currentCollection: {id: 0}, sharing_allowed: false, deletion_allowed: false, is_top_secret: false, modalProps: { show: false, title: "", component: "", action: null } } } componentDidMount() { UserStore.listen(this.onUserChange.bind(this)); UIStore.listen(this.onChange.bind(this)); PermissionStore.listen(this.onPermissionChange.bind(this)); UserActions.fetchCurrentUser(); } componentWillUnmount() { UserStore.unlisten(this.onUserChange.bind(this)); UIStore.unlisten(this.onChange.bind(this)); PermissionStore.unlisten(this.onPermissionChange.bind(this)); } onChange(state) { let elementsFilter = this.filterParamsFromUIState(state); let params = { elements_filter: elementsFilter } PermissionActions.fetchSharingAllowedStatus(params); PermissionActions.fetchDeletionAllowedStatus(params); PermissionActions.fetchTopSecretStatus(params); this.setState({ currentCollection: state.currentCollection }) } onUserChange(state) { this.setState({ currentUser: state.currentUser }) } onPermissionChange(state) { this.setState({ sharing_allowed: state.sharing_allowed, deletion_allowed: state.deletion_allowed, is_top_secret: state.is_top_secret }) } filterParamsFromUIState(uiState) { let collectionId = uiState.currentCollection && uiState.currentCollection.id; let filterParams = { sample: { all: uiState.sample.checkedAll, included_ids: uiState.sample.checkedIds, excluded_ids: uiState.sample.uncheckedIds, collection_id: collectionId }, reaction: { all: uiState.reaction.checkedAll, included_ids: uiState.reaction.checkedIds, excluded_ids: uiState.reaction.uncheckedIds, collection_id: collectionId }, wellplate: { all: uiState.wellplate.checkedAll, included_ids: uiState.wellplate.checkedIds, excluded_ids: uiState.wellplate.uncheckedIds, collection_id: collectionId }, screen: { all: uiState.screen.checkedAll, included_ids: uiState.screen.checkedIds, excluded_ids: uiState.screen.uncheckedIds, collection_id: collectionId } }; return filterParams; } isDisabled() { const {currentCollection} = this.state; if(currentCollection) { return currentCollection.id == 'all' || currentCollection.is_shared == true; } } isShareButtonDisabled() { const {currentCollection} = this.state; let in_all_collection = (currentCollection) ? currentCollection.id == 'all' : false return in_all_collection || this.state.sharing_allowed == false; } isDeleteButtonDisabled() { return this.state.deletion_allowed == false; } isRemoteDisabled() { if(this.state.currentCollection) { let currentCollection = this.state.currentCollection; return currentCollection.id == 'all' || (currentCollection.is_shared == true && currentCollection.shared_by_id != this.state.currentUser.id); } } handleModalHide() { this.setState({ modalProps: { show: false, title: "", component: "", action: null } }); // https://github.com/react-bootstrap/react-bootstrap/issues/1137 document.body.className = document.body.className.replace('modal-open', ''); } handleButtonClick(type) { let title, component, action = ""; switch(type) { case 'share': if(!this.state.is_top_secret) { title = "Sharing"; component = ManagingModalSharing; } else { title = "Sharing not allowed"; component = ManagingModalTopSecret; } break; case 'move': title = "Move to Collection"; component = ManagingModalCollectionActions; action = ElementActions.updateElementsCollection; break; case 'remove': title = "Remove selected elements from this Collection?"; component = ManagingModalRemove; action = ElementActions.removeElementsCollection; break; case 'assign': title = "Assign to Collection"; component = ManagingModalCollectionActions; action = ElementActions.assignElementsCollection; break; case 'delete': title = "Delete from all Collections?"; component = ManagingModalDelete; action = ElementActions.deleteElements; break; case 'import': title = "Import Elements from File"; component = ManagingModalImport; action = ElementActions.importSamplesFromFile; break; } this.setState({ modalProps: { show: true, title, component, action } }); } render() { const {modalProps} = this.state; return ( <div style={{display: 'inline', float: 'left', marginRight: 10}}> <ButtonGroup> <MoveButton isDisabled={this.isDisabled()} onClick={() => this.handleButtonClick('move')}/> <AssignButton isDisabled={this.isDisabled()} onClick={() => this.handleButtonClick('assign')}/> <RemoveButton isDisabled={this.isRemoteDisabled()} onClick={() => this.handleButtonClick('remove')}/> <DeleteButton isDisabled={this.isDeleteButtonDisabled()} onClick={() => this.handleButtonClick('delete')}/> <ShareButton isDisabled={this.isShareButtonDisabled()} onClick={() => this.handleButtonClick('share')}/> <ImportButton onClick={() => this.handleButtonClick('import')}/> <ExportButton isDisabled={this.isDisabled()}/> </ButtonGroup> <ManagingModal show={modalProps.show} title={modalProps.title} Component={modalProps.component} action={modalProps.action} onHide={() => this.handleModalHide()} /> </div> ) } }
Disables Import Button for 'All' collection
app/assets/javascripts/components/managing_actions/ManagingActions.js
Disables Import Button for 'All' collection
<ide><path>pp/assets/javascripts/components/managing_actions/ManagingActions.js <ide> <RemoveButton isDisabled={this.isRemoteDisabled()} onClick={() => this.handleButtonClick('remove')}/> <ide> <DeleteButton isDisabled={this.isDeleteButtonDisabled()} onClick={() => this.handleButtonClick('delete')}/> <ide> <ShareButton isDisabled={this.isShareButtonDisabled()} onClick={() => this.handleButtonClick('share')}/> <del> <ImportButton onClick={() => this.handleButtonClick('import')}/> <add> <ImportButton isDisabled={this.isDisabled()} onClick={() => this.handleButtonClick('import')}/> <ide> <ExportButton isDisabled={this.isDisabled()}/> <ide> </ButtonGroup> <ide> <ManagingModal
Java
apache-2.0
30ade388b064b3430151d4d4ba20cafaed400194
0
youdonghai/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,da1z/intellij-community,FHannes/intellij-community,xfournet/intellij-community,allotria/intellij-community,allotria/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,semonte/intellij-community,allotria/intellij-community,signed/intellij-community,allotria/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,semonte/intellij-community,FHannes/intellij-community,semonte/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,asedunov/intellij-community,allotria/intellij-community,allotria/intellij-community,signed/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,apixandru/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,da1z/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,apixandru/intellij-community,ibinti/intellij-community,da1z/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,asedunov/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,asedunov/intellij-community,allotria/intellij-community,FHannes/intellij-community,apixandru/intellij-community,ibinti/intellij-community,xfournet/intellij-community,da1z/intellij-community,asedunov/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,semonte/intellij-community,asedunov/intellij-community,signed/intellij-community,signed/intellij-community,vvv1559/intellij-community,allotria/intellij-community,da1z/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,da1z/intellij-community,apixandru/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,ibinti/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,signed/intellij-community,signed/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,signed/intellij-community,semonte/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,asedunov/intellij-community,semonte/intellij-community,asedunov/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,signed/intellij-community,semonte/intellij-community,youdonghai/intellij-community,semonte/intellij-community,signed/intellij-community,suncycheng/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,da1z/intellij-community,semonte/intellij-community,ibinti/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,apixandru/intellij-community,apixandru/intellij-community,da1z/intellij-community,suncycheng/intellij-community,signed/intellij-community,allotria/intellij-community,da1z/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,semonte/intellij-community,asedunov/intellij-community,allotria/intellij-community,vvv1559/intellij-community,allotria/intellij-community,asedunov/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community
/* * Copyright 2000-2017 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.projectView; import com.intellij.ide.projectView.ProjectView; import com.intellij.ide.projectView.impl.AbstractProjectTreeStructure; import com.intellij.ide.projectView.impl.PackageViewPane; import com.intellij.ide.projectView.impl.ProjectViewImpl; import com.intellij.lang.properties.projectView.ResourceBundleGrouper; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.module.impl.ModuleManagerImpl; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.testFramework.PlatformTestUtil; import com.intellij.testFramework.TestSourceBasedTestCase; import com.intellij.util.ui.tree.TreeUtil; import org.jetbrains.annotations.NonNls; import javax.swing.*; import java.io.IOException; public class PackagesTreeStructureTest extends TestSourceBasedTestCase { public void testPackageView() throws IOException, InterruptedException { ModuleManagerImpl.getInstanceImpl(myProject).setModuleGroupPath(myModule, new String[]{"Group"}); final VirtualFile srcFile = getSrcDirectory().getVirtualFile(); if (srcFile.findChild("empty") == null){ ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { try { srcFile.createChildDirectory(this, "empty"); } catch (IOException e) { fail(e.getLocalizedMessage()); } } }); } doTest(true, true, "-Project\n" + " -Group: Group\n" + " -Module\n" + " -PsiPackage: com.package1\n" + " Class1.java\n" + " Class2.java\n" + " Class4.java\n" + " emptyClassFile.class\n" + " Form1.form\n" + " Form1.java\n" + " Form2.form\n" + " PsiPackage: empty\n" + " -PsiPackage: java\n" + " Class1.java\n" + " -PsiPackage: javax.servlet\n" + " Class1.java\n" + " -Libraries\n" + " -PsiPackage: java\n" + " +PsiPackage: awt\n" + " +PsiPackage: beans.beancontext\n" + " +PsiPackage: io\n" + " +PsiPackage: lang\n" + " +PsiPackage: net\n" + " +PsiPackage: rmi\n" + " +PsiPackage: security\n" + " +PsiPackage: sql\n" + " +PsiPackage: util\n" + " -PsiPackage: javax.swing\n" + " +PsiPackage: table\n" + " AbstractButton.class\n" + " Icon.class\n" + " JButton.class\n" + " JComponent.class\n" + " JDialog.class\n" + " JFrame.class\n" + " JLabel.class\n" + " JPanel.class\n" + " JScrollPane.class\n" + " JTable.class\n" + " SwingConstants.class\n" + " SwingUtilities.class\n" + " -PsiPackage: META-INF\n" + " MANIFEST.MF\n" + " MANIFEST.MF\n" + " -PsiPackage: org\n" + " +PsiPackage: intellij.lang.annotations\n" + " +PsiPackage: jetbrains.annotations\n" + "" , 5); doTest(false, true, "-Project\n" + " -PsiPackage: com.package1\n" + " Class1.java\n" + " Class2.java\n" + " Class4.java\n" + " emptyClassFile.class\n" + " Form1.form\n" + " Form1.java\n" + " Form2.form\n" + " PsiPackage: empty\n" + " -PsiPackage: java\n" + " Class1.java\n" + " -PsiPackage: javax.servlet\n" + " Class1.java\n" + " -Libraries\n" + " -PsiPackage: java\n" + " +PsiPackage: awt\n" + " +PsiPackage: beans.beancontext\n" + " +PsiPackage: io\n" + " +PsiPackage: lang\n" + " +PsiPackage: net\n" + " +PsiPackage: rmi\n" + " +PsiPackage: security\n" + " +PsiPackage: sql\n" + " +PsiPackage: util\n" + " -PsiPackage: javax.swing\n" + " +PsiPackage: table\n" + " AbstractButton.class\n" + " Icon.class\n" + " JButton.class\n" + " JComponent.class\n" + " JDialog.class\n" + " JFrame.class\n" + " JLabel.class\n" + " JPanel.class\n" + " JScrollPane.class\n" + " JTable.class\n" + " SwingConstants.class\n" + " SwingUtilities.class\n" + " -PsiPackage: META-INF\n" + " MANIFEST.MF\n" + " MANIFEST.MF\n" + " -PsiPackage: org\n" + " +PsiPackage: intellij.lang.annotations\n" + " +PsiPackage: jetbrains.annotations\n" , 3); doTest(true, false, "-Project\n" + " -Group: Group\n" + " -Module\n" + " -PsiPackage: com.package1\n" + " Class1.java\n" + " Class2.java\n" + " Class4.java\n" + " emptyClassFile.class\n" + " Form1.form\n" + " Form1.java\n" + " Form2.form\n" + " PsiPackage: empty\n" + " -PsiPackage: java\n" + " Class1.java\n" + " -PsiPackage: javax.servlet\n" + " Class1.java\n", 4); doTest(false, false, true, true, "-Project\n" + " -PsiPackage: com.package1\n" + " Class1.java\n" + " Class2.java\n" + " Class4.java\n" + " emptyClassFile.class\n" + " Form1.form\n" + " Form1.java\n" + " Form2.form\n" + " PsiPackage: empty\n" + " -PsiPackage: java\n" + " Class1.java\n" + " -PsiPackage: j.servlet\n" + " Class1.java\n", 3); doTest(false, false, "-Project\n" + " -PsiPackage: com.package1\n" + " Class1.java\n" + " Class2.java\n" + " Class4.java\n" + " emptyClassFile.class\n" + " Form1.form\n" + " Form1.java\n" + " Form2.form\n" + " PsiPackage: empty\n" + " -PsiPackage: java\n" + " Class1.java\n" + " -PsiPackage: javax.servlet\n" + " Class1.java\n", 3); } private void doTest(final boolean showModules, final boolean showLibraryContents, @NonNls final String expected, final int levels) throws InterruptedException { doTest(showModules, showLibraryContents, false, false, expected, levels); } private void doTest(final boolean showModules, final boolean showLibraryContents, boolean flattenPackages, boolean abbreviatePackageNames, @NonNls final String expected, final int levels) throws InterruptedException { final ProjectViewImpl projectView = (ProjectViewImpl)ProjectView.getInstance(myProject); projectView.setShowModules(showModules, PackageViewPane.ID); projectView.setShowLibraryContents(showLibraryContents, PackageViewPane.ID); projectView.setFlattenPackages(flattenPackages, PackageViewPane.ID); projectView.setAbbreviatePackageNames(abbreviatePackageNames, PackageViewPane.ID); projectView.setHideEmptyPackages(true, PackageViewPane.ID); PackageViewPane packageViewPane = new PackageViewPane(myProject); packageViewPane.createComponent(); ((AbstractProjectTreeStructure) packageViewPane.getTreeStructure()).setProviders(new ResourceBundleGrouper(myProject)); packageViewPane.updateFromRoot(true); JTree tree = packageViewPane.getTree(); TreeUtil.expand(tree, levels); PlatformTestUtil.assertTreeEqual(tree, expected); BaseProjectViewTestCase.checkContainsMethod(packageViewPane.getTreeStructure().getRootElement(), packageViewPane.getTreeStructure()); Disposer.dispose(packageViewPane); } @Override protected String getTestPath() { return "projectView"; } }
java/java-tests/testSrc/com/intellij/projectView/PackagesTreeStructureTest.java
/* * Copyright (c) 2004 JetBrains s.r.o. 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. * * -Redistribution in binary form must reproduct 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 JetBrains or IntelliJ IDEA * may be used to endorse or promote products derived from this software * without specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. JETBRAINS AND ITS LICENSORS SHALL NOT * BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT * OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL JETBRAINS OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN * IF JETBRAINS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * */ package com.intellij.projectView; import com.intellij.ide.projectView.ProjectView; import com.intellij.ide.projectView.impl.AbstractProjectTreeStructure; import com.intellij.ide.projectView.impl.PackageViewPane; import com.intellij.ide.projectView.impl.ProjectViewImpl; import com.intellij.testFramework.IdeaTestUtil; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.module.impl.ModuleManagerImpl; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.testFramework.TestSourceBasedTestCase; import com.intellij.util.ui.tree.TreeUtil; import com.intellij.lang.properties.projectView.ResourceBundleGrouper; import org.jetbrains.annotations.NonNls; import javax.swing.*; import java.io.IOException; public class PackagesTreeStructureTest extends TestSourceBasedTestCase { public void testPackageView() throws IOException { ModuleManagerImpl.getInstanceImpl(myProject).setModuleGroupPath(myModule, new String[]{"Group"}); final VirtualFile srcFile = getSrcDirectory().getVirtualFile(); if (srcFile.findChild("empty") == null){ ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { try { srcFile.createChildDirectory(this, "empty"); } catch (IOException e) { fail(e.getLocalizedMessage()); } } }); } doTest(true, true, "-Project\n" + " -Group: Group\n" + " -Module\n" + " -PsiPackage: com.package1\n" + " Class1.java\n" + " Class2.java\n" + " Class4.java\n" + " emptyClassFile.class\n" + " Form1.form\n" + " Form1.java\n" + " Form2.form\n" + " PsiPackage: empty\n" + " -PsiPackage: java\n" + " Class1.java\n" + " -PsiPackage: javax.servlet\n" + " Class1.java\n" + " -Libraries\n" + " -PsiPackage: java\n" + " +PsiPackage: awt\n" + " +PsiPackage: beans.beancontext\n" + " +PsiPackage: io\n" + " +PsiPackage: lang\n" + " +PsiPackage: net\n" + " +PsiPackage: rmi\n" + " +PsiPackage: security\n" + " +PsiPackage: sql\n" + " +PsiPackage: util\n" + " -PsiPackage: javax.swing\n" + " +PsiPackage: table\n" + " AbstractButton.class\n" + " Icon.class\n" + " JButton.class\n" + " JComponent.class\n" + " JDialog.class\n" + " JFrame.class\n" + " JLabel.class\n" + " JPanel.class\n" + " JScrollPane.class\n" + " JTable.class\n" + " SwingConstants.class\n" + " SwingUtilities.class\n" + " -PsiPackage: META-INF\n" + " MANIFEST.MF\n" + " MANIFEST.MF\n" + " -PsiPackage: org\n" + " +PsiPackage: intellij.lang.annotations\n" + " +PsiPackage: jetbrains.annotations\n" + "" , 5); doTest(false, true, "-Project\n" + " -PsiPackage: com.package1\n" + " Class1.java\n" + " Class2.java\n" + " Class4.java\n" + " emptyClassFile.class\n" + " Form1.form\n" + " Form1.java\n" + " Form2.form\n" + " PsiPackage: empty\n" + " -PsiPackage: java\n" + " Class1.java\n" + " -PsiPackage: javax.servlet\n" + " Class1.java\n" + " -Libraries\n" + " -PsiPackage: java\n" + " +PsiPackage: awt\n" + " +PsiPackage: beans.beancontext\n" + " +PsiPackage: io\n" + " +PsiPackage: lang\n" + " +PsiPackage: net\n" + " +PsiPackage: rmi\n" + " +PsiPackage: security\n" + " +PsiPackage: sql\n" + " +PsiPackage: util\n" + " -PsiPackage: javax.swing\n" + " +PsiPackage: table\n" + " AbstractButton.class\n" + " Icon.class\n" + " JButton.class\n" + " JComponent.class\n" + " JDialog.class\n" + " JFrame.class\n" + " JLabel.class\n" + " JPanel.class\n" + " JScrollPane.class\n" + " JTable.class\n" + " SwingConstants.class\n" + " SwingUtilities.class\n" + " -PsiPackage: META-INF\n" + " MANIFEST.MF\n" + " MANIFEST.MF\n" + " -PsiPackage: org\n" + " +PsiPackage: intellij.lang.annotations\n" + " +PsiPackage: jetbrains.annotations\n" , 3); doTest(true, false, "-Project\n" + " -Group: Group\n" + " -Module\n" + " -PsiPackage: com.package1\n" + " Class1.java\n" + " Class2.java\n" + " Class4.java\n" + " emptyClassFile.class\n" + " Form1.form\n" + " Form1.java\n" + " Form2.form\n" + " PsiPackage: empty\n" + " -PsiPackage: java\n" + " Class1.java\n" + " -PsiPackage: javax.servlet\n" + " Class1.java\n", 4); doTest(false, false, "-Project\n" + " -PsiPackage: com.package1\n" + " Class1.java\n" + " Class2.java\n" + " Class4.java\n" + " emptyClassFile.class\n" + " Form1.form\n" + " Form1.java\n" + " Form2.form\n" + " PsiPackage: empty\n" + " -PsiPackage: java\n" + " Class1.java\n" + " -PsiPackage: javax.servlet\n" + " Class1.java\n", 3); } private void doTest(final boolean showModules, final boolean showLibraryContents, @NonNls final String expected, final int levels) { final ProjectViewImpl projectView = (ProjectViewImpl)ProjectView.getInstance(myProject); projectView.setShowModules(showModules, PackageViewPane.ID); projectView.setShowLibraryContents(showLibraryContents, PackageViewPane.ID); projectView.setFlattenPackages(false, PackageViewPane.ID); projectView.setHideEmptyPackages(true, PackageViewPane.ID); PackageViewPane packageViewPane = new PackageViewPane(myProject); packageViewPane.createComponent(); ((AbstractProjectTreeStructure) packageViewPane.getTreeStructure()).setProviders(new ResourceBundleGrouper(myProject)); packageViewPane.updateFromRoot(true); JTree tree = packageViewPane.getTree(); TreeUtil.expand(tree, levels); IdeaTestUtil.assertTreeEqual(tree, expected); BaseProjectViewTestCase.checkContainsMethod(packageViewPane.getTreeStructure().getRootElement(), packageViewPane.getTreeStructure()); Disposer.dispose(packageViewPane); } @Override protected String getTestPath() { return "projectView"; } }
add a test for abbreviate package names
java/java-tests/testSrc/com/intellij/projectView/PackagesTreeStructureTest.java
add a test for abbreviate package names
<ide><path>ava/java-tests/testSrc/com/intellij/projectView/PackagesTreeStructureTest.java <ide> /* <del> * Copyright (c) 2004 JetBrains s.r.o. All Rights Reserved. <add> * Copyright 2000-2017 JetBrains s.r.o. <ide> * <del> * Redistribution and use in source and binary forms, with or without <del> * modification, are permitted provided that the following conditions <del> * are met: <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 <ide> * <del> * -Redistributions of source code must retain the above copyright <del> * notice, this list of conditions and the following disclaimer. <add> * http://www.apache.org/licenses/LICENSE-2.0 <ide> * <del> * -Redistribution in binary form must reproduct the above copyright <del> * notice, this list of conditions and the following disclaimer in <del> * the documentation and/or other materials provided with the distribution. <del> * <del> * Neither the name of JetBrains or IntelliJ IDEA <del> * may be used to endorse or promote products derived from this software <del> * without specific prior written permission. <del> * <del> * This software is provided "AS IS," without a warranty of any kind. ALL <del> * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING <del> * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE <del> * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. JETBRAINS AND ITS LICENSORS SHALL NOT <del> * BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT <del> * OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS <del> * DERIVATIVES. IN NO EVENT WILL JETBRAINS OR ITS LICENSORS BE LIABLE FOR ANY LOST <del> * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, <del> * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY <del> * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN <del> * IF JETBRAINS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. <del> * <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. <ide> */ <ide> package com.intellij.projectView; <ide> <ide> import com.intellij.ide.projectView.impl.AbstractProjectTreeStructure; <ide> import com.intellij.ide.projectView.impl.PackageViewPane; <ide> import com.intellij.ide.projectView.impl.ProjectViewImpl; <del>import com.intellij.testFramework.IdeaTestUtil; <add>import com.intellij.lang.properties.projectView.ResourceBundleGrouper; <ide> import com.intellij.openapi.application.ApplicationManager; <ide> import com.intellij.openapi.module.impl.ModuleManagerImpl; <ide> import com.intellij.openapi.util.Disposer; <ide> import com.intellij.openapi.vfs.VirtualFile; <add>import com.intellij.testFramework.PlatformTestUtil; <ide> import com.intellij.testFramework.TestSourceBasedTestCase; <ide> import com.intellij.util.ui.tree.TreeUtil; <del>import com.intellij.lang.properties.projectView.ResourceBundleGrouper; <ide> import org.jetbrains.annotations.NonNls; <ide> <ide> import javax.swing.*; <ide> import java.io.IOException; <ide> <ide> public class PackagesTreeStructureTest extends TestSourceBasedTestCase { <del> public void testPackageView() throws IOException { <add> public void testPackageView() throws IOException, InterruptedException { <ide> ModuleManagerImpl.getInstanceImpl(myProject).setModuleGroupPath(myModule, new String[]{"Group"}); <ide> final VirtualFile srcFile = getSrcDirectory().getVirtualFile(); <ide> if (srcFile.findChild("empty") == null){ <ide> " -PsiPackage: javax.servlet\n" + <ide> " Class1.java\n", 4); <ide> <del> doTest(false, false, "-Project\n" + <add> doTest(false, false, true, true, "-Project\n" + <ide> " -PsiPackage: com.package1\n" + <ide> " Class1.java\n" + <ide> " Class2.java\n" + <ide> " PsiPackage: empty\n" + <ide> " -PsiPackage: java\n" + <ide> " Class1.java\n" + <add> " -PsiPackage: j.servlet\n" + <add> " Class1.java\n", 3); <add> <add> doTest(false, false, "-Project\n" + <add> " -PsiPackage: com.package1\n" + <add> " Class1.java\n" + <add> " Class2.java\n" + <add> " Class4.java\n" + <add> " emptyClassFile.class\n" + <add> " Form1.form\n" + <add> " Form1.java\n" + <add> " Form2.form\n" + <add> " PsiPackage: empty\n" + <add> " -PsiPackage: java\n" + <add> " Class1.java\n" + <ide> " -PsiPackage: javax.servlet\n" + <ide> " Class1.java\n", 3); <del> <del> } <del> <del> private void doTest(final boolean showModules, final boolean showLibraryContents, @NonNls final String expected, final int levels) { <add> } <add> <add> private void doTest(final boolean showModules, final boolean showLibraryContents, @NonNls final String expected, final int levels) <add> throws InterruptedException { <add> doTest(showModules, showLibraryContents, false, false, expected, levels); <add> } <add> <add> private void doTest(final boolean showModules, final boolean showLibraryContents, boolean flattenPackages, boolean abbreviatePackageNames, @NonNls final String expected, final int levels) <add> throws InterruptedException { <ide> final ProjectViewImpl projectView = (ProjectViewImpl)ProjectView.getInstance(myProject); <ide> <ide> projectView.setShowModules(showModules, PackageViewPane.ID); <ide> <ide> projectView.setShowLibraryContents(showLibraryContents, PackageViewPane.ID); <ide> <del> projectView.setFlattenPackages(false, PackageViewPane.ID); <add> projectView.setFlattenPackages(flattenPackages, PackageViewPane.ID); <add> projectView.setAbbreviatePackageNames(abbreviatePackageNames, PackageViewPane.ID); <ide> projectView.setHideEmptyPackages(true, PackageViewPane.ID); <ide> <ide> PackageViewPane packageViewPane = new PackageViewPane(myProject); <ide> packageViewPane.updateFromRoot(true); <ide> JTree tree = packageViewPane.getTree(); <ide> TreeUtil.expand(tree, levels); <del> IdeaTestUtil.assertTreeEqual(tree, expected); <add> PlatformTestUtil.assertTreeEqual(tree, expected); <ide> BaseProjectViewTestCase.checkContainsMethod(packageViewPane.getTreeStructure().getRootElement(), packageViewPane.getTreeStructure()); <ide> Disposer.dispose(packageViewPane); <ide> }
Java
mit
c6f329057c32c26693f4a69d0d0cf28b55582ac0
0
GluuFederation/oxCore
/* * oxCore is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2018, Gluu */ package org.gluu.persist.couchbase.operation.impl; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import org.gluu.persist.couchbase.impl.CouchbaseBatchOperationWraper; import org.gluu.persist.couchbase.model.BucketMapping; import org.gluu.persist.couchbase.model.SearchReturnDataType; import org.gluu.persist.couchbase.operation.CouchbaseOperationService; import org.gluu.persist.couchbase.operation.watch.OperationDurationUtil; import org.gluu.persist.exception.operation.DeleteException; import org.gluu.persist.exception.operation.DuplicateEntryException; import org.gluu.persist.exception.operation.EntryNotFoundException; import org.gluu.persist.exception.operation.PersistenceException; import org.gluu.persist.exception.operation.SearchException; import org.gluu.persist.model.BatchOperation; import org.gluu.persist.model.PagedResult; import org.gluu.persist.model.SearchScope; import org.gluu.persist.operation.auth.PasswordEncryptionHelper; import org.gluu.util.ArrayHelper; import org.gluu.util.StringHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.couchbase.client.core.CouchbaseException; import com.couchbase.client.core.message.kv.subdoc.multi.Mutation; import com.couchbase.client.java.Bucket; import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.json.JsonArray; import com.couchbase.client.java.document.json.JsonObject; import com.couchbase.client.java.query.Delete; import com.couchbase.client.java.query.N1qlParams; import com.couchbase.client.java.query.N1qlQuery; import com.couchbase.client.java.query.N1qlQueryResult; import com.couchbase.client.java.query.N1qlQueryRow; import com.couchbase.client.java.query.Select; import com.couchbase.client.java.query.Statement; import com.couchbase.client.java.query.consistency.ScanConsistency; import com.couchbase.client.java.query.dsl.Expression; import com.couchbase.client.java.query.dsl.Sort; import com.couchbase.client.java.query.dsl.path.GroupByPath; import com.couchbase.client.java.query.dsl.path.LimitPath; import com.couchbase.client.java.query.dsl.path.MutateLimitPath; import com.couchbase.client.java.query.dsl.path.OffsetPath; import com.couchbase.client.java.query.dsl.path.ReturningPath; import com.couchbase.client.java.subdoc.DocumentFragment; import com.couchbase.client.java.subdoc.MutateInBuilder; import com.couchbase.client.java.subdoc.MutationSpec; /** * Base service which performs all supported Couchbase operations * * @author Yuriy Movchan Date: 05/10/2018 */ public class CouchbaseOperationsServiceImpl implements CouchbaseOperationService { private static final Logger LOG = LoggerFactory.getLogger(CouchbaseConnectionProvider.class); private Properties props; private CouchbaseConnectionProvider connectionProvider; private ScanConsistency scanConsistency = ScanConsistency.NOT_BOUNDED; private boolean ignoreAttributeScanConsistency = false; private boolean attemptWithoutAttributeScanConsistency = true; private boolean enableScopeSupport = false; private boolean disableAttributeMapping = false; @SuppressWarnings("unused") private CouchbaseOperationsServiceImpl() { } public CouchbaseOperationsServiceImpl(Properties props, CouchbaseConnectionProvider connectionProvider) { this.props = props; this.connectionProvider = connectionProvider; init(); } private void init() { if (props.containsKey("connection.scan-consistency")) { String scanConsistencyString = StringHelper.toUpperCase(props.get("connection.scan-consistency").toString()); this.scanConsistency = ScanConsistency.valueOf(scanConsistencyString); } if (props.containsKey("connection.ignore-attribute-scan-consistency")) { this.ignoreAttributeScanConsistency = StringHelper.toBoolean(props.get("connection.ignore-attribute-scan-consistency").toString(), this.ignoreAttributeScanConsistency); } if (props.containsKey("connection.attempt-without-attribute-scan-consistency")) { this.attemptWithoutAttributeScanConsistency = StringHelper.toBoolean(props.get("attempt-without-attribute-scan-consistency").toString(), this.attemptWithoutAttributeScanConsistency); } if (props.containsKey("connection.enable-scope-support")) { this.enableScopeSupport = StringHelper.toBoolean(props.get("connection.enable-scope-support").toString(), this.enableScopeSupport); } if (props.containsKey("connection.disable-attribute-mapping")) { this.disableAttributeMapping = StringHelper.toBoolean(props.get("connection.disable-attribute-mapping").toString(), this.disableAttributeMapping); } LOG.info("Option scanConsistency: " + scanConsistency); LOG.info("Option ignoreAttributeScanConsistency: " + ignoreAttributeScanConsistency); LOG.info("Option enableScopeSupport: " + enableScopeSupport); LOG.info("Option disableAttributeMapping: " + disableAttributeMapping); } @Override public CouchbaseConnectionProvider getConnectionProvider() { return connectionProvider; } @Override public boolean authenticate(final String key, final String password) throws SearchException { return authenticateImpl(key, password); } private boolean authenticateImpl(final String key, final String password) throws SearchException { Instant startTime = OperationDurationUtil.instance().now(); boolean result = false; if (password != null) { JsonObject entry = lookup(key, null, USER_PASSWORD); Object userPasswordObj = entry.get(USER_PASSWORD); String userPassword = null; if (userPasswordObj instanceof JsonArray) { userPassword = ((JsonArray) userPasswordObj).getString(0); } else if (userPasswordObj instanceof String) { userPassword = (String) userPasswordObj; } if (userPassword != null) { result = PasswordEncryptionHelper.compareCredentials(password.getBytes(), userPassword.getBytes()); } } Duration duration = OperationDurationUtil.instance().duration(startTime); BucketMapping bucketMapping = connectionProvider.getBucketMappingByKey(key); OperationDurationUtil.instance().logDebug("Couchbase operation: bind, duration: {}, bucket: {}, key: {}", duration, bucketMapping.getBucketName(), key); return result; } @Override public boolean addEntry(String key, JsonObject jsonObject) throws DuplicateEntryException, PersistenceException { Instant startTime = OperationDurationUtil.instance().now(); BucketMapping bucketMapping = connectionProvider.getBucketMappingByKey(key); boolean result = addEntryImpl(bucketMapping, key, jsonObject); Duration duration = OperationDurationUtil.instance().duration(startTime); OperationDurationUtil.instance().logDebug("Couchbase operation: add, duration: {}, bucket: {}, key: {}, json: {}", duration, bucketMapping.getBucketName(), key, jsonObject); return result; } private boolean addEntryImpl(BucketMapping bucketMapping, String key, JsonObject jsonObject) throws PersistenceException { try { JsonDocument jsonDocument = JsonDocument.create(key, jsonObject); JsonDocument result = bucketMapping.getBucket().upsert(jsonDocument); if (result != null) { return true; } } catch (CouchbaseException ex) { throw new PersistenceException("Failed to add entry", ex); } return false; } @Deprecated protected boolean updateEntry(String key, JsonObject attrs) throws UnsupportedOperationException, SearchException { List<MutationSpec> mods = new ArrayList<MutationSpec>(); for (Entry<String, Object> attrEntry : attrs.toMap().entrySet()) { String attributeName = attrEntry.getKey(); Object attributeValue = attrEntry.getValue(); if (attributeName.equalsIgnoreCase(CouchbaseOperationService.OBJECT_CLASS) || attributeName.equalsIgnoreCase(CouchbaseOperationService.DN) || attributeName.equalsIgnoreCase(CouchbaseOperationService.USER_PASSWORD)) { continue; } else { if (attributeValue != null) { mods.add(new MutationSpec(Mutation.REPLACE, attributeName, attributeValue)); } } } return updateEntry(key, mods); } @Override public boolean updateEntry(String key, List<MutationSpec> mods) throws UnsupportedOperationException, SearchException { Instant startTime = OperationDurationUtil.instance().now(); BucketMapping bucketMapping = connectionProvider.getBucketMappingByKey(key); boolean result = updateEntryImpl(bucketMapping, key, mods); Duration duration = OperationDurationUtil.instance().duration(startTime); OperationDurationUtil.instance().logDebug("Couchbase operation: modify, duration: {}, bucket: {}, key: {}, mods: {}", duration, bucketMapping.getBucketName(), key, mods); return result; } private boolean updateEntryImpl(BucketMapping bucketMapping, String key, List<MutationSpec> mods) throws SearchException { try { MutateInBuilder builder = bucketMapping.getBucket().mutateIn(key); return modifyEntry(builder, mods); } catch (final CouchbaseException ex) { throw new SearchException("Failed to update entry", ex); } } protected boolean modifyEntry(MutateInBuilder builder, List<MutationSpec> mods) throws UnsupportedOperationException, SearchException { try { for (MutationSpec mod : mods) { Mutation type = mod.type(); if (Mutation.DICT_ADD == type) { builder.insert(mod.path(), mod.fragment()); } else if (Mutation.REPLACE == type) { builder.replace(mod.path(), mod.fragment()); } else if (Mutation.DELETE == type) { builder.remove(mod.path()); } else { throw new UnsupportedOperationException("Operation type '" + type + "' is not implemented"); } } DocumentFragment<Mutation> result = builder.execute(); if (result.size() > 0) { return result.status(0).isSuccess(); } return false; } catch (final CouchbaseException ex) { throw new SearchException("Failed to update entry", ex); } } @Override public boolean delete(String key) throws EntryNotFoundException { Instant startTime = OperationDurationUtil.instance().now(); BucketMapping bucketMapping = connectionProvider.getBucketMappingByKey(key); boolean result = deleteImpl(bucketMapping, key); Duration duration = OperationDurationUtil.instance().duration(startTime); OperationDurationUtil.instance().logDebug("Couchbase operation: delete, duration: {}, bucket: {}, key: {}", duration, bucketMapping.getBucketName(), key); return result; } private boolean deleteImpl(BucketMapping bucketMapping, String key) throws EntryNotFoundException { try { JsonDocument result = bucketMapping.getBucket().remove(key); return (result != null) && (result.id() != null); } catch (CouchbaseException ex) { throw new EntryNotFoundException("Failed to delete entry", ex); } } @Override public int delete(String key, ScanConsistency scanConsistency, Expression expression, int count) throws DeleteException { Instant startTime = OperationDurationUtil.instance().now(); BucketMapping bucketMapping = connectionProvider.getBucketMappingByKey(key); ScanConsistency useScanConsistency = getScanConsistency(scanConsistency, false); int result = deleteImpl(bucketMapping, key, useScanConsistency, expression, count); String attemptInfo = getScanAttemptLogInfo(scanConsistency, useScanConsistency, false); Duration duration = OperationDurationUtil.instance().duration(startTime); OperationDurationUtil.instance().logDebug("Couchbase operation: delete_search, duration: {}, bucket: {}, key: {}, expression: {}, count: {}, consistency: {}{}", duration, bucketMapping.getBucketName(), key, expression, count, useScanConsistency, attemptInfo); return result; } private int deleteImpl(BucketMapping bucketMapping, String key, ScanConsistency scanConsistency, Expression expression, int count) throws DeleteException { Bucket bucket = bucketMapping.getBucket(); Expression finalExpression = expression; if (enableScopeSupport) { Expression scopeExpression = Expression.path("META().id").like(Expression.s(key + "%")); finalExpression = scopeExpression.and(expression); } MutateLimitPath deleteQuery = Delete.deleteFrom(Expression.i(bucketMapping.getBucketName())).where(finalExpression); ReturningPath query = deleteQuery.limit(count); LOG.debug("Execution query: '" + query + "'"); N1qlQueryResult result = bucket.query(N1qlQuery.simple(query, N1qlParams.build().consistency(scanConsistency))); if (!result.finalSuccess()) { throw new DeleteException(String.format("Failed to delete entries. Query: '%s'. Error: '%s', Error count: '%d'", query, result.errors(), result.info().errorCount()), result.errors().get(0).getInt("code")); } return result.info().mutationCount(); } @Override public boolean deleteRecursively(String key) throws EntryNotFoundException, SearchException { Instant startTime = OperationDurationUtil.instance().now(); BucketMapping bucketMapping = connectionProvider.getBucketMappingByKey(key); boolean result = deleteRecursivelyImpl(bucketMapping, key); Duration duration = OperationDurationUtil.instance().duration(startTime); OperationDurationUtil.instance().logDebug("Couchbase operation: delete_tree, duration: {}, bucket: {}, key: {}", duration, bucketMapping.getBucketName(), key); return result; } private boolean deleteRecursivelyImpl(BucketMapping bucketMapping, String key) throws SearchException, EntryNotFoundException { try { if (enableScopeSupport) { MutateLimitPath deleteQuery = Delete.deleteFrom(Expression.i(bucketMapping.getBucketName())) .where(Expression.path("META().id").like(Expression.s(key + "%"))); N1qlQueryResult result = bucketMapping.getBucket().query(deleteQuery); if (!result.finalSuccess()) { throw new SearchException(String.format("Failed to delete entries. Query: '%s'. Error: '%s', Error count: '%d'", deleteQuery, result.errors(), result.info().errorCount()), result.errors().get(0).getInt("code")); } } else { LOG.warn("Removing only base key without sub-tree: " + key); delete(key); } return true; } catch (CouchbaseException ex) { throw new EntryNotFoundException("Failed to delete entry", ex); } } @Override public JsonObject lookup(String key, ScanConsistency scanConsistency, String... attributes) throws SearchException { Instant startTime = OperationDurationUtil.instance().now(); BucketMapping bucketMapping = connectionProvider.getBucketMappingByKey(key); boolean secondTry = false; ScanConsistency useScanConsistency = getScanConsistency(scanConsistency, attemptWithoutAttributeScanConsistency); JsonObject result = lookupImpl(bucketMapping, key, useScanConsistency, attributes); if ((result == null) || result.isEmpty()) { ScanConsistency useScanConsistency2 = getScanConsistency(scanConsistency, false); if (!useScanConsistency2.equals(useScanConsistency)) { useScanConsistency = useScanConsistency2; secondTry = true; result = lookupImpl(bucketMapping, key, useScanConsistency, attributes); } } String attemptInfo = getScanAttemptLogInfo(scanConsistency, useScanConsistency, secondTry); Duration duration = OperationDurationUtil.instance().duration(startTime); OperationDurationUtil.instance().logDebug("Couchbase operation: lookup, duration: {}, bucket: {}, key: {}, attributes: {}, consistency: {}{}", duration, bucketMapping.getBucketName(), key, attributes, useScanConsistency, attemptInfo); return result; } private JsonObject lookupImpl(BucketMapping bucketMapping, String key, ScanConsistency scanConsistency, String... attributes) throws SearchException { try { Bucket bucket = bucketMapping.getBucket(); if (ArrayHelper.isEmpty(attributes)) { JsonDocument doc = bucket.get(key); if (doc != null) { return doc.content(); } } else { JsonDocument doc = bucket.get(key); if (doc != null) { Set<String> docAtributesKeep = new HashSet<String>(Arrays.asList(attributes)); for (Iterator<String> it = doc.content().getNames().iterator(); it.hasNext();) { String docAtribute = (String) it.next(); if (!docAtributesKeep.contains(docAtribute)) { it.remove(); } } return doc.content(); } // N1qlParams params = N1qlParams.build().consistency(scanConsistency); // OffsetPath select = Select.select(attributes).from(Expression.i(bucketMapping.getBucketName())).useKeys(Expression.s(key)).limit(1); // N1qlQueryResult result = bucket.query(N1qlQuery.simple(select, params)); // if (!result.finalSuccess()) { // throw new SearchException(String.format("Failed to lookup entry. Errors: %s", result.errors()), result.info().errorCount()); // } // // if (result.allRows().size() == 1) { // return result.allRows().get(0).value(); // } } } catch (CouchbaseException ex) { throw new SearchException("Failed to lookup entry", ex); } throw new SearchException("Failed to lookup entry"); } @Override public <O> PagedResult<JsonObject> search(String key, ScanConsistency scanConsistency, Expression expression, SearchScope scope, String[] attributes, Sort[] orderBy, CouchbaseBatchOperationWraper<O> batchOperationWraper, SearchReturnDataType returnDataType, int start, int count, int pageSize) throws SearchException { Instant startTime = OperationDurationUtil.instance().now(); BucketMapping bucketMapping = connectionProvider.getBucketMappingByKey(key); boolean secondTry = false; ScanConsistency useScanConsistency = getScanConsistency(scanConsistency, attemptWithoutAttributeScanConsistency); PagedResult<JsonObject> result = null; int attemps = 20; do { attemps--; try { result = searchImpl(bucketMapping, key, useScanConsistency, expression, scope, attributes, orderBy, batchOperationWraper, returnDataType, start, count, pageSize); break; } catch (SearchException ex) { if (ex.getErrorCode() != 5000) { throw ex; } LOG.warn("Waiting for Indexer Warmup..."); try { Thread.sleep(2000); } catch (InterruptedException ex2) {} } } while (attemps > 0); if ((result == null) || (result.getEntriesCount() == 0)) { ScanConsistency useScanConsistency2 = getScanConsistency(scanConsistency, false); if (!useScanConsistency2.equals(useScanConsistency)) { useScanConsistency = useScanConsistency2; result = searchImpl(bucketMapping, key, useScanConsistency, expression, scope, attributes, orderBy, batchOperationWraper, returnDataType, start, count, pageSize); secondTry = true; } } String attemptInfo = getScanAttemptLogInfo(scanConsistency, useScanConsistency, secondTry); Duration duration = OperationDurationUtil.instance().duration(startTime); OperationDurationUtil.instance().logDebug("Couchbase operation: search, duration: {}, bucket: {}, key: {}, expression: {}, scope: {}, attributes: {}, orderBy: {}, batchOperationWraper: {}, returnDataType: {}, start: {}, count: {}, pageSize: {}, consistency: {}{}", duration, bucketMapping.getBucketName(), key, expression, scope, attributes, orderBy, batchOperationWraper, returnDataType, start, count, pageSize, useScanConsistency, attemptInfo); return result; } private <O> PagedResult<JsonObject> searchImpl(BucketMapping bucketMapping, String key, ScanConsistency scanConsistency, Expression expression, SearchScope scope, String[] attributes, Sort[] orderBy, CouchbaseBatchOperationWraper<O> batchOperationWraper, SearchReturnDataType returnDataType, int start, int count, int pageSize) throws SearchException { Bucket bucket = bucketMapping.getBucket(); BatchOperation<O> ldapBatchOperation = null; if (batchOperationWraper != null) { ldapBatchOperation = (BatchOperation<O>) batchOperationWraper.getBatchOperation(); } if (LOG.isTraceEnabled()) { // Find whole DB search if (StringHelper.equalsIgnoreCase(key, "_")) { LOG.trace("Search in whole DB tree", new Exception()); } } Expression finalExpression = expression; if (enableScopeSupport) { Expression scopeExpression; if (scope == null) { scopeExpression = null; } else if (SearchScope.BASE == scope) { scopeExpression = Expression.path("META().id").like(Expression.s(key + "%")) .and(Expression.path("META().id").notLike(Expression.s(key + "\\\\_%\\\\_"))); } else { scopeExpression = Expression.path("META().id").like(Expression.s(key + "%")); } if (scopeExpression != null) { finalExpression = scopeExpression.and(expression); } } else { if (scope != null) { LOG.warn("Ignoring scope '" + scope + " for expression: " + expression); } } String[] select = attributes; if (select == null) { select = new String[] { "gluu_doc.*", CouchbaseOperationService.DN }; } else if ((select.length == 1) && StringHelper.isEmpty(select[0])) { // Compatibility with Couchbase persistence layer when application pass filter new String[] { "" } select = new String[] { CouchbaseOperationService.DN }; } else { boolean hasDn = Arrays.asList(select).contains(CouchbaseOperationService.DN); if (!hasDn) { select = ArrayHelper.arrayMerge(select, new String[] { CouchbaseOperationService.DN }); } } GroupByPath selectQuery = Select.select(select).from(Expression.i(bucketMapping.getBucketName())).as("gluu_doc").where(finalExpression); LimitPath baseQuery = selectQuery; if (orderBy != null) { baseQuery = selectQuery.orderBy(orderBy); } List<N1qlQueryRow> searchResultList = new ArrayList<N1qlQueryRow>(); if ((SearchReturnDataType.SEARCH == returnDataType) || (SearchReturnDataType.SEARCH_COUNT == returnDataType)) { N1qlQueryResult lastResult = null; if (pageSize > 0) { boolean collectSearchResult; Statement query = null; int currentLimit; try { List<N1qlQueryRow> lastSearchResultList; int resultCount = 0; do { collectSearchResult = true; currentLimit = pageSize; if (count > 0) { currentLimit = Math.min(pageSize, count - resultCount); } query = baseQuery.limit(currentLimit).offset(start + resultCount); LOG.debug("Execution query: '" + query + "'"); lastResult = bucket.query(N1qlQuery.simple(query, N1qlParams.build().consistency(scanConsistency))); if (!lastResult.finalSuccess()) { throw new SearchException(String.format("Failed to search entries. Query: '%s'. Error: '%s', Error count: '%d'", query, lastResult.errors(), lastResult.info().errorCount()), lastResult.errors().get(0).getInt("code")); } lastSearchResultList = lastResult.allRows(); if (ldapBatchOperation != null) { collectSearchResult = ldapBatchOperation.collectSearchResult(lastSearchResultList.size()); } if (collectSearchResult) { searchResultList.addAll(lastSearchResultList); } if (ldapBatchOperation != null) { List<O> entries = batchOperationWraper.createEntities(lastSearchResultList); ldapBatchOperation.performAction(entries); } resultCount += lastSearchResultList.size(); if ((count > 0) && (resultCount >= count)) { break; } } while (lastSearchResultList.size() > 0); } catch (CouchbaseException ex) { throw new SearchException("Failed to search entries. Query: '" + query + "'", ex); } } else { try { Statement query = baseQuery; if (count > 0) { query = ((LimitPath) query).limit(count); } if (start > 0) { query = ((OffsetPath) query).offset(start); } LOG.debug("Execution query: '" + query + "'"); lastResult = bucket.query(N1qlQuery.simple(query, N1qlParams.build().consistency(scanConsistency))); if (!lastResult.finalSuccess()) { throw new SearchException(String.format("Failed to search entries. Query: '%s'. Error: '%s', Error count: '%d'", baseQuery, lastResult.errors(), lastResult.info().errorCount()), lastResult.errors().get(0).getInt("code")); } searchResultList.addAll(lastResult.allRows()); } catch (CouchbaseException ex) { throw new SearchException("Failed to search entries. Query: '" + baseQuery.toString() + "'", ex); } } } List<JsonObject> resultRows = new ArrayList<JsonObject>(searchResultList.size()); for (N1qlQueryRow row : searchResultList) { resultRows.add(row.value()); } PagedResult<JsonObject> result = new PagedResult<JsonObject>(); result.setEntries(resultRows); result.setEntriesCount(resultRows.size()); result.setStart(start); if ((SearchReturnDataType.COUNT == returnDataType) || (SearchReturnDataType.SEARCH_COUNT == returnDataType)) { GroupByPath selectCountQuery = Select.select("COUNT(*) as TOTAL").from(Expression.i(bucketMapping.getBucketName())) .where(finalExpression); try { LOG.debug("Calculating count. Execution query: '" + selectCountQuery + "'"); N1qlQueryResult countResult = bucket.query(N1qlQuery.simple(selectCountQuery, N1qlParams.build().consistency(scanConsistency))); if (!countResult.finalSuccess() || (countResult.info().resultCount() != 1)) { throw new SearchException(String.format("Failed to calculate count entries. Query: '%s'. Error: '%s', Error count: '%d'", selectCountQuery, countResult.errors(), countResult.info().errorCount()), countResult.errors().get(0).getInt("code")); } result.setTotalEntriesCount(countResult.allRows().get(0).value().getInt("TOTAL")); } catch (CouchbaseException ex) { throw new SearchException("Failed to calculate count entries. Query: '" + selectCountQuery.toString() + "'", ex); } } return result; } public String[] createStoragePassword(String[] passwords) { if (ArrayHelper.isEmpty(passwords)) { return passwords; } String[] results = new String[passwords.length]; for (int i = 0; i < passwords.length; i++) { results[i] = PasswordEncryptionHelper.createStoragePassword(passwords[i], connectionProvider.getPasswordEncryptionMethod()); } return results; } @Override public boolean isBinaryAttribute(String attribute) { return this.connectionProvider.isBinaryAttribute(attribute); } @Override public boolean isCertificateAttribute(String attribute) { return this.connectionProvider.isCertificateAttribute(attribute); } private ScanConsistency getScanConsistency(ScanConsistency operationScanConsistency, boolean ignore) { if (ignore) { return scanConsistency; } if (ignoreAttributeScanConsistency) { return scanConsistency; } if (operationScanConsistency != null) { return operationScanConsistency; } return scanConsistency; } public ScanConsistency getScanConsistency() { return scanConsistency; } public boolean isDisableAttributeMapping() { return disableAttributeMapping; } @Override public boolean destroy() { boolean result = true; if (connectionProvider != null) { try { connectionProvider.destory(); } catch (Exception ex) { LOG.error("Failed to destory provider correctly"); result = false; } } return result; } @Override public boolean isConnected() { return connectionProvider.isConnected(); } protected String getScanAttemptLogInfo(ScanConsistency scanConsistency, ScanConsistency usedScanConsistency, boolean secondTry) { String attemptInfo = ""; if (secondTry) { attemptInfo = ", attempt: second"; } else { ScanConsistency useScanConsistency2 = getScanConsistency(scanConsistency, false); if (!useScanConsistency2.equals(usedScanConsistency)) { attemptInfo = ", attempt: first"; } } return attemptInfo; } }
persistence-couchbase/src/main/java/org/gluu/persist/couchbase/operation/impl/CouchbaseOperationsServiceImpl.java
/* * oxCore is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2018, Gluu */ package org.gluu.persist.couchbase.operation.impl; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import org.gluu.persist.couchbase.impl.CouchbaseBatchOperationWraper; import org.gluu.persist.couchbase.model.BucketMapping; import org.gluu.persist.couchbase.model.SearchReturnDataType; import org.gluu.persist.couchbase.operation.CouchbaseOperationService; import org.gluu.persist.couchbase.operation.watch.OperationDurationUtil; import org.gluu.persist.exception.operation.DeleteException; import org.gluu.persist.exception.operation.DuplicateEntryException; import org.gluu.persist.exception.operation.EntryNotFoundException; import org.gluu.persist.exception.operation.PersistenceException; import org.gluu.persist.exception.operation.SearchException; import org.gluu.persist.model.BatchOperation; import org.gluu.persist.model.PagedResult; import org.gluu.persist.model.SearchScope; import org.gluu.persist.operation.auth.PasswordEncryptionHelper; import org.gluu.util.ArrayHelper; import org.gluu.util.StringHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.couchbase.client.core.CouchbaseException; import com.couchbase.client.core.message.kv.subdoc.multi.Mutation; import com.couchbase.client.java.Bucket; import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.json.JsonArray; import com.couchbase.client.java.document.json.JsonObject; import com.couchbase.client.java.query.Delete; import com.couchbase.client.java.query.N1qlParams; import com.couchbase.client.java.query.N1qlQuery; import com.couchbase.client.java.query.N1qlQueryResult; import com.couchbase.client.java.query.N1qlQueryRow; import com.couchbase.client.java.query.Select; import com.couchbase.client.java.query.Statement; import com.couchbase.client.java.query.consistency.ScanConsistency; import com.couchbase.client.java.query.dsl.Expression; import com.couchbase.client.java.query.dsl.Sort; import com.couchbase.client.java.query.dsl.path.GroupByPath; import com.couchbase.client.java.query.dsl.path.LimitPath; import com.couchbase.client.java.query.dsl.path.MutateLimitPath; import com.couchbase.client.java.query.dsl.path.OffsetPath; import com.couchbase.client.java.query.dsl.path.ReturningPath; import com.couchbase.client.java.subdoc.DocumentFragment; import com.couchbase.client.java.subdoc.MutateInBuilder; import com.couchbase.client.java.subdoc.MutationSpec; /** * Base service which performs all supported Couchbase operations * * @author Yuriy Movchan Date: 05/10/2018 */ public class CouchbaseOperationsServiceImpl implements CouchbaseOperationService { private static final Logger LOG = LoggerFactory.getLogger(CouchbaseConnectionProvider.class); private Properties props; private CouchbaseConnectionProvider connectionProvider; private ScanConsistency scanConsistency = ScanConsistency.NOT_BOUNDED; private boolean ignoreAttributeScanConsistency = false; private boolean attemptWithoutAttributeScanConsistency = true; private boolean enableScopeSupport = false; private boolean disableAttributeMapping = false; @SuppressWarnings("unused") private CouchbaseOperationsServiceImpl() { } public CouchbaseOperationsServiceImpl(Properties props, CouchbaseConnectionProvider connectionProvider) { this.props = props; this.connectionProvider = connectionProvider; init(); } private void init() { if (props.containsKey("connection.scan-consistency")) { String scanConsistencyString = StringHelper.toUpperCase(props.get("connection.scan-consistency").toString()); this.scanConsistency = ScanConsistency.valueOf(scanConsistencyString); } if (props.containsKey("connection.ignore-attribute-scan-consistency")) { this.ignoreAttributeScanConsistency = StringHelper.toBoolean(props.get("connection.ignore-attribute-scan-consistency").toString(), this.ignoreAttributeScanConsistency); } if (props.containsKey("connection.attempt-without-attribute-scan-consistency")) { this.attemptWithoutAttributeScanConsistency = StringHelper.toBoolean(props.get("attempt-without-attribute-scan-consistency").toString(), this.attemptWithoutAttributeScanConsistency); } if (props.containsKey("connection.enable-scope-support")) { this.enableScopeSupport = StringHelper.toBoolean(props.get("connection.enable-scope-support").toString(), this.enableScopeSupport); } if (props.containsKey("connection.disable-attribute-mapping")) { this.disableAttributeMapping = StringHelper.toBoolean(props.get("connection.disable-attribute-mapping").toString(), this.disableAttributeMapping); } LOG.info("Option scanConsistency: " + scanConsistency); LOG.info("Option ignoreAttributeScanConsistency: " + ignoreAttributeScanConsistency); LOG.info("Option enableScopeSupport: " + enableScopeSupport); LOG.info("Option disableAttributeMapping: " + disableAttributeMapping); } @Override public CouchbaseConnectionProvider getConnectionProvider() { return connectionProvider; } @Override public boolean authenticate(final String key, final String password) throws SearchException { return authenticateImpl(key, password); } private boolean authenticateImpl(final String key, final String password) throws SearchException { Instant startTime = OperationDurationUtil.instance().now(); boolean result = false; if (password != null) { JsonObject entry = lookup(key, null, USER_PASSWORD); Object userPasswordObj = entry.get(USER_PASSWORD); String userPassword = null; if (userPasswordObj instanceof JsonArray) { userPassword = ((JsonArray) userPasswordObj).getString(0); } else if (userPasswordObj instanceof String) { userPassword = (String) userPasswordObj; } if (userPassword != null) { result = PasswordEncryptionHelper.compareCredentials(password.getBytes(), userPassword.getBytes()); } } Duration duration = OperationDurationUtil.instance().duration(startTime); BucketMapping bucketMapping = connectionProvider.getBucketMappingByKey(key); OperationDurationUtil.instance().logDebug("Couchbase operation: bind, duration: {}, bucket: {}, key: {}", duration, bucketMapping.getBucketName(), key); return result; } @Override public boolean addEntry(String key, JsonObject jsonObject) throws DuplicateEntryException, PersistenceException { Instant startTime = OperationDurationUtil.instance().now(); BucketMapping bucketMapping = connectionProvider.getBucketMappingByKey(key); boolean result = addEntryImpl(bucketMapping, key, jsonObject); Duration duration = OperationDurationUtil.instance().duration(startTime); OperationDurationUtil.instance().logDebug("Couchbase operation: add, duration: {}, bucket: {}, key: {}, json: {}", duration, bucketMapping.getBucketName(), key, jsonObject); return result; } private boolean addEntryImpl(BucketMapping bucketMapping, String key, JsonObject jsonObject) throws PersistenceException { try { JsonDocument jsonDocument = JsonDocument.create(key, jsonObject); JsonDocument result = bucketMapping.getBucket().upsert(jsonDocument); if (result != null) { return true; } } catch (CouchbaseException ex) { throw new PersistenceException("Failed to add entry", ex); } return false; } @Deprecated protected boolean updateEntry(String key, JsonObject attrs) throws UnsupportedOperationException, SearchException { List<MutationSpec> mods = new ArrayList<MutationSpec>(); for (Entry<String, Object> attrEntry : attrs.toMap().entrySet()) { String attributeName = attrEntry.getKey(); Object attributeValue = attrEntry.getValue(); if (attributeName.equalsIgnoreCase(CouchbaseOperationService.OBJECT_CLASS) || attributeName.equalsIgnoreCase(CouchbaseOperationService.DN) || attributeName.equalsIgnoreCase(CouchbaseOperationService.USER_PASSWORD)) { continue; } else { if (attributeValue != null) { mods.add(new MutationSpec(Mutation.REPLACE, attributeName, attributeValue)); } } } return updateEntry(key, mods); } @Override public boolean updateEntry(String key, List<MutationSpec> mods) throws UnsupportedOperationException, SearchException { Instant startTime = OperationDurationUtil.instance().now(); BucketMapping bucketMapping = connectionProvider.getBucketMappingByKey(key); boolean result = updateEntryImpl(bucketMapping, key, mods); Duration duration = OperationDurationUtil.instance().duration(startTime); OperationDurationUtil.instance().logDebug("Couchbase operation: modify, duration: {}, bucket: {}, key: {}, mods: {}", duration, bucketMapping.getBucketName(), key, mods); return result; } private boolean updateEntryImpl(BucketMapping bucketMapping, String key, List<MutationSpec> mods) throws SearchException { try { MutateInBuilder builder = bucketMapping.getBucket().mutateIn(key); return modifyEntry(builder, mods); } catch (final CouchbaseException ex) { throw new SearchException("Failed to update entry", ex); } } protected boolean modifyEntry(MutateInBuilder builder, List<MutationSpec> mods) throws UnsupportedOperationException, SearchException { try { for (MutationSpec mod : mods) { Mutation type = mod.type(); if (Mutation.DICT_ADD == type) { builder.insert(mod.path(), mod.fragment()); } else if (Mutation.REPLACE == type) { builder.replace(mod.path(), mod.fragment()); } else if (Mutation.DELETE == type) { builder.remove(mod.path()); } else { throw new UnsupportedOperationException("Operation type '" + type + "' is not implemented"); } } DocumentFragment<Mutation> result = builder.execute(); if (result.size() > 0) { return result.status(0).isSuccess(); } return false; } catch (final CouchbaseException ex) { throw new SearchException("Failed to update entry", ex); } } @Override public boolean delete(String key) throws EntryNotFoundException { Instant startTime = OperationDurationUtil.instance().now(); BucketMapping bucketMapping = connectionProvider.getBucketMappingByKey(key); boolean result = deleteImpl(bucketMapping, key); Duration duration = OperationDurationUtil.instance().duration(startTime); OperationDurationUtil.instance().logDebug("Couchbase operation: delete, duration: {}, bucket: {}, key: {}", duration, bucketMapping.getBucketName(), key); return result; } private boolean deleteImpl(BucketMapping bucketMapping, String key) throws EntryNotFoundException { try { JsonDocument result = bucketMapping.getBucket().remove(key); return (result != null) && (result.id() != null); } catch (CouchbaseException ex) { throw new EntryNotFoundException("Failed to delete entry", ex); } } @Override public int delete(String key, ScanConsistency scanConsistency, Expression expression, int count) throws DeleteException { Instant startTime = OperationDurationUtil.instance().now(); BucketMapping bucketMapping = connectionProvider.getBucketMappingByKey(key); ScanConsistency useScanConsistency = getScanConsistency(scanConsistency, false); int result = deleteImpl(bucketMapping, key, useScanConsistency, expression, count); String attemptInfo = getScanAttemptLogInfo(scanConsistency, useScanConsistency, false); Duration duration = OperationDurationUtil.instance().duration(startTime); OperationDurationUtil.instance().logDebug("Couchbase operation: delete_search, duration: {}, bucket: {}, key: {}, expression: {}, count: {}, consistency: {}{}", duration, bucketMapping.getBucketName(), key, expression, count, useScanConsistency, attemptInfo); return result; } private int deleteImpl(BucketMapping bucketMapping, String key, ScanConsistency scanConsistency, Expression expression, int count) throws DeleteException { Bucket bucket = bucketMapping.getBucket(); Expression finalExpression = expression; if (enableScopeSupport) { Expression scopeExpression = Expression.path("META().id").like(Expression.s(key + "%")); finalExpression = scopeExpression.and(expression); } MutateLimitPath deleteQuery = Delete.deleteFrom(Expression.i(bucketMapping.getBucketName())).where(finalExpression); ReturningPath query = deleteQuery.limit(count); LOG.debug("Execution query: '" + query + "'"); N1qlQueryResult result = bucket.query(N1qlQuery.simple(query, N1qlParams.build().consistency(scanConsistency))); if (!result.finalSuccess()) { throw new DeleteException(String.format("Failed to delete entries. Query: '%s'. Error: '%s', Error count: '%d'", query, result.errors(), result.info().errorCount()), result.errors().get(0).getInt("code")); } return result.info().mutationCount(); } @Override public boolean deleteRecursively(String key) throws EntryNotFoundException, SearchException { Instant startTime = OperationDurationUtil.instance().now(); BucketMapping bucketMapping = connectionProvider.getBucketMappingByKey(key); boolean result = deleteRecursivelyImpl(bucketMapping, key); Duration duration = OperationDurationUtil.instance().duration(startTime); OperationDurationUtil.instance().logDebug("Couchbase operation: delete_tree, duration: {}, bucket: {}, key: {}", duration, bucketMapping.getBucketName(), key); return result; } private boolean deleteRecursivelyImpl(BucketMapping bucketMapping, String key) throws SearchException, EntryNotFoundException { try { if (enableScopeSupport) { MutateLimitPath deleteQuery = Delete.deleteFrom(Expression.i(bucketMapping.getBucketName())) .where(Expression.path("META().id").like(Expression.s(key + "%"))); N1qlQueryResult result = bucketMapping.getBucket().query(deleteQuery); if (!result.finalSuccess()) { throw new SearchException(String.format("Failed to delete entries. Query: '%s'. Error: '%s', Error count: '%d'", deleteQuery, result.errors(), result.info().errorCount()), result.errors().get(0).getInt("code")); } } else { LOG.warn("Removing only base key without sub-tree: " + key); delete(key); } return true; } catch (CouchbaseException ex) { throw new EntryNotFoundException("Failed to delete entry", ex); } } @Override public JsonObject lookup(String key, ScanConsistency scanConsistency, String... attributes) throws SearchException { Instant startTime = OperationDurationUtil.instance().now(); BucketMapping bucketMapping = connectionProvider.getBucketMappingByKey(key); boolean secondTry = false; ScanConsistency useScanConsistency = getScanConsistency(scanConsistency, attemptWithoutAttributeScanConsistency); JsonObject result = lookupImpl(bucketMapping, key, useScanConsistency, attributes); if ((result == null) || result.isEmpty()) { ScanConsistency useScanConsistency2 = getScanConsistency(scanConsistency, false); if (!useScanConsistency2.equals(useScanConsistency)) { useScanConsistency = useScanConsistency2; secondTry = true; result = lookupImpl(bucketMapping, key, useScanConsistency, attributes); } } String attemptInfo = getScanAttemptLogInfo(scanConsistency, useScanConsistency, secondTry); Duration duration = OperationDurationUtil.instance().duration(startTime); OperationDurationUtil.instance().logDebug("Couchbase operation: lookup, duration: {}, bucket: {}, key: {}, attributes: {}, consistency: {}{}", duration, bucketMapping.getBucketName(), key, attributes, useScanConsistency, attemptInfo); return result; } private JsonObject lookupImpl(BucketMapping bucketMapping, String key, ScanConsistency scanConsistency, String... attributes) throws SearchException { try { Bucket bucket = bucketMapping.getBucket(); if (ArrayHelper.isEmpty(attributes)) { JsonDocument doc = bucket.get(key); if (doc != null) { return doc.content(); } } else { JsonDocument doc = bucket.get(key); if (doc != null) { Set<String> docAtributesKeep = new HashSet<String>(Arrays.asList(attributes)); for (Iterator<String> it = doc.content().getNames().iterator(); it.hasNext();) { String docAtribute = (String) it.next(); if (!docAtributesKeep.contains(docAtribute)) { it.remove(); } } return doc.content(); } // N1qlParams params = N1qlParams.build().consistency(scanConsistency); // OffsetPath select = Select.select(attributes).from(Expression.i(bucketMapping.getBucketName())).useKeys(Expression.s(key)).limit(1); // N1qlQueryResult result = bucket.query(N1qlQuery.simple(select, params)); // if (!result.finalSuccess()) { // throw new SearchException(String.format("Failed to lookup entry. Errors: %s", result.errors()), result.info().errorCount()); // } // // if (result.allRows().size() == 1) { // return result.allRows().get(0).value(); // } } } catch (CouchbaseException ex) { throw new SearchException("Failed to lookup entry", ex); } throw new SearchException("Failed to lookup entry"); } @Override public <O> PagedResult<JsonObject> search(String key, ScanConsistency scanConsistency, Expression expression, SearchScope scope, String[] attributes, Sort[] orderBy, CouchbaseBatchOperationWraper<O> batchOperationWraper, SearchReturnDataType returnDataType, int start, int count, int pageSize) throws SearchException { Instant startTime = OperationDurationUtil.instance().now(); BucketMapping bucketMapping = connectionProvider.getBucketMappingByKey(key); boolean secondTry = false; ScanConsistency useScanConsistency = getScanConsistency(scanConsistency, attemptWithoutAttributeScanConsistency); PagedResult<JsonObject> result = null; int attemps = 20; do { attemps--; try { result = searchImpl(bucketMapping, key, useScanConsistency, expression, scope, attributes, orderBy, batchOperationWraper, returnDataType, start, count, pageSize); } catch (SearchException ex) { if (ex.getErrorCode() != 5000) { throw ex; } LOG.warn("Waiting for Indexer Warmup..."); try { Thread.sleep(2000); } catch (InterruptedException ex2) {} } } while (attemps > 0); if ((result == null) || (result.getEntriesCount() == 0)) { ScanConsistency useScanConsistency2 = getScanConsistency(scanConsistency, false); if (!useScanConsistency2.equals(useScanConsistency)) { useScanConsistency = useScanConsistency2; result = searchImpl(bucketMapping, key, useScanConsistency, expression, scope, attributes, orderBy, batchOperationWraper, returnDataType, start, count, pageSize); secondTry = true; } } String attemptInfo = getScanAttemptLogInfo(scanConsistency, useScanConsistency, secondTry); Duration duration = OperationDurationUtil.instance().duration(startTime); OperationDurationUtil.instance().logDebug("Couchbase operation: search, duration: {}, bucket: {}, key: {}, expression: {}, scope: {}, attributes: {}, orderBy: {}, batchOperationWraper: {}, returnDataType: {}, start: {}, count: {}, pageSize: {}, consistency: {}{}", duration, bucketMapping.getBucketName(), key, expression, scope, attributes, orderBy, batchOperationWraper, returnDataType, start, count, pageSize, useScanConsistency, attemptInfo); return result; } private <O> PagedResult<JsonObject> searchImpl(BucketMapping bucketMapping, String key, ScanConsistency scanConsistency, Expression expression, SearchScope scope, String[] attributes, Sort[] orderBy, CouchbaseBatchOperationWraper<O> batchOperationWraper, SearchReturnDataType returnDataType, int start, int count, int pageSize) throws SearchException { Bucket bucket = bucketMapping.getBucket(); BatchOperation<O> ldapBatchOperation = null; if (batchOperationWraper != null) { ldapBatchOperation = (BatchOperation<O>) batchOperationWraper.getBatchOperation(); } if (LOG.isTraceEnabled()) { // Find whole DB search if (StringHelper.equalsIgnoreCase(key, "_")) { LOG.trace("Search in whole DB tree", new Exception()); } } Expression finalExpression = expression; if (enableScopeSupport) { Expression scopeExpression; if (scope == null) { scopeExpression = null; } else if (SearchScope.BASE == scope) { scopeExpression = Expression.path("META().id").like(Expression.s(key + "%")) .and(Expression.path("META().id").notLike(Expression.s(key + "\\\\_%\\\\_"))); } else { scopeExpression = Expression.path("META().id").like(Expression.s(key + "%")); } if (scopeExpression != null) { finalExpression = scopeExpression.and(expression); } } else { if (scope != null) { LOG.warn("Ignoring scope '" + scope + " for expression: " + expression); } } String[] select = attributes; if (select == null) { select = new String[] { "gluu_doc.*", CouchbaseOperationService.DN }; } else if ((select.length == 1) && StringHelper.isEmpty(select[0])) { // Compatibility with Couchbase persistence layer when application pass filter new String[] { "" } select = new String[] { CouchbaseOperationService.DN }; } else { boolean hasDn = Arrays.asList(select).contains(CouchbaseOperationService.DN); if (!hasDn) { select = ArrayHelper.arrayMerge(select, new String[] { CouchbaseOperationService.DN }); } } GroupByPath selectQuery = Select.select(select).from(Expression.i(bucketMapping.getBucketName())).as("gluu_doc").where(finalExpression); LimitPath baseQuery = selectQuery; if (orderBy != null) { baseQuery = selectQuery.orderBy(orderBy); } List<N1qlQueryRow> searchResultList = new ArrayList<N1qlQueryRow>(); if ((SearchReturnDataType.SEARCH == returnDataType) || (SearchReturnDataType.SEARCH_COUNT == returnDataType)) { N1qlQueryResult lastResult = null; if (pageSize > 0) { boolean collectSearchResult; Statement query = null; int currentLimit; try { List<N1qlQueryRow> lastSearchResultList; int resultCount = 0; do { collectSearchResult = true; currentLimit = pageSize; if (count > 0) { currentLimit = Math.min(pageSize, count - resultCount); } query = baseQuery.limit(currentLimit).offset(start + resultCount); LOG.debug("Execution query: '" + query + "'"); lastResult = bucket.query(N1qlQuery.simple(query, N1qlParams.build().consistency(scanConsistency))); if (!lastResult.finalSuccess()) { throw new SearchException(String.format("Failed to search entries. Query: '%s'. Error: '%s', Error count: '%d'", query, lastResult.errors(), lastResult.info().errorCount()), lastResult.errors().get(0).getInt("code")); } lastSearchResultList = lastResult.allRows(); if (ldapBatchOperation != null) { collectSearchResult = ldapBatchOperation.collectSearchResult(lastSearchResultList.size()); } if (collectSearchResult) { searchResultList.addAll(lastSearchResultList); } if (ldapBatchOperation != null) { List<O> entries = batchOperationWraper.createEntities(lastSearchResultList); ldapBatchOperation.performAction(entries); } resultCount += lastSearchResultList.size(); if ((count > 0) && (resultCount >= count)) { break; } } while (lastSearchResultList.size() > 0); } catch (CouchbaseException ex) { throw new SearchException("Failed to search entries. Query: '" + query + "'", ex); } } else { try { Statement query = baseQuery; if (count > 0) { query = ((LimitPath) query).limit(count); } if (start > 0) { query = ((OffsetPath) query).offset(start); } LOG.debug("Execution query: '" + query + "'"); lastResult = bucket.query(N1qlQuery.simple(query, N1qlParams.build().consistency(scanConsistency))); if (!lastResult.finalSuccess()) { throw new SearchException(String.format("Failed to search entries. Query: '%s'. Error: '%s', Error count: '%d'", baseQuery, lastResult.errors(), lastResult.info().errorCount()), lastResult.errors().get(0).getInt("code")); } searchResultList.addAll(lastResult.allRows()); } catch (CouchbaseException ex) { throw new SearchException("Failed to search entries. Query: '" + baseQuery.toString() + "'", ex); } } } List<JsonObject> resultRows = new ArrayList<JsonObject>(searchResultList.size()); for (N1qlQueryRow row : searchResultList) { resultRows.add(row.value()); } PagedResult<JsonObject> result = new PagedResult<JsonObject>(); result.setEntries(resultRows); result.setEntriesCount(resultRows.size()); result.setStart(start); if ((SearchReturnDataType.COUNT == returnDataType) || (SearchReturnDataType.SEARCH_COUNT == returnDataType)) { GroupByPath selectCountQuery = Select.select("COUNT(*) as TOTAL").from(Expression.i(bucketMapping.getBucketName())) .where(finalExpression); try { LOG.debug("Calculating count. Execution query: '" + selectCountQuery + "'"); N1qlQueryResult countResult = bucket.query(N1qlQuery.simple(selectCountQuery, N1qlParams.build().consistency(scanConsistency))); if (!countResult.finalSuccess() || (countResult.info().resultCount() != 1)) { throw new SearchException(String.format("Failed to calculate count entries. Query: '%s'. Error: '%s', Error count: '%d'", selectCountQuery, countResult.errors(), countResult.info().errorCount()), countResult.errors().get(0).getInt("code")); } result.setTotalEntriesCount(countResult.allRows().get(0).value().getInt("TOTAL")); } catch (CouchbaseException ex) { throw new SearchException("Failed to calculate count entries. Query: '" + selectCountQuery.toString() + "'", ex); } } return result; } public String[] createStoragePassword(String[] passwords) { if (ArrayHelper.isEmpty(passwords)) { return passwords; } String[] results = new String[passwords.length]; for (int i = 0; i < passwords.length; i++) { results[i] = PasswordEncryptionHelper.createStoragePassword(passwords[i], connectionProvider.getPasswordEncryptionMethod()); } return results; } @Override public boolean isBinaryAttribute(String attribute) { return this.connectionProvider.isBinaryAttribute(attribute); } @Override public boolean isCertificateAttribute(String attribute) { return this.connectionProvider.isCertificateAttribute(attribute); } private ScanConsistency getScanConsistency(ScanConsistency operationScanConsistency, boolean ignore) { if (ignore) { return scanConsistency; } if (ignoreAttributeScanConsistency) { return scanConsistency; } if (operationScanConsistency != null) { return operationScanConsistency; } return scanConsistency; } public ScanConsistency getScanConsistency() { return scanConsistency; } public boolean isDisableAttributeMapping() { return disableAttributeMapping; } @Override public boolean destroy() { boolean result = true; if (connectionProvider != null) { try { connectionProvider.destory(); } catch (Exception ex) { LOG.error("Failed to destory provider correctly"); result = false; } } return result; } @Override public boolean isConnected() { return connectionProvider.isConnected(); } protected String getScanAttemptLogInfo(ScanConsistency scanConsistency, ScanConsistency usedScanConsistency, boolean secondTry) { String attemptInfo = ""; if (secondTry) { attemptInfo = ", attempt: second"; } else { ScanConsistency useScanConsistency2 = getScanConsistency(scanConsistency, false); if (!useScanConsistency2.equals(usedScanConsistency)) { attemptInfo = ", attempt: first"; } } return attemptInfo; } }
Fix search when indexed warmed up already
persistence-couchbase/src/main/java/org/gluu/persist/couchbase/operation/impl/CouchbaseOperationsServiceImpl.java
Fix search when indexed warmed up already
<ide><path>ersistence-couchbase/src/main/java/org/gluu/persist/couchbase/operation/impl/CouchbaseOperationsServiceImpl.java <ide> try { <ide> result = searchImpl(bucketMapping, key, useScanConsistency, expression, scope, attributes, orderBy, batchOperationWraper, <ide> returnDataType, start, count, pageSize); <add> break; <ide> } catch (SearchException ex) { <ide> if (ex.getErrorCode() != 5000) { <ide> throw ex;
Java
apache-2.0
ffb9a4f85c03b30b8be94980e1b522d6c41a052b
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testFramework; import com.intellij.configurationStore.StateStorageManagerKt; import com.intellij.configurationStore.StoreReloadManager; import com.intellij.execution.ExecutionException; import com.intellij.execution.Executor; import com.intellij.execution.*; import com.intellij.execution.actions.ConfigurationContext; import com.intellij.execution.actions.ConfigurationFromContext; import com.intellij.execution.actions.RunConfigurationProducer; import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.execution.executors.DefaultRunExecutor; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.process.ProcessOutput; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.runners.ProgramRunner; import com.intellij.execution.ui.RunContentDescriptor; import com.intellij.execution.util.ExecUtil; import com.intellij.ide.DataManager; import com.intellij.ide.IdeEventQueue; import com.intellij.ide.fileTemplates.FileTemplateManager; import com.intellij.ide.fileTemplates.impl.FileTemplateManagerImpl; import com.intellij.ide.util.treeView.AbstractTreeBuilder; import com.intellij.ide.util.treeView.AbstractTreeNode; import com.intellij.ide.util.treeView.AbstractTreeStructure; import com.intellij.ide.util.treeView.AbstractTreeUi; import com.intellij.model.psi.PsiSymbolReferenceService; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.impl.LaterInvocator; import com.intellij.openapi.application.impl.NonBlockingReadActionImpl; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.extensions.ProjectExtensionPointName; import com.intellij.openapi.extensions.impl.ExtensionPointImpl; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.impl.LoadTextUtil; import com.intellij.openapi.fileTypes.FileTypeRegistry; import com.intellij.openapi.fileTypes.FileTypes; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.paths.UrlReference; import com.intellij.openapi.paths.WebReference; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ex.ProjectManagerEx; import com.intellij.openapi.ui.Queryable; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileFilter; import com.intellij.openapi.vfs.ex.temp.TempFileSystem; import com.intellij.psi.*; import com.intellij.psi.impl.source.resolve.reference.impl.PsiMultiReference; import com.intellij.rt.execution.junit.FileComparisonFailure; import com.intellij.testFramework.fixtures.IdeaTestExecutionPolicy; import com.intellij.ui.tree.AsyncTreeModel; import com.intellij.util.*; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.concurrency.AppScheduledExecutorService; import com.intellij.util.io.Decompressor; import com.intellij.util.lang.JavaVersion; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.tree.TreeUtil; import gnu.trove.Equality; import junit.framework.AssertionFailedError; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.concurrency.AsyncPromise; import org.jetbrains.concurrency.Promise; import javax.swing.*; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import java.awt.*; import java.awt.event.InvocationEvent; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.List; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import java.util.function.Predicate; import java.util.jar.JarFile; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.Assert.*; /** * @author yole */ @SuppressWarnings({"UseOfSystemOutOrSystemErr", "TestOnlyProblems"}) public final class PlatformTestUtil { private static final Logger LOG = Logger.getInstance(PlatformTestUtil.class); public static final boolean COVERAGE_ENABLED_BUILD = "true".equals(System.getProperty("idea.coverage.enabled.build")); private static final List<Runnable> ourProjectCleanups = new CopyOnWriteArrayList<>(); private static final long MAX_WAIT_TIME = TimeUnit.MINUTES.toMillis(2); public static @NotNull String getTestName(@NotNull String name, boolean lowercaseFirstLetter) { name = StringUtil.trimStart(name, "test"); return StringUtil.isEmpty(name) ? "" : lowercaseFirstLetter(name, lowercaseFirstLetter); } public static @NotNull String lowercaseFirstLetter(@NotNull String name, boolean lowercaseFirstLetter) { if (lowercaseFirstLetter && !isAllUppercaseName(name)) { name = Character.toLowerCase(name.charAt(0)) + name.substring(1); } return name; } public static boolean isAllUppercaseName(@NotNull String name) { int uppercaseChars = 0; for (int i = 0; i < name.length(); i++) { if (Character.isLowerCase(name.charAt(i))) { return false; } if (Character.isUpperCase(name.charAt(i))) { uppercaseChars++; } } return uppercaseChars >= 3; } /** * @see ExtensionPointImpl#maskAll(List, Disposable, boolean) */ public static <T> void maskExtensions(@NotNull ProjectExtensionPointName<T> pointName, @NotNull Project project, @NotNull List<? extends T> newExtensions, @NotNull Disposable parentDisposable) { ((ExtensionPointImpl<T>)pointName.getPoint(project)).maskAll(newExtensions, parentDisposable, true); } public static @Nullable String toString(@Nullable Object node, @Nullable Queryable.PrintInfo printInfo) { if (node instanceof AbstractTreeNode) { if (printInfo != null) { return ((AbstractTreeNode<?>)node).toTestString(printInfo); } else { //noinspection deprecation return ((AbstractTreeNode<?>)node).getTestPresentation(); } } return String.valueOf(node); } @NotNull public static String print(@NotNull JTree tree, boolean withSelection) { return print(tree, new TreePath(tree.getModel().getRoot()), withSelection, null, null); } @NotNull public static String print(@NotNull JTree tree, @NotNull TreePath path, @Nullable Queryable.PrintInfo printInfo, boolean withSelection) { return print(tree, path, withSelection, printInfo, null); } @NotNull public static String print(@NotNull JTree tree, boolean withSelection, @Nullable Predicate<? super String> nodePrintCondition) { return print(tree, new TreePath(tree.getModel().getRoot()), withSelection, null, nodePrintCondition); } @NotNull private static String print(@NotNull JTree tree, @NotNull TreePath path, boolean withSelection, @Nullable Queryable.PrintInfo printInfo, @Nullable Predicate<? super String> nodePrintCondition) { return StringUtil.join(printAsList(tree, path, withSelection, printInfo, nodePrintCondition), "\n"); } @NotNull private static Collection<String> printAsList(@NotNull JTree tree, @NotNull TreePath path, boolean withSelection, @Nullable Queryable.PrintInfo printInfo, @Nullable Predicate<? super String> nodePrintCondition) { Collection<String> strings = new ArrayList<>(); printImpl(tree, path, strings, 0, withSelection, printInfo, nodePrintCondition); return strings; } private static void printImpl(@NotNull JTree tree, @NotNull TreePath path, @NotNull Collection<? super String> strings, int level, boolean withSelection, @Nullable Queryable.PrintInfo printInfo, @Nullable Predicate<? super String> nodePrintCondition) { Object pathComponent = path.getLastPathComponent(); Object userObject = TreeUtil.getUserObject(pathComponent); String nodeText = toString(userObject, printInfo); if (nodePrintCondition != null && !nodePrintCondition.test(nodeText)) { return; } StringBuilder buff = new StringBuilder(); StringUtil.repeatSymbol(buff, ' ', level); boolean expanded = tree.isExpanded(path); int childCount = tree.getModel().getChildCount(pathComponent); if (childCount > 0) { buff.append(expanded ? "-" : "+"); } boolean selected = tree.getSelectionModel().isPathSelected(path); if (withSelection && selected) { buff.append("["); } buff.append(nodeText); if (withSelection && selected) { buff.append("]"); } strings.add(buff.toString()); if (expanded) { for (int i = 0; i < childCount; i++) { TreePath childPath = path.pathByAddingChild(tree.getModel().getChild(pathComponent, i)); printImpl(tree, childPath, strings, level + 1, withSelection, printInfo, nodePrintCondition); } } } public static void assertTreeEqual(@NotNull JTree tree, @NonNls String expected) { assertTreeEqual(tree, expected, false); } public static void assertTreeEqual(@NotNull JTree tree, String expected, boolean checkSelected) { assertTreeEqual(tree, expected, checkSelected, false); } public static void assertTreeEqual(@NotNull JTree tree, @NotNull String expected, boolean checkSelected, boolean ignoreOrder) { String treeStringPresentation = print(tree, checkSelected); if (ignoreOrder) { final Set<String> actualLines = Set.of(treeStringPresentation.split("\n")); final Set<String> expectedLines = Set.of(expected.split("\n")); assertEquals("Expected:\n" + expected + "\nActual:" + treeStringPresentation, expectedLines, actualLines); } else { assertEquals(expected.trim(), treeStringPresentation.trim()); } } public static void expand(@NotNull JTree tree, int @NotNull ... rows) { for (int row : rows) { tree.expandRow(row); waitWhileBusy(tree); } } public static void expandAll(@NotNull JTree tree) { waitForPromise(TreeUtil.promiseExpandAll(tree)); } private static long getMillisSince(long startTimeMillis) { return System.currentTimeMillis() - startTimeMillis; } private static void assertMaxWaitTimeSince(long startTimeMillis) { assertMaxWaitTimeSince(startTimeMillis, MAX_WAIT_TIME); } private static void assertMaxWaitTimeSince(long startTimeMillis, long timeout) { long took = getMillisSince(startTimeMillis); assert took <= timeout : String.format("the waiting takes too long. Expected to take no more than: %d ms but took: %d ms", timeout, took); } private static void assertDispatchThreadWithoutWriteAccess() { assertDispatchThreadWithoutWriteAccess(ApplicationManager.getApplication()); } private static void assertDispatchThreadWithoutWriteAccess(Application application) { if (application != null) { assert !application.isWriteAccessAllowed() : "do not wait under write action to avoid possible deadlock"; assert application.isDispatchThread(); } else { // do not check for write access in simple tests assert EventQueue.isDispatchThread(); } } private static boolean isBusy(@NotNull JTree tree, TreeModel model) { UIUtil.dispatchAllInvocationEvents(); if (model instanceof AsyncTreeModel) { AsyncTreeModel async = (AsyncTreeModel)model; if (async.isProcessing()) return true; UIUtil.dispatchAllInvocationEvents(); return async.isProcessing(); } //noinspection deprecation AbstractTreeBuilder builder = AbstractTreeBuilder.getBuilderFor(tree); if (builder == null) return false; //noinspection deprecation AbstractTreeUi ui = builder.getUi(); if (ui == null) return false; return ui.hasPendingWork(); } public static void waitWhileBusy(@NotNull JTree tree) { assertDispatchThreadWithoutWriteAccess(); long startTimeMillis = System.currentTimeMillis(); while (isBusy(tree, tree.getModel())) { assertMaxWaitTimeSince(startTimeMillis); TimeoutUtil.sleep(5); } } public static void waitForCallback(@NotNull ActionCallback callback) { AsyncPromise<?> promise = new AsyncPromise<>(); callback.doWhenDone(() -> promise.setResult(null)).doWhenRejected((@NotNull Runnable)promise::cancel); waitForPromise(promise); } public static @Nullable <T> T waitForPromise(@NotNull Promise<T> promise) { return waitForPromise(promise, MAX_WAIT_TIME); } public static @Nullable <T> T waitForPromise(@NotNull Promise<T> promise, long timeout) { return waitForPromise(promise, timeout, false); } public static <T> T assertPromiseSucceeds(@NotNull Promise<T> promise) { return waitForPromise(promise, MAX_WAIT_TIME, true); } private static @Nullable <T> T waitForPromise(@NotNull Promise<T> promise, long timeout, boolean assertSucceeded) { assertDispatchThreadWithoutWriteAccess(); long start = System.currentTimeMillis(); while (true) { if (promise.getState() == Promise.State.PENDING) { UIUtil.dispatchAllInvocationEvents(); } try { return promise.blockingGet(20, TimeUnit.MILLISECONDS); } catch (TimeoutException ignore) { } catch (Exception e) { if (assertSucceeded) { throw new AssertionError(e); } else { return null; } } assertMaxWaitTimeSince(start, timeout); } } public static <T> T waitForFuture(@NotNull Future<T> future, long timeoutMillis) { assertDispatchThreadWithoutWriteAccess(); long start = System.currentTimeMillis(); while (true) { if (!future.isDone()) { UIUtil.dispatchAllInvocationEvents(); } try { return future.get(10, TimeUnit.MILLISECONDS); } catch (TimeoutException ignore) { } catch (Exception e) { throw new AssertionError(e); } assertMaxWaitTimeSince(start, timeoutMillis); } } public static void waitForAlarm(final int delay) { @NotNull Application app = ApplicationManager.getApplication(); assertDispatchThreadWithoutWriteAccess(); Disposable tempDisposable = Disposer.newDisposable(); final AtomicBoolean runnableInvoked = new AtomicBoolean(); final AtomicBoolean pooledRunnableInvoked = new AtomicBoolean(); final AtomicBoolean alarmInvoked1 = new AtomicBoolean(); final AtomicBoolean alarmInvoked2 = new AtomicBoolean(); final Alarm alarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD); final Alarm pooledAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, tempDisposable); ModalityState initialModality = ModalityState.current(); alarm.addRequest(() -> { alarmInvoked1.set(true); app.invokeLater(() -> { runnableInvoked.set(true); alarm.addRequest(() -> alarmInvoked2.set(true), delay); }); }, delay); pooledAlarm.addRequest(() -> pooledRunnableInvoked.set(true), delay); UIUtil.dispatchAllInvocationEvents(); long start = System.currentTimeMillis(); try { boolean sleptAlready = false; while (!alarmInvoked2.get()) { AtomicBoolean laterInvoked = new AtomicBoolean(); app.invokeLater(() -> laterInvoked.set(true)); UIUtil.dispatchAllInvocationEvents(); assertTrue(laterInvoked.get()); TimeoutUtil.sleep(sleptAlready ? 10 : delay); sleptAlready = true; if (getMillisSince(start) > MAX_WAIT_TIME) { String queue = ((AppScheduledExecutorService)AppExecutorUtil.getAppScheduledExecutorService()).dumpQueue(); throw new AssertionError("Couldn't await alarm" + "; alarm passed=" + alarmInvoked1.get() + "; modality1=" + initialModality + "; modality2=" + ModalityState.current() + "; non-modal=" + (initialModality == ModalityState.NON_MODAL) + "; invokeLater passed=" + runnableInvoked.get() + "; pooled alarm passed=" + pooledRunnableInvoked.get() + "; app.disposed=" + app.isDisposed() + "; alarm.disposed=" + alarm.isDisposed() + "; alarm.requests=" + alarm.getActiveRequestCount() + "\n delayQueue=" + StringUtil.trimLog(queue, 1000) + "\n invocatorEdtQueue=" + LaterInvocator.getLaterInvocatorEdtQueue() + "\n invocatorWtQueue=" + LaterInvocator.getLaterInvocatorWtQueue() ); } } } finally { Disposer.dispose(tempDisposable); } UIUtil.dispatchAllInvocationEvents(); } /** * Dispatch all pending invocation events (if any) in the {@link IdeEventQueue}, ignores and removes all other events from the queue. * Should only be invoked in Swing thread (asserted inside {@link IdeEventQueue#dispatchEvent(AWTEvent)}) */ public static void dispatchAllInvocationEventsInIdeEventQueue() { IdeEventQueue eventQueue = IdeEventQueue.getInstance(); while (true) { AWTEvent event = eventQueue.peekEvent(); if (event == null) break; try { event = eventQueue.getNextEvent(); if (event instanceof InvocationEvent) { eventQueue.dispatchEvent(event); } } catch (InterruptedException e) { throw new RuntimeException(e); } } } /** * Dispatch all pending events (if any) in the {@link IdeEventQueue}. * Should only be invoked in Swing thread (asserted inside {@link IdeEventQueue#dispatchEvent(AWTEvent)}) */ public static void dispatchAllEventsInIdeEventQueue() { IdeEventQueue eventQueue = IdeEventQueue.getInstance(); while (true) { try { if (dispatchNextEventIfAny(eventQueue) == null) break; } catch (InterruptedException e) { throw new RuntimeException(e); } } } /** * Dispatch one pending event (if any) in the {@link IdeEventQueue}. * Should only be invoked in Swing thread (asserted inside {@link IdeEventQueue#dispatchEvent(AWTEvent)}) */ public static AWTEvent dispatchNextEventIfAny(@NotNull IdeEventQueue eventQueue) throws InterruptedException { assert SwingUtilities.isEventDispatchThread() : Thread.currentThread(); AWTEvent event = eventQueue.peekEvent(); if (event == null) return null; AWTEvent event1 = eventQueue.getNextEvent(); eventQueue.dispatchEvent(event1); return event1; } @NotNull public static StringBuilder print(@NotNull AbstractTreeStructure structure, @NotNull Object node, int currentLevel, @Nullable Comparator<?> comparator, int maxRowCount, char paddingChar, @Nullable Queryable.PrintInfo printInfo) { return print(structure, node, currentLevel, comparator, maxRowCount, paddingChar, o -> toString(o, printInfo)); } @NotNull public static String print(@NotNull AbstractTreeStructure structure, @NotNull Object node, @NotNull Function<Object, String> nodePresenter) { return print(structure, node, 0, Comparator.comparing(nodePresenter), -1, ' ', nodePresenter).toString(); } @NotNull private static StringBuilder print(@NotNull AbstractTreeStructure structure, @NotNull Object node, int currentLevel, @Nullable Comparator<?> comparator, int maxRowCount, char paddingChar, @NotNull Function<Object, String> nodePresenter) { StringBuilder buffer = new StringBuilder(); doPrint(buffer, currentLevel, node, structure, comparator, maxRowCount, 0, paddingChar, nodePresenter); return buffer; } private static int doPrint(@NotNull StringBuilder buffer, int currentLevel, @NotNull Object node, @NotNull AbstractTreeStructure structure, @Nullable Comparator<?> comparator, int maxRowCount, int currentLine, char paddingChar, @NotNull Function<Object, String> nodePresenter) { if (currentLine >= maxRowCount && maxRowCount != -1) return currentLine; StringUtil.repeatSymbol(buffer, paddingChar, currentLevel); buffer.append(nodePresenter.apply(node)).append("\n"); currentLine++; Object[] children = structure.getChildElements(node); if (comparator != null) { List<?> list = new ArrayList<>(Arrays.asList(children)); @SuppressWarnings("unchecked") Comparator<Object> c = (Comparator<Object>)comparator; list.sort(c); children = ArrayUtil.toObjectArray(list); } for (Object child : children) { currentLine = doPrint(buffer, currentLevel + 1, child, structure, comparator, maxRowCount, currentLine, paddingChar, nodePresenter); } return currentLine; } @NotNull public static String print(Object @NotNull [] objects) { return print(Arrays.asList(objects)); } @NotNull public static String print(@NotNull Collection<?> c) { return c.stream().map(each -> toString(each, null)).collect(Collectors.joining("\n")); } @NotNull public static String print(@NotNull ListModel<?> model) { StringBuilder result = new StringBuilder(); for (int i = 0; i < model.getSize(); i++) { result.append(toString(model.getElementAt(i), null)); result.append("\n"); } return result.toString(); } @NotNull public static String print(@NotNull JTree tree) { return print(tree, false); } public static void invokeNamedAction(@NotNull String actionId) { final AnAction action = ActionManager.getInstance().getAction(actionId); assertNotNull(action); final Presentation presentation = new Presentation(); @SuppressWarnings("deprecation") final DataContext context = DataManager.getInstance().getDataContext(); final AnActionEvent event = AnActionEvent.createFromAnAction(action, null, "", context); action.beforeActionPerformedUpdate(event); assertTrue(presentation.isEnabled()); action.actionPerformed(event); } public static void assertTiming(@NotNull String message, final long expectedMs, final long actual) { if (COVERAGE_ENABLED_BUILD) return; long expectedOnMyMachine = Math.max(1, expectedMs * Timings.CPU_TIMING / Timings.REFERENCE_CPU_TIMING); // Allow 10% more in case of test machine is busy. String logMessage = message; if (actual > expectedOnMyMachine) { int percentage = (int)(100.0 * (actual - expectedOnMyMachine) / expectedOnMyMachine); logMessage += ". Operation took " + percentage + "% longer than expected"; } logMessage += ". Expected on my machine: " + expectedOnMyMachine + "." + " Actual: " + actual + "." + " Expected on Standard machine: " + expectedMs + ";" + " Timings: CPU=" + Timings.CPU_TIMING + ", I/O=" + Timings.IO_TIMING + "."; final double acceptableChangeFactor = 1.1; if (actual < expectedOnMyMachine) { System.out.println(logMessage); TeamCityLogger.info(logMessage); } else if (actual < expectedOnMyMachine * acceptableChangeFactor) { TeamCityLogger.warning(logMessage, null); } else { // throw AssertionFailedError to try one more time throw new AssertionFailedError(logMessage); } } /** * An example: {@code startPerformanceTest("calculating pi",100, testRunnable).assertTiming();} */ @Contract(pure = true) // to warn about not calling .assertTiming() in the end @NotNull public static PerformanceTestInfo startPerformanceTest(@NonNls @NotNull String what, int expectedMs, @NotNull ThrowableRunnable<?> test) { return new PerformanceTestInfo(test, expectedMs, what); } public static void assertPathsEqual(@Nullable String expected, @Nullable String actual) { if (expected != null) expected = FileUtil.toSystemIndependentName(expected); if (actual != null) actual = FileUtil.toSystemIndependentName(actual); assertEquals(expected, actual); } public static @NotNull String getJavaExe() { return SystemProperties.getJavaHome() + (SystemInfo.isWindows ? "\\bin\\java.exe" : "/bin/java"); } public static @NotNull URL getRtJarURL() { String home = SystemProperties.getJavaHome(); try { return JavaVersion.current().feature >= 9 ? new URL("jrt:" + home) : new File(home + "/lib/rt.jar").toURI().toURL(); } catch (MalformedURLException e) { throw new RuntimeException(e); } } public static void forceCloseProjectWithoutSaving(@NotNull Project project) { if (!project.isDisposed()) { ApplicationManager.getApplication().invokeAndWait(() -> ProjectManagerEx.getInstanceEx().forceCloseProject(project)); } } public static void saveProject(@NotNull Project project) { saveProject(project, false); } public static void saveProject(@NotNull Project project, boolean isForceSavingAllSettings) { StoreReloadManager.getInstance().flushChangedProjectFileAlarm(); StateStorageManagerKt.saveComponentManager(project, isForceSavingAllSettings); } static void waitForAllBackgroundActivityToCalmDown() { for (int i = 0; i < 50; i++) { CpuUsageData data = CpuUsageData.measureCpuUsage(() -> TimeoutUtil.sleep(100)); if (!data.hasAnyActivityBesides(Thread.currentThread())) { break; } } } public static void assertTiming(@NotNull String message, long expected, @NotNull Runnable actionToMeasure) { assertTiming(message, expected, 4, actionToMeasure); } @SuppressWarnings("CallToSystemGC") public static void assertTiming(@NotNull String message, long expected, int attempts, @NotNull Runnable actionToMeasure) { while (true) { attempts--; waitForAllBackgroundActivityToCalmDown(); long duration = TimeoutUtil.measureExecutionTime(actionToMeasure::run); try { assertTiming(message, expected, duration); break; } catch (AssertionFailedError e) { if (attempts == 0) throw e; System.gc(); System.gc(); System.gc(); String s = e.getMessage() + "\n " + attempts + " " + StringUtil.pluralize("attempt", attempts) + " remain"; TeamCityLogger.warning(s, null); System.err.println(s); } } } @NotNull private static Map<String, VirtualFile> buildNameToFileMap(VirtualFile @NotNull [] files, @Nullable VirtualFileFilter filter) { Map<String, VirtualFile> map = new HashMap<>(); for (VirtualFile file : files) { if (filter != null && !filter.accept(file)) continue; map.put(file.getName(), file); } return map; } public static void assertDirectoriesEqual(@NotNull VirtualFile dirExpected, @NotNull VirtualFile dirActual) throws IOException { assertDirectoriesEqual(dirExpected, dirActual, null); } @SuppressWarnings("UnsafeVfsRecursion") public static void assertDirectoriesEqual(@NotNull VirtualFile dirExpected, @NotNull VirtualFile dirActual, @Nullable VirtualFileFilter fileFilter) throws IOException { FileDocumentManager.getInstance().saveAllDocuments(); VirtualFile[] childrenAfter = dirExpected.getChildren(); shallowCompare(dirExpected, childrenAfter); VirtualFile[] childrenBefore = dirActual.getChildren(); shallowCompare(dirActual, childrenBefore); Map<String, VirtualFile> mapAfter = buildNameToFileMap(childrenAfter, fileFilter); Map<String, VirtualFile> mapBefore = buildNameToFileMap(childrenBefore, fileFilter); Set<String> keySetAfter = mapAfter.keySet(); Set<String> keySetBefore = mapBefore.keySet(); assertEquals(dirExpected.getPath(), keySetAfter, keySetBefore); for (String name : keySetAfter) { VirtualFile fileAfter = mapAfter.get(name); VirtualFile fileBefore = mapBefore.get(name); if (fileAfter.isDirectory()) { assertDirectoriesEqual(fileAfter, fileBefore, fileFilter); } else { assertFilesEqual(fileAfter, fileBefore); } } } private static void shallowCompare(@NotNull VirtualFile dir, VirtualFile @NotNull [] vfs) { if (dir.isInLocalFileSystem() && dir.getFileSystem() != TempFileSystem.getInstance()) { String vfsPaths = Stream.of(vfs).map(VirtualFile::getPath).sorted().collect(Collectors.joining("\n")); File[] io = Objects.requireNonNull(new File(dir.getPath()).listFiles()); String ioPaths = Stream.of(io).map(f -> FileUtil.toSystemIndependentName(f.getPath())).sorted().collect(Collectors.joining("\n")); assertEquals(vfsPaths, ioPaths); } } public static void assertFilesEqual(@NotNull VirtualFile fileExpected, @NotNull VirtualFile fileActual) throws IOException { try { assertJarFilesEqual(VfsUtilCore.virtualToIoFile(fileExpected), VfsUtilCore.virtualToIoFile(fileActual)); } catch (IOException e) { String actual = fileText(fileActual); String expected = fileText(fileExpected); if (expected == null || actual == null) { assertArrayEquals(fileExpected.getPath(), fileExpected.contentsToByteArray(), fileActual.contentsToByteArray()); } else if (!StringUtil.equals(expected, actual)) { throw new FileComparisonFailure("Text mismatch in the file " + fileExpected.getName(), expected, actual, fileExpected.getPath()); } } } private static String fileText(@NotNull VirtualFile file) throws IOException { Document doc = FileDocumentManager.getInstance().getDocument(file); if (doc != null) { return doc.getText(); } if (!file.getFileType().isBinary() || FileTypeRegistry.getInstance().isFileOfType(file, FileTypes.UNKNOWN)) { return LoadTextUtil.getTextByBinaryPresentation(file.contentsToByteArray(false), file).toString(); } return null; } private static void assertJarFilesEqual(@NotNull File file1, @NotNull File file2) throws IOException { File tempDir = null; try (JarFile jarFile1 = new JarFile(file1); JarFile jarFile2 = new JarFile(file2)) { tempDir = FileUtilRt.createTempDirectory("assert_jar_tmp", null, false); final File tempDirectory1 = new File(tempDir, "tmp1"); final File tempDirectory2 = new File(tempDir, "tmp2"); FileUtilRt.createDirectory(tempDirectory1); FileUtilRt.createDirectory(tempDirectory2); new Decompressor.Zip(new File(jarFile1.getName())).extract(tempDirectory1); new Decompressor.Zip(new File(jarFile2.getName())).extract(tempDirectory2); final VirtualFile dirAfter = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory1); assertNotNull(tempDirectory1.toString(), dirAfter); final VirtualFile dirBefore = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory2); assertNotNull(tempDirectory2.toString(), dirBefore); ApplicationManager.getApplication().runWriteAction(() -> { dirAfter.refresh(false, true); dirBefore.refresh(false, true); }); assertDirectoriesEqual(dirAfter, dirBefore); } finally { if (tempDir != null) { FileUtilRt.delete(tempDir); } } } public static @NotNull String getCommunityPath() { final String homePath = IdeaTestExecutionPolicy.getHomePathWithPolicy(); if (new File(homePath, "community/.idea").isDirectory()) { return homePath + File.separatorChar + "community"; } return homePath; } public static @NotNull String getPlatformTestDataPath() { return getCommunityPath().replace(File.separatorChar, '/') + "/platform/platform-tests/testData/"; } @Contract(pure = true) public static @NotNull Comparator<AbstractTreeNode<?>> createComparator(final Queryable.PrintInfo printInfo) { return (o1, o2) -> { String displayText1 = o1.toTestString(printInfo); String displayText2 = o2.toTestString(printInfo); return Comparing.compare(displayText1, displayText2); }; } public static @NotNull String loadFileText(@NotNull String fileName) throws IOException { return StringUtil.convertLineSeparators(FileUtil.loadFile(new File(fileName))); } public static void withEncoding(@NotNull String encoding, @NotNull ThrowableRunnable<?> r) { Charset.forName(encoding); // check the encoding exists try { Charset oldCharset = Charset.defaultCharset(); try { patchSystemFileEncoding(encoding); r.run(); } finally { patchSystemFileEncoding(oldCharset.name()); } } catch (Throwable t) { throw new RuntimeException(t); } } private static void patchSystemFileEncoding(@NotNull String encoding) { ReflectionUtil.resetField(Charset.class, Charset.class, "defaultCharset"); System.setProperty("file.encoding", encoding); } @SuppressWarnings("ImplicitDefaultCharsetUsage") public static void withStdErrSuppressed(@NotNull Runnable r) { PrintStream std = System.err; System.setErr(new PrintStream(NULL)); try { r.run(); } finally { System.setErr(std); } } @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") private static final OutputStream NULL = new OutputStream() { @Override public void write(int b) { } }; public static void assertSuccessful(@NotNull GeneralCommandLine command) { try { ProcessOutput output = ExecUtil.execAndGetOutput(command.withRedirectErrorStream(true)); assertEquals(output.getStdout(), 0, output.getExitCode()); } catch (ExecutionException e) { throw new RuntimeException(e); } } public static @NotNull List<WebReference> collectWebReferences(@NotNull PsiElement element) { List<WebReference> refs = new ArrayList<>(); element.accept(new PsiRecursiveElementWalkingVisitor() { @Override public void visitElement(@NotNull PsiElement element) { for (PsiReference ref : element.getReferences()) { if (ref instanceof WebReference) { refs.add((WebReference)ref); } } super.visitElement(element); } }); return refs; } public static @NotNull List<UrlReference> collectUrlReferences(@NotNull PsiElement element) { List<UrlReference> result = new SmartList<>(); element.accept(new PsiRecursiveElementWalkingVisitor() { @Override public void visitElement(@NotNull PsiElement element) { result.addAll(PsiSymbolReferenceService.getService().getReferences(element, UrlReference.class)); super.visitElement(element); } }); return result; } public static @NotNull <T extends PsiReference> T getReferenceOfTypeWithAssertion(@Nullable PsiReference reference, @NotNull Class<T> refType) { if (refType.isInstance(reference)) { //noinspection unchecked return (T)reference; } if (reference instanceof PsiMultiReference) { PsiReference[] psiReferences = ((PsiMultiReference)reference).getReferences(); for (PsiReference psiReference : psiReferences) { if (refType.isInstance(psiReference)) { //noinspection unchecked return (T)psiReference; } } } throw new AssertionError("given reference should be " + refType + " but " + (reference != null ? reference.getClass() : null) + " was given"); } public static void registerProjectCleanup(@NotNull Runnable cleanup) { ourProjectCleanups.add(cleanup); } public static void cleanupAllProjects() { for (Runnable each : ourProjectCleanups) { each.run(); } ourProjectCleanups.clear(); } public static void captureMemorySnapshot() { try { String className = "com.jetbrains.performancePlugin.profilers.YourKitProfilerHandler"; Method snapshot = ReflectionUtil.getMethod(Class.forName(className), "captureMemorySnapshot"); if (snapshot != null) { Object path = snapshot.invoke(null); System.out.println("Memory snapshot captured to '" + path + "'"); } } catch (ClassNotFoundException e) { // YourKitProfilerHandler is missing from the classpath, ignore } catch (Exception e) { e.printStackTrace(System.err); } } public static <T> void assertComparisonContractNotViolated(@NotNull List<? extends T> values, @NotNull Comparator<? super T> comparator, @NotNull Equality<? super T> equality) { for (int i1 = 0; i1 < values.size(); i1++) { for (int i2 = i1; i2 < values.size(); i2++) { T value1 = values.get(i1); T value2 = values.get(i2); int result12 = comparator.compare(value1, value2); int result21 = comparator.compare(value2, value1); if (equality.equals(value1, value2)) { if (result12 != 0) fail(String.format("Equal, but not 0: '%s' - '%s'", value1, value2)); if (result21 != 0) fail(String.format("Equal, but not 0: '%s' - '%s'", value2, value1)); } else { if (result12 == 0) fail(String.format("Not equal, but 0: '%s' - '%s'", value1, value2)); if (result21 == 0) fail(String.format("Not equal, but 0: '%s' - '%s'", value2, value1)); if (Integer.signum(result12) == Integer.signum(result21)) { fail(String.format("Not symmetrical: '%s' - '%s'", value1, value2)); } } for (int i3 = i2; i3 < values.size(); i3++) { T value3 = values.get(i3); int result23 = comparator.compare(value2, value3); int result31 = comparator.compare(value3, value1); if (!isTransitive(result12, result23, result31)) { fail(String.format("Not transitive: '%s' - '%s' - '%s'", value1, value2, value3)); } } } } } private static boolean isTransitive(int result12, int result23, int result31) { if (result12 == 0 && result23 == 0 && result31 == 0) return true; if (result12 > 0 && result23 > 0 && result31 > 0) return false; if (result12 < 0 && result23 < 0 && result31 < 0) return false; if (result12 == 0 && Integer.signum(result23) * Integer.signum(result31) >= 0) return false; if (result23 == 0 && Integer.signum(result12) * Integer.signum(result31) >= 0) return false; if (result31 == 0 && Integer.signum(result23) * Integer.signum(result12) >= 0) return false; return true; } public static void setLongMeaninglessFileIncludeTemplateTemporarilyFor(@NotNull Project project, @NotNull Disposable parentDisposable) { FileTemplateManagerImpl templateManager = (FileTemplateManagerImpl)FileTemplateManager.getInstance(project); templateManager.setDefaultFileIncludeTemplateTextTemporarilyForTest(FileTemplateManager.FILE_HEADER_TEMPLATE_NAME, "/**\n" + " * Created by ${USER} on ${DATE}.\n" + " */\n", parentDisposable); } /* * 1. Think twice before use - do you really need to use VFS. * 2. Be aware the method doesn't refresh VFS as it should be done in tests (see {@link PlatformTestCase#synchronizeTempDirVfs}) * (it is assumed that project is already created in a correct way). */ public static @NotNull VirtualFile getOrCreateProjectBaseDir(@NotNull Project project) { return HeavyTestHelper.getOrCreateProjectBaseDir(project); } public static @Nullable RunConfiguration getRunConfiguration(@NotNull PsiElement element, @NotNull RunConfigurationProducer<?> producer) { MapDataContext dataContext = new MapDataContext(); dataContext.put(CommonDataKeys.PROJECT, element.getProject()); dataContext.put(LangDataKeys.MODULE, ModuleUtilCore.findModuleForPsiElement(element)); final Location<PsiElement> location = PsiLocation.fromPsiElement(element); dataContext.put(Location.DATA_KEY, location); ConfigurationContext cc = ConfigurationContext.getFromContext(dataContext); final ConfigurationFromContext configuration = producer.createConfigurationFromContext(cc); return configuration != null ? configuration.getConfiguration() : null; } /** * Executing {@code runConfiguration} with {@link DefaultRunExecutor#EXECUTOR_ID run} executor and wait for 60 seconds till process ends. */ @NotNull public static ExecutionEnvironment executeConfigurationAndWait(@NotNull RunConfiguration runConfiguration) throws InterruptedException { return executeConfigurationAndWait(runConfiguration, DefaultRunExecutor.EXECUTOR_ID); } /** * Executing {@code runConfiguration} with executor {@code executoId} and wait for 60 seconds till process ends. */ @NotNull public static ExecutionEnvironment executeConfigurationAndWait(@NotNull RunConfiguration runConfiguration, @NotNull String executorId) throws InterruptedException { return executeConfigurationAndWait(runConfiguration, executorId, 60); } /** * Executing {@code runConfiguration} with executor {@code executoId} and wait for the {@code timeoutInSeconds} seconds till process ends. */ @NotNull public static ExecutionEnvironment executeConfigurationAndWait(@NotNull RunConfiguration runConfiguration, @NotNull String executorId, long timeoutInSeconds) throws InterruptedException { Pair<@NotNull ExecutionEnvironment, RunContentDescriptor> result = executeConfiguration(runConfiguration, executorId); ProcessHandler processHandler = result.second.getProcessHandler(); if (!processHandler.waitFor(timeoutInSeconds * 1000)) { fail("Process failed to finish in " + timeoutInSeconds + " seconds: " + processHandler); } return result.first; } @NotNull public static Pair<@NotNull ExecutionEnvironment, RunContentDescriptor> executeConfiguration(@NotNull RunConfiguration runConfiguration, @NotNull String executorId) throws InterruptedException { Executor executor = ExecutorRegistry.getInstance().getExecutorById(executorId); assertNotNull("Unable to find executor: " + executorId, executor); return executeConfiguration(runConfiguration, executor); } /** * Executes {@code runConfiguration} with executor defined by {@code executorId} and returns pair of {@link ExecutionEnvironment} and * {@link RunContentDescriptor} */ @NotNull public static Pair<@NotNull ExecutionEnvironment, RunContentDescriptor> executeConfiguration(@NotNull RunConfiguration runConfiguration, @NotNull Executor executor) throws InterruptedException { Project project = runConfiguration.getProject(); ConfigurationFactory factory = runConfiguration.getFactory(); if (factory == null) { fail("No factory found for: " + runConfiguration); } RunnerAndConfigurationSettings runnerAndConfigurationSettings = RunManager.getInstance(project).createConfiguration(runConfiguration, factory); ProgramRunner<?> runner = ProgramRunner.getRunner(executor.getId(), runConfiguration); if (runner == null) { fail("No runner found for: " + executor.getId() + " and " + runConfiguration); } Ref<RunContentDescriptor> refRunContentDescriptor = new Ref<>(); ExecutionEnvironment executionEnvironment = new ExecutionEnvironment(executor, runner, runnerAndConfigurationSettings, project); CountDownLatch latch = new CountDownLatch(1); ProgramRunnerUtil.executeConfigurationAsync(executionEnvironment, false, false, descriptor -> { LOG.debug("Process started"); ProcessHandler processHandler = descriptor.getProcessHandler(); assertNotNull(processHandler); processHandler.addProcessListener(new ProcessAdapter() { @Override public void startNotified(@NotNull ProcessEvent event) { LOG.debug("Process notified"); } @Override public void processTerminated(@NotNull ProcessEvent event) { LOG.debug("Process terminated: exitCode: " + event.getExitCode() + "; text: " + event.getText()); } @Override public void onTextAvailable(@NotNull ProcessEvent event, @NotNull Key outputType) { LOG.debug(outputType + ": " + event.getText()); } }); refRunContentDescriptor.set(descriptor); latch.countDown(); }); NonBlockingReadActionImpl.waitForAsyncTaskCompletion(); LOG.debug("Waiting for process to start"); if (!latch.await(60, TimeUnit.SECONDS)) { fail("Process failed to start in 60 seconds"); } return Pair.create(executionEnvironment, refRunContentDescriptor.get()); } public static PsiElement findElementBySignature(@NotNull String signature, @NotNull String fileRelativePath, @NotNull Project project) { String filePath = project.getBasePath() + File.separator + fileRelativePath; VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(filePath); if (virtualFile == null || !virtualFile.exists()) { throw new IllegalArgumentException(String.format("File '%s' doesn't exist", filePath)); } PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile); if (psiFile == null) { return null; } int offset = psiFile.getText().indexOf(signature); return psiFile.findElementAt(offset); } public static void useAppConfigDir(@NotNull ThrowableRunnable<? extends Exception> task) throws Exception { Path configDir = PathManager.getConfigDir(); Path configCopy; if (Files.exists(configDir)) { configCopy = Files.move(configDir, Paths.get(configDir + "_bak"), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); } else { FileUtil.delete(configDir); configCopy = null; } try { task.run(); } finally { FileUtil.delete(configDir); if (configCopy != null) { Files.move(configCopy, configDir, StandardCopyOption.ATOMIC_MOVE); } } } public static @NotNull Project loadAndOpenProject(@NotNull Path path, @NotNull Disposable parent) { Project project = Objects.requireNonNull(ProjectManagerEx.getInstanceEx().openProject(path, new OpenProjectTaskBuilder().build())); Disposer.register(parent, () -> forceCloseProjectWithoutSaving(project)); return project; } public static void openProject(@NotNull Project project) { if (!ProjectManagerEx.getInstanceEx().openProject(project)) { throw new IllegalStateException("openProject returned false"); } if (ApplicationManager.getApplication().isDispatchThread()) { dispatchAllInvocationEventsInIdeEventQueue(); } } }
platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testFramework; import com.intellij.configurationStore.StateStorageManagerKt; import com.intellij.configurationStore.StoreReloadManager; import com.intellij.execution.ExecutionException; import com.intellij.execution.Executor; import com.intellij.execution.*; import com.intellij.execution.actions.ConfigurationContext; import com.intellij.execution.actions.ConfigurationFromContext; import com.intellij.execution.actions.RunConfigurationProducer; import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.execution.executors.DefaultRunExecutor; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.process.ProcessOutput; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.runners.ProgramRunner; import com.intellij.execution.ui.RunContentDescriptor; import com.intellij.execution.util.ExecUtil; import com.intellij.ide.DataManager; import com.intellij.ide.IdeEventQueue; import com.intellij.ide.fileTemplates.FileTemplateManager; import com.intellij.ide.fileTemplates.impl.FileTemplateManagerImpl; import com.intellij.ide.util.treeView.AbstractTreeBuilder; import com.intellij.ide.util.treeView.AbstractTreeNode; import com.intellij.ide.util.treeView.AbstractTreeStructure; import com.intellij.ide.util.treeView.AbstractTreeUi; import com.intellij.model.psi.PsiSymbolReferenceService; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.impl.LaterInvocator; import com.intellij.openapi.application.impl.NonBlockingReadActionImpl; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.extensions.ProjectExtensionPointName; import com.intellij.openapi.extensions.impl.ExtensionPointImpl; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.impl.LoadTextUtil; import com.intellij.openapi.fileTypes.FileTypeRegistry; import com.intellij.openapi.fileTypes.FileTypes; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.paths.UrlReference; import com.intellij.openapi.paths.WebReference; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ex.ProjectManagerEx; import com.intellij.openapi.ui.Queryable; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileFilter; import com.intellij.openapi.vfs.ex.temp.TempFileSystem; import com.intellij.psi.*; import com.intellij.psi.impl.source.resolve.reference.impl.PsiMultiReference; import com.intellij.rt.execution.junit.FileComparisonFailure; import com.intellij.testFramework.fixtures.IdeaTestExecutionPolicy; import com.intellij.ui.tree.AsyncTreeModel; import com.intellij.util.*; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.concurrency.AppScheduledExecutorService; import com.intellij.util.io.Decompressor; import com.intellij.util.lang.JavaVersion; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.tree.TreeUtil; import gnu.trove.Equality; import junit.framework.AssertionFailedError; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.concurrency.AsyncPromise; import org.jetbrains.concurrency.Promise; import javax.swing.*; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import java.awt.*; import java.awt.event.InvocationEvent; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.List; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import java.util.function.Predicate; import java.util.jar.JarFile; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.Assert.*; /** * @author yole */ @SuppressWarnings({"UseOfSystemOutOrSystemErr", "TestOnlyProblems"}) public final class PlatformTestUtil { private static final Logger LOG = Logger.getInstance(PlatformTestUtil.class); public static final boolean COVERAGE_ENABLED_BUILD = "true".equals(System.getProperty("idea.coverage.enabled.build")); private static final List<Runnable> ourProjectCleanups = new CopyOnWriteArrayList<>(); private static final long MAX_WAIT_TIME = TimeUnit.MINUTES.toMillis(2); public static @NotNull String getTestName(@NotNull String name, boolean lowercaseFirstLetter) { name = StringUtil.trimStart(name, "test"); return StringUtil.isEmpty(name) ? "" : lowercaseFirstLetter(name, lowercaseFirstLetter); } public static @NotNull String lowercaseFirstLetter(@NotNull String name, boolean lowercaseFirstLetter) { if (lowercaseFirstLetter && !isAllUppercaseName(name)) { name = Character.toLowerCase(name.charAt(0)) + name.substring(1); } return name; } public static boolean isAllUppercaseName(@NotNull String name) { int uppercaseChars = 0; for (int i = 0; i < name.length(); i++) { if (Character.isLowerCase(name.charAt(i))) { return false; } if (Character.isUpperCase(name.charAt(i))) { uppercaseChars++; } } return uppercaseChars >= 3; } /** * @see ExtensionPointImpl#maskAll(List, Disposable, boolean) */ public static <T> void maskExtensions(@NotNull ProjectExtensionPointName<T> pointName, @NotNull Project project, @NotNull List<? extends T> newExtensions, @NotNull Disposable parentDisposable) { ((ExtensionPointImpl<T>)pointName.getPoint(project)).maskAll(newExtensions, parentDisposable, true); } public static @Nullable String toString(@Nullable Object node, @Nullable Queryable.PrintInfo printInfo) { if (node instanceof AbstractTreeNode) { if (printInfo != null) { return ((AbstractTreeNode<?>)node).toTestString(printInfo); } else { //noinspection deprecation return ((AbstractTreeNode<?>)node).getTestPresentation(); } } return String.valueOf(node); } @NotNull public static String print(@NotNull JTree tree, boolean withSelection) { return print(tree, new TreePath(tree.getModel().getRoot()), withSelection, null, null); } @NotNull public static String print(@NotNull JTree tree, @NotNull TreePath path, @Nullable Queryable.PrintInfo printInfo, boolean withSelection) { return print(tree, path, withSelection, printInfo, null); } @NotNull public static String print(@NotNull JTree tree, boolean withSelection, @Nullable Predicate<? super String> nodePrintCondition) { return print(tree, new TreePath(tree.getModel().getRoot()), withSelection, null, nodePrintCondition); } @NotNull private static String print(@NotNull JTree tree, @NotNull TreePath path, boolean withSelection, @Nullable Queryable.PrintInfo printInfo, @Nullable Predicate<? super String> nodePrintCondition) { return StringUtil.join(printAsList(tree, path, withSelection, printInfo, nodePrintCondition), "\n"); } @NotNull private static Collection<String> printAsList(@NotNull JTree tree, @NotNull TreePath path, boolean withSelection, @Nullable Queryable.PrintInfo printInfo, @Nullable Predicate<? super String> nodePrintCondition) { Collection<String> strings = new ArrayList<>(); printImpl(tree, path, strings, 0, withSelection, printInfo, nodePrintCondition); return strings; } private static void printImpl(@NotNull JTree tree, @NotNull TreePath path, @NotNull Collection<? super String> strings, int level, boolean withSelection, @Nullable Queryable.PrintInfo printInfo, @Nullable Predicate<? super String> nodePrintCondition) { Object pathComponent = path.getLastPathComponent(); Object userObject = TreeUtil.getUserObject(pathComponent); String nodeText = toString(userObject, printInfo); if (nodePrintCondition != null && !nodePrintCondition.test(nodeText)) { return; } StringBuilder buff = new StringBuilder(); StringUtil.repeatSymbol(buff, ' ', level); boolean expanded = tree.isExpanded(path); int childCount = tree.getModel().getChildCount(pathComponent); if (childCount > 0) { buff.append(expanded ? "-" : "+"); } boolean selected = tree.getSelectionModel().isPathSelected(path); if (withSelection && selected) { buff.append("["); } buff.append(nodeText); if (withSelection && selected) { buff.append("]"); } strings.add(buff.toString()); if (expanded) { for (int i = 0; i < childCount; i++) { TreePath childPath = path.pathByAddingChild(tree.getModel().getChild(pathComponent, i)); printImpl(tree, childPath, strings, level + 1, withSelection, printInfo, nodePrintCondition); } } } public static void assertTreeEqual(@NotNull JTree tree, @NonNls String expected) { assertTreeEqual(tree, expected, false); } public static void assertTreeEqual(@NotNull JTree tree, String expected, boolean checkSelected) { assertTreeEqual(tree, expected, checkSelected, false); } public static void assertTreeEqual(@NotNull JTree tree, @NotNull String expected, boolean checkSelected, boolean ignoreOrder) { String treeStringPresentation = print(tree, checkSelected); if (ignoreOrder) { final Set<String> actualLines = Set.of(treeStringPresentation.split("\n")); final Set<String> expectedLines = Set.of(expected.split("\n")); assertEquals("Expected:\n" + expected + "\nActual\n:" + treeStringPresentation, expectedLines, actualLines); } else { assertEquals(expected.trim(), treeStringPresentation.trim()); } } public static void expand(@NotNull JTree tree, int @NotNull ... rows) { for (int row : rows) { tree.expandRow(row); waitWhileBusy(tree); } } public static void expandAll(@NotNull JTree tree) { waitForPromise(TreeUtil.promiseExpandAll(tree)); } private static long getMillisSince(long startTimeMillis) { return System.currentTimeMillis() - startTimeMillis; } private static void assertMaxWaitTimeSince(long startTimeMillis) { assertMaxWaitTimeSince(startTimeMillis, MAX_WAIT_TIME); } private static void assertMaxWaitTimeSince(long startTimeMillis, long timeout) { long took = getMillisSince(startTimeMillis); assert took <= timeout : String.format("the waiting takes too long. Expected to take no more than: %d ms but took: %d ms", timeout, took); } private static void assertDispatchThreadWithoutWriteAccess() { assertDispatchThreadWithoutWriteAccess(ApplicationManager.getApplication()); } private static void assertDispatchThreadWithoutWriteAccess(Application application) { if (application != null) { assert !application.isWriteAccessAllowed() : "do not wait under write action to avoid possible deadlock"; assert application.isDispatchThread(); } else { // do not check for write access in simple tests assert EventQueue.isDispatchThread(); } } private static boolean isBusy(@NotNull JTree tree, TreeModel model) { UIUtil.dispatchAllInvocationEvents(); if (model instanceof AsyncTreeModel) { AsyncTreeModel async = (AsyncTreeModel)model; if (async.isProcessing()) return true; UIUtil.dispatchAllInvocationEvents(); return async.isProcessing(); } //noinspection deprecation AbstractTreeBuilder builder = AbstractTreeBuilder.getBuilderFor(tree); if (builder == null) return false; //noinspection deprecation AbstractTreeUi ui = builder.getUi(); if (ui == null) return false; return ui.hasPendingWork(); } public static void waitWhileBusy(@NotNull JTree tree) { assertDispatchThreadWithoutWriteAccess(); long startTimeMillis = System.currentTimeMillis(); while (isBusy(tree, tree.getModel())) { assertMaxWaitTimeSince(startTimeMillis); TimeoutUtil.sleep(5); } } public static void waitForCallback(@NotNull ActionCallback callback) { AsyncPromise<?> promise = new AsyncPromise<>(); callback.doWhenDone(() -> promise.setResult(null)).doWhenRejected((@NotNull Runnable)promise::cancel); waitForPromise(promise); } public static @Nullable <T> T waitForPromise(@NotNull Promise<T> promise) { return waitForPromise(promise, MAX_WAIT_TIME); } public static @Nullable <T> T waitForPromise(@NotNull Promise<T> promise, long timeout) { return waitForPromise(promise, timeout, false); } public static <T> T assertPromiseSucceeds(@NotNull Promise<T> promise) { return waitForPromise(promise, MAX_WAIT_TIME, true); } private static @Nullable <T> T waitForPromise(@NotNull Promise<T> promise, long timeout, boolean assertSucceeded) { assertDispatchThreadWithoutWriteAccess(); long start = System.currentTimeMillis(); while (true) { if (promise.getState() == Promise.State.PENDING) { UIUtil.dispatchAllInvocationEvents(); } try { return promise.blockingGet(20, TimeUnit.MILLISECONDS); } catch (TimeoutException ignore) { } catch (Exception e) { if (assertSucceeded) { throw new AssertionError(e); } else { return null; } } assertMaxWaitTimeSince(start, timeout); } } public static <T> T waitForFuture(@NotNull Future<T> future, long timeoutMillis) { assertDispatchThreadWithoutWriteAccess(); long start = System.currentTimeMillis(); while (true) { if (!future.isDone()) { UIUtil.dispatchAllInvocationEvents(); } try { return future.get(10, TimeUnit.MILLISECONDS); } catch (TimeoutException ignore) { } catch (Exception e) { throw new AssertionError(e); } assertMaxWaitTimeSince(start, timeoutMillis); } } public static void waitForAlarm(final int delay) { @NotNull Application app = ApplicationManager.getApplication(); assertDispatchThreadWithoutWriteAccess(); Disposable tempDisposable = Disposer.newDisposable(); final AtomicBoolean runnableInvoked = new AtomicBoolean(); final AtomicBoolean pooledRunnableInvoked = new AtomicBoolean(); final AtomicBoolean alarmInvoked1 = new AtomicBoolean(); final AtomicBoolean alarmInvoked2 = new AtomicBoolean(); final Alarm alarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD); final Alarm pooledAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, tempDisposable); ModalityState initialModality = ModalityState.current(); alarm.addRequest(() -> { alarmInvoked1.set(true); app.invokeLater(() -> { runnableInvoked.set(true); alarm.addRequest(() -> alarmInvoked2.set(true), delay); }); }, delay); pooledAlarm.addRequest(() -> pooledRunnableInvoked.set(true), delay); UIUtil.dispatchAllInvocationEvents(); long start = System.currentTimeMillis(); try { boolean sleptAlready = false; while (!alarmInvoked2.get()) { AtomicBoolean laterInvoked = new AtomicBoolean(); app.invokeLater(() -> laterInvoked.set(true)); UIUtil.dispatchAllInvocationEvents(); assertTrue(laterInvoked.get()); TimeoutUtil.sleep(sleptAlready ? 10 : delay); sleptAlready = true; if (getMillisSince(start) > MAX_WAIT_TIME) { String queue = ((AppScheduledExecutorService)AppExecutorUtil.getAppScheduledExecutorService()).dumpQueue(); throw new AssertionError("Couldn't await alarm" + "; alarm passed=" + alarmInvoked1.get() + "; modality1=" + initialModality + "; modality2=" + ModalityState.current() + "; non-modal=" + (initialModality == ModalityState.NON_MODAL) + "; invokeLater passed=" + runnableInvoked.get() + "; pooled alarm passed=" + pooledRunnableInvoked.get() + "; app.disposed=" + app.isDisposed() + "; alarm.disposed=" + alarm.isDisposed() + "; alarm.requests=" + alarm.getActiveRequestCount() + "\n delayQueue=" + StringUtil.trimLog(queue, 1000) + "\n invocatorEdtQueue=" + LaterInvocator.getLaterInvocatorEdtQueue() + "\n invocatorWtQueue=" + LaterInvocator.getLaterInvocatorWtQueue() ); } } } finally { Disposer.dispose(tempDisposable); } UIUtil.dispatchAllInvocationEvents(); } /** * Dispatch all pending invocation events (if any) in the {@link IdeEventQueue}, ignores and removes all other events from the queue. * Should only be invoked in Swing thread (asserted inside {@link IdeEventQueue#dispatchEvent(AWTEvent)}) */ public static void dispatchAllInvocationEventsInIdeEventQueue() { IdeEventQueue eventQueue = IdeEventQueue.getInstance(); while (true) { AWTEvent event = eventQueue.peekEvent(); if (event == null) break; try { event = eventQueue.getNextEvent(); if (event instanceof InvocationEvent) { eventQueue.dispatchEvent(event); } } catch (InterruptedException e) { throw new RuntimeException(e); } } } /** * Dispatch all pending events (if any) in the {@link IdeEventQueue}. * Should only be invoked in Swing thread (asserted inside {@link IdeEventQueue#dispatchEvent(AWTEvent)}) */ public static void dispatchAllEventsInIdeEventQueue() { IdeEventQueue eventQueue = IdeEventQueue.getInstance(); while (true) { try { if (dispatchNextEventIfAny(eventQueue) == null) break; } catch (InterruptedException e) { throw new RuntimeException(e); } } } /** * Dispatch one pending event (if any) in the {@link IdeEventQueue}. * Should only be invoked in Swing thread (asserted inside {@link IdeEventQueue#dispatchEvent(AWTEvent)}) */ public static AWTEvent dispatchNextEventIfAny(@NotNull IdeEventQueue eventQueue) throws InterruptedException { assert SwingUtilities.isEventDispatchThread() : Thread.currentThread(); AWTEvent event = eventQueue.peekEvent(); if (event == null) return null; AWTEvent event1 = eventQueue.getNextEvent(); eventQueue.dispatchEvent(event1); return event1; } @NotNull public static StringBuilder print(@NotNull AbstractTreeStructure structure, @NotNull Object node, int currentLevel, @Nullable Comparator<?> comparator, int maxRowCount, char paddingChar, @Nullable Queryable.PrintInfo printInfo) { return print(structure, node, currentLevel, comparator, maxRowCount, paddingChar, o -> toString(o, printInfo)); } @NotNull public static String print(@NotNull AbstractTreeStructure structure, @NotNull Object node, @NotNull Function<Object, String> nodePresenter) { return print(structure, node, 0, Comparator.comparing(nodePresenter), -1, ' ', nodePresenter).toString(); } @NotNull private static StringBuilder print(@NotNull AbstractTreeStructure structure, @NotNull Object node, int currentLevel, @Nullable Comparator<?> comparator, int maxRowCount, char paddingChar, @NotNull Function<Object, String> nodePresenter) { StringBuilder buffer = new StringBuilder(); doPrint(buffer, currentLevel, node, structure, comparator, maxRowCount, 0, paddingChar, nodePresenter); return buffer; } private static int doPrint(@NotNull StringBuilder buffer, int currentLevel, @NotNull Object node, @NotNull AbstractTreeStructure structure, @Nullable Comparator<?> comparator, int maxRowCount, int currentLine, char paddingChar, @NotNull Function<Object, String> nodePresenter) { if (currentLine >= maxRowCount && maxRowCount != -1) return currentLine; StringUtil.repeatSymbol(buffer, paddingChar, currentLevel); buffer.append(nodePresenter.apply(node)).append("\n"); currentLine++; Object[] children = structure.getChildElements(node); if (comparator != null) { List<?> list = new ArrayList<>(Arrays.asList(children)); @SuppressWarnings("unchecked") Comparator<Object> c = (Comparator<Object>)comparator; list.sort(c); children = ArrayUtil.toObjectArray(list); } for (Object child : children) { currentLine = doPrint(buffer, currentLevel + 1, child, structure, comparator, maxRowCount, currentLine, paddingChar, nodePresenter); } return currentLine; } @NotNull public static String print(Object @NotNull [] objects) { return print(Arrays.asList(objects)); } @NotNull public static String print(@NotNull Collection<?> c) { return c.stream().map(each -> toString(each, null)).collect(Collectors.joining("\n")); } @NotNull public static String print(@NotNull ListModel<?> model) { StringBuilder result = new StringBuilder(); for (int i = 0; i < model.getSize(); i++) { result.append(toString(model.getElementAt(i), null)); result.append("\n"); } return result.toString(); } @NotNull public static String print(@NotNull JTree tree) { return print(tree, false); } public static void invokeNamedAction(@NotNull String actionId) { final AnAction action = ActionManager.getInstance().getAction(actionId); assertNotNull(action); final Presentation presentation = new Presentation(); @SuppressWarnings("deprecation") final DataContext context = DataManager.getInstance().getDataContext(); final AnActionEvent event = AnActionEvent.createFromAnAction(action, null, "", context); action.beforeActionPerformedUpdate(event); assertTrue(presentation.isEnabled()); action.actionPerformed(event); } public static void assertTiming(@NotNull String message, final long expectedMs, final long actual) { if (COVERAGE_ENABLED_BUILD) return; long expectedOnMyMachine = Math.max(1, expectedMs * Timings.CPU_TIMING / Timings.REFERENCE_CPU_TIMING); // Allow 10% more in case of test machine is busy. String logMessage = message; if (actual > expectedOnMyMachine) { int percentage = (int)(100.0 * (actual - expectedOnMyMachine) / expectedOnMyMachine); logMessage += ". Operation took " + percentage + "% longer than expected"; } logMessage += ". Expected on my machine: " + expectedOnMyMachine + "." + " Actual: " + actual + "." + " Expected on Standard machine: " + expectedMs + ";" + " Timings: CPU=" + Timings.CPU_TIMING + ", I/O=" + Timings.IO_TIMING + "."; final double acceptableChangeFactor = 1.1; if (actual < expectedOnMyMachine) { System.out.println(logMessage); TeamCityLogger.info(logMessage); } else if (actual < expectedOnMyMachine * acceptableChangeFactor) { TeamCityLogger.warning(logMessage, null); } else { // throw AssertionFailedError to try one more time throw new AssertionFailedError(logMessage); } } /** * An example: {@code startPerformanceTest("calculating pi",100, testRunnable).assertTiming();} */ @Contract(pure = true) // to warn about not calling .assertTiming() in the end @NotNull public static PerformanceTestInfo startPerformanceTest(@NonNls @NotNull String what, int expectedMs, @NotNull ThrowableRunnable<?> test) { return new PerformanceTestInfo(test, expectedMs, what); } public static void assertPathsEqual(@Nullable String expected, @Nullable String actual) { if (expected != null) expected = FileUtil.toSystemIndependentName(expected); if (actual != null) actual = FileUtil.toSystemIndependentName(actual); assertEquals(expected, actual); } public static @NotNull String getJavaExe() { return SystemProperties.getJavaHome() + (SystemInfo.isWindows ? "\\bin\\java.exe" : "/bin/java"); } public static @NotNull URL getRtJarURL() { String home = SystemProperties.getJavaHome(); try { return JavaVersion.current().feature >= 9 ? new URL("jrt:" + home) : new File(home + "/lib/rt.jar").toURI().toURL(); } catch (MalformedURLException e) { throw new RuntimeException(e); } } public static void forceCloseProjectWithoutSaving(@NotNull Project project) { if (!project.isDisposed()) { ApplicationManager.getApplication().invokeAndWait(() -> ProjectManagerEx.getInstanceEx().forceCloseProject(project)); } } public static void saveProject(@NotNull Project project) { saveProject(project, false); } public static void saveProject(@NotNull Project project, boolean isForceSavingAllSettings) { StoreReloadManager.getInstance().flushChangedProjectFileAlarm(); StateStorageManagerKt.saveComponentManager(project, isForceSavingAllSettings); } static void waitForAllBackgroundActivityToCalmDown() { for (int i = 0; i < 50; i++) { CpuUsageData data = CpuUsageData.measureCpuUsage(() -> TimeoutUtil.sleep(100)); if (!data.hasAnyActivityBesides(Thread.currentThread())) { break; } } } public static void assertTiming(@NotNull String message, long expected, @NotNull Runnable actionToMeasure) { assertTiming(message, expected, 4, actionToMeasure); } @SuppressWarnings("CallToSystemGC") public static void assertTiming(@NotNull String message, long expected, int attempts, @NotNull Runnable actionToMeasure) { while (true) { attempts--; waitForAllBackgroundActivityToCalmDown(); long duration = TimeoutUtil.measureExecutionTime(actionToMeasure::run); try { assertTiming(message, expected, duration); break; } catch (AssertionFailedError e) { if (attempts == 0) throw e; System.gc(); System.gc(); System.gc(); String s = e.getMessage() + "\n " + attempts + " " + StringUtil.pluralize("attempt", attempts) + " remain"; TeamCityLogger.warning(s, null); System.err.println(s); } } } @NotNull private static Map<String, VirtualFile> buildNameToFileMap(VirtualFile @NotNull [] files, @Nullable VirtualFileFilter filter) { Map<String, VirtualFile> map = new HashMap<>(); for (VirtualFile file : files) { if (filter != null && !filter.accept(file)) continue; map.put(file.getName(), file); } return map; } public static void assertDirectoriesEqual(@NotNull VirtualFile dirExpected, @NotNull VirtualFile dirActual) throws IOException { assertDirectoriesEqual(dirExpected, dirActual, null); } @SuppressWarnings("UnsafeVfsRecursion") public static void assertDirectoriesEqual(@NotNull VirtualFile dirExpected, @NotNull VirtualFile dirActual, @Nullable VirtualFileFilter fileFilter) throws IOException { FileDocumentManager.getInstance().saveAllDocuments(); VirtualFile[] childrenAfter = dirExpected.getChildren(); shallowCompare(dirExpected, childrenAfter); VirtualFile[] childrenBefore = dirActual.getChildren(); shallowCompare(dirActual, childrenBefore); Map<String, VirtualFile> mapAfter = buildNameToFileMap(childrenAfter, fileFilter); Map<String, VirtualFile> mapBefore = buildNameToFileMap(childrenBefore, fileFilter); Set<String> keySetAfter = mapAfter.keySet(); Set<String> keySetBefore = mapBefore.keySet(); assertEquals(dirExpected.getPath(), keySetAfter, keySetBefore); for (String name : keySetAfter) { VirtualFile fileAfter = mapAfter.get(name); VirtualFile fileBefore = mapBefore.get(name); if (fileAfter.isDirectory()) { assertDirectoriesEqual(fileAfter, fileBefore, fileFilter); } else { assertFilesEqual(fileAfter, fileBefore); } } } private static void shallowCompare(@NotNull VirtualFile dir, VirtualFile @NotNull [] vfs) { if (dir.isInLocalFileSystem() && dir.getFileSystem() != TempFileSystem.getInstance()) { String vfsPaths = Stream.of(vfs).map(VirtualFile::getPath).sorted().collect(Collectors.joining("\n")); File[] io = Objects.requireNonNull(new File(dir.getPath()).listFiles()); String ioPaths = Stream.of(io).map(f -> FileUtil.toSystemIndependentName(f.getPath())).sorted().collect(Collectors.joining("\n")); assertEquals(vfsPaths, ioPaths); } } public static void assertFilesEqual(@NotNull VirtualFile fileExpected, @NotNull VirtualFile fileActual) throws IOException { try { assertJarFilesEqual(VfsUtilCore.virtualToIoFile(fileExpected), VfsUtilCore.virtualToIoFile(fileActual)); } catch (IOException e) { String actual = fileText(fileActual); String expected = fileText(fileExpected); if (expected == null || actual == null) { assertArrayEquals(fileExpected.getPath(), fileExpected.contentsToByteArray(), fileActual.contentsToByteArray()); } else if (!StringUtil.equals(expected, actual)) { throw new FileComparisonFailure("Text mismatch in the file " + fileExpected.getName(), expected, actual, fileExpected.getPath()); } } } private static String fileText(@NotNull VirtualFile file) throws IOException { Document doc = FileDocumentManager.getInstance().getDocument(file); if (doc != null) { return doc.getText(); } if (!file.getFileType().isBinary() || FileTypeRegistry.getInstance().isFileOfType(file, FileTypes.UNKNOWN)) { return LoadTextUtil.getTextByBinaryPresentation(file.contentsToByteArray(false), file).toString(); } return null; } private static void assertJarFilesEqual(@NotNull File file1, @NotNull File file2) throws IOException { File tempDir = null; try (JarFile jarFile1 = new JarFile(file1); JarFile jarFile2 = new JarFile(file2)) { tempDir = FileUtilRt.createTempDirectory("assert_jar_tmp", null, false); final File tempDirectory1 = new File(tempDir, "tmp1"); final File tempDirectory2 = new File(tempDir, "tmp2"); FileUtilRt.createDirectory(tempDirectory1); FileUtilRt.createDirectory(tempDirectory2); new Decompressor.Zip(new File(jarFile1.getName())).extract(tempDirectory1); new Decompressor.Zip(new File(jarFile2.getName())).extract(tempDirectory2); final VirtualFile dirAfter = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory1); assertNotNull(tempDirectory1.toString(), dirAfter); final VirtualFile dirBefore = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory2); assertNotNull(tempDirectory2.toString(), dirBefore); ApplicationManager.getApplication().runWriteAction(() -> { dirAfter.refresh(false, true); dirBefore.refresh(false, true); }); assertDirectoriesEqual(dirAfter, dirBefore); } finally { if (tempDir != null) { FileUtilRt.delete(tempDir); } } } public static @NotNull String getCommunityPath() { final String homePath = IdeaTestExecutionPolicy.getHomePathWithPolicy(); if (new File(homePath, "community/.idea").isDirectory()) { return homePath + File.separatorChar + "community"; } return homePath; } public static @NotNull String getPlatformTestDataPath() { return getCommunityPath().replace(File.separatorChar, '/') + "/platform/platform-tests/testData/"; } @Contract(pure = true) public static @NotNull Comparator<AbstractTreeNode<?>> createComparator(final Queryable.PrintInfo printInfo) { return (o1, o2) -> { String displayText1 = o1.toTestString(printInfo); String displayText2 = o2.toTestString(printInfo); return Comparing.compare(displayText1, displayText2); }; } public static @NotNull String loadFileText(@NotNull String fileName) throws IOException { return StringUtil.convertLineSeparators(FileUtil.loadFile(new File(fileName))); } public static void withEncoding(@NotNull String encoding, @NotNull ThrowableRunnable<?> r) { Charset.forName(encoding); // check the encoding exists try { Charset oldCharset = Charset.defaultCharset(); try { patchSystemFileEncoding(encoding); r.run(); } finally { patchSystemFileEncoding(oldCharset.name()); } } catch (Throwable t) { throw new RuntimeException(t); } } private static void patchSystemFileEncoding(@NotNull String encoding) { ReflectionUtil.resetField(Charset.class, Charset.class, "defaultCharset"); System.setProperty("file.encoding", encoding); } @SuppressWarnings("ImplicitDefaultCharsetUsage") public static void withStdErrSuppressed(@NotNull Runnable r) { PrintStream std = System.err; System.setErr(new PrintStream(NULL)); try { r.run(); } finally { System.setErr(std); } } @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") private static final OutputStream NULL = new OutputStream() { @Override public void write(int b) { } }; public static void assertSuccessful(@NotNull GeneralCommandLine command) { try { ProcessOutput output = ExecUtil.execAndGetOutput(command.withRedirectErrorStream(true)); assertEquals(output.getStdout(), 0, output.getExitCode()); } catch (ExecutionException e) { throw new RuntimeException(e); } } public static @NotNull List<WebReference> collectWebReferences(@NotNull PsiElement element) { List<WebReference> refs = new ArrayList<>(); element.accept(new PsiRecursiveElementWalkingVisitor() { @Override public void visitElement(@NotNull PsiElement element) { for (PsiReference ref : element.getReferences()) { if (ref instanceof WebReference) { refs.add((WebReference)ref); } } super.visitElement(element); } }); return refs; } public static @NotNull List<UrlReference> collectUrlReferences(@NotNull PsiElement element) { List<UrlReference> result = new SmartList<>(); element.accept(new PsiRecursiveElementWalkingVisitor() { @Override public void visitElement(@NotNull PsiElement element) { result.addAll(PsiSymbolReferenceService.getService().getReferences(element, UrlReference.class)); super.visitElement(element); } }); return result; } public static @NotNull <T extends PsiReference> T getReferenceOfTypeWithAssertion(@Nullable PsiReference reference, @NotNull Class<T> refType) { if (refType.isInstance(reference)) { //noinspection unchecked return (T)reference; } if (reference instanceof PsiMultiReference) { PsiReference[] psiReferences = ((PsiMultiReference)reference).getReferences(); for (PsiReference psiReference : psiReferences) { if (refType.isInstance(psiReference)) { //noinspection unchecked return (T)psiReference; } } } throw new AssertionError("given reference should be " + refType + " but " + (reference != null ? reference.getClass() : null) + " was given"); } public static void registerProjectCleanup(@NotNull Runnable cleanup) { ourProjectCleanups.add(cleanup); } public static void cleanupAllProjects() { for (Runnable each : ourProjectCleanups) { each.run(); } ourProjectCleanups.clear(); } public static void captureMemorySnapshot() { try { String className = "com.jetbrains.performancePlugin.profilers.YourKitProfilerHandler"; Method snapshot = ReflectionUtil.getMethod(Class.forName(className), "captureMemorySnapshot"); if (snapshot != null) { Object path = snapshot.invoke(null); System.out.println("Memory snapshot captured to '" + path + "'"); } } catch (ClassNotFoundException e) { // YourKitProfilerHandler is missing from the classpath, ignore } catch (Exception e) { e.printStackTrace(System.err); } } public static <T> void assertComparisonContractNotViolated(@NotNull List<? extends T> values, @NotNull Comparator<? super T> comparator, @NotNull Equality<? super T> equality) { for (int i1 = 0; i1 < values.size(); i1++) { for (int i2 = i1; i2 < values.size(); i2++) { T value1 = values.get(i1); T value2 = values.get(i2); int result12 = comparator.compare(value1, value2); int result21 = comparator.compare(value2, value1); if (equality.equals(value1, value2)) { if (result12 != 0) fail(String.format("Equal, but not 0: '%s' - '%s'", value1, value2)); if (result21 != 0) fail(String.format("Equal, but not 0: '%s' - '%s'", value2, value1)); } else { if (result12 == 0) fail(String.format("Not equal, but 0: '%s' - '%s'", value1, value2)); if (result21 == 0) fail(String.format("Not equal, but 0: '%s' - '%s'", value2, value1)); if (Integer.signum(result12) == Integer.signum(result21)) { fail(String.format("Not symmetrical: '%s' - '%s'", value1, value2)); } } for (int i3 = i2; i3 < values.size(); i3++) { T value3 = values.get(i3); int result23 = comparator.compare(value2, value3); int result31 = comparator.compare(value3, value1); if (!isTransitive(result12, result23, result31)) { fail(String.format("Not transitive: '%s' - '%s' - '%s'", value1, value2, value3)); } } } } } private static boolean isTransitive(int result12, int result23, int result31) { if (result12 == 0 && result23 == 0 && result31 == 0) return true; if (result12 > 0 && result23 > 0 && result31 > 0) return false; if (result12 < 0 && result23 < 0 && result31 < 0) return false; if (result12 == 0 && Integer.signum(result23) * Integer.signum(result31) >= 0) return false; if (result23 == 0 && Integer.signum(result12) * Integer.signum(result31) >= 0) return false; if (result31 == 0 && Integer.signum(result23) * Integer.signum(result12) >= 0) return false; return true; } public static void setLongMeaninglessFileIncludeTemplateTemporarilyFor(@NotNull Project project, @NotNull Disposable parentDisposable) { FileTemplateManagerImpl templateManager = (FileTemplateManagerImpl)FileTemplateManager.getInstance(project); templateManager.setDefaultFileIncludeTemplateTextTemporarilyForTest(FileTemplateManager.FILE_HEADER_TEMPLATE_NAME, "/**\n" + " * Created by ${USER} on ${DATE}.\n" + " */\n", parentDisposable); } /* * 1. Think twice before use - do you really need to use VFS. * 2. Be aware the method doesn't refresh VFS as it should be done in tests (see {@link PlatformTestCase#synchronizeTempDirVfs}) * (it is assumed that project is already created in a correct way). */ public static @NotNull VirtualFile getOrCreateProjectBaseDir(@NotNull Project project) { return HeavyTestHelper.getOrCreateProjectBaseDir(project); } public static @Nullable RunConfiguration getRunConfiguration(@NotNull PsiElement element, @NotNull RunConfigurationProducer<?> producer) { MapDataContext dataContext = new MapDataContext(); dataContext.put(CommonDataKeys.PROJECT, element.getProject()); dataContext.put(LangDataKeys.MODULE, ModuleUtilCore.findModuleForPsiElement(element)); final Location<PsiElement> location = PsiLocation.fromPsiElement(element); dataContext.put(Location.DATA_KEY, location); ConfigurationContext cc = ConfigurationContext.getFromContext(dataContext); final ConfigurationFromContext configuration = producer.createConfigurationFromContext(cc); return configuration != null ? configuration.getConfiguration() : null; } /** * Executing {@code runConfiguration} with {@link DefaultRunExecutor#EXECUTOR_ID run} executor and wait for 60 seconds till process ends. */ @NotNull public static ExecutionEnvironment executeConfigurationAndWait(@NotNull RunConfiguration runConfiguration) throws InterruptedException { return executeConfigurationAndWait(runConfiguration, DefaultRunExecutor.EXECUTOR_ID); } /** * Executing {@code runConfiguration} with executor {@code executoId} and wait for 60 seconds till process ends. */ @NotNull public static ExecutionEnvironment executeConfigurationAndWait(@NotNull RunConfiguration runConfiguration, @NotNull String executorId) throws InterruptedException { return executeConfigurationAndWait(runConfiguration, executorId, 60); } /** * Executing {@code runConfiguration} with executor {@code executoId} and wait for the {@code timeoutInSeconds} seconds till process ends. */ @NotNull public static ExecutionEnvironment executeConfigurationAndWait(@NotNull RunConfiguration runConfiguration, @NotNull String executorId, long timeoutInSeconds) throws InterruptedException { Pair<@NotNull ExecutionEnvironment, RunContentDescriptor> result = executeConfiguration(runConfiguration, executorId); ProcessHandler processHandler = result.second.getProcessHandler(); if (!processHandler.waitFor(timeoutInSeconds * 1000)) { fail("Process failed to finish in " + timeoutInSeconds + " seconds: " + processHandler); } return result.first; } @NotNull public static Pair<@NotNull ExecutionEnvironment, RunContentDescriptor> executeConfiguration(@NotNull RunConfiguration runConfiguration, @NotNull String executorId) throws InterruptedException { Executor executor = ExecutorRegistry.getInstance().getExecutorById(executorId); assertNotNull("Unable to find executor: " + executorId, executor); return executeConfiguration(runConfiguration, executor); } /** * Executes {@code runConfiguration} with executor defined by {@code executorId} and returns pair of {@link ExecutionEnvironment} and * {@link RunContentDescriptor} */ @NotNull public static Pair<@NotNull ExecutionEnvironment, RunContentDescriptor> executeConfiguration(@NotNull RunConfiguration runConfiguration, @NotNull Executor executor) throws InterruptedException { Project project = runConfiguration.getProject(); ConfigurationFactory factory = runConfiguration.getFactory(); if (factory == null) { fail("No factory found for: " + runConfiguration); } RunnerAndConfigurationSettings runnerAndConfigurationSettings = RunManager.getInstance(project).createConfiguration(runConfiguration, factory); ProgramRunner<?> runner = ProgramRunner.getRunner(executor.getId(), runConfiguration); if (runner == null) { fail("No runner found for: " + executor.getId() + " and " + runConfiguration); } Ref<RunContentDescriptor> refRunContentDescriptor = new Ref<>(); ExecutionEnvironment executionEnvironment = new ExecutionEnvironment(executor, runner, runnerAndConfigurationSettings, project); CountDownLatch latch = new CountDownLatch(1); ProgramRunnerUtil.executeConfigurationAsync(executionEnvironment, false, false, descriptor -> { LOG.debug("Process started"); ProcessHandler processHandler = descriptor.getProcessHandler(); assertNotNull(processHandler); processHandler.addProcessListener(new ProcessAdapter() { @Override public void startNotified(@NotNull ProcessEvent event) { LOG.debug("Process notified"); } @Override public void processTerminated(@NotNull ProcessEvent event) { LOG.debug("Process terminated: exitCode: " + event.getExitCode() + "; text: " + event.getText()); } @Override public void onTextAvailable(@NotNull ProcessEvent event, @NotNull Key outputType) { LOG.debug(outputType + ": " + event.getText()); } }); refRunContentDescriptor.set(descriptor); latch.countDown(); }); NonBlockingReadActionImpl.waitForAsyncTaskCompletion(); LOG.debug("Waiting for process to start"); if (!latch.await(60, TimeUnit.SECONDS)) { fail("Process failed to start in 60 seconds"); } return Pair.create(executionEnvironment, refRunContentDescriptor.get()); } public static PsiElement findElementBySignature(@NotNull String signature, @NotNull String fileRelativePath, @NotNull Project project) { String filePath = project.getBasePath() + File.separator + fileRelativePath; VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(filePath); if (virtualFile == null || !virtualFile.exists()) { throw new IllegalArgumentException(String.format("File '%s' doesn't exist", filePath)); } PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile); if (psiFile == null) { return null; } int offset = psiFile.getText().indexOf(signature); return psiFile.findElementAt(offset); } public static void useAppConfigDir(@NotNull ThrowableRunnable<? extends Exception> task) throws Exception { Path configDir = PathManager.getConfigDir(); Path configCopy; if (Files.exists(configDir)) { configCopy = Files.move(configDir, Paths.get(configDir + "_bak"), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); } else { FileUtil.delete(configDir); configCopy = null; } try { task.run(); } finally { FileUtil.delete(configDir); if (configCopy != null) { Files.move(configCopy, configDir, StandardCopyOption.ATOMIC_MOVE); } } } public static @NotNull Project loadAndOpenProject(@NotNull Path path, @NotNull Disposable parent) { Project project = Objects.requireNonNull(ProjectManagerEx.getInstanceEx().openProject(path, new OpenProjectTaskBuilder().build())); Disposer.register(parent, () -> forceCloseProjectWithoutSaving(project)); return project; } public static void openProject(@NotNull Project project) { if (!ProjectManagerEx.getInstanceEx().openProject(project)) { throw new IllegalStateException("openProject returned false"); } if (ApplicationManager.getApplication().isDispatchThread()) { dispatchAllInvocationEventsInIdeEventQueue(); } } }
RUBY-21118: Add minitest multiple files test GitOrigin-RevId: bdc7e56e8665fc8c2b50ab1ed583960f9c7295b2
platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java
RUBY-21118: Add minitest multiple files test
<ide><path>latform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java <ide> if (ignoreOrder) { <ide> final Set<String> actualLines = Set.of(treeStringPresentation.split("\n")); <ide> final Set<String> expectedLines = Set.of(expected.split("\n")); <del> assertEquals("Expected:\n" + expected + "\nActual\n:" + treeStringPresentation, expectedLines, actualLines); <add> assertEquals("Expected:\n" + expected + "\nActual:" + treeStringPresentation, expectedLines, actualLines); <ide> } <ide> else { <ide> assertEquals(expected.trim(), treeStringPresentation.trim());
Java
apache-2.0
5f53adb741295be83f78d7ca68cea92d880ff464
0
kantega/respiro,kantega/respiro,kantega/respiro
/* * Copyright 2015 Kantega AS * * 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.kantega.respiro.jdbc; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import org.kantega.respiro.api.DataSourceBuilder; import javax.sql.DataSource; import java.util.Collection; public class DefaultDataSourceBuilder implements DataSourceBuilder { private final Collection<DataSourceCustomizer> dataSourceCustomizers; private final long defaultMaxAge; public DefaultDataSourceBuilder(Collection<DataSourceCustomizer> dataSourceCustomizers, long maxAge) { this.defaultMaxAge = maxAge; this.dataSourceCustomizers = dataSourceCustomizers; } @Override public Build datasource(String url) { return new DefaultBuild(url, defaultMaxAge); } private class DefaultBuild implements Build { private final String url; private String username; private String password; private String driverClassname; private long maxAge; public DefaultBuild(String url, long defaultMaxAge) { this.url = url; this.maxAge = defaultMaxAge; } @Override public Build username(String username) { this.username = username; return this; } @Override public Build password(String password) { this.password = password; return this; } @Override public Build driverClassname(String driver) { this.driverClassname = driver; return this; } @Override public Build maxAge(long maxAge) { this.maxAge = maxAge; return this; } @Override public DataSource build() { HikariConfig config = new HikariConfig(); config.setJdbcUrl(url); config.setUsername(username); config.setPassword(password); config.setMaxLifetime(maxAge); config.setDriverClassName(driverClassname); //JDTS does not support connection.isValid() if(driverClassname.toLowerCase().contains("jtds")){ config.setConnectionTestQuery("SELECT 1"); } config.setMaximumPoolSize(3); DataSource dataSource = new HikariDataSource(config); for (DataSourceCustomizer customizer : dataSourceCustomizers) { dataSource = customizer.wrapDataSource(dataSource); } return dataSource; } } }
plugins/core/jdbc/src/main/java/org/kantega/respiro/jdbc/DefaultDataSourceBuilder.java
/* * Copyright 2015 Kantega AS * * 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.kantega.respiro.jdbc; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import org.kantega.respiro.api.DataSourceBuilder; import javax.sql.DataSource; import java.util.Collection; public class DefaultDataSourceBuilder implements DataSourceBuilder { private final Collection<DataSourceCustomizer> dataSourceCustomizers; private final long defaultMaxAge; public DefaultDataSourceBuilder(Collection<DataSourceCustomizer> dataSourceCustomizers, long maxAge) { this.defaultMaxAge = maxAge; this.dataSourceCustomizers = dataSourceCustomizers; } @Override public Build datasource(String url) { return new DefaultBuild(url, defaultMaxAge); } private class DefaultBuild implements Build { private final String url; private String username; private String password; private String driverClassname; private long maxAge; public DefaultBuild(String url, long defaultMaxAge) { this.url = url; this.maxAge = defaultMaxAge; } @Override public Build username(String username) { this.username = username; return this; } @Override public Build password(String password) { this.password = password; return this; } @Override public Build driverClassname(String driver) { this.driverClassname = driver; return this; } @Override public Build maxAge(long maxAge) { this.maxAge = maxAge; return this; } @Override public DataSource build() { HikariConfig config = new HikariConfig(); config.setJdbcUrl(url); config.setUsername(username); config.setPassword(password); config.setMaxLifetime(maxAge); config.setDriverClassName(driverClassname); //JDTS does not support connection.isValid() if(driverClassname.toLowerCase().contains("jdts")){ config.setConnectionTestQuery("SELECT 1"); } config.setMaximumPoolSize(3); DataSource dataSource = new HikariDataSource(config); for (DataSourceCustomizer customizer : dataSourceCustomizers) { dataSource = customizer.wrapDataSource(dataSource); } return dataSource; } } }
Added jdbc connection test query for jdts drivers.
plugins/core/jdbc/src/main/java/org/kantega/respiro/jdbc/DefaultDataSourceBuilder.java
Added jdbc connection test query for jdts drivers.
<ide><path>lugins/core/jdbc/src/main/java/org/kantega/respiro/jdbc/DefaultDataSourceBuilder.java <ide> config.setDriverClassName(driverClassname); <ide> <ide> //JDTS does not support connection.isValid() <del> if(driverClassname.toLowerCase().contains("jdts")){ <add> if(driverClassname.toLowerCase().contains("jtds")){ <ide> config.setConnectionTestQuery("SELECT 1"); <ide> } <ide> config.setMaximumPoolSize(3);
JavaScript
mit
bb53fc53a909e013c73671d51851d901d364c906
0
mhovey/photos,mhovey/photos-api
/* |-------------------------------------------------------------------------- | Dotenv setup to bring in the application config |-------------------------------------------------------------------------- */ require('dotenv').load(); /* |-------------------------------------------------------------------------- | Basic Setup |-------------------------------------------------------------------------- */ var express = require('express'); var mongoose = require('mongoose'); var bodyParser = require('body-parser'); var morgan = require('morgan'); var _ = require('underscore'); var methodOverride = require('method-override'); var Schema = mongoose.Schema; var app = express(); var router = express.Router(); var port = process.env.PORT || 3000; var restify = require('express-restify-mongoose'); var apiPrefix = '/api'; var apiVersion = '/v1'; /* |-------------------------------------------------------------------------- | Import Models |-------------------------------------------------------------------------- */ var User = require('./models/user'); var Photo = require('./models/photo'); var Gallery = require('./models/gallery'); var Tag = require('./models/tag'); /* |-------------------------------------------------------------------------- | Database Connection with Mongoose |-------------------------------------------------------------------------- */ mongoose.connect('mongodb://'+process.env.DB_HOST+'/'+process.env.DB_NAME); /* |-------------------------------------------------------------------------- | Configure the App |-------------------------------------------------------------------------- */ // BodyParser for handling JSON bodies in POST requests app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(methodOverride()); // Morgan to log requests to the console app.use(morgan('dev')); /* |-------------------------------------------------------------------------- | Middleware |-------------------------------------------------------------------------- */ // Add headers app.use(function (req, res, next) { // Website you wish to allow to connect res.setHeader('Access-Control-Allow-Origin', '*'); // Request methods you wish to allow res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // Request headers you wish to allow res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // Set to true if you need the website to include cookies in the requests sent // to the API (e.g. in case you use sessions) res.setHeader('Access-Control-Allow-Credentials', true); // Pass to next layer of middleware next(); }); /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- */ // Base route router.get(apiPrefix+apiVersion, function(req, res) { res.json({ message: 'Good stuff! You have reached the base endpoint for the API.' }); }); // Define Restify options var restifyOptions = { prefix: apiPrefix, version: apiVersion, lowercase: true, plural: true }; // Set up routes for models with restify restify.serve(router, Photo, restifyOptions); restify.serve(router, Gallery, restifyOptions); restify.serve(router, Tag, restifyOptions); app.use(router); /* |-------------------------------------------------------------------------- | Start the server! |-------------------------------------------------------------------------- */ var server = app.listen(port, function() { var host = server.address().address; console.log('Example app listening at http://%s:%s', host, port); });
server.js
/* |-------------------------------------------------------------------------- | Basic Setup |-------------------------------------------------------------------------- */ var express = require('express'); var mongoose = require('mongoose'); var bodyParser = require('body-parser'); var morgan = require('morgan'); var _ = require('underscore'); var methodOverride = require('method-override'); var Schema = mongoose.Schema; var app = express(); var router = express.Router(); var port = process.env.PORT || 3000; var restify = require('express-restify-mongoose'); var apiPrefix = '/api'; var apiVersion = '/v1'; /* |-------------------------------------------------------------------------- | Import Models |-------------------------------------------------------------------------- */ var User = require('./models/user'); var Photo = require('./models/photo'); var Gallery = require('./models/gallery'); var Tag = require('./models/tag'); /* |-------------------------------------------------------------------------- | Database Connection with Mongoose |-------------------------------------------------------------------------- */ mongoose.connect('mongodb://'+process.env.DB_HOST+'/'+process.env.DB_NAME); /* |-------------------------------------------------------------------------- | Configure the App |-------------------------------------------------------------------------- */ // BodyParser for handling JSON bodies in POST requests app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(methodOverride()); // Morgan to log requests to the console app.use(morgan('dev')); /* |-------------------------------------------------------------------------- | Middleware |-------------------------------------------------------------------------- */ // Add headers app.use(function (req, res, next) { // Website you wish to allow to connect res.setHeader('Access-Control-Allow-Origin', '*'); // Request methods you wish to allow res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // Request headers you wish to allow res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // Set to true if you need the website to include cookies in the requests sent // to the API (e.g. in case you use sessions) res.setHeader('Access-Control-Allow-Credentials', true); // Pass to next layer of middleware next(); }); /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- */ // Base route router.get(apiPrefix+apiVersion, function(req, res) { res.json({ message: 'Good stuff! You have reached the base endpoint for the API.' }); }); // Define Restify options var restifyOptions = { prefix: apiPrefix, version: apiVersion, lowercase: true, plural: true }; // Set up routes for models with restify restify.serve(router, Photo, restifyOptions); restify.serve(router, Gallery, restifyOptions); restify.serve(router, Tag, restifyOptions); app.use(router); /* |-------------------------------------------------------------------------- | Start the server! |-------------------------------------------------------------------------- */ var server = app.listen(port, function() { var host = server.address().address; console.log('Example app listening at http://%s:%s', host, port); });
Load dotenv at the very beginning of the application
server.js
Load dotenv at the very beginning of the application
<ide><path>erver.js <add>/* <add>|-------------------------------------------------------------------------- <add>| Dotenv setup to bring in the application config <add>|-------------------------------------------------------------------------- <add>*/ <add> <add>require('dotenv').load(); <add> <ide> /* <ide> |-------------------------------------------------------------------------- <ide> | Basic Setup
Java
unlicense
d96791000abfb20286103830e83d7abfae7fdb21
0
sankark/codelibrary,animesh0353/codelibrary,topkaya/codelibrary,indy256/codelibrary,cksharma/codelibrary,indy256/codelibrary,indy256/codelibrary,topkaya/codelibrary,sankark/codelibrary,animesh0353/codelibrary,topkaya/codelibrary,indy256/codelibrary,topkaya/codelibrary,cksharma/codelibrary,sankark/codelibrary,animesh0353/codelibrary,animesh0353/codelibrary,cksharma/codelibrary,animesh0353/codelibrary,sankark/codelibrary,sankark/codelibrary,cksharma/codelibrary,topkaya/codelibrary
import java.util.*; /** * @author Andrey Naumenko */ public class ContractionHierarchies { int calculatePriority(List<Integer>[] g, List<Integer>[] rg, int v) { // set of shortcuts that would be added if endNode v would be contracted next. Collection<Shortcut> tmpShortcuts = findShortcuts(g, rg, v); // from shortcuts we can compute the edgeDifference // # low influence: with it the shortcut creation is slightly faster // // |shortcuts(v)| − |{(u, v) | v uncontracted}| − |{(v, w) | v uncontracted}| // meanDegree is used instead of outDegree+inDegree as if one endNode is in both directions // only one bucket memory is used. Additionally one shortcut could also stand for two directions. int degree = 0;//GraphUtility.count(g.getEdges(v)); int edgeDifference = tmpShortcuts.size() - degree; // # huge influence: the bigger the less shortcuts gets created and the faster is the preparation // // every endNode has an 'original edge' number associated. initially it is r=1 // when a new shortcut is introduced then r of the associated edges is summed up: // r(u,w)=r(u,v)+r(v,w) now we can define // originalEdgesCount = σ(v) := sum_{ (u,w) ∈ shortcuts(v) } of r(u, w) int originalEdgesCount = 0; for (Shortcut sc : tmpShortcuts) { originalEdgesCount += sc.originalEdges; } // # lowest influence on preparation speed or shortcut creation count // (but according to paper should speed up queries) // // number of already contracted neighbors of v int contractedNeighbors = 0; // EdgeSkipIterator iter = g.getEdges(v); // while (iter.next()) { // if (iter.skippedEdge() >= 0) // contractedNeighbors++; // } // unterfranken example // 10, 50, 1 => 180s preparation, q 3.3ms // 2, 4, 1 => 200s preparation, q 3.0ms // according to the paper do a simple linear combination of the properties to get the priority return 10 * edgeDifference + 50 * originalEdgesCount + contractedNeighbors; } Collection<Shortcut> findShortcuts(int[][] g, int[][] rg, int[][] dist, int v) { final int[] incoming = rg[v]; final int[] outgoing = rg[v]; for (int i = 0; i < incoming.length; i++) { int u = incoming[i]; int distUV = dist[u][i]; } // we can use distance instead of weight, see prepareEdges where distance is overwritten by weight! List<NodeCH> goalNodes = new ArrayList<NodeCH>(); Map<Long, Shortcut> shortcuts = new HashMap<Long, Shortcut>(); //shortcuts.clear(); EdgeWriteIterator iter1 = g.getIncoming(v); // TODO PERFORMANCE collect outgoing nodes (goalnodes) only once and just skip u while (iter1.next()) { int u = iter1.node(); int lu = g.getLevel(u); if (lu != 0) continue; double v_u_weight = iter1.distance(); // one-to-many shortest path goalNodes.clear(); EdgeWriteIterator iter2 = g.getOutgoing(v); double maxWeight = 0; while (iter2.next()) { int w = iter2.node(); int lw = g.getLevel(w); if (w == u || lw != 0) continue; NodeCH n = new NodeCH(); n.endNode = w; n.originalEdges = getOrigEdges(iter2.edge()); n.distance = v_u_weight + iter2.distance(); goalNodes.add(n); if (maxWeight < n.distance) maxWeight = n.distance; } if (goalNodes.isEmpty()) continue; // TODO instead of a weight-limit we could use a hop-limit // and successively increasing it when mean-degree of graph increases algo = new OneToManyDijkstraCH(g).setFilter(edgeFilter.setSkipNode(v)); algo.setLimit(maxWeight).calcPath(u, goalNodes); internalFindShortcuts(goalNodes, u, iter1.edge()); } return shortcuts.values(); } void internalFindShortcuts(List<NodeCH> goalNodes, int u, int uEdgeId) { int uOrigEdge = getOrigEdges(uEdgeId); for (NodeCH n : goalNodes) { if (n.entry != null) { Path path = algo.extractPath(n.entry); if (path.found() && path.weight() <= n.distance) { // FOUND witness path, so do not add shortcut continue; } } // FOUND shortcut but be sure that it is the only shortcut in the collection // and also in the graph for u->w. If existing AND identical length => update flags // Hint: shortcuts are always one-way due to distinct level of every endNode but we don't // know yet the levels so we need to determine the correct direction or if both directions long edgeId = (long) u * refs.length + n.endNode; Shortcut sc = shortcuts.get(edgeId); if (sc == null) sc = shortcuts.get((long) n.endNode * refs.length + u); // minor improvement: if (shortcuts.containsKey((long) n.endNode * refs.length + u)) // then two shortcuts with the same nodes (u<->n.endNode) exists => check current shortcut against both if (sc == null || !NumHelper.equals(sc.distance, n.distance)) { sc = new Shortcut(u, n.endNode, n.distance); shortcuts.put(edgeId, sc); sc.edge = uEdgeId; sc.originalEdges = uOrigEdge + n.originalEdges; } else { // the shortcut already exists in the current collection (different direction) // but has identical length so change the flags! sc.flags = scBothDir; } } } static class Shortcut { final int from; final int to; final double distance; int edge; int originalEdges; public Shortcut(int from, int to, double distance) { this.from = from; this.to = to; this.distance = distance; } public String toString() { return from + "->" + to + ", dist:" + distance; } } static class NodeCH { int endNode; int originalEdges; //EdgeEntry entry; double distance; public String toString() { return "" + endNode; } } static class Edge { final int t; final double dist; Edge(int t, double dist) { this.t = t; this.dist = dist; } } public static void main(String[] args) { int n = 3; List<Edge>[] g = new List[n]; for (int i = 0; i < n; i++) g[i] = new ArrayList<Edge>(); g[2].add(new Edge(0, 1)); g[2].add(new Edge(1, 1)); g[0].add(new Edge(1, 1)); List<Edge>[] rg = new List[n]; for (int i = 0; i < n; i++) rg[i] = new ArrayList<Edge>(); for (int i = 0; i < n; i++) for (Edge e : g[i]) rg[e.t].add(new Edge(i, e.dist)); } }
java/src/ContractionHierarchies.java
import java.util.*; /** * @author Andrey Naumenko */ public class ContractionHierarchies { int calculatePriority(List<Integer>[] g, List<Integer>[] rg, int v) { // set of shortcuts that would be added if endNode v would be contracted next. Collection<Shortcut> tmpShortcuts = findShortcuts(g, rg, v); // from shortcuts we can compute the edgeDifference // # low influence: with it the shortcut creation is slightly faster // // |shortcuts(v)| − |{(u, v) | v uncontracted}| − |{(v, w) | v uncontracted}| // meanDegree is used instead of outDegree+inDegree as if one endNode is in both directions // only one bucket memory is used. Additionally one shortcut could also stand for two directions. int degree = 0;//GraphUtility.count(g.getEdges(v)); int edgeDifference = tmpShortcuts.size() - degree; // # huge influence: the bigger the less shortcuts gets created and the faster is the preparation // // every endNode has an 'original edge' number associated. initially it is r=1 // when a new shortcut is introduced then r of the associated edges is summed up: // r(u,w)=r(u,v)+r(v,w) now we can define // originalEdgesCount = σ(v) := sum_{ (u,w) ∈ shortcuts(v) } of r(u, w) int originalEdgesCount = 0; for (Shortcut sc : tmpShortcuts) { originalEdgesCount += sc.originalEdges; } // # lowest influence on preparation speed or shortcut creation count // (but according to paper should speed up queries) // // number of already contracted neighbors of v int contractedNeighbors = 0; // EdgeSkipIterator iter = g.getEdges(v); // while (iter.next()) { // if (iter.skippedEdge() >= 0) // contractedNeighbors++; // } // unterfranken example // 10, 50, 1 => 180s preparation, q 3.3ms // 2, 4, 1 => 200s preparation, q 3.0ms // according to the paper do a simple linear combination of the properties to get the priority return 10 * edgeDifference + 50 * originalEdgesCount + contractedNeighbors; } Collection<Shortcut> findShortcuts(List<Integer>[] g, List<Integer>[] rg, int v) { // we can use distance instead of weight, see prepareEdges where distance is overwritten by weight! List<NodeCH> goalNodes = new ArrayList<NodeCH>(); Map<Long, Shortcut> shortcuts = new HashMap<Long, Shortcut>(); //shortcuts.clear(); EdgeWriteIterator iter1 = g.getIncoming(v); // TODO PERFORMANCE collect outgoing nodes (goalnodes) only once and just skip u while (iter1.next()) { int u = iter1.node(); int lu = g.getLevel(u); if (lu != 0) continue; double v_u_weight = iter1.distance(); // one-to-many shortest path goalNodes.clear(); EdgeWriteIterator iter2 = g.getOutgoing(v); double maxWeight = 0; while (iter2.next()) { int w = iter2.node(); int lw = g.getLevel(w); if (w == u || lw != 0) continue; NodeCH n = new NodeCH(); n.endNode = w; n.originalEdges = getOrigEdges(iter2.edge()); n.distance = v_u_weight + iter2.distance(); goalNodes.add(n); if (maxWeight < n.distance) maxWeight = n.distance; } if (goalNodes.isEmpty()) continue; // TODO instead of a weight-limit we could use a hop-limit // and successively increasing it when mean-degree of graph increases algo = new OneToManyDijkstraCH(g).setFilter(edgeFilter.setSkipNode(v)); algo.setLimit(maxWeight).calcPath(u, goalNodes); internalFindShortcuts(goalNodes, u, iter1.edge()); } return shortcuts.values(); } void internalFindShortcuts(List<NodeCH> goalNodes, int u, int uEdgeId) { int uOrigEdge = getOrigEdges(uEdgeId); for (NodeCH n : goalNodes) { if (n.entry != null) { Path path = algo.extractPath(n.entry); if (path.found() && path.weight() <= n.distance) { // FOUND witness path, so do not add shortcut continue; } } // FOUND shortcut but be sure that it is the only shortcut in the collection // and also in the graph for u->w. If existing AND identical length => update flags // Hint: shortcuts are always one-way due to distinct level of every endNode but we don't // know yet the levels so we need to determine the correct direction or if both directions long edgeId = (long) u * refs.length + n.endNode; Shortcut sc = shortcuts.get(edgeId); if (sc == null) sc = shortcuts.get((long) n.endNode * refs.length + u); // minor improvement: if (shortcuts.containsKey((long) n.endNode * refs.length + u)) // then two shortcuts with the same nodes (u<->n.endNode) exists => check current shortcut against both if (sc == null || !NumHelper.equals(sc.distance, n.distance)) { sc = new Shortcut(u, n.endNode, n.distance); shortcuts.put(edgeId, sc); sc.edge = uEdgeId; sc.originalEdges = uOrigEdge + n.originalEdges; } else { // the shortcut already exists in the current collection (different direction) // but has identical length so change the flags! sc.flags = scBothDir; } } } static class Shortcut { final int from; final int to; final double distance; int edge; int originalEdges; public Shortcut(int from, int to, double distance) { this.from = from; this.to = to; this.distance = distance; } public String toString() { return from + "->" + to + ", dist:" + distance; } } static class NodeCH { int endNode; int originalEdges; //EdgeEntry entry; double distance; public String toString() { return "" + endNode; } } static class Edge { final int t; final double dist; Edge(int t, double dist) { this.t = t; this.dist = dist; } } public static void main(String[] args) { int n = 3; List<Edge>[] g = new List[n]; for (int i = 0; i < n; i++) g[i] = new ArrayList<Edge>(); g[2].add(new Edge(0, 1)); g[2].add(new Edge(1, 1)); g[0].add(new Edge(1, 1)); List<Edge>[] rg = new List[n]; for (int i = 0; i < n; i++) rg[i] = new ArrayList<Edge>(); for (int i = 0; i < n; i++) for (Edge e : g[i]) rg[e.t].add(new Edge(i, e.dist)); } }
update
java/src/ContractionHierarchies.java
update
<ide><path>ava/src/ContractionHierarchies.java <ide> return 10 * edgeDifference + 50 * originalEdgesCount + contractedNeighbors; <ide> } <ide> <del> Collection<Shortcut> findShortcuts(List<Integer>[] g, List<Integer>[] rg, int v) { <add> Collection<Shortcut> findShortcuts(int[][] g, int[][] rg, int[][] dist, int v) { <add> final int[] incoming = rg[v]; <add> final int[] outgoing = rg[v]; <add> <add> for (int i = 0; i < incoming.length; i++) { <add> int u = incoming[i]; <add> int distUV = dist[u][i]; <add> <add> <add> } <add> <add> <ide> // we can use distance instead of weight, see prepareEdges where distance is overwritten by weight! <ide> List<NodeCH> goalNodes = new ArrayList<NodeCH>(); <ide> Map<Long, Shortcut> shortcuts = new HashMap<Long, Shortcut>();
JavaScript
mit
0d3a6cc61924aa7a2a806cb091025fd96b6932ab
0
3ventic/ShortUrl
var http = require('http'); var url = require('url'); var qs = require('querystring'); var sqlite3 = require('sqlite3').verbose(); var config = require('./config.js'); var port = config.port || 8000; console.log("Starting app"); var db = new sqlite3.Database('links.db', sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, function (err) { if (err) { console.log(err); process.exit(1); } console.log("Starting DB"); db.serialize(function () { db.run("CREATE TABLE IF NOT EXISTS links (path TEXT PRIMARY KEY NOT NULL, destination TEXT NOT NULL, used INT NOT NULL)", function (err) { if (err) { console.log(err); process.exit(2); } console.log("Started DB"); }); }); }); http.createServer(function (req, res) { var url_params = url.parse(req.url); var query = qs.parse(url_params.query); console.log(url_params); console.log(query); if (url_params.pathname && url_params.pathname.length > 2 && url_params.pathname[2] == '.') { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end("Not found"); } else if (query.secret == config.secret) { switch (url_params.pathname) { case "": case "/": res.writeHead(200, { 'Content-Type': 'text/html' }); getFrontPageHtml(function (html) { res.end(html); }); break; case "/new": if (typeof query.target === "undefined" || query.target.length == 0) { returnError(res, 400, "Bad Request: Target must be specified"); } else { var path, target = query.target; if (typeof query.path !== "undefined" && query.path.length > 0) { path = query.path; newLink(res, path, target); } else { db.get('SELECT path FROM links WHERE destination = $destination', { $destination: target }, function (err, row) { if (err) { returnError(res, 500, "SQL Error"); } else { console.log("Existing " + (row ? row.path : "none")); if (row && row.path) { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ status: 200, short: config.base_url + row.path, destination: target })); } else { db.get('SELECT MAX(rowid) AS rowid FROM links', function (err, row) { if (err) { returnError(res, 500, "SQL Error"); } else { console.log(row.rowid); newLink(res, numToPath((row.rowid || -1) + 1), target); } }); } } }); } } break; default: returnError(res, 404, "Not Found"); break; } } else if (url_params.pathname.length < 2) { returnError(res, 200, "Forbidden to access /"); } else { var path = url_params.pathname.substring(1); // Follow redirect db.get('SELECT destination FROM links WHERE path LIKE $path', { $path: path }, function (err, row) { if (err) { console.log(err); returnError(res, 500, "SQL Error"); } else if (!row || !row.destination) { returnError(res, 404, "Not Found"); } else { res.writeHead(301, { 'Content-Type': 'text/html', Location: row.destination }); res.end('<script type="text/javascript">window.location.href="' + row.destination + '";</script><a href="' + row.destination + '">Click here to follow redirect.</a>'); db.run('UPDATE links SET used = used + 1 WHERE path = $path', { $path: path }); } }); } }).listen(port); console.log("Starting HTTP"); var validChars = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890_-'; function numToPath(num) { if (num < validChars.length) return validChars[num]; return numToPath(num / validChars.length) + numToPath(num % validChars.length); } function returnError(res, code, message) { res.writeHead(code, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ status: code, msg: message })); } function newLink(res, path, target) { db.run('INSERT OR IGNORE INTO links VALUES ($path, $destination, 0)', { $path: path, $destination: target }, function (err) { if (err) { console.log(err); returnError(res, 500, "SQL Error"); } else { db.run('UPDATE links SET destination = $destination WHERE path LIKE $path', { $path: path, $destination: target }, function (err) { if (err) { console.log(err); returnError(res, 500, "SQL Error"); } else { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ status: 200, short: config.base_url + path, destination: target })); } }); } }); } function HtmlReplacer(c) { return { '"': '&quot;', '&': '&amp;', "'": '&#39;', '/': '&#47;', '<': '&lt;', '>': '&gt;' }[c] || "[UNKNOWN]"; } function escapeHtml(text) { return text.toString().replace(/["&'\/<>]/g, HtmlReplacer); } function getFrontPageHtml(callback) { var html = '<!DOCTYPE html><html><head><meta charset="utf-8" /><title>Shorten Link</title></head><body>' + '<form action="' + config.base_url + 'new" method="GET"><input type="hidden" name="secret" value="' + config.secret + '" /><input type="text" name="path" placeholder="(optional) path" /><input type="url" name="target" placeholder="target" /><input name="submit" type="submit" value="Create" /></form><ul>'; db.each("SELECT rowid AS id, path, destination, used FROM links", function (err, row) { if (err) { console.log(err); } else { console.log(row.id + " (" + row.used + ") " + row.path + ": " + row.destination); html += '<li>' + row.id + " (" + row.used + ") " + escapeHtml(row.path) + ": " + escapeHtml(row.destination) + '</li>'; } }, function (err) { if (err) { console.log(err); } html += '</ul></body></html>'; callback(html); }); } function exitHandler() { console.log("Closing db connection"); db.close(function (err) { if (err) { console.log(err); process.exit(3); } else process.exit(0); }); } process.on('SIGINT', exitHandler);
ShortUrl/server.js
var http = require('http'); var url = require('url'); var qs = require('querystring'); var sqlite3 = require('sqlite3').verbose(); var config = require('./config.js'); var port = config.port || 8000; console.log("Starting app"); var db = new sqlite3.Database('links.db', sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, function (err) { if (err) { console.log(err); process.exit(1); } console.log("Starting DB"); db.serialize(function () { db.run("CREATE TABLE IF NOT EXISTS links (path TEXT PRIMARY KEY NOT NULL, destination TEXT NOT NULL, used INT NOT NULL)", function (err) { if (err) { console.log(err); process.exit(2); } console.log("Started DB"); }); }); }); http.createServer(function (req, res) { var url_params = url.parse(req.url); var query = qs.parse(url_params.query); console.log(url_params); console.log(query); if (url_params.pathname && url_params.pathname.length > 2 && url_params.pathname[2] == '.') { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end("Not found"); } else if (query.secret == config.secret) { switch (url_params.pathname) { case "": case "/": res.writeHead(200, { 'Content-Type': 'text/html' }); getFrontPageHtml(function (html) { res.end(html); }); break; case "/new": if (typeof query.target === "undefined" || query.target.length == 0) { returnError(res, 400, "Bad Request: Target must be specified"); } else { var path, target = query.target; if (typeof query.path !== "undefined" && query.path.length > 0) { path = query.path; newLink(res, path, target); } else { db.get('SELECT path FROM links WHERE destination = $destination', { $destination: target }, function (err, row) { if (err) { returnError(res, 500, "SQL Error"); } else { console.log("Existing " + (row ? row.path : "none")); if (row && row.path) { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ status: 200, short: config.base_url + row.path, destination: target })); } else { db.get('SELECT MAX(rowid) AS rowid FROM links', function (err, row) { if (err) { returnError(res, 500, "SQL Error"); } else { console.log(row.rowid); newLink(res, numToPath((row.rowid || -1) + 1), target); } }); } } }); } } break; default: returnError(res, 404, "Not Found"); break; } } else if (url_params.pathname.length < 2) { returnError(res, 200, "Forbidden to access /"); } else { var path = url_params.pathname.substring(1); // Follow redirect db.get('SELECT destination FROM links WHERE path LIKE $path', { $path: path }, function (err, row) { if (err) { console.log(err); returnError(res, 500, "SQL Error"); } else if (!row || !row.destination) { returnError(res, 404, "Not Found"); } else { res.writeHead(301, { 'Content-Type': 'text/html', Location: row.destination }); res.end(); db.run('UPDATE links SET used = used + 1 WHERE path = $path', { $path: path }); } }); } }).listen(port); console.log("Starting HTTP"); var validChars = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890_-'; function numToPath(num) { if (num < validChars.length) return validChars[num]; return numToPath(num / validChars.length) + numToPath(num % validChars.length); } function returnError(res, code, message) { res.writeHead(code, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ status: code, msg: message })); } function newLink(res, path, target) { db.run('INSERT OR IGNORE INTO links VALUES ($path, $destination, 0)', { $path: path, $destination: target }, function (err) { if (err) { console.log(err); returnError(res, 500, "SQL Error"); } else { db.run('UPDATE links SET destination = $destination WHERE path LIKE $path', { $path: path, $destination: target }, function (err) { if (err) { console.log(err); returnError(res, 500, "SQL Error"); } else { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ status: 200, short: config.base_url + path, destination: target })); } }); } }); } function HtmlReplacer(c) { return { '"': '&quot;', '&': '&amp;', "'": '&#39;', '/': '&#47;', '<': '&lt;', '>': '&gt;' }[c] || "[UNKNOWN]"; } function escapeHtml(text) { return text.toString().replace(/["&'\/<>]/g, HtmlReplacer); } function getFrontPageHtml(callback) { var html = '<!DOCTYPE html><html><head><meta charset="utf-8" /><title>Shorten Link</title></head><body>' + '<form action="' + config.base_url + 'new" method="GET"><input type="hidden" name="secret" value="' + config.secret + '" /><input type="text" name="path" placeholder="(optional) path" /><input type="url" name="target" placeholder="target" /><input name="submit" type="submit" value="Create" /></form><ul>'; db.each("SELECT rowid AS id, path, destination, used FROM links", function (err, row) { if (err) { console.log(err); } else { console.log(row.id + " (" + row.used + ") " + row.path + ": " + row.destination); html += '<li>' + row.id + " (" + row.used + ") " + escapeHtml(row.path) + ": " + escapeHtml(row.destination) + '</li>'; } }, function (err) { if (err) { console.log(err); } html += '</ul></body></html>'; callback(html); }); } function exitHandler() { console.log("Closing db connection"); db.close(function (err) { if (err) { console.log(err); process.exit(3); } else process.exit(0); }); } process.on('SIGINT', exitHandler);
add html response with js redirect and link
ShortUrl/server.js
add html response with js redirect and link
<ide><path>hortUrl/server.js <ide> else <ide> { <ide> res.writeHead(301, { 'Content-Type': 'text/html', Location: row.destination }); <del> res.end(); <add> res.end('<script type="text/javascript">window.location.href="' + row.destination + '";</script><a href="' + row.destination + '">Click here to follow redirect.</a>'); <ide> db.run('UPDATE links SET used = used + 1 WHERE path = $path', { <ide> $path: path <ide> });
Java
apache-2.0
905dc52ac02c378f4fb8cf002cf6b05007566392
0
wildfly-security/wildfly-elytron,sguilhen/wildfly-elytron,sguilhen/wildfly-elytron,wildfly-security/wildfly-elytron
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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.wildfly.security.auth.callback; import java.io.Serializable; import org.wildfly.common.Assert; import org.wildfly.security._private.ElytronMessages; import org.wildfly.security.credential.AlgorithmCredential; import org.wildfly.security.credential.Credential; /** * A callback used to acquire credentials. On the client side of an authentication mechanism, the callback handler is * required to supply a credential for use in outbound authentication. On the server side, the callback handler is * required to supply a credential for use in inbound authentication, possibly for both verification as well as establishing * authentication parameters. * <p> * This callback must be handled if a default credential was not supplied. The callback * handler is expected to provide a credential to this callback if one is not present. If no credential is available, * {@code null} is set, and authentication may fail. If an unsupported credential type is set, an exception is thrown. * * @author <a href="mailto:[email protected]">David M. Lloyd</a> */ public final class CredentialCallback implements ExtendedCallback, Serializable { private static final long serialVersionUID = 4756568346009259703L; /** * @serial The type of the supported credential. */ private final Class<? extends Credential> credentialType; /** * @serial The algorithm of the required credential, or {@code null} if any algorithm is suitable or the credential * type does not use algorithm names. */ private final String algorithm; /** * @serial The credential itself. */ private Credential credential; /** * Construct a new instance. * * @param credentialType the desired credential type (must not be {@code null}) * @param algorithm the algorithm name, or {@code null} if any algorithm is suitable or the credential * type does not use algorithm names */ public CredentialCallback(final Class<? extends Credential> credentialType, final String algorithm) { Assert.checkNotNullParam("credentialType", credentialType); this.credentialType = credentialType; this.algorithm = algorithm; } /** * Construct a new instance which accepts any algorithm name. * * @param credentialType the desired credential type (must not be {@code null}) */ public CredentialCallback(final Class<? extends Credential> credentialType) { this(credentialType, null); } /** * Get the acquired credential. * * @return the acquired credential, or {@code null} if it wasn't set yet. */ public Credential getCredential() { return credential; } /** * Set the credential. The credential must be of the supported type and algorithm. * * @param credential the credential, or {@code null} to indicate that no credential is available * @throws IllegalArgumentException if the given credential is not supported */ public void setCredential(final Credential credential) { if (credential != null && ! isCredentialSupported(credential)) { throw ElytronMessages.log.credentialNotSupported(); } this.credential = credential; } /** * Determine whether the given credential type is supported. Will be {@code false} if the credential type requires * an algorithm name; in this case, use {@link #isCredentialTypeSupported(Class, String)} instead. * * @param credentialType the credential type (must not be {@code null}) * @return {@code true} if the credential type is supported, {@code false} otherwise */ public boolean isCredentialTypeSupported(final Class<? extends Credential> credentialType) { return isCredentialTypeSupported(credentialType, null); } /** * Determine whether the given credential type is supported for the given algorithm name. * * @param credentialType the credential type (must not be {@code null}) * @param algorithmName the algorithm name, or {@code null} to indicate that no algorithm name will be available * @return {@code true} if the credential type is supported, {@code false} otherwise */ public boolean isCredentialTypeSupported(final Class<? extends Credential> credentialType, final String algorithmName) { Assert.checkNotNullParam("credentialType", credentialType); return this.credentialType.isAssignableFrom(credentialType) && (algorithm == null || AlgorithmCredential.class.isAssignableFrom(credentialType) && algorithm.equals(algorithmName)); } /** * Determine whether the given credential can be set on this callback. * * @param credential the credential (must not be {@code null}) * @return {@code true} if the credential matches the type and optional algorithm of this callback, {@code false} otherwise */ public boolean isCredentialSupported(final Credential credential) { Assert.checkNotNullParam("credential", credential); return credentialType.isInstance(credential) && (algorithm == null || credential instanceof AlgorithmCredential && algorithm.equals(((AlgorithmCredential) credential).getAlgorithm())); } /** * Get the supported credential type. * * @return the supported credential type (not {@code null}) */ public Class<? extends Credential> getCredentialType() { return credentialType; } /** * Get the algorithm name, if any. * * @return the algorithm name, or {@code null} if any algorithm is suitable or the credential * type does not use algorithm names */ public String getAlgorithm() { return algorithm; } public boolean isOptional() { return credential != null; } public boolean needsInformation() { return true; } }
src/main/java/org/wildfly/security/auth/callback/CredentialCallback.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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.wildfly.security.auth.callback; import java.io.Serializable; import org.wildfly.common.Assert; import org.wildfly.security._private.ElytronMessages; import org.wildfly.security.credential.AlgorithmCredential; import org.wildfly.security.credential.Credential; /** * A callback used to acquire credentials, either for outbound or inbound authentication. This callback * is required only if a default credential was not supplied. The callback handler is expected to provide * a credential to this callback if one is not present. If no credential is available, {@code null} is set, and * authentication may fail. If an unsupported credential type is set, authentication may fail. * * @author <a href="mailto:[email protected]">David M. Lloyd</a> */ public final class CredentialCallback implements ExtendedCallback, Serializable { private static final long serialVersionUID = 4756568346009259703L; /** * @serial The type of the supported credential. */ private final Class<? extends Credential> credentialType; /** * @serial The algorithm of the required credential, or {@code null} if any algorithm is suitable or the credential * type does not use algorithm names. */ private final String algorithm; /** * @serial The credential itself. */ private Credential credential; /** * Construct a new instance. * * @param credentialType the desired credential type (must not be {@code null}) * @param algorithm the algorithm name, or {@code null} if any algorithm is suitable or the credential * type does not use algorithm names */ public CredentialCallback(final Class<? extends Credential> credentialType, final String algorithm) { Assert.checkNotNullParam("credentialType", credentialType); this.credentialType = credentialType; this.algorithm = algorithm; } /** * Construct a new instance which accepts any algorithm name. * * @param credentialType the desired credential type (must not be {@code null}) */ public CredentialCallback(final Class<? extends Credential> credentialType) { this(credentialType, null); } /** * Get the acquired credential. * * @return the acquired credential, or {@code null} if it wasn't set yet. */ public Credential getCredential() { return credential; } /** * Set the credential. The credential must be of the supported type and algorithm. * * @param credential the credential, or {@code null} to indicate that no credential is available * @throws IllegalArgumentException if the given credential is not supported */ public void setCredential(final Credential credential) { if (credential != null && ! isCredentialSupported(credential)) { throw ElytronMessages.log.credentialNotSupported(); } this.credential = credential; } /** * Determine whether the given credential type is supported. Will be {@code false} if the credential type requires * an algorithm name; in this case, use {@link #isCredentialTypeSupported(Class, String)} instead. * * @param credentialType the credential type (must not be {@code null}) * @return {@code true} if the credential type is supported, {@code false} otherwise */ public boolean isCredentialTypeSupported(final Class<? extends Credential> credentialType) { return isCredentialTypeSupported(credentialType, null); } /** * Determine whether the given credential type is supported for the given algorithm name. * * @param credentialType the credential type (must not be {@code null}) * @param algorithmName the algorithm name, or {@code null} to indicate that no algorithm name will be available * @return {@code true} if the credential type is supported, {@code false} otherwise */ public boolean isCredentialTypeSupported(final Class<? extends Credential> credentialType, final String algorithmName) { Assert.checkNotNullParam("credentialType", credentialType); return this.credentialType.isAssignableFrom(credentialType) && (algorithm == null || AlgorithmCredential.class.isAssignableFrom(credentialType) && algorithm.equals(algorithmName)); } /** * Determine whether the given credential can be set on this callback. * * @param credential the credential (must not be {@code null}) * @return {@code true} if the credential matches the type and optional algorithm of this callback, {@code false} otherwise */ public boolean isCredentialSupported(final Credential credential) { Assert.checkNotNullParam("credential", credential); return credentialType.isInstance(credential) && (algorithm == null || credential instanceof AlgorithmCredential && algorithm.equals(((AlgorithmCredential) credential).getAlgorithm())); } /** * Get the supported credential type. * * @return the supported credential type (not {@code null}) */ public Class<? extends Credential> getCredentialType() { return credentialType; } /** * Get the algorithm name, if any. * * @return the algorithm name, or {@code null} if any algorithm is suitable or the credential * type does not use algorithm names */ public String getAlgorithm() { return algorithm; } public boolean isOptional() { return credential != null; } public boolean needsInformation() { return true; } }
[ELY-374] Update JavaDoc
src/main/java/org/wildfly/security/auth/callback/CredentialCallback.java
[ELY-374] Update JavaDoc
<ide><path>rc/main/java/org/wildfly/security/auth/callback/CredentialCallback.java <ide> import org.wildfly.security.credential.Credential; <ide> <ide> /** <del> * A callback used to acquire credentials, either for outbound or inbound authentication. This callback <del> * is required only if a default credential was not supplied. The callback handler is expected to provide <del> * a credential to this callback if one is not present. If no credential is available, {@code null} is set, and <del> * authentication may fail. If an unsupported credential type is set, authentication may fail. <add> * A callback used to acquire credentials. On the client side of an authentication mechanism, the callback handler is <add> * required to supply a credential for use in outbound authentication. On the server side, the callback handler is <add> * required to supply a credential for use in inbound authentication, possibly for both verification as well as establishing <add> * authentication parameters. <add> * <p> <add> * This callback must be handled if a default credential was not supplied. The callback <add> * handler is expected to provide a credential to this callback if one is not present. If no credential is available, <add> * {@code null} is set, and authentication may fail. If an unsupported credential type is set, an exception is thrown. <ide> * <ide> * @author <a href="mailto:[email protected]">David M. Lloyd</a> <ide> */
Java
apache-2.0
019666ddc71eca7f87807b9d2836d53a7289592d
0
mta452/Tehreer-Android,mta452/Tehreer-Android,mta452/Tehreer-Android
/* * Copyright (C) 2017 Muhammad Tayyab Akram * * 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.mta.tehreer.layout; import android.graphics.RectF; import android.text.SpannableString; import android.text.Spanned; import com.mta.tehreer.graphics.Typeface; import com.mta.tehreer.internal.text.StringUtils; import com.mta.tehreer.internal.text.TopSpanIterator; import com.mta.tehreer.layout.style.TypeSizeSpan; import com.mta.tehreer.layout.style.TypefaceSpan; import com.mta.tehreer.sfnt.SfntTag; import com.mta.tehreer.sfnt.ShapingEngine; import com.mta.tehreer.sfnt.ShapingResult; import com.mta.tehreer.sfnt.WritingDirection; import com.mta.tehreer.unicode.BaseDirection; import com.mta.tehreer.unicode.BidiAlgorithm; import com.mta.tehreer.unicode.BidiLine; import com.mta.tehreer.unicode.BidiParagraph; import com.mta.tehreer.unicode.BidiRun; import java.text.BreakIterator; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Represents a typesetter which performs text layout. It can be used to create lines, perform line * breaking, and do other contextual analysis based on the characters in the string. */ public class Typesetter { private static final float DEFAULT_FONT_SIZE = 16.0f; private class Finalizable { @Override protected void finalize() throws Throwable { try { dispose(); } finally { super.finalize(); } } } private static final byte BREAK_TYPE_NONE = 0; private static final byte BREAK_TYPE_LINE = 1 << 0; private static final byte BREAK_TYPE_CHARACTER = 1 << 2; private static final byte BREAK_TYPE_PARAGRAPH = 1 << 4; private static byte specializeBreakType(byte breakType, boolean forward) { return (byte) (forward ? breakType : breakType << 1); } private final Finalizable finalizable = new Finalizable(); private String mText; private Spanned mSpanned; private byte[] mBreakRecord; private ArrayList<BidiParagraph> mBidiParagraphs; private ArrayList<IntrinsicRun> mIntrinsicRuns; /** * Constructs the typesetter object using given text, typeface and type size. * * @param text The text to typeset. * @param typeface The typeface to use. * @param typeSize The type size to apply. * * @throws NullPointerException if <code>text</code> is null, or <code>typeface</code> is null. * @throws IllegalArgumentException if <code>text</code> is empty. */ public Typesetter(String text, Typeface typeface, float typeSize) { if (text == null) { throw new NullPointerException("Text is null"); } if (typeface == null) { throw new NullPointerException("Typeface is null"); } if (text.length() == 0) { throw new IllegalArgumentException("Text is empty"); } SpannableString spanned = new SpannableString(text); spanned.setSpan(new TypefaceSpan(typeface), 0, text.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); spanned.setSpan(new TypeSizeSpan(typeSize), 0, text.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); init(text, spanned); } /** * Constructs the typesetter object using a spanned text. * * @param spanned The spanned text to typeset. * * @throws NullPointerException if <code>spanned</code> is null. * @throws IllegalArgumentException if <code>spanned</code> is empty. */ public Typesetter(Spanned spanned) { if (spanned == null) { throw new NullPointerException("Spanned text is null"); } if (spanned.length() == 0) { throw new IllegalArgumentException("Spanned text is empty"); } init(StringUtils.copyString(spanned), spanned); } private void init(String text, Spanned spanned) { mText = text; mSpanned = spanned; mBreakRecord = new byte[text.length()]; mBidiParagraphs = new ArrayList<>(); mIntrinsicRuns = new ArrayList<>(); resolveBreaks(); resolveBidi(); } /** * Returns the spanned source text for which this typesetter object was created. * * @return The spanned source text for which this typesetter object was created. */ public Spanned getSpanned() { return mSpanned; } private void resolveBreaks() { resolveBreaks(BreakIterator.getLineInstance(), BREAK_TYPE_LINE); resolveBreaks(BreakIterator.getCharacterInstance(), BREAK_TYPE_CHARACTER); } private void resolveBreaks(BreakIterator breakIterator, byte breakType) { breakIterator.setText(mText); breakIterator.first(); byte forwardType = specializeBreakType(breakType, true); int charNext; while ((charNext = breakIterator.next()) != BreakIterator.DONE) { mBreakRecord[charNext - 1] |= forwardType; } breakIterator.last(); byte backwardType = specializeBreakType(breakType, false); int charIndex; while ((charIndex = breakIterator.previous()) != BreakIterator.DONE) { mBreakRecord[charIndex] |= backwardType; } } private void resolveBidi() { // TODO: Analyze script runs. BidiAlgorithm bidiAlgorithm = null; ShapingEngine shapingEngine = null; try { bidiAlgorithm = new BidiAlgorithm(mText); shapingEngine = new ShapingEngine(); BaseDirection baseDirection = BaseDirection.DEFAULT_LEFT_TO_RIGHT; byte forwardType = specializeBreakType(BREAK_TYPE_PARAGRAPH, true); byte backwardType = specializeBreakType(BREAK_TYPE_PARAGRAPH, false); int paragraphStart = 0; int suggestedEnd = mText.length(); while (paragraphStart != suggestedEnd) { BidiParagraph paragraph = bidiAlgorithm.createParagraph(paragraphStart, suggestedEnd, baseDirection); for (BidiRun bidiRun : paragraph.getLogicalRuns()) { int scriptTag = SfntTag.make(bidiRun.isRightToLeft() ? "arab" : "latn"); WritingDirection writingDirection = ShapingEngine.getScriptDirection(scriptTag); shapingEngine.setScriptTag(scriptTag); shapingEngine.setWritingDirection(writingDirection); resolveTypefaces(bidiRun.charStart, bidiRun.charEnd, bidiRun.embeddingLevel, shapingEngine); } mBidiParagraphs.add(paragraph); mBreakRecord[paragraph.getCharStart()] |= backwardType; mBreakRecord[paragraph.getCharEnd() - 1] |= forwardType; paragraphStart = paragraph.getCharEnd(); } } finally { if (shapingEngine != null) { shapingEngine.dispose(); } if (bidiAlgorithm != null) { bidiAlgorithm.dispose(); } } } private void resolveTypefaces(int charStart, int charEnd, byte bidiLevel, ShapingEngine shapingEngine) { Spanned spanned = mSpanned; TopSpanIterator<TypefaceSpan> iterator = new TopSpanIterator<>(spanned, charStart, charEnd, TypefaceSpan.class); while (iterator.hasNext()) { TypefaceSpan spanObject = iterator.next(); int spanStart = iterator.getSpanStart(); int spanEnd = iterator.getSpanEnd(); if (spanObject == null || spanObject.getTypeface() == null) { throw new IllegalArgumentException("No typeface is specified for range [" + spanStart + ".." + spanEnd + ")"); } resolveFonts(spanStart, spanEnd, bidiLevel, shapingEngine, spanObject.getTypeface()); } } private void resolveFonts(int charStart, int charEnd, byte bidiLevel, ShapingEngine shapingEngine, Typeface typeface) { Spanned spanned = mSpanned; TopSpanIterator<TypeSizeSpan> iterator = new TopSpanIterator<>(spanned, charStart, charEnd, TypeSizeSpan.class); while (iterator.hasNext()) { TypeSizeSpan spanObject = iterator.next(); int spanStart = iterator.getSpanStart(); int spanEnd = iterator.getSpanEnd(); float typeSize; if (spanObject == null) { typeSize = DEFAULT_FONT_SIZE; } else { typeSize = spanObject.getSize(); if (typeSize < 0.0f) { typeSize = 0.0f; } } IntrinsicRun intrinsicRun = resolveGlyphs(spanStart, spanEnd, bidiLevel, shapingEngine, typeface, typeSize); mIntrinsicRuns.add(intrinsicRun); } } private IntrinsicRun resolveGlyphs(int charStart, int charEnd, byte bidiLevel, ShapingEngine shapingEngine, Typeface typeface, float typeSize) { shapingEngine.setTypeface(typeface); shapingEngine.setTypeSize(typeSize); ShapingResult shapingResult = null; IntrinsicRun intrinsicRun = null; try { shapingResult = shapingEngine.shapeText(mText, charStart, charEnd); intrinsicRun = new IntrinsicRun(shapingResult, typeface, typeSize, bidiLevel, shapingEngine.getWritingDirection()); } finally { if (shapingResult != null) { shapingResult.dispose(); } } return intrinsicRun; } private String checkRange(int charStart, int charEnd) { if (charStart < 0) { return ("Char Start: " + charStart); } if (charEnd > mText.length()) { return ("Char End: " + charEnd + ", Text Length: " + mText.length()); } if (charStart >= charEnd) { return ("Bad Range: [" + charStart + ".." + charEnd + ")"); } return null; } private int indexOfBidiParagraph(final int charIndex) { return Collections.binarySearch(mBidiParagraphs, null, new Comparator<BidiParagraph>() { @Override public int compare(BidiParagraph obj1, BidiParagraph obj2) { if (charIndex < obj1.getCharStart()) { return 1; } if (charIndex >= obj1.getCharEnd()) { return -1; } return 0; } }); } private int indexOfGlyphRun(final int charIndex) { return Collections.binarySearch(mIntrinsicRuns, null, new Comparator<IntrinsicRun>() { @Override public int compare(IntrinsicRun obj1, IntrinsicRun obj2) { if (charIndex < obj1.charStart) { return 1; } if (charIndex >= obj1.charEnd) { return -1; } return 0; } }); } private byte getCharParagraphLevel(int charIndex) { int paragraphIndex = indexOfBidiParagraph(charIndex); BidiParagraph charParagraph = mBidiParagraphs.get(paragraphIndex); return charParagraph.getBaseLevel(); } private float measureChars(int charStart, int charEnd) { float measuredWidth = 0.0f; if (charEnd > charStart) { int runIndex = indexOfGlyphRun(charStart); do { IntrinsicRun intrinsicRun = mIntrinsicRuns.get(runIndex); int glyphStart = intrinsicRun.charGlyphStart(charStart); int glyphEnd; int segmentEnd = Math.min(charEnd, intrinsicRun.charEnd); glyphEnd = intrinsicRun.charGlyphEnd(segmentEnd - 1); measuredWidth += intrinsicRun.measureGlyphs(glyphStart, glyphEnd); charStart = segmentEnd; runIndex++; } while (charStart < charEnd); } return measuredWidth; } private int findForwardBreak(byte breakType, int charStart, int charEnd, float maxWidth) { int forwardBreak = charStart; int charIndex = charStart; float measuredWidth = 0.0f; byte mustType = specializeBreakType(BREAK_TYPE_PARAGRAPH, true); breakType = specializeBreakType(breakType, true); while (charIndex < charEnd) { byte charType = mBreakRecord[charIndex]; // Handle necessary break. if ((charType & mustType) == mustType) { int segmentEnd = charIndex + 1; measuredWidth += measureChars(forwardBreak, segmentEnd); if (measuredWidth <= maxWidth) { forwardBreak = segmentEnd; } break; } // Handle optional break. if ((charType & breakType) == breakType) { int segmentEnd = charIndex + 1; measuredWidth += measureChars(forwardBreak, segmentEnd); if (measuredWidth > maxWidth) { int whitespaceStart = StringUtils.getTrailingWhitespaceStart(mText, forwardBreak, segmentEnd); float whitespaceWidth = measureChars(whitespaceStart, segmentEnd); // Break if excluding whitespaces width helps. if ((measuredWidth - whitespaceWidth) <= maxWidth) { forwardBreak = segmentEnd; } break; } forwardBreak = segmentEnd; } charIndex++; } return forwardBreak; } private int findBackwardBreak(byte breakType, int charStart, int charEnd, float maxWidth) { int backwardBreak = charEnd; int charIndex = charEnd - 1; float measuredWidth = 0.0f; byte mustType = specializeBreakType(BREAK_TYPE_PARAGRAPH, false); breakType = specializeBreakType(breakType, false); while (charIndex >= charStart) { byte charType = mBreakRecord[charIndex]; // Handle necessary break. if ((charType & mustType) == mustType) { measuredWidth += measureChars(backwardBreak, charIndex); if (measuredWidth <= maxWidth) { backwardBreak = charIndex; } break; } // Handle optional break. if ((charType & breakType) == breakType) { measuredWidth += measureChars(charIndex, backwardBreak); if (measuredWidth > maxWidth) { int whitespaceStart = StringUtils.getTrailingWhitespaceStart(mText, charIndex, backwardBreak); float whitespaceWidth = measureChars(whitespaceStart, backwardBreak); // Break if excluding trailing whitespaces helps. if ((measuredWidth - whitespaceWidth) <= maxWidth) { backwardBreak = charIndex; } break; } backwardBreak = charIndex; } charIndex--; } return backwardBreak; } private int suggestForwardCharBreak(int charStart, int charEnd, float maxWidth) { int forwardBreak = findForwardBreak(BREAK_TYPE_CHARACTER, charStart, charEnd, maxWidth); // Take at least one character (grapheme) if max size is too small. if (forwardBreak == charStart) { for (int i = charStart; i < charEnd; i++) { if ((mBreakRecord[i] & BREAK_TYPE_CHARACTER) != 0) { forwardBreak = i + 1; break; } } // Character range does not cover even a single grapheme? if (forwardBreak == charStart) { forwardBreak = Math.min(charStart + 1, charEnd); } } return forwardBreak; } private int suggestBackwardCharBreak(int charStart, int charEnd, float maxWidth) { int backwardBreak = findBackwardBreak(BREAK_TYPE_CHARACTER, charStart, charEnd, maxWidth); // Take at least one character (grapheme) if max size is too small. if (backwardBreak == charEnd) { for (int i = charEnd - 1; i >= charStart; i++) { if ((mBreakRecord[i] & BREAK_TYPE_CHARACTER) != 0) { backwardBreak = i; break; } } // Character range does not cover even a single grapheme? if (backwardBreak == charEnd) { backwardBreak = Math.max(charEnd - 1, charStart); } } return backwardBreak; } private int suggestForwardLineBreak(int charStart, int charEnd, float maxWidth) { int forwardBreak = findForwardBreak(BREAK_TYPE_LINE, charStart, charEnd, maxWidth); // Fallback to character break if no line break occurs in max size. if (forwardBreak == charStart) { forwardBreak = suggestForwardCharBreak(charStart, charEnd, maxWidth); } return forwardBreak; } private int suggestBackwardLineBreak(int charStart, int charEnd, float maxWidth) { int backwardBreak = findBackwardBreak(BREAK_TYPE_LINE, charStart, charEnd, maxWidth); // Fallback to character break if no line break occurs in max size. if (backwardBreak == charEnd) { backwardBreak = suggestBackwardCharBreak(charStart, charEnd, maxWidth); } return backwardBreak; } /** * Suggests a forward break index based on the provided range and width. The measurement * proceeds from first character to last character. If there is still room after measuring all * characters, then last index is returned. Otherwise, break index is returned. * * @param charStart The index to the first character (inclusive) for break calculations. * @param charEnd The index to the last character (exclusive) for break calculations. * @param breakWidth The requested break width. * @param breakMode The requested break mode. * @return The index (exclusive) that would cause the break. * * @throws NullPointerException if <code>breakMode</code> is null. * @throws IllegalArgumentException if <code>charStart</code> is negative, or * <code>charEnd</code> is greater than the length of source text, or * <code>charStart</code> is greater than or equal to <code>charEnd</code> */ public int suggestForwardBreak(int charStart, int charEnd, float breakWidth, BreakMode breakMode) { if (breakMode == null) { throw new NullPointerException("Break mode is null"); } String rangeError = checkRange(charStart, charEnd); if (rangeError != null) { throw new IllegalArgumentException(rangeError); } switch (breakMode) { case CHARACTER: return suggestForwardCharBreak(charStart, charEnd, breakWidth); case LINE: return suggestForwardLineBreak(charStart, charEnd, breakWidth); } return -1; } /** * Suggests a backward break index based on the provided range and width. The measurement * proceeds from last character to first character. If there is still room after measuring all * characters, then first index is returned. Otherwise, break index is returned. * * @param charStart The index to the first character (inclusive) for break calculations. * @param charEnd The index to the last character (exclusive) for break calculations. * @param breakWidth The requested break width. * @param breakMode The requested break mode. * @return The index (inclusive) that would cause the break. * * @throws NullPointerException if <code>breakMode</code> is null. * @throws IllegalArgumentException if <code>charStart</code> is negative, or * <code>charEnd</code> is greater than the length of source text, or * <code>charStart</code> is greater than or equal to <code>charEnd</code> */ public int suggestBackwardBreak(int charStart, int charEnd, float breakWidth, BreakMode breakMode) { if (breakMode == null) { throw new NullPointerException("Break mode is null"); } String rangeError = checkRange(charStart, charEnd); if (rangeError != null) { throw new IllegalArgumentException(rangeError); } switch (breakMode) { case CHARACTER: return suggestBackwardCharBreak(charStart, charEnd, breakWidth); case LINE: return suggestBackwardLineBreak(charStart, charEnd, breakWidth); } return -1; } /** * Creates a simple line of specified string range. * * @param charStart The index to first character of the line in source text. * @param charEnd The index after the last character of the line in source text. * @return The new line object. * * @throws IllegalArgumentException if <code>charStart</code> is negative, or * <code>charEnd</code> is greater than the length of source text, or * <code>charStart</code> is greater than or equal to <code>charEnd</code> */ public ComposedLine createSimpleLine(int charStart, int charEnd) { String rangeError = checkRange(charStart, charEnd); if (rangeError != null) { throw new IllegalArgumentException(rangeError); } ArrayList<GlyphRun> lineRuns = new ArrayList<>(); addContinuousLineRuns(charStart, charEnd, lineRuns); return new ComposedLine(mText, charStart, charEnd, lineRuns, getCharParagraphLevel(charStart)); } private ComposedLine createTruncationToken(int charStart, int charEnd, TruncationPlace truncationPlace, String tokenStr) { int truncationIndex = 0; switch (truncationPlace) { case START: truncationIndex = charStart; break; case MIDDLE: truncationIndex = (charStart + charEnd) / 2; break; case END: truncationIndex = charEnd - 1; break; } Object[] charSpans = mSpanned.getSpans(truncationIndex, truncationIndex + 1, Object.class); TypefaceSpan typefaceSpan = null; TypeSizeSpan typeSizeSpan = null; final int typefaceBit = 1; final int typeSizeBit = 1 << 1; final int requiredBits = typefaceBit | typeSizeBit; int foundBits = 0; for (Object span : charSpans) { if (span instanceof TypefaceSpan) { if (typefaceSpan == null) { typefaceSpan = (TypefaceSpan) span; foundBits |= typefaceBit; } } else if (span instanceof TypeSizeSpan) { if (typeSizeSpan == null) { typeSizeSpan = (TypeSizeSpan) span; foundBits |= typeSizeBit; } } if (foundBits == requiredBits) { Typeface tokenTypeface = typefaceSpan.getTypeface(); float tokenTypeSize = typeSizeSpan.getSize(); if (tokenStr == null || tokenStr.length() == 0) { // Token string is not given. Use ellipsis character if available; fallback to // three dots. int ellipsisGlyphId = tokenTypeface.getGlyphId(0x2026); if (ellipsisGlyphId == 0) { tokenStr = "..."; } else { tokenStr = "\u2026"; } } Typesetter typesetter = new Typesetter(tokenStr, tokenTypeface, tokenTypeSize); return typesetter.createSimpleLine(0, tokenStr.length()); } } return null; } /** * Creates a line of specified string range, truncating it with ellipsis character (U+2026) or * three dots if it overflows the max width. * * @param charStart The index to first character of the line in source text. * @param charEnd The index after the last character of the line in source text. * @param maxWidth The width at which truncation will begin. * @param breakMode The truncation mode to be used on the line. * @param truncationPlace The place of truncation for the line. * @return The new line which is truncated if it overflows the <code>maxWidth</code>. * * @throws NullPointerException if <code>breakMode</code> is null, or * <code>truncationPlace</code> is null. * @throws IllegalArgumentException if any of the following is true: * <ul> * <li><code>charStart</code> is negative</li> * <li><code>charEnd</code> is greater than the length of source text</li> * <li><code>charStart</code> is greater than or equal to <code>charEnd</code></li> * </ul> */ public ComposedLine createTruncatedLine(int charStart, int charEnd, float maxWidth, BreakMode breakMode, TruncationPlace truncationPlace) { if (breakMode == null) { throw new NullPointerException("Break mode is null"); } if (truncationPlace == null) { throw new NullPointerException("Truncation place is null"); } String rangeError = checkRange(charStart, charEnd); if (rangeError != null) { throw new IllegalArgumentException(rangeError); } return createCompactLine(charStart, charEnd, maxWidth, breakMode, truncationPlace, createTruncationToken(charStart, charEnd, truncationPlace, null)); } /** * Creates a line of specified string range, truncating it if it overflows the max width. * * @param charStart The index to first character of the line in source text. * @param charEnd The index after the last character of the line in source text. * @param maxWidth The width at which truncation will begin. * @param breakMode The truncation mode to be used on the line. * @param truncationPlace The place of truncation for the line. * @param truncationToken The token to indicate the line truncation. * @return The new line which is truncated if it overflows the <code>maxWidth</code>. * * @throws NullPointerException if <code>breakMode</code> is null, or * <code>truncationPlace</code> is null, or <code>truncationToken</code> is null * @throws IllegalArgumentException if any of the following is true: * <ul> * <li><code>charStart</code> is negative</li> * <li><code>charEnd</code> is greater than the length of source text</li> * <li><code>charStart</code> is greater than or equal to <code>charEnd</code></li> * </ul> */ public ComposedLine createTruncatedLine(int charStart, int charEnd, float maxWidth, BreakMode breakMode, TruncationPlace truncationPlace, String truncationToken) { if (breakMode == null) { throw new NullPointerException("Break mode is null"); } if (truncationPlace == null) { throw new NullPointerException("Truncation place is null"); } if (truncationToken == null) { throw new NullPointerException("Truncation token is null"); } String rangeError = checkRange(charStart, charEnd); if (rangeError != null) { throw new IllegalArgumentException(rangeError); } if (truncationToken.length() == 0) { throw new IllegalArgumentException("Truncation token is empty"); } return createCompactLine(charStart, charEnd, maxWidth, breakMode, truncationPlace, createTruncationToken(charStart, charEnd, truncationPlace, truncationToken)); } /** * Creates a line of specified string range, truncating it if it overflows the max width. * * @param charStart The index to first character of the line in source text. * @param charEnd The index after the last character of the line in source text. * @param maxWidth The width at which truncation will begin. * @param breakMode The truncation mode to be used on the line. * @param truncationPlace The place of truncation for the line. * @param truncationToken The token to indicate the line truncation. * @return The new line which is truncated if it overflows the <code>maxWidth</code>. * * @throws NullPointerException if <code>breakMode</code> is null, or * <code>truncationPlace</code> is null, or <code>truncationToken</code> is null * @throws IllegalArgumentException if any of the following is true: * <ul> * <li><code>charStart</code> is negative</li> * <li><code>charEnd</code> is greater than the length of source text</li> * <li><code>charStart</code> is greater than or equal to <code>charEnd</code></li> * </ul> */ public ComposedLine createTruncatedLine(int charStart, int charEnd, float maxWidth, BreakMode breakMode, TruncationPlace truncationPlace, ComposedLine truncationToken) { if (breakMode == null) { throw new NullPointerException("Break mode is null"); } if (truncationPlace == null) { throw new NullPointerException("Truncation place is null"); } if (truncationToken == null) { throw new NullPointerException("Truncation token is null"); } String rangeError = checkRange(charStart, charEnd); if (rangeError != null) { throw new IllegalArgumentException(rangeError); } return createCompactLine(charStart, charEnd, maxWidth, breakMode, truncationPlace, truncationToken); } public ComposedLine createCompactLine(int charStart, int charEnd, float maxWidth, BreakMode breakMode, TruncationPlace truncationPlace, ComposedLine truncationToken) { float tokenlessWidth = maxWidth - truncationToken.getWidth(); switch (truncationPlace) { case START: return createStartTruncatedLine(charStart, charEnd, tokenlessWidth, breakMode, truncationToken); case MIDDLE: return createMiddleTruncatedLine(charStart, charEnd, tokenlessWidth, breakMode, truncationToken); case END: return createEndTruncatedLine(charStart, charEnd, tokenlessWidth, breakMode, truncationToken); } return null; } private interface BidiRunConsumer { void accept(BidiRun bidiRun); } private class TruncationHandler implements BidiRunConsumer { final int charStart; final int charEnd; final int skipStart; final int skipEnd; final List<GlyphRun> runList; int leadingTokenIndex = -1; int trailingTokenIndex = -1; TruncationHandler(int charStart, int charEnd, int skipStart, int skipEnd, List<GlyphRun> runList) { this.charStart = charStart; this.charEnd = charEnd; this.skipStart = skipStart; this.skipEnd = skipEnd; this.runList = runList; } @Override public void accept(BidiRun bidiRun) { int visualStart = bidiRun.charStart; int visualEnd = bidiRun.charEnd; if (bidiRun.isRightToLeft()) { // Handle second part of characters. if (visualEnd >= skipEnd) { addVisualRuns(Math.max(visualStart, skipEnd), visualEnd, runList); if (visualStart < skipEnd) { trailingTokenIndex = runList.size(); } } // Handle first part of characters. if (visualStart <= skipStart) { if (visualEnd > skipStart) { leadingTokenIndex = runList.size(); } addVisualRuns(visualStart, Math.min(visualEnd, skipStart), runList); } } else { // Handle first part of characters. if (visualStart <= skipStart) { addVisualRuns(visualStart, Math.min(visualEnd, skipStart), runList); if (visualEnd > skipStart) { leadingTokenIndex = runList.size(); } } // Handle second part of characters. if (visualEnd >= skipEnd) { if (visualStart < skipEnd) { trailingTokenIndex = runList.size(); } addVisualRuns(Math.max(visualStart, skipEnd), visualEnd, runList); } } } void addAllRuns() { addContinuousLineRuns(charStart, charEnd, this); } } private ComposedLine createStartTruncatedLine(int charStart, int charEnd, float tokenlessWidth, BreakMode breakMode, ComposedLine truncationToken) { int truncatedStart = suggestBackwardBreak(charStart, charEnd, tokenlessWidth, breakMode); if (truncatedStart > charStart) { ArrayList<GlyphRun> runList = new ArrayList<>(); int tokenInsertIndex = 0; if (truncatedStart < charEnd) { TruncationHandler truncationHandler = new TruncationHandler(charStart, charEnd, charStart, truncatedStart, runList); truncationHandler.addAllRuns(); tokenInsertIndex = truncationHandler.trailingTokenIndex; } addTruncationTokenRuns(truncationToken, runList, tokenInsertIndex); return new ComposedLine(mText, truncatedStart, charEnd, runList, getCharParagraphLevel(truncatedStart)); } return createSimpleLine(truncatedStart, charEnd); } private ComposedLine createMiddleTruncatedLine(int charStart, int charEnd, float tokenlessWidth, BreakMode breakMode, ComposedLine truncationToken) { float halfWidth = tokenlessWidth / 2.0f; int firstMidEnd = suggestForwardBreak(charStart, charEnd, halfWidth, breakMode); int secondMidStart = suggestBackwardBreak(charStart, charEnd, halfWidth, breakMode); if (firstMidEnd < secondMidStart) { // Exclude inner whitespaces as truncation token replaces them. firstMidEnd = StringUtils.getTrailingWhitespaceStart(mText, charStart, firstMidEnd); secondMidStart = StringUtils.getLeadingWhitespaceEnd(mText, secondMidStart, charEnd); ArrayList<GlyphRun> runList = new ArrayList<>(); int tokenInsertIndex = 0; if (charStart < firstMidEnd || secondMidStart < charEnd) { TruncationHandler truncationHandler = new TruncationHandler(charStart, charEnd, firstMidEnd, secondMidStart, runList); truncationHandler.addAllRuns(); tokenInsertIndex = truncationHandler.leadingTokenIndex; } addTruncationTokenRuns(truncationToken, runList, tokenInsertIndex); return new ComposedLine(mText, charStart, charEnd, runList, getCharParagraphLevel(charStart)); } return createSimpleLine(charStart, charEnd); } private ComposedLine createEndTruncatedLine(int charStart, int charEnd, float tokenlessWidth, BreakMode breakMode, ComposedLine truncationToken) { int truncatedEnd = suggestForwardBreak(charStart, charEnd, tokenlessWidth, breakMode); if (truncatedEnd < charEnd) { // Exclude trailing whitespaces as truncation token replaces them. truncatedEnd = StringUtils.getTrailingWhitespaceStart(mText, charStart, truncatedEnd); ArrayList<GlyphRun> runList = new ArrayList<>(); int tokenInsertIndex = 0; if (charStart < truncatedEnd) { TruncationHandler truncationHandler = new TruncationHandler(charStart, charEnd, truncatedEnd, charEnd, runList); truncationHandler.addAllRuns(); tokenInsertIndex = truncationHandler.leadingTokenIndex; } addTruncationTokenRuns(truncationToken, runList, tokenInsertIndex); return new ComposedLine(mText, charStart, truncatedEnd, runList, getCharParagraphLevel(charStart)); } return createSimpleLine(charStart, truncatedEnd); } private void addTruncationTokenRuns(ComposedLine truncationToken, ArrayList<GlyphRun> runList, int insertIndex) { for (GlyphRun truncationRun : truncationToken.getRuns()) { GlyphRun modifiedRun = new GlyphRun(truncationRun); runList.add(insertIndex, modifiedRun); insertIndex++; } } private void addContinuousLineRuns(int charStart, int charEnd, BidiRunConsumer runConsumer) { int paragraphIndex = indexOfBidiParagraph(charStart); int feasibleStart; int feasibleEnd; do { BidiParagraph bidiParagraph = mBidiParagraphs.get(paragraphIndex); feasibleStart = Math.max(bidiParagraph.getCharStart(), charStart); feasibleEnd = Math.min(bidiParagraph.getCharEnd(), charEnd); BidiLine bidiLine = bidiParagraph.createLine(feasibleStart, feasibleEnd); for (BidiRun bidiRun : bidiLine.getVisualRuns()) { runConsumer.accept(bidiRun); } bidiLine.dispose(); paragraphIndex++; } while (feasibleEnd != charEnd); } private void addContinuousLineRuns(int charStart, int charEnd, final List<GlyphRun> runList) { addContinuousLineRuns(charStart, charEnd, new BidiRunConsumer() { @Override public void accept(BidiRun bidiRun) { int visualStart = bidiRun.charStart; int visualEnd = bidiRun.charEnd; addVisualRuns(visualStart, visualEnd, runList); } }); } private void addVisualRuns(int visualStart, int visualEnd, List<GlyphRun> runList) { if (visualStart < visualEnd) { // ASSUMPTIONS: // - Visual range may fall in one or more glyph runs. // - Consecutive intrinsic runs may have same bidi level. int insertIndex = runList.size(); IntrinsicRun previousRun = null; do { int runIndex = indexOfGlyphRun(visualStart); IntrinsicRun intrinsicRun = mIntrinsicRuns.get(runIndex); int feasibleStart = Math.max(intrinsicRun.charStart, visualStart); int feasibleEnd = Math.min(intrinsicRun.charEnd, visualEnd); GlyphRun glyphRun = new GlyphRun(intrinsicRun, feasibleStart, feasibleEnd); if (previousRun != null) { byte bidiLevel = intrinsicRun.bidiLevel; if (bidiLevel != previousRun.bidiLevel || (bidiLevel & 1) == 0) { insertIndex = runList.size(); } } runList.add(insertIndex, glyphRun); previousRun = intrinsicRun; visualStart = feasibleEnd; } while (visualStart != visualEnd); } } /** * Creates a frame full of lines in the rectangle provided by the <code>frameRect</code> * parameter. The typesetter will continue to fill the frame until it either runs out of text or * it finds that text no longer fits. * * @param charStart The index to first character of the frame in source text. * @param charEnd The index after the last character of the frame in source text. * @param frameRect The rectangle specifying the frame to fill. * @param textAlignment The horizontal text alignment of the lines in frame. * @return The new frame object. */ public ComposedFrame createFrame(int charStart, int charEnd, RectF frameRect, TextAlignment textAlignment) { if (frameRect == null) { throw new NullPointerException("Frame rect is null"); } if (textAlignment == null) { throw new NullPointerException("Text alignment is null"); } String rangeError = checkRange(charStart, charEnd); if (rangeError != null) { throw new IllegalArgumentException(rangeError); } if (frameRect.isEmpty()) { throw new IllegalArgumentException("Frame rect is empty"); } float flushFactor; switch (textAlignment) { case RIGHT: flushFactor = 1.0f; break; case CENTER: flushFactor = 0.5f; break; default: flushFactor = 0.0f; break; } float frameWidth = frameRect.width(); float frameBottom = frameRect.bottom; ArrayList<ComposedLine> frameLines = new ArrayList<>(); int lineStart = charStart; float lineY = frameRect.top; while (lineStart != charEnd) { int lineEnd = suggestForwardBreak(lineStart, charEnd, frameWidth, BreakMode.LINE); ComposedLine composedLine = createSimpleLine(lineStart, lineEnd); float lineX = composedLine.getFlushPenOffset(flushFactor, frameWidth); float lineAscent = composedLine.getAscent(); float lineHeight = lineAscent + composedLine.getDescent(); if ((lineY + lineHeight) > frameBottom) { break; } composedLine.setOriginX(frameRect.left + lineX); composedLine.setOriginY(lineY + lineAscent); frameLines.add(composedLine); lineStart = lineEnd; lineY += lineHeight; } return new ComposedFrame(charStart, lineStart, frameLines); } void dispose() { for (BidiParagraph paragraph : mBidiParagraphs) { paragraph.dispose(); } } }
tehreer-android/src/main/java/com/mta/tehreer/layout/Typesetter.java
/* * Copyright (C) 2017 Muhammad Tayyab Akram * * 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.mta.tehreer.layout; import android.graphics.RectF; import android.text.SpannableString; import android.text.Spanned; import com.mta.tehreer.graphics.Typeface; import com.mta.tehreer.internal.text.StringUtils; import com.mta.tehreer.internal.text.TopSpanIterator; import com.mta.tehreer.layout.style.TypeSizeSpan; import com.mta.tehreer.layout.style.TypefaceSpan; import com.mta.tehreer.sfnt.SfntTag; import com.mta.tehreer.sfnt.ShapingEngine; import com.mta.tehreer.sfnt.ShapingResult; import com.mta.tehreer.sfnt.WritingDirection; import com.mta.tehreer.unicode.BaseDirection; import com.mta.tehreer.unicode.BidiAlgorithm; import com.mta.tehreer.unicode.BidiLine; import com.mta.tehreer.unicode.BidiParagraph; import com.mta.tehreer.unicode.BidiRun; import java.text.BreakIterator; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Represents a typesetter which performs text layout. It can be used to create lines, perform line * breaking, and do other contextual analysis based on the characters in the string. */ public class Typesetter { private static final float DEFAULT_FONT_SIZE = 16.0f; private class Finalizable { @Override protected void finalize() throws Throwable { try { dispose(); } finally { super.finalize(); } } } private static final byte BREAK_TYPE_NONE = 0; private static final byte BREAK_TYPE_LINE = 1 << 0; private static final byte BREAK_TYPE_CHARACTER = 1 << 2; private static final byte BREAK_TYPE_PARAGRAPH = 1 << 4; private static byte specializeBreakType(byte breakType, boolean forward) { return (byte) (forward ? breakType : breakType << 1); } private final Finalizable finalizable = new Finalizable(); private String mText; private Spanned mSpanned; private byte[] mBreakRecord; private ArrayList<BidiParagraph> mBidiParagraphs; private ArrayList<IntrinsicRun> mIntrinsicRuns; /** * Constructs the typesetter object using given text, typeface and type size. * * @param text The text to typeset. * @param typeface The typeface to use. * @param typeSize The type size to apply. * * @throws NullPointerException if <code>text</code> is null, or <code>typeface</code> is null. * @throws IllegalArgumentException if <code>text</code> is empty. */ public Typesetter(String text, Typeface typeface, float typeSize) { if (text == null) { throw new NullPointerException("Text is null"); } if (typeface == null) { throw new NullPointerException("Typeface is null"); } if (text.length() == 0) { throw new IllegalArgumentException("Text is empty"); } SpannableString spanned = new SpannableString(text); spanned.setSpan(new TypefaceSpan(typeface), 0, text.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); spanned.setSpan(new TypeSizeSpan(typeSize), 0, text.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); init(text, spanned); } /** * Constructs the typesetter object using a spanned text. * * @param spanned The spanned text to typeset. * * @throws NullPointerException if <code>spanned</code> is null. * @throws IllegalArgumentException if <code>spanned</code> is empty. */ public Typesetter(Spanned spanned) { if (spanned == null) { throw new NullPointerException("Spanned text is null"); } if (spanned.length() == 0) { throw new IllegalArgumentException("Spanned text is empty"); } init(StringUtils.copyString(spanned), spanned); } private void init(String text, Spanned spanned) { mText = text; mSpanned = spanned; mBreakRecord = new byte[text.length()]; mBidiParagraphs = new ArrayList<>(); mIntrinsicRuns = new ArrayList<>(); resolveBreaks(); resolveBidi(); } /** * Returns the spanned source text for which this typesetter object was created. * * @return The spanned source text for which this typesetter object was created. */ public Spanned getSpanned() { return mSpanned; } private void resolveBreaks() { resolveBreaks(BreakIterator.getLineInstance(), BREAK_TYPE_LINE); resolveBreaks(BreakIterator.getCharacterInstance(), BREAK_TYPE_CHARACTER); } private void resolveBreaks(BreakIterator breakIterator, byte breakType) { breakIterator.setText(mText); breakIterator.first(); byte forwardType = specializeBreakType(breakType, true); int charNext; while ((charNext = breakIterator.next()) != BreakIterator.DONE) { mBreakRecord[charNext - 1] |= forwardType; } breakIterator.last(); byte backwardType = specializeBreakType(breakType, false); int charIndex; while ((charIndex = breakIterator.previous()) != BreakIterator.DONE) { mBreakRecord[charIndex] |= backwardType; } } private void resolveBidi() { // TODO: Analyze script runs. BidiAlgorithm bidiAlgorithm = null; ShapingEngine shapingEngine = null; try { bidiAlgorithm = new BidiAlgorithm(mText); shapingEngine = new ShapingEngine(); BaseDirection baseDirection = BaseDirection.DEFAULT_LEFT_TO_RIGHT; byte forwardType = specializeBreakType(BREAK_TYPE_PARAGRAPH, true); byte backwardType = specializeBreakType(BREAK_TYPE_PARAGRAPH, false); int paragraphStart = 0; int suggestedEnd = mText.length(); while (paragraphStart != suggestedEnd) { BidiParagraph paragraph = bidiAlgorithm.createParagraph(paragraphStart, suggestedEnd, baseDirection); for (BidiRun bidiRun : paragraph.getLogicalRuns()) { int scriptTag = SfntTag.make(bidiRun.isRightToLeft() ? "arab" : "latn"); WritingDirection writingDirection = ShapingEngine.getScriptDirection(scriptTag); shapingEngine.setScriptTag(scriptTag); shapingEngine.setWritingDirection(writingDirection); resolveTypefaces(bidiRun.charStart, bidiRun.charEnd, bidiRun.embeddingLevel, shapingEngine); } mBidiParagraphs.add(paragraph); mBreakRecord[paragraph.getCharStart()] |= backwardType; mBreakRecord[paragraph.getCharEnd() - 1] |= forwardType; paragraphStart = paragraph.getCharEnd(); } } finally { if (shapingEngine != null) { shapingEngine.dispose(); } if (bidiAlgorithm != null) { bidiAlgorithm.dispose(); } } } private void resolveTypefaces(int charStart, int charEnd, byte bidiLevel, ShapingEngine shapingEngine) { Spanned spanned = mSpanned; TopSpanIterator<TypefaceSpan> iterator = new TopSpanIterator<>(spanned, charStart, charEnd, TypefaceSpan.class); while (iterator.hasNext()) { TypefaceSpan spanObject = iterator.next(); int spanStart = iterator.getSpanStart(); int spanEnd = iterator.getSpanEnd(); if (spanObject == null || spanObject.getTypeface() == null) { throw new IllegalArgumentException("No typeface is specified for range [" + spanStart + ".." + spanEnd + ")"); } resolveFonts(spanStart, spanEnd, bidiLevel, shapingEngine, spanObject.getTypeface()); } } private void resolveFonts(int charStart, int charEnd, byte bidiLevel, ShapingEngine shapingEngine, Typeface typeface) { Spanned spanned = mSpanned; TopSpanIterator<TypeSizeSpan> iterator = new TopSpanIterator<>(spanned, charStart, charEnd, TypeSizeSpan.class); while (iterator.hasNext()) { TypeSizeSpan spanObject = iterator.next(); int spanStart = iterator.getSpanStart(); int spanEnd = iterator.getSpanEnd(); float typeSize; if (spanObject == null) { typeSize = DEFAULT_FONT_SIZE; } else { typeSize = spanObject.getSize(); if (typeSize < 0.0f) { typeSize = 0.0f; } } IntrinsicRun intrinsicRun = resolveGlyphs(spanStart, spanEnd, bidiLevel, shapingEngine, typeface, typeSize); mIntrinsicRuns.add(intrinsicRun); } } private IntrinsicRun resolveGlyphs(int charStart, int charEnd, byte bidiLevel, ShapingEngine shapingEngine, Typeface typeface, float typeSize) { shapingEngine.setTypeface(typeface); shapingEngine.setTypeSize(typeSize); ShapingResult shapingResult = null; IntrinsicRun intrinsicRun = null; try { shapingResult = shapingEngine.shapeText(mText, charStart, charEnd); intrinsicRun = new IntrinsicRun(shapingResult, typeface, typeSize, bidiLevel, shapingEngine.getWritingDirection()); } finally { if (shapingResult != null) { shapingResult.dispose(); } } return intrinsicRun; } private String checkRange(int charStart, int charEnd) { if (charStart < 0) { return ("Char Start: " + charStart); } if (charEnd > mText.length()) { return ("Char End: " + charEnd + ", Text Length: " + mText.length()); } if (charStart >= charEnd) { return ("Bad Range: [" + charStart + ".." + charEnd + ")"); } return null; } private int indexOfBidiParagraph(final int charIndex) { return Collections.binarySearch(mBidiParagraphs, null, new Comparator<BidiParagraph>() { @Override public int compare(BidiParagraph obj1, BidiParagraph obj2) { if (charIndex < obj1.getCharStart()) { return 1; } if (charIndex >= obj1.getCharEnd()) { return -1; } return 0; } }); } private int indexOfGlyphRun(final int charIndex) { return Collections.binarySearch(mIntrinsicRuns, null, new Comparator<IntrinsicRun>() { @Override public int compare(IntrinsicRun obj1, IntrinsicRun obj2) { if (charIndex < obj1.charStart) { return 1; } if (charIndex >= obj1.charEnd) { return -1; } return 0; } }); } private byte getCharParagraphLevel(int charIndex) { int paragraphIndex = indexOfBidiParagraph(charIndex); BidiParagraph charParagraph = mBidiParagraphs.get(paragraphIndex); return charParagraph.getBaseLevel(); } private float measureChars(int charStart, int charEnd) { float measuredWidth = 0.0f; if (charEnd > charStart) { int runIndex = indexOfGlyphRun(charStart); do { IntrinsicRun intrinsicRun = mIntrinsicRuns.get(runIndex); int glyphStart = intrinsicRun.charGlyphStart(charStart); int glyphEnd; int segmentEnd = Math.min(charEnd, intrinsicRun.charEnd); glyphEnd = intrinsicRun.charGlyphEnd(segmentEnd - 1); measuredWidth += intrinsicRun.measureGlyphs(glyphStart, glyphEnd); charStart = segmentEnd; runIndex++; } while (charStart < charEnd); } return measuredWidth; } private int findForwardBreak(byte breakType, int charStart, int charEnd, float maxWidth) { int forwardBreak = charStart; int charIndex = charStart; float measuredWidth = 0.0f; byte mustType = specializeBreakType(BREAK_TYPE_PARAGRAPH, true); breakType = specializeBreakType(breakType, true); while (charIndex < charEnd) { byte charType = mBreakRecord[charIndex]; // Handle necessary break. if ((charType & mustType) == mustType) { int segmentEnd = charIndex + 1; measuredWidth += measureChars(forwardBreak, segmentEnd); if (measuredWidth <= maxWidth) { forwardBreak = segmentEnd; } break; } // Handle optional break. if ((charType & breakType) == breakType) { int segmentEnd = charIndex + 1; measuredWidth += measureChars(forwardBreak, segmentEnd); if (measuredWidth > maxWidth) { int whitespaceStart = StringUtils.getTrailingWhitespaceStart(mText, forwardBreak, segmentEnd); float whitespaceWidth = measureChars(whitespaceStart, segmentEnd); // Break if excluding whitespaces width helps. if ((measuredWidth - whitespaceWidth) <= maxWidth) { forwardBreak = segmentEnd; } break; } forwardBreak = segmentEnd; } charIndex++; } return forwardBreak; } private int findBackwardBreak(byte breakType, int charStart, int charEnd, float maxWidth) { int backwardBreak = charEnd; int charIndex = charEnd - 1; float measuredWidth = 0.0f; byte mustType = specializeBreakType(BREAK_TYPE_PARAGRAPH, false); breakType = specializeBreakType(breakType, false); while (charIndex >= charStart) { byte charType = mBreakRecord[charIndex]; // Handle necessary break. if ((charType & mustType) == mustType) { measuredWidth += measureChars(backwardBreak, charIndex); if (measuredWidth <= maxWidth) { backwardBreak = charIndex; } break; } // Handle optional break. if ((charType & breakType) == breakType) { measuredWidth += measureChars(charIndex, backwardBreak); if (measuredWidth > maxWidth) { int whitespaceStart = StringUtils.getTrailingWhitespaceStart(mText, charIndex, backwardBreak); float whitespaceWidth = measureChars(whitespaceStart, backwardBreak); // Break if excluding trailing whitespaces helps. if ((measuredWidth - whitespaceWidth) <= maxWidth) { backwardBreak = charIndex; } break; } backwardBreak = charIndex; } charIndex--; } return backwardBreak; } private int suggestForwardCharBreak(int charStart, int charEnd, float maxWidth) { int forwardBreak = findForwardBreak(BREAK_TYPE_CHARACTER, charStart, charEnd, maxWidth); // Take at least one character (grapheme) if max size is too small. if (forwardBreak == charStart) { for (int i = charStart; i < charEnd; i++) { if ((mBreakRecord[i] & BREAK_TYPE_CHARACTER) != 0) { forwardBreak = i + 1; break; } } // Character range does not cover even a single grapheme? if (forwardBreak == charStart) { forwardBreak = Math.min(charStart + 1, charEnd); } } return forwardBreak; } private int suggestBackwardCharBreak(int charStart, int charEnd, float maxWidth) { int backwardBreak = findBackwardBreak(BREAK_TYPE_CHARACTER, charStart, charEnd, maxWidth); // Take at least one character (grapheme) if max size is too small. if (backwardBreak == charEnd) { for (int i = charEnd - 1; i >= charStart; i++) { if ((mBreakRecord[i] & BREAK_TYPE_CHARACTER) != 0) { backwardBreak = i; break; } } // Character range does not cover even a single grapheme? if (backwardBreak == charEnd) { backwardBreak = Math.max(charEnd - 1, charStart); } } return backwardBreak; } private int suggestForwardLineBreak(int charStart, int charEnd, float maxWidth) { int forwardBreak = findForwardBreak(BREAK_TYPE_LINE, charStart, charEnd, maxWidth); // Fallback to character break if no line break occurs in max size. if (forwardBreak == charStart) { forwardBreak = suggestForwardCharBreak(charStart, charEnd, maxWidth); } return forwardBreak; } private int suggestBackwardLineBreak(int charStart, int charEnd, float maxWidth) { int backwardBreak = findBackwardBreak(BREAK_TYPE_LINE, charStart, charEnd, maxWidth); // Fallback to character break if no line break occurs in max size. if (backwardBreak == charEnd) { backwardBreak = suggestBackwardCharBreak(charStart, charEnd, maxWidth); } return backwardBreak; } /** * Suggests a forward break index based on the provided range and width. The measurement * proceeds from first character to last character. If there is still room after measuring all * characters, then last index is returned. Otherwise, break index is returned. * * @param charStart The index to the first character (inclusive) for break calculations. * @param charEnd The index to the last character (exclusive) for break calculations. * @param breakWidth The requested break width. * @param breakMode The requested break mode. * @return The index (exclusive) that would cause the break. * * @throws NullPointerException if <code>breakMode</code> is null. * @throws IllegalArgumentException if <code>charStart</code> is negative, or * <code>charEnd</code> is greater than the length of source text, or * <code>charStart</code> is greater than or equal to <code>charEnd</code> */ public int suggestForwardBreak(int charStart, int charEnd, float breakWidth, BreakMode breakMode) { if (breakMode == null) { throw new NullPointerException("Break mode is null"); } String rangeError = checkRange(charStart, charEnd); if (rangeError != null) { throw new IllegalArgumentException(rangeError); } switch (breakMode) { case CHARACTER: return suggestForwardCharBreak(charStart, charEnd, breakWidth); case LINE: return suggestForwardLineBreak(charStart, charEnd, breakWidth); } return -1; } /** * Suggests a backward break index based on the provided range and width. The measurement * proceeds from last character to first character. If there is still room after measuring all * characters, then first index is returned. Otherwise, break index is returned. * * @param charStart The index to the first character (inclusive) for break calculations. * @param charEnd The index to the last character (exclusive) for break calculations. * @param breakWidth The requested break width. * @param breakMode The requested break mode. * @return The index (inclusive) that would cause the break. * * @throws NullPointerException if <code>breakMode</code> is null. * @throws IllegalArgumentException if <code>charStart</code> is negative, or * <code>charEnd</code> is greater than the length of source text, or * <code>charStart</code> is greater than or equal to <code>charEnd</code> */ public int suggestBackwardBreak(int charStart, int charEnd, float breakWidth, BreakMode breakMode) { if (breakMode == null) { throw new NullPointerException("Break mode is null"); } String rangeError = checkRange(charStart, charEnd); if (rangeError != null) { throw new IllegalArgumentException(rangeError); } switch (breakMode) { case CHARACTER: return suggestBackwardCharBreak(charStart, charEnd, breakWidth); case LINE: return suggestBackwardLineBreak(charStart, charEnd, breakWidth); } return -1; } /** * Creates a simple line of specified string range. * * @param charStart The index to first character of the line in source text. * @param charEnd The index after the last character of the line in source text. * @return The new line object. * * @throws IllegalArgumentException if <code>charStart</code> is negative, or * <code>charEnd</code> is greater than the length of source text, or * <code>charStart</code> is greater than or equal to <code>charEnd</code> */ public ComposedLine createSimpleLine(int charStart, int charEnd) { String rangeError = checkRange(charStart, charEnd); if (rangeError != null) { throw new IllegalArgumentException(rangeError); } ArrayList<GlyphRun> lineRuns = new ArrayList<>(); addContinuousLineRuns(charStart, charEnd, lineRuns); return new ComposedLine(mText, charStart, charEnd, lineRuns, getCharParagraphLevel(charStart)); } private ComposedLine createTruncationToken(int charStart, int charEnd, TruncationPlace truncationPlace, String tokenStr) { int truncationIndex = 0; switch (truncationPlace) { case START: truncationIndex = charStart; break; case MIDDLE: truncationIndex = (charStart + charEnd) / 2; break; case END: truncationIndex = charEnd - 1; break; } Object[] charSpans = mSpanned.getSpans(truncationIndex, truncationIndex + 1, Object.class); TypefaceSpan typefaceSpan = null; TypeSizeSpan typeSizeSpan = null; final int typefaceBit = 1; final int typeSizeBit = 1 << 1; final int requiredBits = typefaceBit | typeSizeBit; int foundBits = 0; for (Object span : charSpans) { if (span instanceof TypefaceSpan) { if (typefaceSpan == null) { typefaceSpan = (TypefaceSpan) span; foundBits |= typefaceBit; } } else if (span instanceof TypeSizeSpan) { if (typeSizeSpan == null) { typeSizeSpan = (TypeSizeSpan) span; foundBits |= typeSizeBit; } } if (foundBits == requiredBits) { Typeface tokenTypeface = typefaceSpan.getTypeface(); float tokenTypeSize = typeSizeSpan.getSize(); if (tokenStr == null || tokenStr.length() == 0) { // Token string is not given. Use ellipsis character if available; fallback to // three dots. int ellipsisGlyphId = tokenTypeface.getGlyphId(0x2026); if (ellipsisGlyphId == 0) { tokenStr = "..."; } else { tokenStr = "\u2026"; } } Typesetter typesetter = new Typesetter(tokenStr, tokenTypeface, tokenTypeSize); return typesetter.createSimpleLine(0, tokenStr.length()); } } return null; } /** * Creates a line of specified string range, truncating it with ellipsis character (U+2026) or * three dots if it overflows the max width. * * @param charStart The index to first character of the line in source text. * @param charEnd The index after the last character of the line in source text. * @param maxWidth The width at which truncation will begin. * @param breakMode The truncation mode to be used on the line. * @param truncationPlace The place of truncation for the line. * @return The new line which is truncated if it overflows the <code>maxWidth</code>. * * @throws NullPointerException if <code>breakMode</code> is null, or * <code>truncationPlace</code> is null. * @throws IllegalArgumentException if any of the following is true: * <ul> * <li><code>charStart</code> is negative</li> * <li><code>charEnd</code> is greater than the length of source text</li> * <li><code>charStart</code> is greater than or equal to <code>charEnd</code></li> * </ul> */ public ComposedLine createTruncatedLine(int charStart, int charEnd, float maxWidth, BreakMode breakMode, TruncationPlace truncationPlace) { if (breakMode == null) { throw new NullPointerException("Break mode is null"); } if (truncationPlace == null) { throw new NullPointerException("Truncation place is null"); } String rangeError = checkRange(charStart, charEnd); if (rangeError != null) { throw new IllegalArgumentException(rangeError); } return createCompactLine(charStart, charEnd, maxWidth, breakMode, truncationPlace, createTruncationToken(charStart, charEnd, truncationPlace, null)); } /** * Creates a line of specified string range, truncating it if it overflows the max width. * * @param charStart The index to first character of the line in source text. * @param charEnd The index after the last character of the line in source text. * @param maxWidth The width at which truncation will begin. * @param breakMode The truncation mode to be used on the line. * @param truncationPlace The place of truncation for the line. * @param truncationToken The token to indicate the line truncation. * @return The new line which is truncated if it overflows the <code>maxWidth</code>. * * @throws NullPointerException if <code>breakMode</code> is null, or * <code>truncationPlace</code> is null, or <code>truncationToken</code> is null * @throws IllegalArgumentException if any of the following is true: * <ul> * <li><code>charStart</code> is negative</li> * <li><code>charEnd</code> is greater than the length of source text</li> * <li><code>charStart</code> is greater than or equal to <code>charEnd</code></li> * </ul> */ public ComposedLine createTruncatedLine(int charStart, int charEnd, float maxWidth, BreakMode breakMode, TruncationPlace truncationPlace, String truncationToken) { if (breakMode == null) { throw new NullPointerException("Break mode is null"); } if (truncationPlace == null) { throw new NullPointerException("Truncation place is null"); } if (truncationToken == null) { throw new NullPointerException("Truncation token is null"); } String rangeError = checkRange(charStart, charEnd); if (rangeError != null) { throw new IllegalArgumentException(rangeError); } if (truncationToken.length() == 0) { throw new IllegalArgumentException("Truncation token is empty"); } return createCompactLine(charStart, charEnd, maxWidth, breakMode, truncationPlace, createTruncationToken(charStart, charEnd, truncationPlace, truncationToken)); } /** * Creates a line of specified string range, truncating it if it overflows the max width. * * @param charStart The index to first character of the line in source text. * @param charEnd The index after the last character of the line in source text. * @param maxWidth The width at which truncation will begin. * @param breakMode The truncation mode to be used on the line. * @param truncationPlace The place of truncation for the line. * @param truncationToken The token to indicate the line truncation. * @return The new line which is truncated if it overflows the <code>maxWidth</code>. * * @throws NullPointerException if <code>breakMode</code> is null, or * <code>truncationPlace</code> is null, or <code>truncationToken</code> is null * @throws IllegalArgumentException if any of the following is true: * <ul> * <li><code>charStart</code> is negative</li> * <li><code>charEnd</code> is greater than the length of source text</li> * <li><code>charStart</code> is greater than or equal to <code>charEnd</code></li> * </ul> */ public ComposedLine createTruncatedLine(int charStart, int charEnd, float maxWidth, BreakMode breakMode, TruncationPlace truncationPlace, ComposedLine truncationToken) { if (breakMode == null) { throw new NullPointerException("Break mode is null"); } if (truncationPlace == null) { throw new NullPointerException("Truncation place is null"); } if (truncationToken == null) { throw new NullPointerException("Truncation token is null"); } String rangeError = checkRange(charStart, charEnd); if (rangeError != null) { throw new IllegalArgumentException(rangeError); } return createCompactLine(charStart, charEnd, maxWidth, breakMode, truncationPlace, truncationToken); } public ComposedLine createCompactLine(int charStart, int charEnd, float maxWidth, BreakMode breakMode, TruncationPlace truncationPlace, ComposedLine truncationToken) { float tokenlessWidth = maxWidth - truncationToken.getWidth(); switch (truncationPlace) { case START: return createStartTruncatedLine(charStart, charEnd, tokenlessWidth, breakMode, truncationToken); case MIDDLE: return createMiddleTruncatedLine(charStart, charEnd, tokenlessWidth, breakMode, truncationToken); case END: return createEndTruncatedLine(charStart, charEnd, tokenlessWidth, breakMode, truncationToken); } return null; } private interface BidiRunConsumer { void accept(BidiRun bidiRun); } private class TruncationHandler implements BidiRunConsumer { final int charStart; final int charEnd; final int skipStart; final int skipEnd; final List<GlyphRun> runList; int leadingTokenIndex = -1; int trailingTokenIndex = -1; TruncationHandler(int charStart, int charEnd, int skipStart, int skipEnd, List<GlyphRun> runList) { this.charStart = charStart; this.charEnd = charEnd; this.skipStart = skipStart; this.skipEnd = skipEnd; this.runList = runList; } @Override public void accept(BidiRun bidiRun) { int visualStart = bidiRun.charStart; int visualEnd = bidiRun.charEnd; if (bidiRun.isRightToLeft()) { // Handle second part of characters. if (visualEnd >= skipEnd) { addVisualRuns(Math.max(visualStart, skipEnd), visualEnd, runList); if (visualStart < skipEnd) { trailingTokenIndex = runList.size(); } } // Handle first part of characters. if (visualStart <= skipStart) { if (visualEnd > skipStart) { leadingTokenIndex = runList.size(); } addVisualRuns(visualStart, Math.min(visualEnd, skipStart), runList); } } else { // Handle first part of characters. if (visualStart <= skipStart) { addVisualRuns(visualStart, Math.min(visualEnd, skipStart), runList); if (visualEnd > skipStart) { leadingTokenIndex = runList.size(); } } // Handle second part of characters. if (visualEnd >= skipEnd) { if (visualStart < skipEnd) { trailingTokenIndex = runList.size(); } addVisualRuns(Math.max(visualStart, skipEnd), visualEnd, runList); } } } void addAllRuns() { addContinuousLineRuns(charStart, charEnd, this); } } private ComposedLine createStartTruncatedLine(int charStart, int charEnd, float tokenlessWidth, BreakMode breakMode, ComposedLine truncationToken) { int truncatedStart = suggestBackwardBreak(charStart, charEnd, tokenlessWidth, breakMode); if (truncatedStart > charStart) { ArrayList<GlyphRun> runList = new ArrayList<>(); int tokenInsertIndex = 0; if (truncatedStart < charEnd) { TruncationHandler truncationHandler = new TruncationHandler(charStart, charEnd, charStart, truncatedStart, runList); truncationHandler.addAllRuns(); tokenInsertIndex = truncationHandler.trailingTokenIndex; } addTruncationTokenRuns(truncationToken, runList, tokenInsertIndex); return new ComposedLine(mText, truncatedStart, charEnd, runList, getCharParagraphLevel(truncatedStart)); } return createSimpleLine(truncatedStart, charEnd); } private ComposedLine createMiddleTruncatedLine(int charStart, int charEnd, float tokenlessWidth, BreakMode breakMode, ComposedLine truncationToken) { float halfWidth = tokenlessWidth / 2.0f; int firstMidEnd = suggestForwardBreak(charStart, charEnd, halfWidth, breakMode); int secondMidStart = suggestBackwardBreak(charStart, charEnd, halfWidth, breakMode); if (firstMidEnd < secondMidStart) { // Exclude inner whitespaces as truncation token replaces them. firstMidEnd = StringUtils.getTrailingWhitespaceStart(mText, charStart, firstMidEnd); secondMidStart = StringUtils.getLeadingWhitespaceEnd(mText, secondMidStart, charEnd); ArrayList<GlyphRun> runList = new ArrayList<>(); int tokenInsertIndex = 0; if (charStart < firstMidEnd || secondMidStart < charEnd) { TruncationHandler truncationHandler = new TruncationHandler(charStart, charEnd, firstMidEnd, secondMidStart, runList); truncationHandler.addAllRuns(); tokenInsertIndex = truncationHandler.leadingTokenIndex; } addTruncationTokenRuns(truncationToken, runList, tokenInsertIndex); return new ComposedLine(mText, charStart, charEnd, runList, getCharParagraphLevel(charStart)); } return createSimpleLine(charStart, charEnd); } private ComposedLine createEndTruncatedLine(int charStart, int charEnd, float tokenlessWidth, BreakMode breakMode, ComposedLine truncationToken) { int truncatedEnd = suggestForwardBreak(charStart, charEnd, tokenlessWidth, breakMode); if (truncatedEnd < charEnd) { // Exclude trailing whitespaces as truncation token replaces them. truncatedEnd = StringUtils.getTrailingWhitespaceStart(mText, charStart, truncatedEnd); ArrayList<GlyphRun> runList = new ArrayList<>(); int tokenInsertIndex = 0; if (charStart < truncatedEnd) { TruncationHandler truncationHandler = new TruncationHandler(charStart, charEnd, truncatedEnd, charEnd, runList); truncationHandler.addAllRuns(); tokenInsertIndex = truncationHandler.leadingTokenIndex; } addTruncationTokenRuns(truncationToken, runList, tokenInsertIndex); return new ComposedLine(mText, charStart, truncatedEnd, runList, getCharParagraphLevel(charStart)); } return createSimpleLine(charStart, truncatedEnd); } private void addTruncationTokenRuns(ComposedLine truncationToken, ArrayList<GlyphRun> runList, int insertIndex) { for (GlyphRun truncationRun : truncationToken.getRuns()) { GlyphRun modifiedRun = new GlyphRun(truncationRun); runList.add(insertIndex, modifiedRun); insertIndex++; } } private void addContinuousLineRuns(int charStart, int charEnd, BidiRunConsumer runConsumer) { int paragraphIndex = indexOfBidiParagraph(charStart); int feasibleStart; int feasibleEnd; do { BidiParagraph bidiParagraph = mBidiParagraphs.get(paragraphIndex); feasibleStart = Math.max(bidiParagraph.getCharStart(), charStart); feasibleEnd = Math.min(bidiParagraph.getCharEnd(), charEnd); BidiLine bidiLine = bidiParagraph.createLine(feasibleStart, feasibleEnd); for (BidiRun bidiRun : bidiLine.getVisualRuns()) { runConsumer.accept(bidiRun); } bidiLine.dispose(); paragraphIndex++; } while (feasibleEnd != charEnd); } private void addContinuousLineRuns(int charStart, int charEnd, final List<GlyphRun> runList) { addContinuousLineRuns(charStart, charEnd, new BidiRunConsumer() { @Override public void accept(BidiRun bidiRun) { int visualStart = bidiRun.charStart; int visualEnd = bidiRun.charEnd; addVisualRuns(visualStart, visualEnd, runList); } }); } private void addVisualRuns(int visualStart, int visualEnd, List<GlyphRun> runList) { if (visualStart < visualEnd) { // ASSUMPTIONS: // - Visual range may fall in one or more glyph runs. // - Consecutive intrinsic runs may have same bidi level. int insertIndex = runList.size(); IntrinsicRun previousRun = null; do { int runIndex = indexOfGlyphRun(visualStart); IntrinsicRun intrinsicRun = mIntrinsicRuns.get(runIndex); int feasibleStart = Math.max(intrinsicRun.charStart, visualStart); int feasibleEnd = Math.min(intrinsicRun.charEnd, visualEnd); GlyphRun glyphRun = new GlyphRun(intrinsicRun, feasibleStart, feasibleEnd); if (previousRun != null) { byte bidiLevel = intrinsicRun.bidiLevel; if (bidiLevel != previousRun.bidiLevel || (bidiLevel & 1) == 0) { insertIndex = runList.size(); } } runList.add(insertIndex, glyphRun); previousRun = intrinsicRun; visualStart = feasibleEnd; } while (visualStart != visualEnd); } } /** * Creates a frame full of lines in the rectangle provided by the <code>frameRect</code> * parameter. The typesetter will continue to fill the frame until it either runs out of text or * it finds that text no longer fits. * * @param charStart The index to first character of the frame in source text. * @param charEnd The index after the last character of the frame in source text. * @param frameRect The rectangle specifying the frame to fill. * @param textAlignment The horizontal text alignment of the lines in frame. * @return The new frame object. */ public ComposedFrame createFrame(int charStart, int charEnd, RectF frameRect, TextAlignment textAlignment) { if (frameRect == null) { throw new NullPointerException("Frame rect is null"); } if (textAlignment == null) { throw new NullPointerException("Text alignment is null"); } String rangeError = checkRange(charStart, charEnd); if (rangeError != null) { throw new IllegalArgumentException(rangeError); } if (frameRect.isEmpty()) { throw new IllegalArgumentException("Frame rect is empty"); } float flushFactor; switch (textAlignment) { case RIGHT: flushFactor = 1.0f; break; case CENTER: flushFactor = 0.5f; break; default: flushFactor = 0.0f; break; } float frameWidth = frameRect.width(); float frameHeight = frameRect.height(); ArrayList<ComposedLine> frameLines = new ArrayList<>(); int lineStart = charStart; float lineY = frameRect.top; while (lineStart != charEnd) { int lineEnd = suggestForwardBreak(lineStart, charEnd, frameWidth, BreakMode.LINE); ComposedLine composedLine = createSimpleLine(lineStart, lineEnd); float lineX = composedLine.getFlushPenOffset(flushFactor, frameWidth); float lineAscent = composedLine.getAscent(); float lineHeight = lineAscent + composedLine.getDescent(); if ((lineY + lineHeight) > frameHeight) { break; } composedLine.setOriginX(frameRect.left + lineX); composedLine.setOriginY(lineY + lineAscent); frameLines.add(composedLine); lineStart = lineEnd; lineY += lineHeight; } return new ComposedFrame(charStart, lineStart, frameLines); } void dispose() { for (BidiParagraph paragraph : mBidiParagraphs) { paragraph.dispose(); } } }
[lib] Fixed frame height calculation issue in typesetter...
tehreer-android/src/main/java/com/mta/tehreer/layout/Typesetter.java
[lib] Fixed frame height calculation issue in typesetter...
<ide><path>ehreer-android/src/main/java/com/mta/tehreer/layout/Typesetter.java <ide> } <ide> <ide> float frameWidth = frameRect.width(); <del> float frameHeight = frameRect.height(); <add> float frameBottom = frameRect.bottom; <ide> <ide> ArrayList<ComposedLine> frameLines = new ArrayList<>(); <ide> int lineStart = charStart; <ide> float lineAscent = composedLine.getAscent(); <ide> float lineHeight = lineAscent + composedLine.getDescent(); <ide> <del> if ((lineY + lineHeight) > frameHeight) { <add> if ((lineY + lineHeight) > frameBottom) { <ide> break; <ide> } <ide>
Java
apache-2.0
4fa567331ee6c31343ec2801cfa7a9e13962d3dd
0
asedunov/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,allotria/intellij-community,joewalnes/idea-community,slisson/intellij-community,caot/intellij-community,suncycheng/intellij-community,kool79/intellij-community,FHannes/intellij-community,jagguli/intellij-community,da1z/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,caot/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,da1z/intellij-community,allotria/intellij-community,signed/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,fitermay/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,apixandru/intellij-community,consulo/consulo,semonte/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,supersven/intellij-community,vladmm/intellij-community,diorcety/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,blademainer/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,caot/intellij-community,dslomov/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,kdwink/intellij-community,samthor/intellij-community,da1z/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,xfournet/intellij-community,caot/intellij-community,signed/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,allotria/intellij-community,jagguli/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,allotria/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,holmes/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,caot/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,apixandru/intellij-community,slisson/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,supersven/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,holmes/intellij-community,dslomov/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,joewalnes/idea-community,clumsy/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,ernestp/consulo,kool79/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,xfournet/intellij-community,caot/intellij-community,youdonghai/intellij-community,semonte/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,jexp/idea2,ol-loginov/intellij-community,akosyakov/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,semonte/intellij-community,diorcety/intellij-community,diorcety/intellij-community,hurricup/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,jagguli/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,apixandru/intellij-community,jexp/idea2,amith01994/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,consulo/consulo,michaelgallacher/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,adedayo/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,ryano144/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,supersven/intellij-community,youdonghai/intellij-community,allotria/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,amith01994/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,da1z/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,consulo/consulo,FHannes/intellij-community,fnouama/intellij-community,kool79/intellij-community,supersven/intellij-community,holmes/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,signed/intellij-community,dslomov/intellij-community,supersven/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,holmes/intellij-community,joewalnes/idea-community,FHannes/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,signed/intellij-community,fnouama/intellij-community,xfournet/intellij-community,dslomov/intellij-community,slisson/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,joewalnes/idea-community,petteyg/intellij-community,asedunov/intellij-community,kool79/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,izonder/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,diorcety/intellij-community,consulo/consulo,asedunov/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,izonder/intellij-community,dslomov/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,signed/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,hurricup/intellij-community,semonte/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,vladmm/intellij-community,holmes/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,ryano144/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,apixandru/intellij-community,jexp/idea2,lucafavatella/intellij-community,fnouama/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,joewalnes/idea-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,petteyg/intellij-community,kdwink/intellij-community,amith01994/intellij-community,adedayo/intellij-community,da1z/intellij-community,signed/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,jexp/idea2,ol-loginov/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,izonder/intellij-community,retomerz/intellij-community,holmes/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,semonte/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,joewalnes/idea-community,vvv1559/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,jexp/idea2,adedayo/intellij-community,asedunov/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,joewalnes/idea-community,supersven/intellij-community,jexp/idea2,youdonghai/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,Lekanich/intellij-community,consulo/consulo,retomerz/intellij-community,jagguli/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,jexp/idea2,ibinti/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,kool79/intellij-community,supersven/intellij-community,fitermay/intellij-community,retomerz/intellij-community,caot/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,semonte/intellij-community,clumsy/intellij-community,adedayo/intellij-community,diorcety/intellij-community,blademainer/intellij-community,slisson/intellij-community,signed/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,holmes/intellij-community,FHannes/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,signed/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,holmes/intellij-community,ibinti/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,retomerz/intellij-community,xfournet/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,apixandru/intellij-community,caot/intellij-community,salguarnieri/intellij-community,ernestp/consulo,petteyg/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,kool79/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,dslomov/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,izonder/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,joewalnes/idea-community,adedayo/intellij-community,vladmm/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,kool79/intellij-community,amith01994/intellij-community,signed/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,ernestp/consulo,fitermay/intellij-community,semonte/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,amith01994/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,signed/intellij-community,slisson/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,joewalnes/idea-community,clumsy/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,youdonghai/intellij-community,samthor/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,ernestp/consulo,SerCeMan/intellij-community,petteyg/intellij-community,semonte/intellij-community,jexp/idea2,tmpgit/intellij-community,adedayo/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,samthor/intellij-community,diorcety/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,clumsy/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,izonder/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,caot/intellij-community,amith01994/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,signed/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,da1z/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,da1z/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,kool79/intellij-community,izonder/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,fnouama/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,ernestp/consulo,tmpgit/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,fnouama/intellij-community,ernestp/consulo,suncycheng/intellij-community,retomerz/intellij-community,dslomov/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,ibinti/intellij-community,retomerz/intellij-community,consulo/consulo,ahb0327/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,fitermay/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community
/* * Copyright 2005 Sascha Weinreuter * * 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.intellij.lang.xpath.xslt.refactoring; import org.intellij.lang.xpath.xslt.XsltConfig; import org.intellij.lang.xpath.xslt.refactoring.extractTemplate.XsltExtractTemplateAction; import org.intellij.lang.xpath.xslt.refactoring.introduceParameter.XsltIntroduceParameterAction; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.ActionManagerEx; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.diagnostic.Logger; import org.jetbrains.annotations.NotNull; import java.util.HashMap; import java.util.Map; import java.util.Set; public class XsltRefactoringSupport implements ApplicationComponent { private static final Logger LOG = Logger.getInstance("org.intellij.lang.xpath.xslt.refactoring.XsltRefactoringSupport"); private static final String REFACTORING_MENU_ID = "RefactoringMenu"; // private static final String INTRODUCE_VARIABLE = "IntroduceVariable"; private static final String INTRODUCE_PARAMETER = "IntroduceParameter"; private static final String EXTRACT_METHOD = "ExtractMethod"; private static final String INLINE = "Inline"; private final XsltConfig myConfig; private final Map<String, HookedAction> myActions = new HashMap<String, HookedAction>(); private boolean myInstalled; public XsltRefactoringSupport(XsltConfig config) { myConfig = config; } @NotNull public String getComponentName() { return "XsltRefactoringSupport.Installer"; } public void initComponent() { if (myConfig.isEnabled()) { install(false); } } public void disposeComponent() { if (myInstalled) { uninstall(false); } } public void setEnabled(boolean b) { if (!myInstalled && b) { install(true); } else if (myInstalled && !b) { uninstall(true); } } private void install(boolean full) { LOG.assertTrue(!myInstalled); // install(INTRODUCE_VARIABLE, new XsltIntroduceVariableAction(), full); install(INTRODUCE_PARAMETER, new XsltIntroduceParameterAction(), full); install(INLINE, new XsltInlineAction(), full); install(EXTRACT_METHOD, new XsltExtractTemplateAction(), full); myInstalled = true; } @SuppressWarnings({"RawUseOfParameterizedType"}) private void install(String actionName, XsltRefactoringActionBase newAction, boolean full) { final ActionManagerEx amgr = ActionManagerEx.getInstanceEx(); final AnAction action = amgr.getAction(actionName); if (action != null) { newAction.setHookedAction(action); if (full) { fullInstall(action, newAction, amgr); } amgr.unregisterAction(actionName); } amgr.registerAction(actionName, newAction); myActions.put(actionName, newAction); } private void fullInstall(AnAction action, AnAction newAction, ActionManagerEx amgr) { final AnAction menu = amgr.getAction(REFACTORING_MENU_ID); if (menu instanceof DefaultActionGroup) { final DefaultActionGroup actionGroup = ((DefaultActionGroup)menu); final AnAction[] children = actionGroup.getChildren(null); for (int i = 0; i < children.length; i++) { final AnAction child = children[i]; if (child == action) { if (!(child instanceof HookedAction)) { replaceAction(child, i, newAction, actionGroup, amgr); } break; } } } } private void uninstall(boolean full) { LOG.assertTrue(myInstalled); final ActionManagerEx amgr = ActionManagerEx.getInstanceEx(); final Set<String> actionNames = myActions.keySet(); for (String name : actionNames) { final AnAction action = amgr.getAction(name); if (action == myActions.get(name)) { final AnAction origAction = ((HookedAction)action).getHookedAction(); if (full) { fullUninstall(action, origAction, amgr); } amgr.unregisterAction(name); amgr.registerAction(name, origAction); } else { LOG.info("Cannot uninstall action '" + name + "'. It has been hooked by another action: " + action.getClass().getName()); } } myActions.clear(); myInstalled = false; } private void fullUninstall(AnAction action, AnAction origAction, ActionManagerEx amgr) { final AnAction menu = amgr.getAction(REFACTORING_MENU_ID); if (menu instanceof DefaultActionGroup) { final DefaultActionGroup actionGroup = ((DefaultActionGroup)menu); final AnAction[] children = actionGroup.getChildren(null); for (int i = 0; i < children.length; i++) { final AnAction child = children[i]; if (child == action) { replaceAction(child, i, origAction, actionGroup, amgr); break; } } } } private static void replaceAction(AnAction child, int i, AnAction newAction, DefaultActionGroup actionGroup, ActionManager amgr) { AnAction[] children = actionGroup.getChildren(null); actionGroup.remove(child); final Constraints constraint; if (i == 0) { constraint = new Constraints(Anchor.FIRST, null); } else { final AnAction prevChild = children[i - 1]; if (prevChild instanceof Separator) { if (i < children.length - 1) { constraint = new Constraints(Anchor.BEFORE, amgr.getId(children[i + 1])); } else { constraint = new Constraints(Anchor.LAST, null); } } else { constraint = new Constraints(Anchor.AFTER, amgr.getId(prevChild)); } } actionGroup.add(newAction, constraint); } public static XsltRefactoringSupport getInstance() { return ApplicationManager.getApplication().getComponent(XsltRefactoringSupport.class); } }
plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/refactoring/XsltRefactoringSupport.java
/* * Copyright 2005 Sascha Weinreuter * * 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.intellij.lang.xpath.xslt.refactoring; import org.intellij.lang.xpath.xslt.XsltConfig; import org.intellij.lang.xpath.xslt.refactoring.extractTemplate.XsltExtractTemplateAction; import org.intellij.lang.xpath.xslt.refactoring.introduceParameter.XsltIntroduceParameterAction; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.ActionManagerEx; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.diagnostic.Logger; import org.jetbrains.annotations.NotNull; import java.util.HashMap; import java.util.Map; import java.util.Set; public class XsltRefactoringSupport implements ApplicationComponent { private static final Logger LOG = Logger.getInstance("org.intellij.lang.xpath.xslt.refactoring.XsltRefactoringSupport"); private static final String REFACTORING_MENU_ID = "RefactoringMenu"; // private static final String INTRODUCE_VARIABLE = "IntroduceVariable"; private static final String INTRODUCE_PARAMETER = "IntroduceParameter"; private static final String EXTRACT_METHOD = "ExtractMethod"; private static final String INLINE = "Inline"; private final XsltConfig myConfig; private final Map<String, HookedAction> myActions = new HashMap<String, HookedAction>(); private boolean myInstalled; public XsltRefactoringSupport(XsltConfig config) { myConfig = config; } @NotNull public String getComponentName() { return "XsltRefactoringSupport.Installer"; } public void initComponent() { if (myConfig.isEnabled()) { install(false); } } public void disposeComponent() { if (myInstalled) { uninstall(false); } } public void setEnabled(boolean b) { if (!myInstalled && b) { install(true); } else if (myInstalled && !b) { uninstall(true); } } private void install(boolean full) { LOG.assertTrue(!myInstalled); // install(INTRODUCE_VARIABLE, new XsltIntroduceVariableAction(), full); install(INTRODUCE_PARAMETER, new XsltIntroduceParameterAction(), full); install(INLINE, new XsltInlineAction(), full); install(EXTRACT_METHOD, new XsltExtractTemplateAction(), full); myInstalled = true; } @SuppressWarnings({"RawUseOfParameterizedType"}) private void install(String actionName, XsltRefactoringActionBase newAction, boolean full) { final ActionManagerEx amgr = ActionManagerEx.getInstanceEx(); final AnAction action = amgr.getAction(actionName); newAction.setHookedAction(action); if (full) { fullInstall(action, newAction, amgr); } amgr.unregisterAction(actionName); amgr.registerAction(actionName, newAction); myActions.put(actionName, newAction); } private void fullInstall(AnAction action, AnAction newAction, ActionManagerEx amgr) { final AnAction menu = amgr.getAction(REFACTORING_MENU_ID); if (menu instanceof DefaultActionGroup) { final DefaultActionGroup actionGroup = ((DefaultActionGroup)menu); final AnAction[] children = actionGroup.getChildren(null); for (int i = 0; i < children.length; i++) { final AnAction child = children[i]; if (child == action) { if (!(child instanceof HookedAction)) { replaceAction(child, i, newAction, actionGroup, amgr); } break; } } } } private void uninstall(boolean full) { LOG.assertTrue(myInstalled); final ActionManagerEx amgr = ActionManagerEx.getInstanceEx(); final Set<String> actionNames = myActions.keySet(); for (String name : actionNames) { final AnAction action = amgr.getAction(name); if (action == myActions.get(name)) { final AnAction origAction = ((HookedAction)action).getHookedAction(); if (full) { fullUninstall(action, origAction, amgr); } amgr.unregisterAction(name); amgr.registerAction(name, origAction); } else { LOG.info("Cannot uninstall action '" + name + "'. It has been hooked by another action: " + action.getClass().getName()); } } myActions.clear(); myInstalled = false; } private void fullUninstall(AnAction action, AnAction origAction, ActionManagerEx amgr) { final AnAction menu = amgr.getAction(REFACTORING_MENU_ID); if (menu instanceof DefaultActionGroup) { final DefaultActionGroup actionGroup = ((DefaultActionGroup)menu); final AnAction[] children = actionGroup.getChildren(null); for (int i = 0; i < children.length; i++) { final AnAction child = children[i]; if (child == action) { replaceAction(child, i, origAction, actionGroup, amgr); break; } } } } private static void replaceAction(AnAction child, int i, AnAction newAction, DefaultActionGroup actionGroup, ActionManager amgr) { AnAction[] children = actionGroup.getChildren(null); actionGroup.remove(child); final Constraints constraint; if (i == 0) { constraint = new Constraints(Anchor.FIRST, null); } else { final AnAction prevChild = children[i - 1]; if (prevChild instanceof Separator) { if (i < children.length - 1) { constraint = new Constraints(Anchor.BEFORE, amgr.getId(children[i + 1])); } else { constraint = new Constraints(Anchor.LAST, null); } } else { constraint = new Constraints(Anchor.AFTER, amgr.getId(prevChild)); } } actionGroup.add(newAction, constraint); } public static XsltRefactoringSupport getInstance() { return ApplicationManager.getApplication().getComponent(XsltRefactoringSupport.class); } }
correctly handling nall actions
plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/refactoring/XsltRefactoringSupport.java
correctly handling nall actions
<ide><path>lugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/refactoring/XsltRefactoringSupport.java <ide> final ActionManagerEx amgr = ActionManagerEx.getInstanceEx(); <ide> <ide> final AnAction action = amgr.getAction(actionName); <del> newAction.setHookedAction(action); <add> if (action != null) { <add> newAction.setHookedAction(action); <ide> <del> if (full) { <del> fullInstall(action, newAction, amgr); <add> if (full) { <add> fullInstall(action, newAction, amgr); <add> } <add> <add> amgr.unregisterAction(actionName); <ide> } <del> <del> amgr.unregisterAction(actionName); <ide> amgr.registerAction(actionName, newAction); <ide> myActions.put(actionName, newAction); <ide> }
Java
lgpl-2.1
7bca41af32c6dd6392ca32d1e6ee94be07351b03
0
xwiki/xwiki-commons,xwiki/xwiki-commons
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.extension.repository.internal; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.io.IOUtils; import org.xwiki.extension.Extension; import org.xwiki.extension.ExtensionDependency; import org.xwiki.extension.ExtensionException; import org.xwiki.extension.LocalExtension; import org.xwiki.extension.repository.ExtensionRepository; public class DefaultLocalExtension implements LocalExtension { private File file; private boolean enabled = true; private boolean isDependency; private String id; private String version; private String type; private String description; private String author; private String website; private List<ExtensionDependency> dependencies = new ArrayList<ExtensionDependency>(); private DefaultLocalExtensionRepository repository; public DefaultLocalExtension(DefaultLocalExtensionRepository repository, String id, String version, String type) { this.repository = repository; this.id = id; this.version = version; this.type = type; } public DefaultLocalExtension(DefaultLocalExtensionRepository repository, Extension extension) { this(repository, extension.getId(), extension.getVersion(), extension.getType()); this.dependencies.addAll(extension.getDependencies()); setDescription(extension.getDescription()); setAuthor(extension.getAuthor()); setWebsite(extension.getWebSite()); } public void setFile(File file) { this.file = file; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public void setDependency(boolean isDependency) { this.isDependency = isDependency; } // Extension public void setDescription(String description) { this.description = description; } public void setAuthor(String author) { this.author = author; } public void setWebsite(String website) { this.website = website; } public void download(File file) throws ExtensionException { InputStream sourceStream = null; OutputStream targetStream = null; try { sourceStream = new FileInputStream(getFile()); targetStream = new FileOutputStream(file); IOUtils.copy(sourceStream, targetStream); } catch (Exception e) { throw new ExtensionException("Failed to copy file", e); } finally { IOException closeException = null; if (sourceStream != null) { try { sourceStream.close(); } catch (IOException e) { closeException = e; } } if (targetStream != null) { try { targetStream.close(); } catch (IOException e) { closeException = e; } } if (closeException != null) { throw new ExtensionException("Failed to close file", closeException); } } } public String getId() { return this.id; } public String getVersion() { return this.version; } public String getType() { return this.type; } public String getDescription() { return this.description; } public String getAuthor() { return this.author; } public String getWebSite() { return this.website; } public void addDependency(ExtensionDependency dependency) { this.dependencies.add(dependency); } public List<ExtensionDependency> getDependencies() { return Collections.unmodifiableList(this.dependencies); } public ExtensionRepository getRepository() { return this.repository; } // LocalExtension public File getFile() { return this.file; } public boolean isEnabled() { return this.enabled; } public boolean isDependency() { return this.isDependency; } @Override public String toString() { return getId() + '-' + getVersion(); } }
xwiki-commons-core/xwiki-commons-extension/src/main/java/org/xwiki/extension/repository/internal/DefaultLocalExtension.java
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.extension.repository.internal; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.log4j.lf5.util.StreamUtils; import org.xwiki.extension.Extension; import org.xwiki.extension.ExtensionDependency; import org.xwiki.extension.ExtensionException; import org.xwiki.extension.LocalExtension; import org.xwiki.extension.repository.ExtensionRepository; public class DefaultLocalExtension implements LocalExtension { private File file; private boolean enabled = true; private boolean isDependency; private String id; private String version; private String type; private String description; private String author; private String website; private List<ExtensionDependency> dependencies = new ArrayList<ExtensionDependency>(); private DefaultLocalExtensionRepository repository; public DefaultLocalExtension(DefaultLocalExtensionRepository repository, String id, String version, String type) { this.repository = repository; this.id = id; this.version = version; this.type = type; } public DefaultLocalExtension(DefaultLocalExtensionRepository repository, Extension extension) { this(repository, extension.getId(), extension.getVersion(), extension.getType()); this.dependencies.addAll(extension.getDependencies()); setDescription(extension.getDescription()); setAuthor(extension.getAuthor()); setWebsite(extension.getWebSite()); } public void setFile(File file) { this.file = file; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public void setDependency(boolean isDependency) { this.isDependency = isDependency; } // Extension public void setDescription(String description) { this.description = description; } public void setAuthor(String author) { this.author = author; } public void setWebsite(String website) { this.website = website; } public void download(File file) throws ExtensionException { InputStream sourceStream = null; OutputStream targetStream = null; try { sourceStream = new FileInputStream(getFile()); targetStream = new FileOutputStream(file); StreamUtils.copy(sourceStream, targetStream); } catch (Exception e) { throw new ExtensionException("Failed to copy file", e); } finally { IOException closeException = null; if (sourceStream != null) { try { sourceStream.close(); } catch (IOException e) { closeException = e; } } if (targetStream != null) { try { targetStream.close(); } catch (IOException e) { closeException = e; } } if (closeException != null) { throw new ExtensionException("Failed to close file", closeException); } } } public String getId() { return this.id; } public String getVersion() { return this.version; } public String getType() { return this.type; } public String getDescription() { return this.description; } public String getAuthor() { return this.author; } public String getWebSite() { return this.website; } public void addDependency(ExtensionDependency dependency) { this.dependencies.add(dependency); } public List<ExtensionDependency> getDependencies() { return Collections.unmodifiableList(this.dependencies); } public ExtensionRepository getRepository() { return this.repository; } // LocalExtension public File getFile() { return this.file; } public boolean isEnabled() { return this.enabled; } public boolean isDependency() { return this.isDependency; } @Override public String toString() { return getId() + '-' + getVersion(); } }
[misc] Exclude log4j coming with aether (logging implementation to use is distribution choice) Fix code that was using the wrong class (log4j one instead of commons io) git-svn-id: d23d7a6431d93e1bdd218a46658458610974b053@31749 f329d543-caf0-0310-9063-dda96c69346f
xwiki-commons-core/xwiki-commons-extension/src/main/java/org/xwiki/extension/repository/internal/DefaultLocalExtension.java
[misc] Exclude log4j coming with aether (logging implementation to use is distribution choice) Fix code that was using the wrong class (log4j one instead of commons io)
<ide><path>wiki-commons-core/xwiki-commons-extension/src/main/java/org/xwiki/extension/repository/internal/DefaultLocalExtension.java <ide> import java.util.Collections; <ide> import java.util.List; <ide> <del>import org.apache.log4j.lf5.util.StreamUtils; <add>import org.apache.commons.io.IOUtils; <ide> import org.xwiki.extension.Extension; <ide> import org.xwiki.extension.ExtensionDependency; <ide> import org.xwiki.extension.ExtensionException; <ide> this(repository, extension.getId(), extension.getVersion(), extension.getType()); <ide> <ide> this.dependencies.addAll(extension.getDependencies()); <del> <add> <ide> setDescription(extension.getDescription()); <ide> setAuthor(extension.getAuthor()); <ide> setWebsite(extension.getWebSite()); <ide> sourceStream = new FileInputStream(getFile()); <ide> targetStream = new FileOutputStream(file); <ide> <del> StreamUtils.copy(sourceStream, targetStream); <add> IOUtils.copy(sourceStream, targetStream); <ide> } catch (Exception e) { <ide> throw new ExtensionException("Failed to copy file", e); <ide> } finally {
Java
mit
382d37f8fa38c1f4ff45cba59322dc880fbd38d7
0
Akhier/Java-DijkstraAlgorithm
/** * "Edge" represents a connection between one point to another including the cost of traversing this connection * @author Akhier Dragonheart * @version 1.0 */ public class Edge { public Integer cost; private static int edgeIdCount = -1; private int edgeId; public int edgeId() { return edgeId; } private Vector2D pointA, pointB; /** * The first point this Edge is connected to * @return Vector2D 'pointA' */ public Vector2D pointA() { return pointA; } /** * The second point this Edge is connected to * @return Vector2D 'pointB */ public Vector2D pointB() { return pointB; } /** * @param pointa is a Vector2D for the first point the Edge connects to * @param pointb is a Vector2D for the second point the Edge connects to * @param cost is how much it costs to traverse this Edge */ public Edge(Vector2D pointa, Vector2D pointb, int cost) { this.cost = cost; pointA = pointa; pointB = pointb; edgeId = ++edgeIdCount; } /** * Gets the Vector2D of the other side of the Edge to the provided Vector2D * @param basevector is the starting Vector2D * @return Vector2D that is either the other Vector2D to the edge or null if the provided Vector2D is not in the Edge */ public Vector2D getOtherVector(Vector2D basevector) { if(basevector == pointA) { return pointB; } else if (basevector == pointB) { return pointA; } else { return null; } } @Override public String toString() { return "Edge ID: " + edgeId + " - Connected to vectors " + pointA.vectorId() + " and " + pointB.vectorId() + " at a cost of " + cost; } /** * @param otheredge is the Edge to compare the current Edge to * @return int which is 0 if the Edge costs are equal, less if this Edge's cost is lower, and more if this Edge's cost is higher */ public int compareTo(Edge otheredge) { return cost.compareTo(otheredge.cost); } }
Edge.java
/** * @author Akhier Dragonheart * @version 1.0 */ public class Edge { public Integer cost; private static int edgeIdCount = -1; private int edgeId; public int edgeId() { return edgeId; } private Vector2D pointA, pointB; public Vector2D pointA() { return pointA; } public Vector2D pointB() { return pointB; } public Edge(Vector2D pointa, Vector2D pointb, int cost) { this.cost = cost; pointA = pointa; pointB = pointb; edgeId = ++edgeIdCount; } public Vector2D getOtherVector(Vector2D basevector) { if(basevector == pointA) { return pointB; } else if (basevector == pointB) { return pointA; } else { return null; } } @Override public String toString() { return "Edge ID: " + edgeId + " - Connected to vectors " + pointA.vectorId() + " and " + pointB.vectorId() + " at a cost of " + cost; } public int compareTo(Edge otheredge) { return cost.compareTo(otheredge.cost); } }
Added comments to Edge
Edge.java
Added comments to Edge
<ide><path>dge.java <ide> /** <add> * "Edge" represents a connection between one point to another including the cost of traversing this connection <ide> * @author Akhier Dragonheart <ide> * @version 1.0 <ide> */ <ide> } <ide> <ide> private Vector2D pointA, pointB; <add> /** <add> * The first point this Edge is connected to <add> * @return Vector2D 'pointA' <add> */ <ide> public Vector2D pointA() { <ide> return pointA; <ide> } <add> /** <add> * The second point this Edge is connected to <add> * @return Vector2D 'pointB <add> */ <ide> public Vector2D pointB() { <ide> return pointB; <ide> } <ide> <add> /** <add> * @param pointa is a Vector2D for the first point the Edge connects to <add> * @param pointb is a Vector2D for the second point the Edge connects to <add> * @param cost is how much it costs to traverse this Edge <add> */ <ide> public Edge(Vector2D pointa, Vector2D pointb, int cost) { <ide> this.cost = cost; <ide> pointA = pointa; <ide> edgeId = ++edgeIdCount; <ide> } <ide> <add> /** <add> * Gets the Vector2D of the other side of the Edge to the provided Vector2D <add> * @param basevector is the starting Vector2D <add> * @return Vector2D that is either the other Vector2D to the edge or null if the provided Vector2D is not in the Edge <add> */ <ide> public Vector2D getOtherVector(Vector2D basevector) { <ide> if(basevector == pointA) { <ide> return pointB; <ide> return "Edge ID: " + edgeId + " - Connected to vectors " + pointA.vectorId() + " and " + pointB.vectorId() + " at a cost of " + cost; <ide> } <ide> <add> /** <add> * @param otheredge is the Edge to compare the current Edge to <add> * @return int which is 0 if the Edge costs are equal, less if this Edge's cost is lower, and more if this Edge's cost is higher <add> */ <ide> public int compareTo(Edge otheredge) { <ide> return cost.compareTo(otheredge.cost); <ide> }
Java
agpl-3.0
a959c01d18b88db2068c33fdcf915dede6c7e212
0
opencadc/ac,opencadc/ac
/* ************************************************************************ ******************* CANADIAN ASTRONOMY DATA CENTRE ******************* ************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES ************** * * (c) 2014. (c) 2014. * Government of Canada Gouvernement du Canada * National Research Council Conseil national de recherches * Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6 * All rights reserved Tous droits réservés * * NRC disclaims any warranties, Le CNRC dénie toute garantie * expressed, implied, or énoncée, implicite ou légale, * statutory, of any kind with de quelque nature que ce * respect to the software, soit, concernant le logiciel, * including without limitation y compris sans restriction * any warranty of merchantability toute garantie de valeur * or fitness for a particular marchande ou de pertinence * purpose. NRC shall not be pour un usage particulier. * liable in any event for any Le CNRC ne pourra en aucun cas * damages, whether direct or être tenu responsable de tout * indirect, special or general, dommage, direct ou indirect, * consequential or incidental, particulier ou général, * arising from the use of the accessoire ou fortuit, résultant * software. Neither the name de l'utilisation du logiciel. Ni * of the National Research le nom du Conseil National de * Council of Canada nor the Recherches du Canada ni les noms * names of its contributors may de ses participants ne peuvent * be used to endorse or promote être utilisés pour approuver ou * products derived from this promouvoir les produits dérivés * software without specific prior de ce logiciel sans autorisation * written permission. préalable et particulière * par écrit. * * This file is part of the Ce fichier fait partie du projet * OpenCADC project. OpenCADC. * * OpenCADC is free software: OpenCADC est un logiciel libre ; * you can redistribute it and/or vous pouvez le redistribuer ou le * modify it under the terms of modifier suivant les termes de * the GNU Affero General Public la “GNU Affero General Public * License as published by the License” telle que publiée * Free Software Foundation, par la Free Software Foundation * either version 3 of the : soit la version 3 de cette * License, or (at your option) licence, soit (à votre gré) * any later version. toute version ultérieure. * * OpenCADC is distributed in the OpenCADC est distribué * hope that it will be useful, dans l’espoir qu’il vous * but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE * without even the implied GARANTIE : sans même la garantie * warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ * or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF * PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence * General Public License for Générale Publique GNU Affero * more details. pour plus de détails. * * You should have received Vous devriez avoir reçu une * a copy of the GNU Affero copie de la Licence Générale * General Public License along Publique GNU Affero avec * with OpenCADC. If not, see OpenCADC ; si ce n’est * <http://www.gnu.org/licenses/>. pas le cas, consultez : * <http://www.gnu.org/licenses/>. * * $Revision: 4 $ * ************************************************************************ */ package ca.nrc.cadc.ac.json; import ca.nrc.cadc.ac.ReaderException; import ca.nrc.cadc.ac.User; import ca.nrc.cadc.ac.UserRequest; import org.json.JSONException; import org.json.JSONObject; import java.io.*; import java.security.Principal; import java.util.Scanner; public class UserRequestReader { /** * Construct a UserRequest from an JSON String source. * * @param json String of the JSON. * @return UserRequest UserRequest. * @throws IOException */ public static UserRequest<Principal> read(String json) throws IOException { if (json == null) { throw new IllegalArgumentException("JSON must not be null"); } else { try { return parseUserRequest(new JSONObject(json)); } catch (JSONException e) { String error = "Unable to parse JSON to User because " + e.getMessage(); throw new ReaderException(error, e); } } } /** * Construct a User from a InputStream. * * @param in InputStream. * @return User User. * @throws ReaderException * @throws IOException */ public static UserRequest<Principal> read(InputStream in) throws IOException { if (in == null) { throw new IOException("stream closed"); } Scanner s = new Scanner(in).useDelimiter("\\A"); String json = s.hasNext() ? s.next() : ""; return read(json); } /** * Construct a User from a Reader. * * @param reader Reader. * @return User User. * @throws ReaderException * @throws IOException */ public static UserRequest<Principal> read(Reader reader) throws IOException { if (reader == null) { throw new IllegalArgumentException("reader must not be null"); } Scanner s = new Scanner(reader).useDelimiter("\\A"); String json = s.hasNext() ? s.next() : ""; return read(json); } protected static UserRequest<Principal> parseUserRequest( JSONObject userRequestObject) throws ReaderException, JSONException { final User<Principal> user = ca.nrc.cadc.ac.json.UserReader.parseUser( userRequestObject.getJSONObject("user")); return new UserRequest<Principal>(user, userRequestObject. getString("password")); } }
projects/cadcAccessControl/src/ca/nrc/cadc/ac/json/UserRequestReader.java
/* ************************************************************************ ******************* CANADIAN ASTRONOMY DATA CENTRE ******************* ************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES ************** * * (c) 2014. (c) 2014. * Government of Canada Gouvernement du Canada * National Research Council Conseil national de recherches * Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6 * All rights reserved Tous droits réservés * * NRC disclaims any warranties, Le CNRC dénie toute garantie * expressed, implied, or énoncée, implicite ou légale, * statutory, of any kind with de quelque nature que ce * respect to the software, soit, concernant le logiciel, * including without limitation y compris sans restriction * any warranty of merchantability toute garantie de valeur * or fitness for a particular marchande ou de pertinence * purpose. NRC shall not be pour un usage particulier. * liable in any event for any Le CNRC ne pourra en aucun cas * damages, whether direct or être tenu responsable de tout * indirect, special or general, dommage, direct ou indirect, * consequential or incidental, particulier ou général, * arising from the use of the accessoire ou fortuit, résultant * software. Neither the name de l'utilisation du logiciel. Ni * of the National Research le nom du Conseil National de * Council of Canada nor the Recherches du Canada ni les noms * names of its contributors may de ses participants ne peuvent * be used to endorse or promote être utilisés pour approuver ou * products derived from this promouvoir les produits dérivés * software without specific prior de ce logiciel sans autorisation * written permission. préalable et particulière * par écrit. * * This file is part of the Ce fichier fait partie du projet * OpenCADC project. OpenCADC. * * OpenCADC is free software: OpenCADC est un logiciel libre ; * you can redistribute it and/or vous pouvez le redistribuer ou le * modify it under the terms of modifier suivant les termes de * the GNU Affero General Public la “GNU Affero General Public * License as published by the License” telle que publiée * Free Software Foundation, par la Free Software Foundation * either version 3 of the : soit la version 3 de cette * License, or (at your option) licence, soit (à votre gré) * any later version. toute version ultérieure. * * OpenCADC is distributed in the OpenCADC est distribué * hope that it will be useful, dans l’espoir qu’il vous * but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE * without even the implied GARANTIE : sans même la garantie * warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ * or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF * PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence * General Public License for Générale Publique GNU Affero * more details. pour plus de détails. * * You should have received Vous devriez avoir reçu une * a copy of the GNU Affero copie de la Licence Générale * General Public License along Publique GNU Affero avec * with OpenCADC. If not, see OpenCADC ; si ce n’est * <http://www.gnu.org/licenses/>. pas le cas, consultez : * <http://www.gnu.org/licenses/>. * * $Revision: 4 $ * ************************************************************************ */ package ca.nrc.cadc.ac.json; import ca.nrc.cadc.ac.ReaderException; import ca.nrc.cadc.ac.User; import ca.nrc.cadc.ac.UserRequest; import org.json.JSONException; import org.json.JSONObject; import java.io.*; import java.security.Principal; import java.util.Scanner; public class UserRequestReader { /** * Construct a UserRequest from an JSON String source. * * @param json String of the JSON. * @return UserRequest UserRequest. * @throws IOException */ public static UserRequest<Principal> read(String json) throws IOException { if (json == null) { throw new IllegalArgumentException("XML must not be null"); } else { try { return parseUserRequest(new JSONObject(json)); } catch (JSONException e) { String error = "Unable to parse JSON to User because " + e.getMessage(); throw new ReaderException(error, e); } } } /** * Construct a User from a InputStream. * * @param in InputStream. * @return User User. * @throws ReaderException * @throws IOException */ public static UserRequest<Principal> read(InputStream in) throws IOException { if (in == null) { throw new IOException("stream closed"); } Scanner s = new Scanner(in).useDelimiter("\\A"); String json = s.hasNext() ? s.next() : ""; return read(json); } /** * Construct a User from a Reader. * * @param reader Reader. * @return User User. * @throws ReaderException * @throws IOException */ public static UserRequest<Principal> read(Reader reader) throws IOException { if (reader == null) { throw new IllegalArgumentException("reader must not be null"); } Scanner s = new Scanner(reader).useDelimiter("\\A"); String json = s.hasNext() ? s.next() : ""; return read(json); } protected static UserRequest<Principal> parseUserRequest( JSONObject userRequestObject) throws ReaderException, JSONException { final User<Principal> user = ca.nrc.cadc.ac.json.UserReader.parseUser( userRequestObject.getJSONObject("user")); return new UserRequest<Principal>(user, userRequestObject. getString("password")); } }
AC2: Code cleanup and comment correction.
projects/cadcAccessControl/src/ca/nrc/cadc/ac/json/UserRequestReader.java
AC2: Code cleanup and comment correction.
<ide><path>rojects/cadcAccessControl/src/ca/nrc/cadc/ac/json/UserRequestReader.java <ide> { <ide> if (json == null) <ide> { <del> throw new IllegalArgumentException("XML must not be null"); <add> throw new IllegalArgumentException("JSON must not be null"); <ide> } <ide> else <ide> {