diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/src/com/jjw/addressbook/pojo/Person.java b/src/com/jjw/addressbook/pojo/Person.java index 79813a8..3666a46 100644 --- a/src/com/jjw/addressbook/pojo/Person.java +++ b/src/com/jjw/addressbook/pojo/Person.java @@ -1,123 +1,122 @@ package com.jjw.addressbook.pojo; public class Person { private String myName; private String myAddress; private String myCity; private String myState; private String myPhoneNumber; /** * Default constructor */ public Person() { } /** * Constructor used to initialize all values * * @param name * @param address * @param city * @param state * @param phoneNumber */ public Person(String name, String address, String city, String state, String phoneNumber) { - super(); myName = name; myAddress = address; myCity = city; myState = state; myPhoneNumber = phoneNumber; } /** * @return the name */ public String getName() { return myName; } /** * @param name the name to set */ public void setName(String name) { myName = name; } /** * @return the address */ public String getAddress() { return myAddress; } /** * @param address the address to set */ public void setAddress(String address) { myAddress = address; } /** * @return the city */ public String getCity() { return myCity; } /** * @param city the city to set */ public void setCity(String city) { myCity = city; } /** * @return the state */ public String getState() { return myState; } /** * @param state the state to set */ public void setState(String state) { myState = state; } /** * @return the phoneNumber */ public String getPhoneNumber() { return myPhoneNumber; } /** * @param phoneNumber the phoneNumber to set */ public void setPhoneNumber(String phoneNumber) { myPhoneNumber = phoneNumber; } @Override public String toString() { return "name: " + myName + ", address: " + myAddress + ", city: " + myCity + ", state: " + myState + ", phoneNumber: " + myPhoneNumber; } }
true
true
public Person(String name, String address, String city, String state, String phoneNumber) { super(); myName = name; myAddress = address; myCity = city; myState = state; myPhoneNumber = phoneNumber; }
public Person(String name, String address, String city, String state, String phoneNumber) { myName = name; myAddress = address; myCity = city; myState = state; myPhoneNumber = phoneNumber; }
diff --git a/src/org/openstreetmap/josm/actions/SaveAction.java b/src/org/openstreetmap/josm/actions/SaveAction.java index 76668ec5..d0a4a0b9 100644 --- a/src/org/openstreetmap/josm/actions/SaveAction.java +++ b/src/org/openstreetmap/josm/actions/SaveAction.java @@ -1,41 +1,43 @@ // License: GPL. Copyright 2007 by Immanuel Scholz and others package org.openstreetmap.josm.actions; import static org.openstreetmap.josm.tools.I18n.tr; import java.awt.event.KeyEvent; import java.io.File; import org.openstreetmap.josm.Main; import org.openstreetmap.josm.gui.layer.Layer; import org.openstreetmap.josm.gui.layer.GpxLayer; import org.openstreetmap.josm.gui.ExtendedDialog; import org.openstreetmap.josm.tools.Shortcut; /** * Export the data as an OSM xml file. * * @author imi */ public class SaveAction extends SaveActionBase { /** * Construct the action with "Save" as label. * @param layer Save this layer. */ public SaveAction(Layer layer) { super(tr("Save"), "save", tr("Save the current data."), Shortcut.registerShortcut("system:save", tr("File: {0}", tr("Save")), KeyEvent.VK_S, Shortcut.GROUP_MENU), layer); } @Override public File getFile(Layer layer) { File f = layer.getAssociatedFile(); - if(f != null && layer instanceof GpxLayer && f.exists() && 1 != + if(f != null && ! f.exists()) + f=null; + if(f != null && layer instanceof GpxLayer && 1 != new ExtendedDialog(Main.parent, tr("Overwrite"), tr("File {0} exists. Overwrite?", f.getName()), new String[] {tr("Overwrite"), tr("Cancel")}, new String[] {"save_as.png", "cancel.png"}).getValue()) f = null; return f == null ? openFileDialog(layer) : f; } }
true
true
@Override public File getFile(Layer layer) { File f = layer.getAssociatedFile(); if(f != null && layer instanceof GpxLayer && f.exists() && 1 != new ExtendedDialog(Main.parent, tr("Overwrite"), tr("File {0} exists. Overwrite?", f.getName()), new String[] {tr("Overwrite"), tr("Cancel")}, new String[] {"save_as.png", "cancel.png"}).getValue()) f = null; return f == null ? openFileDialog(layer) : f; }
@Override public File getFile(Layer layer) { File f = layer.getAssociatedFile(); if(f != null && ! f.exists()) f=null; if(f != null && layer instanceof GpxLayer && 1 != new ExtendedDialog(Main.parent, tr("Overwrite"), tr("File {0} exists. Overwrite?", f.getName()), new String[] {tr("Overwrite"), tr("Cancel")}, new String[] {"save_as.png", "cancel.png"}).getValue()) f = null; return f == null ? openFileDialog(layer) : f; }
diff --git a/ecologylab/net/ParsedURL.java b/ecologylab/net/ParsedURL.java index 0ec7cf1e..e7407b01 100644 --- a/ecologylab/net/ParsedURL.java +++ b/ecologylab/net/ParsedURL.java @@ -1,1427 +1,1428 @@ package ecologylab.net; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import javax.imageio.ImageIO; import ecologylab.collections.CollectionTools; import ecologylab.generic.Debug; import ecologylab.generic.IntSlot; import ecologylab.generic.StringTools; import ecologylab.io.Files; import ecologylab.xml.ElementState; import ecologylab.xml.TranslationScope; import ecologylab.xml.XMLTranslationException; /** * Extends the URL with many features for the convenience and power of network programmers. * New class for manipulating and displaying URLs. * * Uses lazy evaluation to minimize storage allocation. * * @author andruid * @author eunyee * @author madhur */ public class ParsedURL extends Debug implements MimeType { private static final String NOT_IN_THE_FORMAT_OF_A_WEB_ADDRESS = " is not in the format of a web address"; private static final String DEFAULT_USER_AGENT = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7"; /** * this is the no hash url, that is, the one with # and anything after it stripped out. */ protected URL url = null; /** * If this is built from an entity of the local file system, store * a reference to the object for that here. */ File file; /** * URL with hash, that is, a reference to an anchor within the document. */ protected URL hashUrl = null; /** * Directory that the document referred to by the URL resides in. */ protected URL directory = null; private ParsedURL directoryPURL; /** * String representation of the URL. */ protected String string = null; /** * Shorter version of the string, for printing in tight spaces. */ String shortString; /* lower case of the url string */ protected String lc = null; /* suffix string of the url */ protected String suffix = null; /* domain value string of the ulr */ protected String domain = null; public ParsedURL(URL url) { String hash = url.getRef(); if (hash == null) { this.url = url; this.hashUrl = url; } else { this.hashUrl = url; try { // form no hash url (toss hash) this.url = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile()); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * * @return true if this refers to a file, and that file exists. */ public boolean isNotFileOrExists() { return (file == null) || file.exists(); } /** * Create a ParsedURL from a file. * If the file is a directory, append "/" to the path, so that relative URLs * will be formed properly later. * * @param file */ public ParsedURL(File file) { try { String urlString = "file://"+file.getAbsolutePath(); urlString = urlString.replace('\\', '/'); if (file.isDirectory()) urlString += "/"; this.url = new URL(urlString); } catch (MalformedURLException e) { e.printStackTrace(); } this.file = file; } /* * Constructor with a url string parameter. * get absolute URL with getAbsolute() method. */ /* public ParsedURL(String urlString) { // The second parameter of getAbolute method is error description. this.url = getAbsolute(urlString, "").url(); } */ /////////////////////////////////////////////////////////////////////// /** * Create a PURL from an absolute address. * (Do it the quick and dirty way, providing less error handling.) * NB: Only call this method if you are *sure* a MalformedURlException * would never be produced. * */ public static ParsedURL getAbsolute(String webAddr) { return getAbsolute(webAddr, "getAbsolute(String) "); } /** * Create a PURL from an absolute address. * * @param webAddr url string * @param errorDescriptor which will be printed out in the trace file if there is something happen * converting from the url string to URL. * @return ParsedURL from url string parameter named webAddr, * or null if the param is malformed. */ public static ParsedURL getAbsolute(String webAddr, String errorDescriptor) { if (webAddr == null) { println("ERROR: ParsedURL.getAbsoltute() webAddr = null!"); Thread.dumpStack(); } else { try { URL url = new URL(webAddr); if (isUndetectedMalformedURL(url)) return null; return new ParsedURL(url); } catch (MalformedURLException e) { if (!"".equals(errorDescriptor)) errorDescriptor = "\n" + errorDescriptor; Debug.error(webAddr, NOT_IN_THE_FORMAT_OF_A_WEB_ADDRESS + "." + errorDescriptor); } } return null; } /** * Determines a URL is malformed since Java fails to detect this. * @param url * @return */ private static boolean isUndetectedMalformedURL(URL url) { // originally checked against "file:", but on OS X, we just get "file"; this is probably true everywhere else too, but I will leave "file:" for the time being. -Zach boolean isFileProtocol = url.getProtocol() == "file" || url.getProtocol() == "file:"; String host = url.getHost().trim(); return ((!isFileProtocol && (host == "" || host == "/")) || (isFileProtocol && (url.getPath().trim() != "" || "localhost".equalsIgnoreCase(host)))); } /** * Form a ParsedURL, based on a relative path, using this as the base. * * @param relativeURLPath Path relative to this. * @param errorDescriptor * * @return New ParsedURL based on this and the relative path. */ public final ParsedURL getRelative(String relativeURLPath, String errorDescriptor) { if (isFile()) { File newFile = Files.newFile(file, relativeURLPath); return new ParsedURL(newFile); } else return getRelative(url, relativeURLPath, errorDescriptor); } /** * Form a ParsedURL, based on a relative path, using this as the base. * * @param relativeURLPath Path relative to this. * * @return New ParsedURL based on this and the relative path. */ public final ParsedURL getRelative(String relativeURLPath) { return getRelative(relativeURLPath, ""); } /** * Form a new ParsedURL, relative from a supplied base URL. * Checks to see if the relativePath starts w a protocol spec. * If so, calls getAbsolute(). * Otherwise, forms a relative URL using the URL base. * @param relativeURLPath * @param errorDescriptor * @return New ParsedURL */ public static ParsedURL getRelative(URL base, String relativeURLPath, String errorDescriptor) { if (relativeURLPath == null) return null; ParsedURL result = null; if (!relativeURLPath.startsWith("http://") && !relativeURLPath.startsWith("ftp://")) { try { URL resultURL = new URL(base, relativeURLPath); result = new ParsedURL(resultURL); } catch (MalformedURLException e) { if (!"".equals(errorDescriptor)) errorDescriptor = "\n" + errorDescriptor; Debug.error(relativeURLPath, NOT_IN_THE_FORMAT_OF_A_WEB_ADDRESS + "[" + base + "]." + errorDescriptor); } } else return getAbsolute(relativeURLPath, errorDescriptor); return result; } /** * Use this as the source of stuff to translate from XML * * @param translationSpace Translations that specify package + class names for translating. * @return ElementState object derived from XML at the InputStream of this. * @throws XMLTranslationException */ public ElementState translateFromXML(TranslationScope translationSpace) throws XMLTranslationException { return ElementState.translateFromXML(this, translationSpace); } public static URL getURL(URL base, String path, String error) { // ??? might want to allow this default behaviour ??? if (path == null) return null; try { //System.err.println("\nGENERIC - base, path, error = \n" + base + "\n" + path); URL newURL = new URL(base,path); //System.err.println("\nNEW URL = " + newURL); return newURL; } catch (MalformedURLException e) { if (error != null) throw new Error(e + "\n" + error + " " + base + " -> " + path); return null; } } /** * Uses lazy evaluation to minimize storage allocation. * * @return The URL as a String. */ public String toString() { String result = string; if (result == null) { result = StringTools.pageString(url); string = result; } return result; } /** * Uses lazy evaluation to minimize storage allocation. * * @return Lower case rendition of the URL String. */ public String lc() { String result = lc; if (result == null) { result = toString().toLowerCase(); lc = result; } return result; } /** * Uses lazy evaluation to minimize storage allocation. * * @return The suffix of the filename, in lower case. */ public String suffix() { String result = suffix; if (result == null) { String path = url.getPath(); if (path != null) { result = suffix(path.toLowerCase()); } //TODO make sure that there isnt code somewhere testing suffix for null! if (result == null) result = ""; suffix = result; } return result; } /** * Form a ParsedURL based on this, if this is a directory. * Otherwise, form the ParsedURL from the parent of this. * Process files carefully to propagate their file-ness. * * @return */ public ParsedURL directoryPURL() { ParsedURL result = directoryPURL; if (result == null) { if (isFile()) { if (file.isDirectory()) result = this; else { File parent = file.getParentFile(); result = new ParsedURL(parent); } } else { result = new ParsedURL(directory()); } this.directoryPURL = result; } return result; } /** * Get the URL for the directory associated with this. * Requires looking for slash at the end, looking for a suffix or arguments. * As a result, we sometimes add a slash at the end, sometimes peel off the filename. * Result is cached a la lazy evaluation. * * @return Directory URL */ public URL directory() { URL result = this.directory; if (result == null) { if (StringTools.endsWithSlash(toString())) result = this.url; if (result == null) { String suffix = suffix(); try { String path = url.getPath(); String args = url.getQuery(); String protocol = url.getProtocol(); String host = url.getHost(); int port = url.getPort(); if (suffix.length() == 0) { // this is a directory that is unterminated by slash; we need to fix that if (path.length() == 0) result = new URL(protocol, host, port, "/"); else { if ((args == null) || (args.length() == 0)) result = new URL(protocol, host, port, path + '/'); else // this is a tricky executable with no suffix { // result = null; // drop down into the next block, and peel off that suffix-less executable name } } } // else if (result == null) { // you have a suffix, so we need to trim off the filename int lastSlashIndex = path.lastIndexOf('/'); if (lastSlashIndex == -1) // suffix, but not within any subdirectory result = new URL(protocol, host, port, "/"); else { String pathThroughLastSlash = path.substring(0, lastSlashIndex+1); result = new URL(protocol, host, port, pathThroughLastSlash); } } } catch (MalformedURLException e) { debug("Unexpected ERROR forming directory."); e.printStackTrace(); } } this.directory = result; } return result; } /** * Uses lazy evaluation to minimize storage allocation. * * @return The domain of the URL. */ public String domain() { String result = domain; if (result == null) { result = StringTools.domain(url); domain = result; } return result; } /** * @return The suffix of the filename, in whatever case is found in the input string. */ public static String suffix(String lc) { int afterDot = lc.lastIndexOf('.') + 1; int lastSlash = lc.lastIndexOf('/'); String result = ((afterDot == 0) || (afterDot < lastSlash)) ? "" : lc.substring(afterDot); return result; } /** * Uses lazy evaluation to minimize storage allocation. * * @return the URL. */ public final URL url() { return url; } public final URL hashUrl() { if( hashUrl == null ) return url(); else return hashUrl; } /* * return noAnchor no query page string */ public String noAnchorNoQueryPageString() { String string = toString(); String result = null; if (string != null) { int qIndex = string.indexOf('?'); if (qIndex == -1) { // strip anchor int aIndex = string.indexOf('#'); if (qIndex != -1) result= string.substring(0, aIndex); else result= string; } else // dont worry about stripping anchor cause if it was there, it'd be after ? result = string.substring(0, qIndex); // strip query } return result; } /* * return no anchor no page string. */ public String noAnchorPageString() { return StringTools.noAnchorPageString(url); } /** * @return true if the suffix of this is equal to that of the argument. */ public final boolean hasSuffix(String s) { return lc().endsWith(s); // return suffix().equals(s); } final static String unsupportedMimeStrings[] = { "ai", "bmp", "eps", "ps", "psd", "svg", "tif", "vrml", "doc", "xls", "pps", "ppt", "adp", "rtf", "vbs", "vsd", "wht", "aif", "aiff", "aifc", "au", "mp3", "wav", "ra", "ram", "wm", "wma", "wmf", "wmp", "wms", "wmv", "wmx", "wmz", "avi", "mov", "mpa", "mpeg", "mpg", "ppj", "swf", "spl", "qdb", "cab", "chm", "gzip", "hqx", "jar", "lzh", "tar", "zip", "xml", "xsl", }; final static HashMap unsupportedMimes = CollectionTools.buildHashMapFromStrings(unsupportedMimeStrings); static final String[] unsupportedProtocolStrings = { "mailto", "vbscript", "news", "rtsp", "https", }; static final HashMap unsupportedProtocols = CollectionTools.buildHashMapFromStrings(unsupportedProtocolStrings); static final String[] supportedProtocolStrings = { "http", "ftp", "file", }; static final HashMap supportedProtocols = CollectionTools.buildHashMapFromStrings(supportedProtocolStrings); static final String[] imgSuffixStrings = ImageIO.getReaderFormatNames(); /* { "jpg", "jpeg", "pjpg", "pjpeg", "gif", "png", }; */ static final HashMap imgSuffixMap = CollectionTools.buildHashMapFromLCStrings(imgSuffixStrings); // formats from jdk contain lower & upper case static final String[] jpegMimeStrings = { "jpg", "JPG", "jpeg", "JPEG", "pjpg", "pjpeg", }; static final String[] gifMimeStrings = { "gif", "GIF", }; static final String[] pngMimeStrings = { "png", "PNG", }; static final HashMap jpegSuffixMap = CollectionTools.buildHashMapFromStrings(jpegMimeStrings); static final String[] htmlMimeStrings = { "html", "htm", "stm", "php", "jhtml", "jsp", "asp", "txt", "shtml", "pl", "plx", "exe" }; static final String[] noAlphaMimeStrings = { "bmp", "wbmp","jpg","jpeg", "pjpg","pjpeg" }; static final HashMap noAlphaSuffixMap = CollectionTools.buildHashMapFromStrings(noAlphaMimeStrings); static final HashMap htmlSuffixMap = CollectionTools.buildHashMapFromStrings(htmlMimeStrings); static final String[] pdfMimeStrings = { "pdf" }; static final HashMap pdfSuffixMap = CollectionTools.buildHashMapFromStrings(pdfMimeStrings); static final String[] rssMimeStrings = { "rss", "xml" }; static final HashMap rssSuffixMap = CollectionTools.buildHashMapFromStrings(rssMimeStrings); static final HashMap<String, IntSlot> suffixesToMap = new HashMap<String, IntSlot>(); static { for( int i=0; i<pdfMimeStrings.length; i++ ) CollectionTools.stringIntMapEntry(suffixesToMap, pdfMimeStrings[i], PDF); for( int i=0; i<htmlMimeStrings.length; i++ ) CollectionTools.stringIntMapEntry(suffixesToMap, htmlMimeStrings[i], HTML); for( int i=0; i<rssMimeStrings.length; i++ ) CollectionTools.stringIntMapEntry(suffixesToMap, rssMimeStrings[i], RSS); for( int i=0; i<jpegMimeStrings.length; i++ ) CollectionTools.stringIntMapEntry(suffixesToMap, jpegMimeStrings[i], JPG); for( int i=0; i<gifMimeStrings.length; i++ ) CollectionTools.stringIntMapEntry(suffixesToMap, gifMimeStrings[i], GIF); for( int i=0; i<pngMimeStrings.length; i++ ) CollectionTools.stringIntMapEntry(suffixesToMap, pngMimeStrings[i], PNG); } /** * Called while processing (parsing) HTML. * Used to create new <code>ParsedURL</code>s from urlStrings in * response to such as the <code>a</code> element's <code>href</code> * attribute, the <code>img</code> element's <code>src</code> attribute, * etc. * <p> * Does processing of some fancy stuff, like, in the case of * <code>javascript:</code> URLs, it mines them for embedded absolute * URLs, if possible, and uses only those embedded URLs. * * @param addressString This may be specify a relative or absolute url. * * @return The resulting ParsedURL. It may be null. It will never have * protocol <code>javascript:</code>. */ public ParsedURL createFromHTML(String addressString) { return createFromHTML(addressString, false); } /** * Called while processing (parsing) HTML. * Used to create new <code>ParsedURL</code>s from urlStrings in * response to such as the <code>a</code> element's <code>href</code> * attribute, the <code>img</code> element's <code>src</code> attribute, * etc. * <p> * Does processing of some fancy stuff, like, in the case of * <code>javascript:</code> URLs, it mines them for embedded absolute * URLs, if possible, and uses only those embedded URLs. * * @param addressString This may be specify a relative or absolute url. * * @param fromSearchPage If false, then add <code>/</code> to the end * of the URL if it seems to be a directory. * * @return The resulting ParsedURL. It may be null. It will never have * protocol <code>javascript:</code>. */ public ParsedURL createFromHTML(String addressString, boolean fromSearchPage) { return createFromHTML(this, addressString, fromSearchPage); } protected static ParsedURL get(URL url, String addressString) { try { return new ParsedURL(new URL(url, addressString)); } catch (MalformedURLException e) { println("ParsedURL.get() cant from url from: " + /*url +"\n\taddressString = "+*/ addressString); //e.printStackTrace(); } return null; } /** * Called while processing (parsing) HTML. * Used to create new <code>ParsedURL</code>s from urlStrings in * response to such as the <code>a</code> element's <code>href</code> * attribute, the <code>img</code> element's <code>src</code> attribute, * etc. * <p> * Does processing of some fancy stuff, like, in the case of * <code>javascript:</code> URLs, it mines them for embedded absolute * URLs, if possible, and uses only those embedded URLs. * * @param addressString This may be specify a relative or absolute url. * * @param fromSearchPage If false, then add <code>/</code> to the end * of the URL if it seems to be a directory. * * @return The resulting ParsedURL. It may be null. It will never have * protocol <code>javascript:</code>. */ public static ParsedURL createFromHTML(ParsedURL contextPURL, String addressString, boolean fromSearchPage) { if ((addressString == null) || (addressString.length() == 0)) return null; if( addressString.startsWith("#") ) { //return get(contextPURL.url(), addressString); return null; } String lc = addressString.toLowerCase(); boolean javascript = lc.startsWith("javascript:"); // mine urls from javascript quoted strings if (javascript) { // !!! Could do an even better job here of mining quoted // !!! javascript strings. // println("Container.newURL("+s); int http = lc.lastIndexOf("http://"); // TODO learn to mine PDFs as well as html!! int html = lc.lastIndexOf(".html"); int pdf = lc.lastIndexOf(".pdf"); // println("Container.newURL() checking javascript url:="+s+ // " http="+http+" html="+html); if (http > -1) { // seek absolute web addrs if ((html > -1) && (http < html)) { int end = html + 5; addressString= addressString.substring(http, end); //println("Container.newURL fixed javascript:= " + s); lc = lc.substring(http, end); javascript = false; } else if ((pdf > -1) && (http < pdf)) { int end = pdf + 4; addressString= addressString.substring(http, end); //println("Container.newURL fixed javascript:= " + s); lc = lc.substring(http, end); javascript = false; } } else { // seek relative addresses // need to find the bounds of a quoted string, if there is one } // !!! What we should really do here is find quoted strings // (usually with single quote, but perhaps double as well) // (use regular expressions?? - are they fast enough?) // and look at each one to see if either protocol is supported // or suffix is htmlMime or imgMime. } if (javascript) return null; char argDelim = '?'; // url string always keep hash string. String hashString = StringTools.EMPTY_STRING; if (fromSearchPage) { // handle embedded http:// int lastHttp = addressString.lastIndexOf("http://"); // usually ? but could be & if (lastHttp > 0) { // this is search engine crap addressString = addressString.substring(lastHttp); // debugA("now addressString="+addressString); // handle any embedded args (for google mess) argDelim = '&'; } } else { // TODO do we really need to do any of this??????????????????????? // 1) peel off hash int hashPos = addressString.indexOf('#'); // String hashString= StringTools.EMPTY_STRING; if (hashPos > -1) { hashString = addressString.substring(hashPos); addressString = addressString.substring(0, hashPos); } // 2) peel off args int argPos = addressString.indexOf(argDelim); String argString = StringTools.EMPTY_STRING; if (argPos > -1) { argString = addressString.substring(argPos); addressString = addressString.substring(0, argPos); } - else - { - // 3) if what's left is a directory (w/o a mime type),add slash - int endingSlash = addressString.lastIndexOf('/'); - int lastChar = addressString.length() - 1; - if (endingSlash == -1) - endingSlash++; - if ((lastChar > 0) && - (lastChar != endingSlash) && - (addressString.substring(endingSlash).indexOf('.') == -1)) - addressString += '/'; - } +// This seems uneccessary, crawling any wikimedia based site will break by adding an extra slash. +// else +// { +// // 3) if what's left is a directory (w/o a mime type),add slash +// int endingSlash = addressString.lastIndexOf('/'); +// int lastChar = addressString.length() - 1; +// if (endingSlash == -1) +// endingSlash++; +// if ((lastChar > 0) && +// (lastChar != endingSlash) && +// (addressString.substring(endingSlash).indexOf('.') == -1)) +// addressString += '/'; +// } // 4) put back what we peeled off addressString += argString; addressString += hashString; } int protocolEnd = addressString.indexOf(":"); if (protocolEnd != -1) { // this is an absolute URL; check for supported protocol String protocol = addressString.substring(0, protocolEnd); if (protocolIsUnsupported(protocol)) return null; } ParsedURL parsedUrl; if (contextPURL == null || addressString.startsWith("http://")) { parsedUrl = getAbsolute(addressString, "in createFromHTML()"); } else { ParsedURL directoryPURL = contextPURL.directoryPURL(); parsedUrl = directoryPURL.getRelative(addressString); } return parsedUrl; } /** * * @return A String version of the URL path, in which all punctuation characters have been changed into spaces. */ public String removePunctuation() { return StringTools.removePunctuation(toString()); } /** * @return true if they have same domains. * false if they have different domains. */ public boolean sameDomain(ParsedURL other) { return (other != null) && domain().equals(other.domain()); } /** * @return true if they have same hosts. * false if they have different hosts. */ public boolean sameHost(ParsedURL other) { return (other != null) && url.getHost().equals(other.url().getHost()); } /** * Use unsupportedMimes and protocolIsSupported to determine if this * is content fit for processing. * * @return true if this seems to be a web addr we can crawl to. * (currently that means html). **/ public boolean crawlable() { return protocolIsSupported() && !unsupportedMimes.containsKey(suffix()); } /** * Check whether the protocol is supported or not. * Currently, only http and ftp are. */ public boolean protocolIsSupported() { return (url != null) && protocolIsSupported(url.getProtocol()); } /** * Check whether the protocol is supported or not. * Currently, only http and ftp are. */ public static boolean protocolIsSupported(String protocol) { return supportedProtocols.containsKey(protocol); } /** * Check whether the protocol is supported or not. * Currently, only http and ftp are. */ public boolean protocolIsUnsupported() { return (url != null) && protocolIsUnsupported(url.getProtocol()); } /** * Check whether the protocol is supported or not. * Currently, only http and ftp are. */ public static boolean protocolIsUnsupported(String protocol) { return unsupportedProtocols.containsKey(protocol); } /** * @return true if this is an image file. */ public boolean isImg() { return isImageSuffix(suffix()); } /** * * @param thatSuffix * @return true if the suffix passed in is one for an image type that we can handle. */ public static boolean isImageSuffix(String thatSuffix) { return imgSuffixMap.containsKey(thatSuffix); } /** * @return true if this is a JPEG image file. */ public boolean isJpeg() { return jpegSuffixMap.containsKey(suffix()); } /** * @return true if we can tell the image file wont have alpha, just from its suffix. * This is currently the case for jpeg and bmp. */ public boolean isNoAlpha() { return jpegSuffixMap.containsKey(suffix()); } /** * Test type of document this refers to. * * @return true if this refers to an HTML file */ public boolean isHTML() { return htmlSuffixMap.containsKey(suffix()); } /** * Test type of document this refers to. * * @return true if this refers to a PDF file */ public boolean isPDF() { return pdfSuffixMap.containsKey(suffix()); } /** * Test type of document this refers to. * * @return true if this refers to an RSS feed */ public boolean isRSS() { return rssSuffixMap.containsKey(suffix()); } int mimeIndex = -1; /** * Get MimeType index by seeing suffix(). * * @param parsedURL */ public int mimeIndex() { if( mimeIndex == -1 ) { IntSlot mimeSlot = (IntSlot) suffixesToMap.get(suffix()); mimeIndex = (mimeSlot != null) ? mimeSlot.value : UNKNOWN_MIME; return mimeIndex; } else return mimeIndex; } /** * Get Media MimeType indexes. * Media MimeTypes are currently text and all kinds of images such as JPG, GIF, and PNG. * * @param parsedURL */ public int mediaMimeIndex() { return (mimeIndex()>=MimeType.UNKNOWN_MIME)? MimeType.UNKNOWN_MIME : mimeIndex(); } /* * Check the suffix whether it is in the unsupportedMimes or not. * If it is in the unsupportedMimes, return true, and if it is not, return false. */ public boolean isUnsupported() { return unsupportedMimes.containsKey(suffix()); } /* * return the inverse of isUnsupported(). * Then, if the suffix is in the unsupportedMimes, return false, and if it is not, return true. */ public boolean supportedMime() { return !isUnsupported(); } /** * @return The directory of this, with protocol and host. */ public String directoryString() { String path = pathDirectoryString(); int portNum = url.getPort(); String port = (portNum == -1) ? "" : ":" + portNum; String host = url.getHost(); String protocol = url.getProtocol(); int stringLength = protocol.length() + 3 + host.length() + port.length() + path.length(); StringBuffer buffy = new StringBuffer(stringLength); buffy.append(protocol).append("://").append(host). append(port).append(path); return buffy.toString(); // dont copy; wont reuse buffy } /** * * @return The directory of this, without protocol and host. */ public String pathDirectoryString() { String path = url.getPath(); int lastSlash = path.lastIndexOf("/"); int lastDot = path.lastIndexOf("."); if (lastDot > lastSlash) path = path.substring(0,lastSlash); return path; } /** * Return true if the other object is either a ParsedURL or a URL * that refers to the same location as this. * Note: this is our own implementation. It is *much* faster and slightly less careful than JavaSoft's. * Checks port, host, file, protocol, and query. Ignores ref = hash. */ public boolean equals(Object other) { if (other == null) return false; boolean otherIsPURL = other instanceof ParsedURL; if (!(otherIsPURL || (other instanceof URL))) return false; URL url = this.url; URL otherURL = otherIsPURL ? ((ParsedURL) other).url : (URL) other; // compare port if (url.getPort() != otherURL.getPort()) return false; // compare host if (!bothNullOrEqual(url.getHost(), otherURL.getHost())) return false; // compare file if (!bothNullOrEqual(url.getFile(), otherURL.getFile())) return false; // compare protocol if (!bothNullOrEqual(url.getProtocol(), otherURL.getProtocol())) return false; // compare arguments return bothNullOrEqual(url.getQuery(), otherURL.getQuery()); } private static boolean bothNullOrEqual(String a, String b) { return ((a == b) || // both are null or the same string ((a != null) && a.equals(b))); // now safe to use a.equals() } /** * Hash this by its URL. */ public int hashCode() { return /* (url == null) ? -1 : */ url.hashCode(); } /** * A shorter string for displaing in the modeline for debugging, and * in popup messages. */ public String shortString() { String shortString = this.shortString; if (shortString == null) { URL url = this.url; if (url == null) shortString = "null"; else { String file = url.getFile(); shortString = url.getHost() + "/.../" + file.substring(file.lastIndexOf('/') + 1); } this.shortString = shortString; } return shortString; } /** * True if this ParsedURL represents an entity on the local file system. * @return true if this is a local File object. */ public boolean isFile() { return file != null; } /** * @return The file system object associated with this, if this is an entity on * the local file system, or null, otherwise. */ public File file() { return file; } /** * Form a new ParsedURL from this, and the args passed in. * A question mark is appended to the String form of this, and then args are appended. * * @param args * @return ParsedURL with args after ? */ public ParsedURL withArgs(String args) { try { URL url = new URL(toString() + "?" + args); return new ParsedURL(url); } catch (MalformedURLException e) { return null; } } /** * Returns the name of the file or directory denoted by this abstract pathname. * This is just the last name in the pathname's name sequence. * If the pathname's name sequence is empty, then the empty string is returned. * <p/> * Analagous to File.getName(). * * @return Name of this, without directory, host, or protocol. */ public String getName() { URL url = this.url; String path = url.getPath(); int lastSlash = path.lastIndexOf('/'); if (lastSlash > -1) { path = path.substring(lastSlash+1); } return path; } /** * Basic ConnectionHelper. Does *nothing special* when encountering directories, re-directs, ... */ private static final ConnectionAdapter connectionAdapter = new ConnectionAdapter(); // Set the URLConnection timeout a little smaller than our DownloadMonitor timeout. public static final int CONNECT_TIMEOUT = 6000; public static final int READ_TIMEOUT = 25000; /** * Create a connection, using the standard timeouts of 23 seconds, and the super-basic ConnectionAdapter, * which does *nothing special* when encountering directories, re-directs, ... * * @param connectionHelper * @return */ public PURLConnection connect() { return connect(connectionAdapter); } public PURLConnection connect(String userAgentName) { return connect(connectionAdapter, userAgentName); } /** * Create a connection, using the standard timeouts of 23 seconds. * * @param connectionHelper * @return */ public PURLConnection connect(ConnectionHelper connectionHelper) { return connect(connectionHelper, DEFAULT_USER_AGENT, CONNECT_TIMEOUT, READ_TIMEOUT); } public PURLConnection connect(ConnectionHelper connectionHelper, String userAgentString) { return (userAgentString != null) ? connect(connectionHelper, userAgentString, CONNECT_TIMEOUT, READ_TIMEOUT) : connect(connectionHelper); } /** * Create a connection. * * @param connectionHelper * @param userAgent TODO * @param connectionTimeout * @param readTimeout * @return */ public PURLConnection connect(ConnectionHelper connectionHelper, String userAgent, int connectionTimeout, int readTimeout) { URLConnection connection= null; InputStream inStream = null; PURLConnection result = null; // get an InputStream, and set the mimeType, if not bad if (isFile()) { File file = file(); if (file.isDirectory()) connectionHelper.handleFileDirectory(file); else { String suffix = suffix(); if (suffix != null) { if (connectionHelper.parseFilesWithSuffix(suffix)) { try { inStream = new FileInputStream(file); result = new PURLConnection(null, inStream); } catch (FileNotFoundException e) { connectionHelper.badResult(); println("Can't open because FileNotFoundException: " + this); } } } } return result; } else { // network based URL boolean bad = false; try { connection = this.url().openConnection(); // hack so google thinks we're a normal browser // (otherwise, it wont serve us) // connection.setRequestProperty("user-agent", GOOGLE_BOT_USER_AGENT_0); connection.setRequestProperty("user-agent", userAgent); // Set the connection and read timeout. connection.setConnectTimeout(connectionTimeout); connection.setReadTimeout(readTimeout); /*//TODO include more structure instead of this total hack! if ("nytimes.com".equals(this.domain())) { String auth = new sun.misc.BASE64Encoder().encode("fred66:fred66".getBytes()); connection.setRequestProperty("Authorization", auth); } */ String mimeType = connection.getContentType(); // no one uses the encoding header: connection.getContentEncoding(); String unsupportedCharset = NetTools.isCharsetSupported(mimeType); if (unsupportedCharset != null) { connectionHelper.displayStatus("Cant process charset " + unsupportedCharset + " in " + this); return null; } // notice if url changed between request and retrieved connection // if so, this is a server-side redirect URL connectionURL = connection.getURL(); if (!this.equals(connectionURL)) // follow redirects! { // avoid doubly stuffed urls String connectionFile = connectionURL.getFile(); String file = url().getFile(); if ((file.indexOf("http://") != -1) || (connectionFile.indexOf("http://") == -1)) { if (connectionHelper.processRedirect(connectionURL)) inStream = connection.getInputStream(); } else println("WEIRD: skipping double stuffed url: " + connectionURL); } else // no redirect, eveything is kewl inStream = connection.getInputStream(); } catch (SocketTimeoutException e) { bad = true; timeout = true; error("connect() " + e); } catch (FileNotFoundException e) { bad = true; error("connect() " + e); } catch (IOException e) { bad = true; error("connect() " + e); } catch (Exception e) // catch all exceptions, including security { bad = true; error("connect() " + e); } return ((inStream == null) || bad)? null : new PURLConnection(connection, inStream); } // end else network based URL //TODO -- how are the headers (like ContentType) read? // is the inputStream really created automatically for us behind the scences??? // if so, we need to get it, close it, disconnect() it, etc. -- // just because we read the headers??? } /** * If true, check for timeout during connect(). */ boolean timeout = false; public boolean getTimeout() { return timeout; } /** * Free some memory resources. They can be re-allocated through subsequent lazy evaluation. * The object is still fully functional after this call. */ public void resetCaches() { this.directory = null; this.string = null; this.shortString = null; this.lc = null; this.suffix = null; this.domain = null; if (directoryPURL != null) { this.directoryPURL.recycle(); this.directoryPURL = null; } //TODO -- is this too agressive?! this.hashUrl = null; } /** * Free <b>all</b> all resources associated with this, rendering it no longer usable. */ public void recycle() { resetCaches(); url = null; file = null; } public String host() { return (url == null) ? null : url.getHost(); } }
true
true
public static ParsedURL createFromHTML(ParsedURL contextPURL, String addressString, boolean fromSearchPage) { if ((addressString == null) || (addressString.length() == 0)) return null; if( addressString.startsWith("#") ) { //return get(contextPURL.url(), addressString); return null; } String lc = addressString.toLowerCase(); boolean javascript = lc.startsWith("javascript:"); // mine urls from javascript quoted strings if (javascript) { // !!! Could do an even better job here of mining quoted // !!! javascript strings. // println("Container.newURL("+s); int http = lc.lastIndexOf("http://"); // TODO learn to mine PDFs as well as html!! int html = lc.lastIndexOf(".html"); int pdf = lc.lastIndexOf(".pdf"); // println("Container.newURL() checking javascript url:="+s+ // " http="+http+" html="+html); if (http > -1) { // seek absolute web addrs if ((html > -1) && (http < html)) { int end = html + 5; addressString= addressString.substring(http, end); //println("Container.newURL fixed javascript:= " + s); lc = lc.substring(http, end); javascript = false; } else if ((pdf > -1) && (http < pdf)) { int end = pdf + 4; addressString= addressString.substring(http, end); //println("Container.newURL fixed javascript:= " + s); lc = lc.substring(http, end); javascript = false; } } else { // seek relative addresses // need to find the bounds of a quoted string, if there is one } // !!! What we should really do here is find quoted strings // (usually with single quote, but perhaps double as well) // (use regular expressions?? - are they fast enough?) // and look at each one to see if either protocol is supported // or suffix is htmlMime or imgMime. } if (javascript) return null; char argDelim = '?'; // url string always keep hash string. String hashString = StringTools.EMPTY_STRING; if (fromSearchPage) { // handle embedded http:// int lastHttp = addressString.lastIndexOf("http://"); // usually ? but could be & if (lastHttp > 0) { // this is search engine crap addressString = addressString.substring(lastHttp); // debugA("now addressString="+addressString); // handle any embedded args (for google mess) argDelim = '&'; } } else { // TODO do we really need to do any of this??????????????????????? // 1) peel off hash int hashPos = addressString.indexOf('#'); // String hashString= StringTools.EMPTY_STRING; if (hashPos > -1) { hashString = addressString.substring(hashPos); addressString = addressString.substring(0, hashPos); } // 2) peel off args int argPos = addressString.indexOf(argDelim); String argString = StringTools.EMPTY_STRING; if (argPos > -1) { argString = addressString.substring(argPos); addressString = addressString.substring(0, argPos); } else { // 3) if what's left is a directory (w/o a mime type),add slash int endingSlash = addressString.lastIndexOf('/'); int lastChar = addressString.length() - 1; if (endingSlash == -1) endingSlash++; if ((lastChar > 0) && (lastChar != endingSlash) && (addressString.substring(endingSlash).indexOf('.') == -1)) addressString += '/'; } // 4) put back what we peeled off addressString += argString; addressString += hashString; } int protocolEnd = addressString.indexOf(":"); if (protocolEnd != -1) { // this is an absolute URL; check for supported protocol String protocol = addressString.substring(0, protocolEnd); if (protocolIsUnsupported(protocol)) return null; } ParsedURL parsedUrl; if (contextPURL == null || addressString.startsWith("http://")) { parsedUrl = getAbsolute(addressString, "in createFromHTML()"); } else { ParsedURL directoryPURL = contextPURL.directoryPURL(); parsedUrl = directoryPURL.getRelative(addressString); } return parsedUrl; }
public static ParsedURL createFromHTML(ParsedURL contextPURL, String addressString, boolean fromSearchPage) { if ((addressString == null) || (addressString.length() == 0)) return null; if( addressString.startsWith("#") ) { //return get(contextPURL.url(), addressString); return null; } String lc = addressString.toLowerCase(); boolean javascript = lc.startsWith("javascript:"); // mine urls from javascript quoted strings if (javascript) { // !!! Could do an even better job here of mining quoted // !!! javascript strings. // println("Container.newURL("+s); int http = lc.lastIndexOf("http://"); // TODO learn to mine PDFs as well as html!! int html = lc.lastIndexOf(".html"); int pdf = lc.lastIndexOf(".pdf"); // println("Container.newURL() checking javascript url:="+s+ // " http="+http+" html="+html); if (http > -1) { // seek absolute web addrs if ((html > -1) && (http < html)) { int end = html + 5; addressString= addressString.substring(http, end); //println("Container.newURL fixed javascript:= " + s); lc = lc.substring(http, end); javascript = false; } else if ((pdf > -1) && (http < pdf)) { int end = pdf + 4; addressString= addressString.substring(http, end); //println("Container.newURL fixed javascript:= " + s); lc = lc.substring(http, end); javascript = false; } } else { // seek relative addresses // need to find the bounds of a quoted string, if there is one } // !!! What we should really do here is find quoted strings // (usually with single quote, but perhaps double as well) // (use regular expressions?? - are they fast enough?) // and look at each one to see if either protocol is supported // or suffix is htmlMime or imgMime. } if (javascript) return null; char argDelim = '?'; // url string always keep hash string. String hashString = StringTools.EMPTY_STRING; if (fromSearchPage) { // handle embedded http:// int lastHttp = addressString.lastIndexOf("http://"); // usually ? but could be & if (lastHttp > 0) { // this is search engine crap addressString = addressString.substring(lastHttp); // debugA("now addressString="+addressString); // handle any embedded args (for google mess) argDelim = '&'; } } else { // TODO do we really need to do any of this??????????????????????? // 1) peel off hash int hashPos = addressString.indexOf('#'); // String hashString= StringTools.EMPTY_STRING; if (hashPos > -1) { hashString = addressString.substring(hashPos); addressString = addressString.substring(0, hashPos); } // 2) peel off args int argPos = addressString.indexOf(argDelim); String argString = StringTools.EMPTY_STRING; if (argPos > -1) { argString = addressString.substring(argPos); addressString = addressString.substring(0, argPos); } // This seems uneccessary, crawling any wikimedia based site will break by adding an extra slash. // else // { // // 3) if what's left is a directory (w/o a mime type),add slash // int endingSlash = addressString.lastIndexOf('/'); // int lastChar = addressString.length() - 1; // if (endingSlash == -1) // endingSlash++; // if ((lastChar > 0) && // (lastChar != endingSlash) && // (addressString.substring(endingSlash).indexOf('.') == -1)) // addressString += '/'; // } // 4) put back what we peeled off addressString += argString; addressString += hashString; } int protocolEnd = addressString.indexOf(":"); if (protocolEnd != -1) { // this is an absolute URL; check for supported protocol String protocol = addressString.substring(0, protocolEnd); if (protocolIsUnsupported(protocol)) return null; } ParsedURL parsedUrl; if (contextPURL == null || addressString.startsWith("http://")) { parsedUrl = getAbsolute(addressString, "in createFromHTML()"); } else { ParsedURL directoryPURL = contextPURL.directoryPURL(); parsedUrl = directoryPURL.getRelative(addressString); } return parsedUrl; }
diff --git a/src/com/stefankopieczek/audinance/conversion/multiplexers/SimpleMultiplexer.java b/src/com/stefankopieczek/audinance/conversion/multiplexers/SimpleMultiplexer.java index 5063825..637999e 100644 --- a/src/com/stefankopieczek/audinance/conversion/multiplexers/SimpleMultiplexer.java +++ b/src/com/stefankopieczek/audinance/conversion/multiplexers/SimpleMultiplexer.java @@ -1,97 +1,98 @@ package com.stefankopieczek.audinance.conversion.multiplexers; import java.util.Arrays; import com.stefankopieczek.audinance.audiosources.DecodedSource; import com.stefankopieczek.audinance.audiosources.NoMoreDataException; import com.stefankopieczek.audinance.formats.*; public class SimpleMultiplexer implements Multiplexer { /** * Remix the specified audio, returning a copy with precisely the specified * number of channels. If it has too few, we add channels equal to the mix * of all existing channels. If it has too many, we flatten the last few * channels into a single track. */ public DecodedAudio toNChannels(DecodedAudio result, Integer targetNumChannels) { DecodedSource[] oldChannels = result.getChannels(); - DecodedSource[] newChannels = new DecodedSource[targetNumChannels]; + DecodedSource[] newChannels = + new DecodedSource[targetNumChannels.intValue()]; if (targetNumChannels > oldChannels.length) { // More channels have been requested than currently exist. // Copy the existing channels unchanged. for (int idx = 0; idx < oldChannels.length; idx++) { newChannels[idx] = oldChannels[idx]; } // Make up the total by adding channels which are simply a // flattened copy of all existing channels. for (int idx = oldChannels.length; idx < targetNumChannels; idx++) { newChannels[idx] = new CombinedAudio(oldChannels); } } else { // Fewer channels have been requested than currently exist. // We don't want to lose audio data, so instead of dropping the // surplus channels, we flatten them into a single channel. // Copy the first n-1 channels unchanged. for (int idx = 0; idx < targetNumChannels - 1; idx++) { newChannels[idx] = oldChannels[idx]; } // Flatten all remaining channels into a single track, and add it. newChannels[targetNumChannels-1] = new CombinedAudio(Arrays.copyOfRange(oldChannels, targetNumChannels, oldChannels.length)); } DecodedAudio newAudio = new DecodedAudio(result.getFormat(), newChannels); return newAudio; } private class CombinedAudio extends DecodedSource { DecodedSource[] mSources; public CombinedAudio(DecodedSource... sources) { mSources = sources; } public double getSample(int idx) { double sampleValue = 0; // Mixing audio is as simple as adding the values of each channel // in the frame together. // TODO: Scale audio if it clips. for (DecodedSource source : mSources) { try { // TODO: Test for numeric overflow. sampleValue += source.getSample(idx); } catch (NoMoreDataException e) { // This source has no data at this instant, so makes no // contribution to the mixed audio. } } return sampleValue; } } }
true
true
public DecodedAudio toNChannels(DecodedAudio result, Integer targetNumChannels) { DecodedSource[] oldChannels = result.getChannels(); DecodedSource[] newChannels = new DecodedSource[targetNumChannels]; if (targetNumChannels > oldChannels.length) { // More channels have been requested than currently exist. // Copy the existing channels unchanged. for (int idx = 0; idx < oldChannels.length; idx++) { newChannels[idx] = oldChannels[idx]; } // Make up the total by adding channels which are simply a // flattened copy of all existing channels. for (int idx = oldChannels.length; idx < targetNumChannels; idx++) { newChannels[idx] = new CombinedAudio(oldChannels); } } else { // Fewer channels have been requested than currently exist. // We don't want to lose audio data, so instead of dropping the // surplus channels, we flatten them into a single channel. // Copy the first n-1 channels unchanged. for (int idx = 0; idx < targetNumChannels - 1; idx++) { newChannels[idx] = oldChannels[idx]; } // Flatten all remaining channels into a single track, and add it. newChannels[targetNumChannels-1] = new CombinedAudio(Arrays.copyOfRange(oldChannels, targetNumChannels, oldChannels.length)); } DecodedAudio newAudio = new DecodedAudio(result.getFormat(), newChannels); return newAudio; }
public DecodedAudio toNChannels(DecodedAudio result, Integer targetNumChannels) { DecodedSource[] oldChannels = result.getChannels(); DecodedSource[] newChannels = new DecodedSource[targetNumChannels.intValue()]; if (targetNumChannels > oldChannels.length) { // More channels have been requested than currently exist. // Copy the existing channels unchanged. for (int idx = 0; idx < oldChannels.length; idx++) { newChannels[idx] = oldChannels[idx]; } // Make up the total by adding channels which are simply a // flattened copy of all existing channels. for (int idx = oldChannels.length; idx < targetNumChannels; idx++) { newChannels[idx] = new CombinedAudio(oldChannels); } } else { // Fewer channels have been requested than currently exist. // We don't want to lose audio data, so instead of dropping the // surplus channels, we flatten them into a single channel. // Copy the first n-1 channels unchanged. for (int idx = 0; idx < targetNumChannels - 1; idx++) { newChannels[idx] = oldChannels[idx]; } // Flatten all remaining channels into a single track, and add it. newChannels[targetNumChannels-1] = new CombinedAudio(Arrays.copyOfRange(oldChannels, targetNumChannels, oldChannels.length)); } DecodedAudio newAudio = new DecodedAudio(result.getFormat(), newChannels); return newAudio; }
diff --git a/DVST/src/com/dhbw/dvst/helper/SpielerListeArrayAdapter.java b/DVST/src/com/dhbw/dvst/helper/SpielerListeArrayAdapter.java index 1b67ad4..1dd6661 100644 --- a/DVST/src/com/dhbw/dvst/helper/SpielerListeArrayAdapter.java +++ b/DVST/src/com/dhbw/dvst/helper/SpielerListeArrayAdapter.java @@ -1,136 +1,136 @@ package com.dhbw.dvst.helper; import java.util.ArrayList; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.dhbw.dvst.R; import com.dhbw.dvst.activities.SpielerBearbeitenActivity; import com.dhbw.dvst.model.Control; import com.dhbw.dvst.model.Spiel; import com.dhbw.dvst.model.Spieler; public class SpielerListeArrayAdapter extends ArrayAdapter<Spieler> { /** * Speichert alle Spieler als Values und einen hochzählenden int-Wert als Key */ // private HashMap<Integer, Spieler> mIdMap = HashMap<Integer, Spieler>(); SparseArray<Spieler> mIdMap = new SparseArray<Spieler>(); private Activity activity; private int position; private View zeilenansicht; /** * * @param context momentaner Kontext * @param resourceId ID der Layout-Datei * @param textViewId ID des Textviews in der Layout-Datei * @param alleSpieler Listenobjekte */ public SpielerListeArrayAdapter(Activity activity, int resourceId, int textViewId, ArrayList<Spieler> alleSpieler) { super(activity, resourceId, textViewId, alleSpieler); this.activity = activity; for (int i = 0; i < alleSpieler.size(); ++i) { mIdMap.put(i, alleSpieler.get(i)); } } @Override public boolean hasStableIds() { return true; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) activity .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View zeilenansicht = inflater.inflate(R.layout.zeilenansicht, parent, false); this.zeilenansicht = zeilenansicht; this.position = position; return fuelleListViewItem(); } private View fuelleListViewItem() { setFigurIcon(); setSpielerName(); initBearbeitenButton(); initLoeschenButton(); return zeilenansicht; } private void setFigurIcon() { ImageView imageView = (ImageView) this.zeilenansicht.findViewById(R.id.img_gewaehlte_figur); int resID = activity.getResources().getIdentifier(baueBildNamen(), "drawable", "com.dhbw.dvst"); imageView.setImageResource(resID); } private String baueBildNamen() { String form = this.getItem(this.position).getSpielfigur().getForm().getText_en(); String farbe = this.getItem(this.position).getSpielfigur().getFarbe().getText_en(); String bildName = form +"_"+ farbe; return bildName; } private void setSpielerName() { TextView textView = (TextView) this.zeilenansicht.findViewById(R.id.tv_gewaehlter_name); textView.setText(getItem(this.position).toString()); } protected void initBearbeitenButton() { Button btn_bearbeiten = (Button) this.zeilenansicht.findViewById(R.id.btn_spieler_bearbeiten); btn_bearbeiten.setTag(this.position); //TODO: bearbeitungsicon btn_bearbeiten.setBackgroundResource(R.drawable.ic_launcher); setBearbeitenListener(btn_bearbeiten); } protected void setBearbeitenListener(Button btn_bearbeiten) { btn_bearbeiten.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent_edit_spieler = new Intent(activity,SpielerBearbeitenActivity.class) .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent_edit_spieler.putExtra("spieler_index", (Integer)v.getTag()); activity.startActivity(intent_edit_spieler); } }); } protected void initLoeschenButton() { Button btn_loeschen = (Button) this.zeilenansicht.findViewById(R.id.btn_spieler_loeschen); btn_loeschen.setTag(getItem(this.position)); //TODO: löschicon btn_loeschen.setBackgroundResource(R.drawable.ic_launcher); setLoeschenListener(btn_loeschen); } protected void setLoeschenListener(Button btn_loeschen) { btn_loeschen.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { OnClickListener spielerLoeschen = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { - SpielerListeArrayAdapter.this.remove(SpielerListeArrayAdapter.this.mIdMap.get(position)); + SpielerListeArrayAdapter.this.remove((Spieler)v.getTag()); Spiel spiel = Control.getInstance(); spiel.spielerLoeschen((Spieler)v.getTag()); } }; new LoeschDialog(activity, activity.getString(R.string.wirklich_loeschen), spielerLoeschen); } }); } }
true
true
protected void setLoeschenListener(Button btn_loeschen) { btn_loeschen.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { OnClickListener spielerLoeschen = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { SpielerListeArrayAdapter.this.remove(SpielerListeArrayAdapter.this.mIdMap.get(position)); Spiel spiel = Control.getInstance(); spiel.spielerLoeschen((Spieler)v.getTag()); } }; new LoeschDialog(activity, activity.getString(R.string.wirklich_loeschen), spielerLoeschen); } }); }
protected void setLoeschenListener(Button btn_loeschen) { btn_loeschen.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { OnClickListener spielerLoeschen = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { SpielerListeArrayAdapter.this.remove((Spieler)v.getTag()); Spiel spiel = Control.getInstance(); spiel.spielerLoeschen((Spieler)v.getTag()); } }; new LoeschDialog(activity, activity.getString(R.string.wirklich_loeschen), spielerLoeschen); } }); }
diff --git a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/session/SipSessionImpl.java b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/session/SipSessionImpl.java index 3a747995a..83702f55b 100644 --- a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/session/SipSessionImpl.java +++ b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/session/SipSessionImpl.java @@ -1,2188 +1,2195 @@ /* * 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.mobicents.servlet.sip.core.session; import gov.nist.javax.sip.ServerTransactionExt; import gov.nist.javax.sip.address.SipUri; import gov.nist.javax.sip.message.MessageExt; import gov.nist.javax.sip.message.SIPMessage; import gov.nist.javax.sip.message.SIPRequest; import java.io.IOException; import java.io.Serializable; import java.net.InetAddress; import java.net.InetSocketAddress; import java.security.AccessController; import java.security.Principal; import java.security.PrivilegedAction; import java.text.ParseException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.Vector; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicBoolean; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.sip.Address; import javax.servlet.sip.ServletParseException; import javax.servlet.sip.SipApplicationSession; import javax.servlet.sip.SipServletRequest; import javax.servlet.sip.SipServletResponse; import javax.servlet.sip.SipSessionActivationListener; import javax.servlet.sip.SipSessionAttributeListener; import javax.servlet.sip.SipSessionBindingEvent; import javax.servlet.sip.SipSessionBindingListener; import javax.servlet.sip.SipSessionEvent; import javax.servlet.sip.SipSessionListener; import javax.servlet.sip.SipURI; import javax.servlet.sip.URI; import javax.servlet.sip.ar.SipApplicationRouterInfo; import javax.servlet.sip.ar.SipApplicationRoutingRegion; import javax.sip.ClientTransaction; import javax.sip.Dialog; import javax.sip.DialogState; import javax.sip.InvalidArgumentException; import javax.sip.ListeningPoint; import javax.sip.ObjectInUseException; import javax.sip.ServerTransaction; import javax.sip.SipException; import javax.sip.SipProvider; import javax.sip.Transaction; import javax.sip.TransactionState; import javax.sip.header.AuthenticationInfoHeader; import javax.sip.header.CSeqHeader; import javax.sip.header.CallIdHeader; import javax.sip.header.ContactHeader; import javax.sip.header.EventHeader; import javax.sip.header.FromHeader; import javax.sip.header.Parameters; import javax.sip.header.RouteHeader; import javax.sip.header.ToHeader; import javax.sip.header.ViaHeader; import javax.sip.message.Request; import javax.sip.message.Response; import org.apache.catalina.Container; import org.apache.catalina.security.SecurityUtil; import org.apache.log4j.Logger; import org.apache.log4j.Priority; import org.mobicents.ha.javax.sip.SipLoadBalancer; import org.mobicents.javax.servlet.sip.SipSessionAsynchronousWork; import org.mobicents.servlet.sip.JainSipUtils; import org.mobicents.servlet.sip.SipFactories; import org.mobicents.servlet.sip.address.AddressImpl; import org.mobicents.servlet.sip.address.SipURIImpl; import org.mobicents.servlet.sip.annotation.ConcurrencyControlMode; import org.mobicents.servlet.sip.core.RoutingState; import org.mobicents.servlet.sip.core.SipApplicationDispatcher; import org.mobicents.servlet.sip.core.SipNetworkInterfaceManager; import org.mobicents.servlet.sip.core.dispatchers.MessageDispatcher; import org.mobicents.servlet.sip.message.B2buaHelperImpl; import org.mobicents.servlet.sip.message.MobicentsSipSessionFacade; import org.mobicents.servlet.sip.message.SipFactoryImpl; import org.mobicents.servlet.sip.message.SipServletMessageImpl; import org.mobicents.servlet.sip.message.SipServletRequestImpl; import org.mobicents.servlet.sip.message.SipServletResponseImpl; import org.mobicents.servlet.sip.message.TransactionApplicationData; import org.mobicents.servlet.sip.proxy.ProxyImpl; import org.mobicents.servlet.sip.startup.SipContext; /** * * <p>Implementation of the SipSession interface. * An instance of this sip session can only be retrieved through the Session Manager * (extended class from Tomcat's manager classes implementing the <code>Manager</code> interface) * to constrain the creation of sip session and to make sure that all sessions created * can be retrieved only through the session manager</p> * * <p> * As a SipApplicationSession represents a dialog, * the call id and from header URI, from tag, to Header (and to Tag to identify forked requests) * are used as a unique key for a given SipSession instance. * </p> * * @author vralev * @author mranga * @author <A HREF="mailto:[email protected]">Jean Deruelle</A> */ public class SipSessionImpl implements MobicentsSipSession { private static final Logger logger = Logger.getLogger(SipSessionImpl.class); protected transient SipApplicationSessionKey sipApplicationSessionKey; //lazy loaded and not serialized protected transient MobicentsSipApplicationSession sipApplicationSession; protected ProxyImpl proxy; protected B2buaHelperImpl b2buaHelper; protected transient int requestsPending; volatile protected Map<String, Object> sipSessionAttributeMap; protected transient SipSessionKey key; protected transient Principal userPrincipal; protected long cseq = -1; protected String transport; // protected transient ThreadPoolExecutor executorService = new ThreadPoolExecutor(1, 1, 90, TimeUnit.SECONDS, // new LinkedBlockingQueue<Runnable>()); /** * Creation time. */ protected long creationTime; /** * Last access time. */ protected long lastAccessedTime; /** * Routing region per session/dialog. */ protected transient SipApplicationRoutingRegion routingRegion; /** * AR state info */ protected transient Serializable stateInfo; /** * AR router info for the next app in chain */ protected transient SipApplicationRouterInfo nextSipApplicationRouterInfo; /** * Current state of the session, one of INTITIAL, EARLY, ESTABLISHED and TERMINATED. */ protected State state; /** * Is the session valid. */ protected AtomicBoolean isValidInternal; protected transient boolean isValid; /** * The name of the servlet withing this same app to handle all subsequent requests. */ protected String handlerServlet; /** * Subscriber URI should be set for outbound sessions, from requests created in the container. */ protected transient String subscriberURI; /** * Outbound interface is one of the allowed values in the Servlet Context attribute * "javax.servlet.ip.outboundinterfaces" * This one is not serialized, it has to be reset by the app on sessionActivated listener method */ protected transient String outboundInterface; // === THESE ARE THE OBJECTS A SIP SESSION CAN BE ASSIGNED TO === // TODO: Refactor this into two Session classes to avoid nulls // and branching on nulls /** * We use this for dialog-related requests. In this case the dialog * directly corresponds to the session. */ protected transient Dialog sessionCreatingDialog; /** * We use this for REGISTER or MESSAGE, where a dialog doesn't exist to carry the session info. * In this case the session only spans a single transaction. */ protected transient SipServletRequestImpl sessionCreatingTransactionRequest; protected transient boolean isSessionCreatingTransactionServer; // ============================================================= // TODO : Can be optimized into separate server tx and client tx to speed up some parts of the code protected transient Set<Transaction> ongoingTransactions; volatile protected transient ConcurrentHashMap<String, MobicentsSipSession> derivedSipSessions; /* * The almighty provider */ protected transient SipFactoryImpl sipFactory; protected boolean invalidateWhenReady = true; protected boolean readyToInvalidate = false; /* * If this is a derived session, have a pointer to the parent session. */ protected transient MobicentsSipSession parentSession = null; //parties used when this is an outgoing request that has not yet been sent protected transient Address localParty = null; protected transient Address remoteParty = null; //Subscriptions used for RFC 3265 compliance to be able to determine when the session can be invalidated // A subscription is destroyed when a notifier sends a NOTIFY request with a "Subscription-State" of "terminated". // If a subscription's destruction leaves no other application state associated with the dialog, the dialog terminates volatile protected transient Set<EventHeader> subscriptions = null; //original transaction that started this session is stored so that we know if the session should end when all subscriptions have terminated or when the BYE has come protected transient String originalMethod = null; protected transient boolean okToByeSentOrReceived = false; // Issue 2066 Miss Record-Route in Response To Subsequent Requests for non RFC3261 compliant servers protected transient boolean copyRecordRouteHeadersOnSubsequentResponses = false; protected transient Semaphore semaphore; protected transient MobicentsSipSessionFacade facade = null; protected transient ConcurrentHashMap<Long, Boolean> acksReceived = new ConcurrentHashMap<Long, Boolean>(2); // Added for Issue 2173 http://code.google.com/p/mobicents/issues/detail?id=2173 // Handle Header [Authentication-Info: nextnonce="xyz"] in sip authorization responses protected transient SipSessionSecurity sipSessionSecurity; protected SipSessionImpl (SipSessionKey key, SipFactoryImpl sipFactoryImpl, MobicentsSipApplicationSession mobicentsSipApplicationSession) { this.key = key; setSipApplicationSession(mobicentsSipApplicationSession); this.sipFactory = sipFactoryImpl; this.creationTime = this.lastAccessedTime = System.currentTimeMillis(); this.state = State.INITIAL; this.isValidInternal = new AtomicBoolean(true); this.isValid = true; this.ongoingTransactions = new CopyOnWriteArraySet<Transaction>(); if(mobicentsSipApplicationSession.getSipContext() != null && ConcurrencyControlMode.SipSession.equals(mobicentsSipApplicationSession.getSipContext().getConcurrencyControlMode())) { semaphore = new Semaphore(1); } } /** * Notifies the listeners that a lifecycle event occured on that sip session * @param sipSessionEventType the type of event that happened */ public void notifySipSessionListeners(SipSessionEventType sipSessionEventType) { MobicentsSipApplicationSession sipApplicationSession = getSipApplicationSession(); if(sipApplicationSession != null) { SipContext sipContext = sipApplicationSession.getSipContext(); List<SipSessionListener> sipSessionListeners = sipContext.getListeners().getSipSessionListeners(); if(sipSessionListeners.size() > 0) { if(logger.isDebugEnabled()) { logger.debug("notifying sip session listeners of context " + sipContext.getApplicationName() + " of following event " + sipSessionEventType); } ClassLoader oldLoader = java.lang.Thread.currentThread().getContextClassLoader(); java.lang.Thread.currentThread().setContextClassLoader(sipContext.getLoader().getClassLoader()); SipSessionEvent sipSessionEvent = new SipSessionEvent(this.getSession()); for (SipSessionListener sipSessionListener : sipSessionListeners) { try { if(logger.isDebugEnabled()) { logger.debug("notifying sip session listener " + sipSessionListener.getClass().getName() + " of context " + key.getApplicationName() + " of following event " + sipSessionEventType); } if(SipSessionEventType.CREATION.equals(sipSessionEventType)) { sipSessionListener.sessionCreated(sipSessionEvent); } else if (SipSessionEventType.DELETION.equals(sipSessionEventType)) { sipSessionListener.sessionDestroyed(sipSessionEvent); } else if (SipSessionEventType.READYTOINVALIDATE.equals(sipSessionEventType)) { sipSessionListener.sessionReadyToInvalidate(sipSessionEvent); } } catch (Throwable t) { logger.error("SipSessionListener threw exception", t); } } java.lang.Thread.currentThread().setContextClassLoader(oldLoader); } } } /* * (non-Javadoc) * @see javax.servlet.sip.SipSession#createRequest(java.lang.String) */ public SipServletRequest createRequest(final String method) { if(method.equalsIgnoreCase(Request.ACK) || method.equalsIgnoreCase(Request.PRACK) || method.equalsIgnoreCase(Request.CANCEL)) { throw new IllegalArgumentException( "Can not create ACK, PRACK or CANCEL requests with this method"); } if(!isValid()) { throw new IllegalStateException("cannot create a subsequent request " + method + " because the session " + key + " is invalid"); } if(State.TERMINATED.equals(state)) { throw new IllegalStateException("cannot create a subsequent request " + method + " because the session " + key + " is in TERMINATED state"); } // if((State.INITIAL.equals(state) && hasOngoingTransaction())) { // throw new IllegalStateException("cannot create a request because the session is in INITIAL state with ongoing transactions"); // } if(logger.isDebugEnabled()) { logger.debug("dialog associated with this session to create the new request " + method + " within that dialog "+ sessionCreatingDialog); + if(sessionCreatingDialog != null) { + logger.debug("dialog state " + sessionCreatingDialog.getState() + " for that dialog "+ sessionCreatingDialog); + } } SipServletRequestImpl sipServletRequest = null; + // Fix for Issue http://code.google.com/p/mobicents/issues/detail?id=2230 BYE is routed to unexpected IP + // MSS should throw an IllegalStateException when a subsequent request is being created on a TERMINATED dialog + // don't do it on the BYE method as a 408 within a dialog could have make the dialog TERMINATED and MSS should allow the app to create the subsequent BYE from any thread if(sessionCreatingDialog != null && DialogState.TERMINATED.equals(sessionCreatingDialog.getState()) && !method.equalsIgnoreCase(Request.BYE)) { - // Fix for Issue http://code.google.com/p/mobicents/issues/detail?id=2230 BYE is routed to unexpected IP - // MSS should throw an IllegalStateException when a subsequent request is being created on a TERMINATED dialog - // don't do it on the BYE method as a 408 within a dialog could have make the dialog TERMINATED and MSS should allow the app to create the subsequent BYE from any thread - throw new IllegalStateException("cannot create a subsequent request " + method + " because the dialog " + sessionCreatingDialog + " for session " + key + " is in TERMINATED state"); + // don't do it for authentication as the dialog will go back to TERMINATED state, so we should allow to create challenge requests + if(sessionCreatingTransactionRequest == null || sessionCreatingTransactionRequest.getLastFinalResponse() == null || + (sessionCreatingTransactionRequest.getLastFinalResponse().getStatus() != 401 && sessionCreatingTransactionRequest.getLastFinalResponse().getStatus() != 407)) { + throw new IllegalStateException("cannot create a subsequent request " + method + " because the dialog " + sessionCreatingDialog + " for session " + key + " is in TERMINATED state"); + } } if(this.sessionCreatingDialog != null && !DialogState.TERMINATED.equals(sessionCreatingDialog.getState())) { if(logger.isDebugEnabled()) { logger.debug("dialog " + sessionCreatingDialog + " used to create the new request " + method); } try { final Request methodRequest = this.sessionCreatingDialog.createRequest(method); if(methodRequest.getHeader(ContactHeader.NAME) != null) { // if a sip load balancer is present in front of the server, the contact header is the one from the sip lb // so that the subsequent requests can be failed over try { ContactHeader contactHeader = null; FromHeader from = (FromHeader) methodRequest.getHeader(FromHeader.NAME); String displayName = from.getAddress().getDisplayName(); String userName = null; javax.sip.address.URI uri = from.getAddress().getURI(); if(uri.isSipURI()) { userName = ((javax.sip.address.SipURI)uri).getUser(); } if(sipFactory.isUseLoadBalancer()) { SipLoadBalancer loadBalancerToUse = sipFactory.getLoadBalancerToUse(); javax.sip.address.SipURI sipURI = SipFactories.addressFactory.createSipURI(userName, loadBalancerToUse.getAddress().getHostAddress()); sipURI.setHost(loadBalancerToUse.getAddress().getHostAddress()); sipURI.setPort(loadBalancerToUse.getSipPort()); // TODO: Is this enough or we must specify the transport somewhere? // We can leave it like this. It will be updated if needed in the send() method sipURI.setTransportParam(ListeningPoint.UDP); javax.sip.address.Address contactAddress = SipFactories.addressFactory.createAddress(sipURI); contactHeader = SipFactories.headerFactory.createContactHeader(contactAddress); } else { contactHeader = JainSipUtils.createContactHeader(sipFactory.getSipNetworkInterfaceManager(), methodRequest, displayName, userName, outboundInterface); } methodRequest.setHeader(contactHeader); } catch (Exception e) { logger.error("Can not create contact header for subsequent request " + method + " for session " + key, e); } } // Fix for Issue 1130 (http://code.google.com/p/mobicents/issues/detail?id=1130) : // NullPointerException when sending request to client which support both UDP and TCP transport // before removing the via header we store the transport into its app data ListIterator<ViaHeader> viaHeaders = methodRequest.getHeaders(ViaHeader.NAME); if(viaHeaders != null && viaHeaders.hasNext()) { ViaHeader viaHeader = viaHeaders.next(); ((MessageExt)methodRequest).setApplicationData(viaHeader.getTransport()); } //Issue 112 fix by folsson methodRequest.removeHeader(ViaHeader.NAME); //if a SUBSCRIBE or BYE is sent for exemple, it will reuse the prexisiting dialog sipServletRequest = new SipServletRequestImpl( methodRequest, this.sipFactory, this, null, sessionCreatingDialog, false); } catch (SipException e) { logger.error("Cannot create the " + method + " request from the dialog " + sessionCreatingDialog,e); throw new IllegalArgumentException("Cannot create the " + method + " request from the dialog " + sessionCreatingDialog + " for sip session " + key,e); } } else { //case where other requests are sent with the same session like REGISTER or for challenge requests if(sessionCreatingTransactionRequest != null) { if(!isSessionCreatingTransactionServer) { if(logger.isDebugEnabled()) { logger.debug("orignal tx for creating susbequent request " + method + " on session " + key +" was a Client Tx"); } Request request = (Request) sessionCreatingTransactionRequest.getMessage().clone(); // Issue 1524 : Caused by: java.text.ParseException: CSEQ method mismatch with Request-Line javax.sip.address.URI requestUri = (javax.sip.address.URI) request.getRequestURI().clone(); ((SIPRequest)request).setMethod(method); ((SIPRequest)request).setRequestURI(requestUri); ((SIPMessage)request).setApplicationData(null); final CSeqHeader cSeqHeader = (CSeqHeader) request.getHeader((CSeqHeader.NAME)); try { cSeqHeader.setSeqNumber(cSeqHeader.getSeqNumber() + 1l); cSeqHeader.setMethod(method); } catch (InvalidArgumentException e) { logger.error("Cannot increment the Cseq header to the new " + method + " on the susbequent request to create on session " + key,e); throw new IllegalArgumentException("Cannot create the " + method + " on the susbequent request to create on session " + key,e); } catch (ParseException e) { throw new IllegalArgumentException("Cannot set the " + method + " on the susbequent request to create on session " + key,e); } // Fix for Issue 1130 (http://code.google.com/p/mobicents/issues/detail?id=1130) : // NullPointerException when sending request to client which support both UDP and TCP transport // before removing the ViaHeader we store the transport into its app data ListIterator<ViaHeader> viaHeaders = request.getHeaders(ViaHeader.NAME); if(viaHeaders != null && viaHeaders.hasNext()) { ViaHeader viaHeader = viaHeaders.next(); ((MessageExt)request).setApplicationData(viaHeader.getTransport()); } request.removeHeader(ViaHeader.NAME); final SipNetworkInterfaceManager sipNetworkInterfaceManager = sipFactory.getSipNetworkInterfaceManager(); final SipProvider sipProvider = sipNetworkInterfaceManager.findMatchingListeningPoint( JainSipUtils.findTransport(request), false).getSipProvider(); final SipApplicationDispatcher sipApplicationDispatcher = sipFactory.getSipApplicationDispatcher(); final String branch = JainSipUtils.createBranch(getSipApplicationSession().getKey().getId(), sipApplicationDispatcher.getHashFromApplicationName(getKey().getApplicationName())); ViaHeader viaHeader = JainSipUtils.createViaHeader( sipNetworkInterfaceManager, request, branch, outboundInterface); request.addHeader(viaHeader); sipServletRequest = new SipServletRequestImpl( request, this.sipFactory, this, null, sessionCreatingDialog, true); // Fix for Issue http://code.google.com/p/mobicents/issues/detail?id=2230 BYE is routed to unexpected IP if(sessionCreatingDialog != null && sessionCreatingDialog.getRemoteTarget() != null) { SipUri sipUri = (SipUri) sessionCreatingDialog.getRemoteTarget().getURI().clone(); sipUri.clearUriParms(); if(logger.isDebugEnabled()) { logger.debug("setting request uri to " + sipUri); } request.setRequestURI(sipUri); } } else { if(logger.isDebugEnabled()) { logger.debug("orignal tx for creating susbequent request " + method + " on session " + key +" was a Server Tx"); } try { // copying original params and call id final Request originalRequest = (Request) sessionCreatingTransactionRequest.getMessage(); final FromHeader fromHeader = (FromHeader) originalRequest.getHeader(FromHeader.NAME); final ToHeader toHeader = (ToHeader) originalRequest.getHeader(ToHeader.NAME); final AddressImpl currentLocalParty = (AddressImpl)this.getLocalParty().clone(); final AddressImpl currentRemoteParty = (AddressImpl)this.getRemoteParty().clone(); ((Parameters)currentRemoteParty .getAddress().getURI()).removeParameter("tag"); ((Parameters)currentLocalParty .getAddress().getURI()).removeParameter("tag"); final String originalCallId = ((CallIdHeader)originalRequest.getHeader(CallIdHeader.NAME)).getCallId(); sipServletRequest =(SipServletRequestImpl) sipFactory.createRequest( getSipApplicationSession(), method, currentLocalParty, currentRemoteParty, handlerServlet, originalCallId, fromHeader.getTag()); final Request request = ((Request)sipServletRequest.getMessage()); sipServletRequest.getSipSession().setCseq(((CSeqHeader)request.getHeader(CSeqHeader.NAME)).getSeqNumber()); final Map<String, String> fromParameters = new HashMap<String, String>(); final Iterator<String> fromParameterNames = fromHeader.getParameterNames(); while (fromParameterNames.hasNext()) { String parameterName = (String) fromParameterNames.next(); if(sessionCreatingDialog != null || !SipFactoryImpl.FORBIDDEN_PARAMS.contains(parameterName)) { fromParameters.put(parameterName, fromHeader.getParameter(parameterName)); } } final Map<String, String> toParameters = new HashMap<String, String>(); final Iterator<String> toParameterNames = toHeader.getParameterNames(); while (toParameterNames.hasNext()) { String parameterName = (String) toParameterNames.next(); if(sessionCreatingDialog != null || !SipFactoryImpl.FORBIDDEN_PARAMS.contains(parameterName)) { toParameters.put(parameterName, toHeader.getParameter(parameterName)); } } final ToHeader newTo = (ToHeader) request.getHeader(ToHeader.NAME); for (Entry<String, String> fromParameter : fromParameters.entrySet()) { String value = fromParameter.getValue(); if(value == null) { value = ""; } newTo.setParameter(fromParameter.getKey(), value); } final FromHeader newFrom = (FromHeader) request.getHeader(FromHeader.NAME); for (Entry<String, String> toParameter : toParameters.entrySet()) { String value = toParameter.getValue(); if(value == null) { value = ""; } newFrom.setParameter(toParameter.getKey(), value); } // Fix for Issue http://code.google.com/p/mobicents/issues/detail?id=2230 BYE is routed to unexpected IP if(sessionCreatingDialog != null && sessionCreatingDialog.getRemoteTarget() != null) { SipUri sipUri = (SipUri) sessionCreatingDialog.getRemoteTarget().getURI().clone(); sipUri.clearUriParms(); if(logger.isDebugEnabled()) { logger.debug("setting request uri to " + sipUri); } request.setRequestURI(sipUri); } } catch (ParseException e) { throw new IllegalArgumentException("Problem setting param on the newly created susbequent request " + sipServletRequest,e); } } if(sipSessionSecurity != null && sipSessionSecurity.getNextNonce() != null) { sipServletRequest.updateAuthorizationHeadersWithNextNonce(); } return sipServletRequest; } else { String errorMessage = "Couldn't create the subsequent request " + method + " for this session " + key + ", isValid " + isValid() + ", session state " + state + " , sessionCreatingDialog = " + sessionCreatingDialog; if(sessionCreatingDialog != null) { errorMessage += " , dialog state " + sessionCreatingDialog.getState(); } errorMessage += " , sessionCreatingTransactionRequest = " + sessionCreatingTransactionRequest; throw new IllegalStateException(errorMessage); } } //Application Routing : //removing the route headers and adding them back again except the one //corresponding to the app that is creating the subsequent request //avoid going through the same app that created the subsequent request Request request = (Request) sipServletRequest.getMessage(); final ListIterator<RouteHeader> routeHeaders = request.getHeaders(RouteHeader.NAME); request.removeHeader(RouteHeader.NAME); while (routeHeaders.hasNext()) { RouteHeader routeHeader = routeHeaders.next(); String routeAppNameHashed = ((javax.sip.address.SipURI)routeHeader .getAddress().getURI()). getParameter(MessageDispatcher.RR_PARAM_APPLICATION_NAME); String routeAppName = null; if(routeAppNameHashed != null) { routeAppName = sipFactory.getSipApplicationDispatcher().getApplicationNameFromHash(routeAppNameHashed); } if(routeAppName == null || !routeAppName.equals(getKey().getApplicationName())) { request.addHeader(routeHeader); } } if(sipSessionSecurity != null && sipSessionSecurity.getNextNonce() != null) { sipServletRequest.updateAuthorizationHeadersWithNextNonce(); } return sipServletRequest; } /* * (non-Javadoc) * @see javax.servlet.sip.SipSession#getApplicationSession() */ public SipApplicationSession getApplicationSession() { MobicentsSipApplicationSession sipApplicationSession = getSipApplicationSession(); if(sipApplicationSession == null) { return null; } else { return sipApplicationSession.getSession(); } } // Does it need to be synchronized? protected Map<String, Object> getAttributeMap() { if(this.sipSessionAttributeMap == null) { this.sipSessionAttributeMap = new ConcurrentHashMap<String, Object>(); } return this.sipSessionAttributeMap; } /* * (non-Javadoc) * @see javax.servlet.sip.SipSession#getAttribute(java.lang.String) */ public Object getAttribute(String name) { if(!isValid()) { throw new IllegalStateException("SipApplicationSession already invalidated !"); } return getAttributeMap().get(name); } /* * (non-Javadoc) * @see javax.servlet.sip.SipSession#getAttributeNames() */ public Enumeration<String> getAttributeNames() { if(!isValid()) { throw new IllegalStateException("SipApplicationSession already invalidated !"); } Vector<String> names = new Vector<String>(getAttributeMap().keySet()); return names.elements(); } /* * (non-Javadoc) * @see javax.servlet.sip.SipSession#getCallId() */ public String getCallId() { if(this.sessionCreatingDialog != null) return this.sessionCreatingDialog.getCallId().getCallId(); else return ((CallIdHeader)this.sessionCreatingTransactionRequest.getMessage().getHeader(CallIdHeader.NAME)).getCallId(); } /* * (non-Javadoc) * @see javax.servlet.sip.SipSession#getCreationTime() */ public long getCreationTime() { return creationTime; } /* * (non-Javadoc) * @see javax.servlet.sip.SipSession#getId() */ public String getId() { return key.toString(); } /* * (non-Javadoc) * @see javax.servlet.sip.SipSession#getLastAccessedTime() */ public long getLastAccessedTime() { return lastAccessedTime; } private void setLastAccessedTime(long lastAccessedTime) { this.lastAccessedTime= lastAccessedTime; } /** * Update the accessed time information for this session. This method * should be called by the context when a request comes in for a particular * session, even if the application does not reference it. */ public void access() { setLastAccessedTime(System.currentTimeMillis()); } /* * (non-Javadoc) * @see javax.servlet.sip.SipSession#getLocalParty() */ public Address getLocalParty() { if(sessionCreatingDialog != null) { return new AddressImpl(sessionCreatingDialog.getLocalParty(), null, false); } else if (sessionCreatingTransactionRequest != null){ if(isSessionCreatingTransactionServer) { ToHeader toHeader = (ToHeader) sessionCreatingTransactionRequest.getMessage().getHeader(ToHeader.NAME); return new AddressImpl(toHeader.getAddress(), AddressImpl.getParameters((Parameters)toHeader), false); } else { FromHeader fromHeader = (FromHeader)sessionCreatingTransactionRequest.getMessage().getHeader(FromHeader.NAME); return new AddressImpl(fromHeader.getAddress(), AddressImpl.getParameters((Parameters)fromHeader), false); } } else { return localParty; } } /** * {@inheritDoc} */ public SipApplicationRoutingRegion getRegion() { if(!isValid()) { throw new IllegalStateException("the session has been invalidated"); } if(routingRegion == null) { throw new IllegalStateException("This methos can be called only on initial requests"); } return routingRegion; } /** * {@inheritDoc} */ public SipApplicationRoutingRegion getRegionInternal() { return routingRegion; } /** * This method allows the application to set the region that the application * is in with respect to this SipSession * @param routingRegion the region that the application is in */ public void setRoutingRegion(SipApplicationRoutingRegion routingRegion) { this.routingRegion = routingRegion; } /** * @return the stateInfo */ public Serializable getStateInfo() { return stateInfo; } /** * @param stateInfo the stateInfo to set */ public void setStateInfo(Serializable stateInfo) { this.stateInfo = stateInfo; } /* * (non-Javadoc) * @see javax.servlet.sip.SipSession#getRemoteParty() */ public Address getRemoteParty() { if(sessionCreatingDialog != null) { return new AddressImpl(sessionCreatingDialog.getRemoteParty(), null, false); } else if (sessionCreatingTransactionRequest != null){ try { if(!isSessionCreatingTransactionServer) { ToHeader toHeader = (ToHeader)sessionCreatingTransactionRequest.getMessage().getHeader(ToHeader.NAME); return new AddressImpl(toHeader.getAddress(), AddressImpl.getParameters((Parameters)toHeader), false); } else { FromHeader fromHeader = (FromHeader)sessionCreatingTransactionRequest.getMessage().getHeader(FromHeader.NAME); return new AddressImpl(fromHeader.getAddress(), AddressImpl.getParameters((Parameters)fromHeader), false); } } catch(Exception e) { throw new IllegalArgumentException("Error creating Address", e); } } else { return remoteParty; } } /* * (non-Javadoc) * @see javax.servlet.sip.SipSession#getState() */ public State getState() { if(!isValid()) { throw new IllegalStateException("the session has been invalidated"); } return this.state; } // public ThreadPoolExecutor getExecutorService() { // return executorService; // } /** * {@inheritDoc} */ public URI getSubscriberURI() { if(!isValid()) { throw new IllegalStateException("the session has been invalidated"); } if (this.subscriberURI == null) throw new IllegalStateException("Subscriber URI is only available for outbound sessions."); else { try { return sipFactory.createURI(subscriberURI); } catch (ServletParseException e) { throw new IllegalArgumentException("couldn't parse the outbound interface " + subscriberURI, e); } } } /* * (non-Javadoc) * @see javax.servlet.sip.SipSession#invalidate() */ public void invalidate() { if(!isValidInternal.compareAndSet(true, false)) { throw new IllegalStateException("SipSession already invalidated !"); } if(logger.isInfoEnabled()) { logger.info("Invalidating the sip session " + key); } // No need for checks after JSR 289 PFD spec //checkInvalidation(); if(sipSessionAttributeMap != null) { for (String key : sipSessionAttributeMap.keySet()) { removeAttribute(key, true); } } notifySipSessionListeners(SipSessionEventType.DELETION); isValid = false; if(derivedSipSessions != null) { for (MobicentsSipSession derivedMobicentsSipSession : derivedSipSessions.values()) { derivedMobicentsSipSession.invalidate(); } derivedSipSessions.clear(); } /* * Compute how long this session has been alive, and update * session manager's related properties accordingly */ long timeNow = System.currentTimeMillis(); int timeAlive = (int) ((timeNow - creationTime)/1000); final MobicentsSipApplicationSession sipApplicationSession = getSipApplicationSession(); SipManager manager = sipApplicationSession.getSipContext().getSipManager(); synchronized (manager) { if (timeAlive > manager.getSipSessionMaxAliveTime()) { manager.setSipSessionMaxAliveTime(timeAlive); } int numExpired = manager.getExpiredSipSessions(); numExpired++; manager.setExpiredSipSessions(numExpired); int average = manager.getSipSessionAverageAliveTime(); average = ((average * (numExpired-1)) + timeAlive)/numExpired; manager.setSipSessionAverageAliveTime(average); } manager.removeSipSession(key); sipApplicationSession.getSipContext().getSipSessionsUtil().removeCorrespondingSipSession(key); sipApplicationSession.onSipSessionReadyToInvalidate(this); if(ongoingTransactions != null) { if(logger.isDebugEnabled()) { logger.debug(ongoingTransactions.size() + " ongoing transactions still present in the following sip session " + key + " on invalidation"); } for(Transaction transaction : ongoingTransactions) { if(!TransactionState.TERMINATED.equals(transaction.getState())) { if(transaction.getApplicationData() != null) { ((TransactionApplicationData)transaction.getApplicationData()).cleanUp(); } try { transaction.terminate(); } catch (ObjectInUseException e) { // no worries about this one, we just try to eagerly terminate the tx is the sip session has been forcefully invalidated } } } ongoingTransactions.clear(); } if(subscriptions != null) { subscriptions.clear(); } if(acksReceived != null) { acksReceived.clear(); } if(sipSessionSecurity != null) { sipSessionSecurity.getCachedAuthInfos().clear(); } // executorService.shutdown(); parentSession = null; userPrincipal = null; // executorService = null; // If the sip app session is nullified com.bea.sipservlet.tck.agents.api.javax_servlet_sip.B2buaHelperTest.testCreateResponseToOriginalRequest102 will fail // because it will try to get the B2BUAHelper after the session has been invalidated // sipApplicationSession = null; manager = null; if(b2buaHelper != null) { b2buaHelper.unlinkSipSessionsInternal(this, false); b2buaHelper= null; } derivedSipSessions = null; // not collecting it here to avoid race condition from // http://code.google.com/p/mobicents/issues/detail?id=2130#c19 // handlerServlet = null; localParty = null; ongoingTransactions = null; originalMethod = null; outboundInterface = null; sipSessionAttributeMap = null; // key = null; if(sessionCreatingDialog != null) { // terminating dialog to make sure there is not retention, if the app didn't send a BYE for invite tx by example if(!DialogState.TERMINATED.equals(sessionCreatingDialog.getState())) { sessionCreatingDialog.delete(); } // sessionCreatingDialog.setApplicationData(null); sessionCreatingDialog = null; } if(sessionCreatingTransactionRequest != null) { // sessionCreatingTransaction.setApplicationData(null); Transaction sessionCreatingTransaction = sessionCreatingTransactionRequest.getTransaction(); if(sessionCreatingTransaction != null) { // terminating transaction to make sure there is not retention if(!TransactionState.TERMINATED.equals(sessionCreatingTransaction.getState())) { try { sessionCreatingTransaction.terminate(); } catch (ObjectInUseException e) { // never thrown by jain sip and anyway there is nothing we can do about it } } } sessionCreatingTransactionRequest.cleanUp(); sessionCreatingTransactionRequest = null; } if(proxy != null) { try { proxy.cancel(); } catch (Exception e) { logger.debug("Problem cancelling proxy. We just try our best. This is not a critical error.", e); } proxy.getTransactionMap().clear(); proxy.getProxyBranchesMap().clear(); proxy = null; } remoteParty = null; routingRegion = null; sipFactory = null; state = null; stateInfo = null; subscriberURI = null; subscriptions = null; acksReceived = null; sipSessionSecurity = null; // don't release or nullify the semaphore, it should be done externally // see Issue http://code.google.com/p/mobicents/issues/detail?id=1294 // if(semaphore != null) { // semaphore.release(); // semaphore = null; // } facade = null; } /** * Not needed anymore after PFD JSR 289 spec */ // protected void checkInvalidation() { // if(state.equals(State.CONFIRMED) // || state.equals(State.EARLY)) // throw new IllegalStateException("Can not invalidate sip session in " + // state.toString() + " state."); // if(isSupervisedMode() && hasOngoingTransaction()) { // dumpOngoingTransactions(); // throw new IllegalStateException("Can not invalidate sip session with " + // ongoingTransactions.size() + " ongoing transactions in supervised mode."); // } // } // private void dumpOngoingTransactions() { // if(logger.isDebugEnabled()) { // logger.debug("ongoing transactions in sip the session " + key); // // for (Transaction transaction : ongoingTransactions) { // logger.debug("Transaction " + transaction + " : state = " + transaction.getState()); // } // } // } /** * Removed from the interface in PFD stage * so making it protected */ protected boolean hasOngoingTransaction() { if(!isSupervisedMode()) { return false; } else { if(ongoingTransactions != null) { for (Transaction transaction : ongoingTransactions) { if(TransactionState.CALLING.equals(transaction.getState()) || TransactionState.TRYING.equals(transaction.getState()) || TransactionState.PROCEEDING.equals(transaction.getState()) || TransactionState.COMPLETED.equals(transaction.getState()) || TransactionState.CONFIRMED.equals(transaction.getState())) { return true; } } } return false; } } /* * (non-Javadoc) * @see javax.servlet.sip.SipSession#isValid() */ public boolean isValid() { return this.isValid; } /* * (non-Javadoc) * @see org.mobicents.servlet.sip.core.session.MobicentsSipSession#isValidInternal() */ public boolean isValidInternal() { return isValidInternal.get(); } /** * @param isValid the isValid to set */ public void setValid(boolean isValid) { this.isValidInternal.set(isValid); } /* * (non-Javadoc) * @see javax.servlet.sip.SipSession#removeAttribute(java.lang.String) */ public void removeAttribute(String name) { removeAttribute(name, false); } public void removeAttribute(String name, boolean byPassValidCheck) { if(!byPassValidCheck && !isValid()) throw new IllegalStateException("Can not bind object to session that has been invalidated!!"); if(name==null) // throw new NullPointerException("Name of attribute to bind cant be null!!!"); return; SipSessionBindingEvent event = null; Object value = getAttributeMap().get(name); // Call the valueUnbound() method if necessary if (value != null && value instanceof SipSessionBindingListener) { event = new SipSessionBindingEvent(this, name); ((SipSessionBindingListener) value).valueUnbound(event); } this.getAttributeMap().remove(name); // Notifying Listeners of attribute removal SipListenersHolder sipListenersHolder = this.getSipApplicationSession().getSipContext().getListeners(); List<SipSessionAttributeListener> listenersList = sipListenersHolder.getSipSessionAttributeListeners(); if(listenersList.size() > 0) { if(event == null) { event = new SipSessionBindingEvent(this, name); } for (SipSessionAttributeListener listener : listenersList) { if(logger.isDebugEnabled()) { logger.debug("notifying SipSessionAttributeListener " + listener.getClass().getCanonicalName() + " of attribute removed on key "+ key); } try{ listener.attributeRemoved(event); } catch (Throwable t) { logger.error("SipSessionAttributeListener threw exception", t); } } } } /* * (non-Javadoc) * @see javax.servlet.sip.SipSession#setAttribute(java.lang.String, java.lang.Object) */ public void setAttribute(String key, Object attribute) { if(!isValid()) { throw new IllegalStateException("Can not bind object to session that has been invalidated!!"); } if(key == null) { throw new NullPointerException("Name of attribute to bind cant be null!!!"); } if(attribute == null) { throw new NullPointerException("Attribute that is to be bound cant be null!!!"); } // Construct an event with the new value SipSessionBindingEvent event = null; // Call the valueBound() method if necessary if (attribute instanceof SipSessionBindingListener) { // Don't call any notification if replacing with the same value Object oldValue = getAttributeMap().get(key); if (attribute != oldValue) { event = new SipSessionBindingEvent(this, key); try { ((SipSessionBindingListener) attribute).valueBound(event); } catch (Throwable t){ logger.error("SipSessionBindingListener threw exception", t); } } } Object previousValue = this.getAttributeMap().put(key, attribute); if (previousValue != null && previousValue != attribute && previousValue instanceof SipSessionBindingListener) { try { ((SipSessionBindingListener) previousValue).valueUnbound (new SipSessionBindingEvent(this, key)); } catch (Throwable t) { logger.error("SipSessionBindingListener threw exception", t); } } // Notifying Listeners of attribute addition or modification SipListenersHolder sipListenersHolder = this.getSipApplicationSession().getSipContext().getListeners(); List<SipSessionAttributeListener> listenersList = sipListenersHolder.getSipSessionAttributeListeners(); if(listenersList.size() > 0) { if(event == null) { event = new SipSessionBindingEvent(this, key); } if (previousValue == null) { // This is initial, we need to send value bound event for (SipSessionAttributeListener listener : listenersList) { if(logger.isDebugEnabled()) { logger.debug("notifying SipSessionAttributeListener " + listener.getClass().getCanonicalName() + " of attribute added on key "+ key); } try { listener.attributeAdded(event); } catch (Throwable t) { logger.error("SipSessionAttributeListener threw exception", t); } } } else { for (SipSessionAttributeListener listener : listenersList) { if(logger.isDebugEnabled()) { logger.debug("notifying SipSessionAttributeListener " + listener.getClass().getCanonicalName() + " of attribute replaced on key "+ key); } try { listener.attributeReplaced(event); } catch (Throwable t) { logger.error("SipSessionAttributeListener threw exception", t); } } } } } /* * (non-Javadoc) * @see javax.servlet.sip.SipSession#setHandler(java.lang.String) */ public void setHandler(String name) throws ServletException { if(!isValid()) { throw new IllegalStateException("the session has already been invalidated, no handler can be set on it anymore !"); } if(name != null && name.equals(handlerServlet)) { return ; } SipContext sipContext = getSipApplicationSession().getSipContext(); Container container = sipContext.findChildrenByName(name); if(container == null && sipContext.getSipRubyController() == null) { throw new ServletException("the sip servlet with the name "+ name + " doesn't exist in the sip application " + sipContext.getApplicationName()); } this.handlerServlet = name; getSipApplicationSession().setCurrentRequestHandler(handlerServlet); if(logger.isDebugEnabled()) { if(name !=null) { logger.debug("Session Handler for application " + getKey().getApplicationName() + " set to " + handlerServlet + " on sip session " + key); } else { logger.debug("Session Handler for application " + getKey().getApplicationName() + " set to " + sipContext.getSipRubyController() + " on sip session " + key); } } } /** * Retrieve the handler associated with this sip session * @return the handler associated with this sip session */ public String getHandler() { return handlerServlet; } /** * @param dialog the dialog to set */ public void setSessionCreatingDialog(Dialog dialog) { this.sessionCreatingDialog = dialog; if(logger.isDebugEnabled()) { logger.debug("setting session creating dialog for this session to " + dialog); if(dialog != null) { logger.debug("session creating dialog dialogId " + dialog.getDialogId()); } } } /** * @return the dialog */ public Dialog getSessionCreatingDialog() { return sessionCreatingDialog; } public MobicentsSipApplicationSession getSipApplicationSession() { if(sipApplicationSession == null) { final String applicationName = key.getApplicationName(); final SipContext sipContext = sipFactory.getSipApplicationDispatcher().findSipApplication(applicationName); if(sipContext != null) { sipApplicationSession = sipContext.getSipManager().getSipApplicationSession(sipApplicationSessionKey, false); } } return sipApplicationSession; } protected void setSipApplicationSession( MobicentsSipApplicationSession sipApplicationSession) { if (sipApplicationSession != null) { this.sipApplicationSessionKey = sipApplicationSession.getKey(); sipApplicationSession.addSipSession(this); } } public SipServletRequestImpl getSessionCreatingTransactionRequest() { return sessionCreatingTransactionRequest; } /** * @param sessionCreatingTransaction the sessionCreatingTransaction to set */ public void setSessionCreatingTransactionRequest(SipServletMessageImpl message) { if(message != null) { if(message instanceof SipServletRequestImpl) { this.sessionCreatingTransactionRequest = (SipServletRequestImpl) message; this.isSessionCreatingTransactionServer = message.getTransaction() instanceof ServerTransaction; } else if(message.getTransaction() != null && message.getTransaction().getApplicationData() != null) { SipServletMessageImpl sipServletMessageImpl = ((TransactionApplicationData)message.getTransaction().getApplicationData()).getSipServletMessage(); if(sipServletMessageImpl != null && sipServletMessageImpl instanceof SipServletRequestImpl) { this.sessionCreatingTransactionRequest = (SipServletRequestImpl) sipServletMessageImpl; this.isSessionCreatingTransactionServer = message.getTransaction() instanceof ServerTransaction; } } } if(sessionCreatingTransactionRequest != null) { if(originalMethod == null) { originalMethod = sessionCreatingTransactionRequest.getMethod(); } addOngoingTransaction(sessionCreatingTransactionRequest.getTransaction()); // Issue 906 : CSeq is not increased correctly for REGISTER requests if registrar requires authentication. // http://code.google.com/p/mobicents/issues/detail?id=906 // we update the parent session for the REGISTER so that the CSeq is correctly increased // if the session is stored if(parentSession != null && Request.REGISTER.equals(originalMethod)) { parentSession.setSessionCreatingTransactionRequest(message); } } } public boolean isSupervisedMode() { if(proxy == null) { return true; } else { return this.proxy.getSupervised(); } } public void setSipSubscriberURI(String subscriberURI) { this.subscriberURI = subscriberURI; } public String getSipSubscriberURI() { return subscriberURI; } public String getOutboundInterface() { return outboundInterface; } public void onDialogTimeout(Dialog dialog) { if(hasOngoingTransaction()) { throw new IllegalStateException("Dialog timed out, but there are active transactions."); } this.state = State.TERMINATED; } public void setState(State state) { this.state = state; } public void onTerminatedState() { if(isValidInternal()) { onReadyToInvalidate(); if(this.parentSession != null) { Iterator<MobicentsSipSession> derivedSessionsIterator = parentSession.getDerivedSipSessions(); while (derivedSessionsIterator.hasNext()) { MobicentsSipSession mobicentsSipSession = (MobicentsSipSession) derivedSessionsIterator .next(); if(mobicentsSipSession.isValidInternal() && !mobicentsSipSession.isReadyToInvalidate()) { return; } } this.parentSession.onReadyToInvalidate(); } } } /** * Add an ongoing tx to the session. */ public void addOngoingTransaction(Transaction transaction) { if(transaction != null && ongoingTransactions != null && !isReadyToInvalidate() ) { boolean added = this.ongoingTransactions.add(transaction); if(added) { if(logger.isDebugEnabled()) { logger.debug("transaction "+ transaction +" has been added to sip session's ongoingTransactions" ); } setReadyToInvalidate(false); } } } /** * Remove an ongoing tx to the session. */ public void removeOngoingTransaction(Transaction transaction) { boolean removed = false; if(this.ongoingTransactions != null) { removed = this.ongoingTransactions.remove(transaction); } // if(sessionCreatingTransactionRequest != null && sessionCreatingTransactionRequest.getMessage() != null && JainSipUtils.DIALOG_CREATING_METHODS.contains(sessionCreatingTransactionRequest.getMethod())) { // sessionCreatingTransactionRequest = null; // } if(sessionCreatingTransactionRequest != null && sessionCreatingTransactionRequest.getTransaction()!= null && sessionCreatingTransactionRequest.getTransaction().equals(transaction)) { sessionCreatingTransactionRequest.cleanUp(); } if(logger.isDebugEnabled()) { logger.debug("transaction "+ transaction +" has been removed from sip session's ongoingTransactions ? " + removed ); } updateReadyToInvalidate(transaction); } public Set<Transaction> getOngoingTransactions() { return this.ongoingTransactions; } /** * Update the sip session state upon sending/receiving a response * Covers JSR 289 Section 6.2.1 along with updateStateOnRequest method * @param response the response received/to send * @param receive true if the response has been received, false if it is to be sent. */ public void updateStateOnResponse(SipServletResponseImpl response, boolean receive) { final String method = response.getMethod(); if(sipSessionSecurity != null && response.getStatus() >= 200 && response.getStatus() < 300) { // Issue 2173 http://code.google.com/p/mobicents/issues/detail?id=2173 // it means some credentials were cached need to check if we need to store the nextnonce if the response have one AuthenticationInfoHeader authenticationInfoHeader = (AuthenticationInfoHeader)response.getMessage().getHeader(AuthenticationInfoHeader.NAME); if(authenticationInfoHeader != null) { String nextNonce = authenticationInfoHeader.getNextNonce(); if(logger.isDebugEnabled()) { logger.debug("Storing nextNonce " + nextNonce + " for session " + key); } sipSessionSecurity.setNextNonce(nextNonce); } } // JSR 289 Section 6.2.1 Point 2 of rules governing the state of SipSession // In general, whenever a non-dialog creating request is sent or received, // the SipSession state remains unchanged. Similarly, a response received // for a non-dialog creating request also leaves the SipSession state unchanged. // The exception to the general rule is that it does not apply to requests (e.g. BYE, CANCEL) // that are dialog terminating according to the appropriate RFC rules relating to the kind of dialog. if(!JainSipUtils.DIALOG_CREATING_METHODS.contains(method) && !JainSipUtils.DIALOG_TERMINATING_METHODS.contains(method)) { if(getSessionCreatingDialog() == null && proxy == null) { // Fix for issue http://code.google.com/p/mobicents/issues/detail?id=2116 // avoid creating derived sessions for non dialogcreating requests if(logger.isDebugEnabled()) { logger.debug("resetting the to tag since a response to a non dialog creating and terminating method has been received for non proxy session with no dialog in state " + state); } key.setToTag(null); } return; } // Mapping to the sip session state machine (proxy is covered here too) if( (State.INITIAL.equals(state) || State.EARLY.equals(state)) && response.getStatus() >= 200 && response.getStatus() < 300 && !JainSipUtils.DIALOG_TERMINATING_METHODS.contains(method)) { this.setState(State.CONFIRMED); if(this.proxy != null && response.getProxyBranch() != null && !response.getProxyBranch().getRecordRoute()) { // Section 6.2.4.1.2 Invalidate When Ready Mechanism : // "The container determines the SipSession to be in the ready-to-invalidate state under any of the following conditions: // 2. A SipSession transitions to the CONFIRMED state when it is acting as a non-record-routing proxy." setReadyToInvalidate(true); } if(logger.isDebugEnabled()) { logger.debug("the following sip session " + getKey() + " has its state updated to " + state); } } // Mapping to the sip session state machine // We will transition from INITIAL to EARLY here for 100 Trying (not clear from the spec) // Figure 6-1 The SIP Dialog State Machine // and Figure 6-2 The SipSession State Machine if( State.INITIAL.equals(state) && response.getStatus() >= 100 && response.getStatus() < 200 ) { this.setState(State.EARLY); if(logger.isDebugEnabled()) { logger.debug("the following sip session " + getKey() + " has its state updated to " + state); } } if( (State.INITIAL.equals(state) || State.EARLY.equals(state)) && response.getStatus() >= 300 && response.getStatus() < 700 && JainSipUtils.DIALOG_CREATING_METHODS.contains(method) && !JainSipUtils.DIALOG_TERMINATING_METHODS.contains(method)) { // If the servlet acts as a UAC and sends a dialog creating request, // then the SipSession state tracks directly the SIP dialog state except // that non-2XX final responses received in the EARLY or INITIAL states // cause the SipSession state to return to the INITIAL state rather than going to TERMINATED. // + // If the servlet acts as a proxy for a dialog creating request then // the SipSession state tracks the SIP dialog state except that non-2XX // final responses received from downstream in the EARLY or INITIAL states // cause the SipSession state to return to INITIAL rather than going to TERMINATED. if(receive) { if(proxy == null) { // Fix for issue http://code.google.com/p/mobicents/issues/detail?id=2083 if(logger.isDebugEnabled()) { logger.debug("resetting the to tag since a non 2xx response has been received for non proxy session in state " + state); } key.setToTag(null); } setState(State.INITIAL); // readyToInvalidate = true; if(logger.isDebugEnabled()) { logger.debug("the following sip session " + getKey() + " has its state updated to " + state); } } // If the servlet acts as a UAS and receives a dialog creating request, // then the SipSession state directly tracks the SIP dialog state. // Unlike a UAC, a non-2XX final response sent by the UAS in the EARLY or INITIAL // states causes the SipSession state to go directly to the TERMINATED state. // + // This enables proxy servlets to proxy requests to additional destinations // when called by the container in the doResponse() method for a tentative // non-2XX best response. // After all such additional proxy branches have been responded to and after // considering any servlet created responses, the container eventually arrives at // the overall best response and forwards this response upstream. // If this best response is a non-2XX final response, then when the forwarding takes place, // the state of the SipSession object becomes TERMINATED. else { setState(State.TERMINATED); setReadyToInvalidate(true); if(logger.isDebugEnabled()) { logger.debug("the following sip session " + getKey() + " has its state updated to " + state); } } } if(((State.CONFIRMED.equals(state) || State.TERMINATED.equals(state)) && response.getStatus() >= 200 && Request.BYE.equals(method)) // http://code.google.com/p/mobicents/issues/detail?id=1438 // Sip Session become TERMINATED after receiving 487 response to subsequent request => !confirmed clause added || (!State.CONFIRMED.equals(state) && response.getStatus() == 487)) { boolean hasOngoingSubscriptions = false; if(subscriptions != null) { if(subscriptions.size() > 0) { hasOngoingSubscriptions = true; } if(logger.isDebugEnabled()) { logger.debug("the following sip session " + getKey() + " has " + subscriptions.size() + " subscriptions"); } if(!hasOngoingSubscriptions) { if(sessionCreatingDialog != null) { sessionCreatingDialog.delete(); } } } if(!hasOngoingSubscriptions) { if(getProxy() == null || response.getStatus() != 487) { setState(State.TERMINATED); setReadyToInvalidate(true); if(logger.isDebugEnabled()) { logger.debug("the following sip session " + getKey() + " has its state updated to " + state); logger.debug("the following sip session " + getKey() + " is ready to be invalidated "); } } } if(logger.isDebugEnabled()) { logger.debug("the following sip session " + getKey() + " has its state updated to " + state); } okToByeSentOrReceived = true; } // we send the CANCEL only for 1xx responses if(response.getTransactionApplicationData().isCanceled() && response.getStatus() < 200 && !response.getMethod().equals(Request.CANCEL)) { SipServletRequestImpl request = (SipServletRequestImpl) response.getTransactionApplicationData().getSipServletMessage(); if(logger.isDebugEnabled()) { logger.debug("request to cancel " + request + " routingstate " + request.getRoutingState() + " requestCseq " + ((MessageExt)request.getMessage()).getCSeqHeader().getSeqNumber() + " responseCseq " + ((MessageExt)response.getMessage()).getCSeqHeader().getSeqNumber()); } if(!request.getRoutingState().equals(RoutingState.CANCELLED) && ((MessageExt)request.getMessage()).getCSeqHeader().getSeqNumber() == ((MessageExt)response.getMessage()).getCSeqHeader().getSeqNumber()) { if(response.getStatus() > 100) { request.setRoutingState(RoutingState.CANCELLED); } try { request.createCancel().send(); } catch (IOException e) { if(logger.isEnabledFor(Priority.WARN)) { logger.warn("Couldn't send CANCEL for a transaction that has been CANCELLED but " + "CANCEL was not sent because there was no response from the other side. We" + " just stopped the retransmissions." + response + "\nThe transaction" + response.getTransaction(), e); } } } } } /** * Update the sip session state upon sending/receiving a subsequent request * Covers JSR 289 Section 6.2.1 along with updateStateOnResponse method * @param request the subsequent request received/to send * @param receive true if the subsequent request has been received, false if it is to be sent. */ public void updateStateOnSubsequentRequest( SipServletRequestImpl request, boolean receive) { //state updated to TERMINATED for CANCEL only if no final response had been received on the inviteTransaction if(((Request.CANCEL.equalsIgnoreCase(request.getMethod())))) { if(!(request.getTransaction() instanceof ServerTransactionExt)) { return; } final Transaction inviteTransaction = ((ServerTransactionExt) request.getTransaction()).getCanceledInviteTransaction(); TransactionApplicationData inviteAppData = (TransactionApplicationData) inviteTransaction.getApplicationData(); SipServletRequestImpl inviteRequest = (SipServletRequestImpl)inviteAppData.getSipServletMessage(); // Issue 1484 : http://code.google.com/p/mobicents/issues/detail?id=1484 // we terminate the session only for initial requests if((inviteRequest != null && inviteRequest.isInitial() && inviteRequest.getLastFinalResponse() == null) || (proxy != null && proxy.getBestResponse() == null)) { this.setState(State.TERMINATED); if(logger.isDebugEnabled()) { logger.debug("the following sip session " + getKey() + " has its state updated to " + state); } } } if(Request.ACK.equalsIgnoreCase(request.getMethod())) { if(sessionCreatingTransactionRequest != null) { sessionCreatingTransactionRequest.cleanUpLastResponses(); } } } private void updateReadyToInvalidate(Transaction transaction) { // Section 6.2.4.1.2 Invalidate When Ready Mechanism : // "The container determines the SipSession to be in the ready-to-invalidate state under any of the following conditions: // 3. A SipSession acting as a UAC transitions from the EARLY state back to // the INITIAL state on account of receiving a non-2xx final response (6.2.1 Relationship to SIP Dialogs, point 4) // and has not initiated any new requests (does not have any pending transactions)." if(!readyToInvalidate && (ongoingTransactions == null || ongoingTransactions.isEmpty()) && transaction instanceof ClientTransaction && getProxy() == null && state != null && state.equals(State.INITIAL) && // Fix for Issue 1734 sessionCreatingTransactionRequest != null && sessionCreatingTransactionRequest.getLastFinalResponse() != null && sessionCreatingTransactionRequest.getLastFinalResponse().getStatus() >= 300) { setReadyToInvalidate(true); } } /** * This method is called immediately when the conditions for read to invalidate * session are met */ public void onReadyToInvalidate() { this.setReadyToInvalidate(true); if(logger.isDebugEnabled()) { logger.debug("invalidateWhenReady flag is set to " + invalidateWhenReady); } if(isValid() && this.invalidateWhenReady) { this.notifySipSessionListeners(SipSessionEventType.READYTOINVALIDATE); //If the application does not explicitly invalidate the session in the callback or has not defined a listener, //the container will invalidate the session. if(isValid()) { invalidate(); } } } /** * @return the key */ public SipSessionKey getKey() { return key; } /** * @param key the key to set */ public void setKey(SipSessionKey key) { this.key = key; } /** * {@inheritDoc} */ public ProxyImpl getProxy() { return proxy; } /** * {@inheritDoc} */ public void setProxy(ProxyImpl proxy) { this.proxy = proxy; } /** * {@inheritDoc} */ public void setB2buaHelper(B2buaHelperImpl helperImpl) { this.b2buaHelper = helperImpl; } /** * {@inheritDoc} */ public B2buaHelperImpl getB2buaHelper() { return this.b2buaHelper; } /** * Perform the internal processing required to passivate * this session. */ public void passivate() { // Notify ActivationListeners SipSessionEvent event = null; if(this.sipSessionAttributeMap != null) { Set<String> keySet = getAttributeMap().keySet(); for (String key : keySet) { Object attribute = getAttributeMap().get(key); if (attribute instanceof SipSessionActivationListener) { if (event == null) event = new SipSessionEvent(this); try { ((SipSessionActivationListener)attribute) .sessionWillPassivate(event); } catch (Throwable t) { logger.error("SipSessionActivationListener threw exception", t); } } } } } /** * Perform internal processing required to activate this * session. */ public void activate() { // Notify ActivationListeners SipSessionEvent event = null; if(sipSessionAttributeMap != null) { Set<String> keySet = getAttributeMap().keySet(); for (String key : keySet) { Object attribute = getAttributeMap().get(key); if (attribute instanceof SipSessionActivationListener) { if (event == null) event = new SipSessionEvent(this); try { ((SipSessionActivationListener)attribute) .sessionDidActivate(event); } catch (Throwable t) { logger.error("SipSessionActivationListener threw exception", t); } } } } } public Principal getUserPrincipal() { return userPrincipal; } public void setUserPrincipal(Principal userPrincipal) { this.userPrincipal = userPrincipal; } public boolean getInvalidateWhenReady() { if(!isValid()) { throw new IllegalStateException("the session has been invalidated"); } return invalidateWhenReady; } public boolean isReadyToInvalidate() { if(!isValid()) { throw new IllegalStateException("the session has been invalidated"); } return readyToInvalidate; } /** * @param readyToInvalidate the readyToInvalidate to set */ public void setReadyToInvalidate(boolean readyToInvalidate) { if(logger.isDebugEnabled()) { logger.debug("readyToInvalidate flag is set to " + readyToInvalidate); } this.readyToInvalidate = readyToInvalidate; } public boolean isReadyToInvalidateInternal() { return readyToInvalidate; } public void setInvalidateWhenReady(boolean arg0) { if(!isValid()) { throw new IllegalStateException("the session has been invalidated"); } invalidateWhenReady = arg0; } /* * (non-Javadoc) * @see javax.servlet.sip.SipSession#setOutboundInterface(java.net.InetAddress) */ public void setOutboundInterface(InetAddress inetAddress) { if(!isValid()) { throw new IllegalStateException("the session has been invalidated"); } if(inetAddress == null) { throw new NullPointerException("parameter is null"); } String address = inetAddress.getHostAddress(); List<SipURI> list = sipFactory.getSipNetworkInterfaceManager().getOutboundInterfaces(); SipURI networkInterface = null; for(SipURI networkInterfaceURI : list) { if(networkInterfaceURI.toString().contains(address)) { networkInterface = networkInterfaceURI; break; } } if(networkInterface == null) throw new IllegalArgumentException("Network interface for " + address + " not found"); try { outboundInterface = new SipURIImpl(SipFactories.addressFactory.createSipURI(null, address)).toString(); } catch (ParseException e) { logger.error("couldn't parse the SipURI from USER[" + null + "] HOST[" + address + "]", e); throw new IllegalArgumentException("Could not create SIP URI user = " + null + " host = " + address); } } /* * (non-Javadoc) * @see javax.servlet.sip.SipSession#setOutboundInterface(java.net.InetSocketAddress) */ public void setOutboundInterface(InetSocketAddress inetSocketAddress) { if(!isValid()) { throw new IllegalStateException("the session has been invalidated"); } if(inetSocketAddress == null) { throw new NullPointerException("parameter is null"); } String address = inetSocketAddress.getAddress().getHostAddress() + ":" + inetSocketAddress.getPort(); List<SipURI> list = sipFactory.getSipNetworkInterfaceManager().getOutboundInterfaces(); SipURI networkInterface = null; for(SipURI networkInterfaceURI : list) { if(networkInterfaceURI.toString().contains(address)) { networkInterface = networkInterfaceURI; break; } } if(networkInterface == null) throw new IllegalArgumentException("Network interface for " + address + " not found"); try { outboundInterface = new SipURIImpl(SipFactories.addressFactory.createSipURI(null, address)).toString(); } catch (ParseException e) { logger.error("couldn't parse the SipURI from USER[" + null + "] HOST[" + address + "]", e); throw new IllegalArgumentException("Could not create SIP URI user = " + null + " host = " + address); } } /* * (non-Javadoc) * @see org.mobicents.javax.servlet.sip.SipSessionExt#setOutboundInterface(javax.servlet.sip.SipURI) */ public void setOutboundInterface(SipURI outboundInterface) { if(!isValid()) { throw new IllegalStateException("the session has been invalidated"); } if(outboundInterface == null) { throw new NullPointerException("parameter is null"); } List<SipURI> list = sipFactory.getSipNetworkInterfaceManager().getOutboundInterfaces(); SipURI networkInterface = null; for(SipURI networkInterfaceURI : list) { if(networkInterfaceURI.equals(outboundInterface)) { networkInterface = networkInterfaceURI; break; } } if(networkInterface == null) throw new IllegalArgumentException("Network interface for " + outboundInterface + " not found"); this.outboundInterface = outboundInterface.toString(); } /** * {@inheritDoc} */ public ServletContext getServletContext() { return getSipApplicationSession().getSipContext().getServletContext(); } /* * (non-Javadoc) * @see org.mobicents.servlet.sip.core.session.MobicentsSipSession#removeDerivedSipSession(java.lang.String) */ public MobicentsSipSession removeDerivedSipSession(String toTag) { return derivedSipSessions.remove(toTag); } /* * (non-Javadoc) * @see org.mobicents.servlet.sip.core.session.MobicentsSipSession#findDerivedSipSession(java.lang.String) */ public MobicentsSipSession findDerivedSipSession(String toTag) { if(derivedSipSessions != null) { return derivedSipSessions.get(toTag); } return null; } /* * (non-Javadoc) * @see org.mobicents.servlet.sip.core.session.MobicentsSipSession#getDerivedSipSessions() */ public Iterator<MobicentsSipSession> getDerivedSipSessions() { if(derivedSipSessions != null) { return derivedSipSessions.values().iterator(); } return new HashMap<String, MobicentsSipSession>().values().iterator(); } /* * (non-Javadoc) * @see org.mobicents.servlet.sip.core.session.MobicentsSipSession#setParentSession(org.mobicents.servlet.sip.core.session.MobicentsSipSession) */ public void setParentSession(MobicentsSipSession mobicentsSipSession) { parentSession = mobicentsSipSession; } /* * (non-Javadoc) * @see org.mobicents.servlet.sip.core.session.MobicentsSipSession#setSipSessionAttributeMap(java.util.Map) */ public void setSipSessionAttributeMap( Map<String, Object> sipSessionAttributeMap) { this.sipSessionAttributeMap = sipSessionAttributeMap; } /* * (non-Javadoc) * @see org.mobicents.servlet.sip.core.session.MobicentsSipSession#addDerivedSipSessions(org.mobicents.servlet.sip.core.session.MobicentsSipSession) */ public void addDerivedSipSessions(MobicentsSipSession derivedSession) { if(derivedSipSessions == null) { this.derivedSipSessions = new ConcurrentHashMap<String, MobicentsSipSession>(); } derivedSipSessions.putIfAbsent(derivedSession.getKey().getToTag(), derivedSession); } /* * (non-Javadoc) * @see org.mobicents.servlet.sip.core.session.MobicentsSipSession#getSipSessionAttributeMap() */ public Map<String, Object> getSipSessionAttributeMap() { return getAttributeMap(); } /* * (non-Javadoc) * @see org.mobicents.servlet.sip.core.session.MobicentsSipSession#setLocalParty(javax.servlet.sip.Address) */ public void setLocalParty(Address localParty) { this.localParty = localParty; } /* * (non-Javadoc) * @see org.mobicents.servlet.sip.core.session.MobicentsSipSession#setRemoteParty(javax.servlet.sip.Address) */ public void setRemoteParty(Address remoteParty) { this.remoteParty = remoteParty; } /** * {@inheritDoc} */ public void addSubscription(SipServletMessageImpl sipServletMessageImpl) throws SipException { EventHeader eventHeader = null; if(sipServletMessageImpl instanceof SipServletResponseImpl) { eventHeader = (EventHeader) ((SipServletRequestImpl)((SipServletResponseImpl)sipServletMessageImpl).getRequest()).getMessage().getHeader(EventHeader.NAME); } else { eventHeader = (EventHeader) sipServletMessageImpl.getMessage().getHeader(EventHeader.NAME); } if(logger.isDebugEnabled()) { logger.debug("adding subscription " + eventHeader + " to sip session " + getId()); } if(subscriptions == null) { this.subscriptions = new CopyOnWriteArraySet<EventHeader>(); } subscriptions.add(eventHeader); if(logger.isDebugEnabled()) { logger.debug("Request from Original Transaction is " + originalMethod); logger.debug("Dialog is " + sessionCreatingDialog); } if(subscriptions.size() < 2 && Request.INVITE.equals(originalMethod)) { sessionCreatingDialog.terminateOnBye(false); } } /** * {@inheritDoc} */ public void removeSubscription(SipServletMessageImpl sipServletMessageImpl) { EventHeader eventHeader = (EventHeader) sipServletMessageImpl.getMessage().getHeader(EventHeader.NAME); if(logger.isDebugEnabled()) { logger.debug("removing subscription " + eventHeader + " to sip session " + getId()); } boolean hasOngoingSubscriptions = false; if(subscriptions != null) { subscriptions.remove(eventHeader); if(subscriptions.size() > 0) { hasOngoingSubscriptions = true; } if(!hasOngoingSubscriptions) { if(subscriptions.size() < 1) { if((originalMethod != null && okToByeSentOrReceived) || !Request.INVITE.equals(originalMethod) ) { setReadyToInvalidate(true); setState(State.TERMINATED); } } } } if(isReadyToInvalidateInternal()) { if(logger.isDebugEnabled()) { logger.debug("no more subscriptions in session " + getId()); } if(sessionCreatingDialog != null) { sessionCreatingDialog.delete(); } } } /** * @return the semaphore */ public Semaphore getSemaphore() { return semaphore; } public MobicentsSipSessionFacade getSession() { if (facade == null){ if (SecurityUtil.isPackageProtectionEnabled()){ final MobicentsSipSession fsession = this; facade = (MobicentsSipSessionFacade)AccessController.doPrivileged(new PrivilegedAction(){ public Object run(){ return new MobicentsSipSessionFacade(fsession); } }); } else { facade = new MobicentsSipSessionFacade(this); } } return (facade); } @Override public boolean equals(Object obj) { if(obj instanceof MobicentsSipSession) { return ((MobicentsSipSession)obj).getKey().equals(getKey()); } return false; } @Override public int hashCode() { return getKey().hashCode(); } @Override public String toString() { return getKey().toString(); } public SipApplicationRouterInfo getNextSipApplicationRouterInfo() { return nextSipApplicationRouterInfo; } public void setNextSipApplicationRouterInfo( SipApplicationRouterInfo routerInfo) { this.nextSipApplicationRouterInfo = routerInfo; } /** * Setting ackReceived for CSeq to specified value in second param. * if the second param is true it will try to cleanup earlier cseq as well to save on memory * @param cSeq cseq to set the ackReceived * @param ackReceived whether or not the ack has been received for this cseq */ public void setAckReceived(long cSeq, boolean ackReceived) { if(logger.isDebugEnabled()) { logger.debug("setting AckReceived to : " + ackReceived + " for CSeq " + cSeq); } acksReceived.put(cSeq, ackReceived); if(ackReceived) { cleanupAcksReceived(cSeq); } } /** * check if the ack has been received for the cseq in param * it may happen that the ackReceived has been removed already if that's the case it will return true * @param cSeq CSeq number to check if the ack has already been received * @return */ protected boolean isAckReceived(long cSeq) { Boolean ackReceived = acksReceived.get(cSeq); if(logger.isDebugEnabled()) { logger.debug("isAckReceived for CSeq " + cSeq +" : " + ackReceived); } if(ackReceived == null) { // if there is no value for it it means that it is a retransmission return true; } return ackReceived; } /** * We clean up the stored acks received when the remoteCSeq in param is greater and * that the ackReceived is true * @param remoteCSeq remoteCSeq the basis CSeq for cleaning up earlier (lower CSeq) stored ackReceived */ protected void cleanupAcksReceived(long remoteCSeq) { List<Long> toBeRemoved = new ArrayList<Long>(); final Iterator<Entry<Long, Boolean>> cSeqs = acksReceived.entrySet().iterator(); while (cSeqs.hasNext()) { final Entry<Long, Boolean> entry = cSeqs.next(); final long cSeq = entry.getKey(); final boolean ackReceived = entry.getValue(); if(ackReceived && cSeq < remoteCSeq) { toBeRemoved.add(cSeq); } } for(Long cSeq: toBeRemoved) { acksReceived.remove(cSeq); if(logger.isDebugEnabled()) { logger.debug("removed ackReceived for CSeq " + cSeq); } } } public long getCseq() { return cseq; } public void setCseq(long cseq) { this.cseq = cseq; } //CSeq validation should only be done for non proxy applications public boolean validateCSeq(SipServletRequestImpl sipServletRequest) { final Request request = (Request) sipServletRequest.getMessage(); final long localCseq = cseq; final long remoteCSeq = ((CSeqHeader) request.getHeader(CSeqHeader.NAME)).getSeqNumber(); final String method = request.getMethod(); final boolean isAck = Request.ACK.equalsIgnoreCase(method); final boolean isPrackCancel= Request.PRACK.equalsIgnoreCase(method) || Request.CANCEL.equalsIgnoreCase(method); boolean resetLocalCSeq = true; if(isAck && isAckReceived(remoteCSeq)) { // Filter out ACK retransmissions for JSIP patch for http://code.google.com/p/mobicents/issues/detail?id=766 logger.debug("ACK filtered out as a retransmission. This Sip Session already has been ACKed."); return false; } if(isAck) { if(logger.isDebugEnabled()) { logger.debug("localCSeq : " + localCseq + ", remoteCSeq : " + remoteCSeq); } setAckReceived(remoteCSeq, true); } if(localCseq == remoteCSeq && !isAck) { logger.debug("dropping retransmission " + request + " since it matches the current sip session cseq " + localCseq); return false; } if(localCseq > remoteCSeq) { if(!isAck && !isPrackCancel) { logger.error("CSeq out of order for the following request " + sipServletRequest); if(Request.INVITE.equalsIgnoreCase(method)) { setAckReceived(remoteCSeq, false); } final SipServletResponse response = sipServletRequest.createResponse(Response.SERVER_INTERNAL_ERROR, "CSeq out of order"); try { response.send(); } catch (IOException e) { logger.error("Can not send error response", e); } return false; } else { // Issue 1714 : if the local cseq is greater then the remote one don't reset the local cseq resetLocalCSeq= false; } } if(logger.isDebugEnabled()) { logger.debug("resetLocalCSeq : " + resetLocalCSeq); } if(resetLocalCSeq) { setCseq(remoteCSeq); if(Request.INVITE.equalsIgnoreCase(method)) { setAckReceived(remoteCSeq, false); } } return true; } public String getTransport() { return transport; } public void setTransport(String transport) { this.transport = transport; } /* * (non-Javadoc) * @see org.mobicents.javax.servlet.sip.SipSessionExt#scheduleAsynchronousWork(org.mobicents.javax.servlet.sip.SipSessionAsynchronousWork) */ public void scheduleAsynchronousWork(SipSessionAsynchronousWork work) { sipFactory.getSipApplicationDispatcher().getAsynchronousExecutor().execute(new SipSessionAsyncTask(key, work, sipFactory)); } public int getRequestsPending() { return requestsPending; } public void setRequestsPending(int requests) { // Sometimes the count might not match due to retransmissing of ACK after OK is missing or CANCEL, // we should never go negative here if(requests < 0) requests = 0; requestsPending = requests; } /* * (non-Javadoc) * @see org.mobicents.javax.servlet.sip.SipSessionExt#setCopyRecordRouteHeadersOnSubsequentResponses(boolean) */ public void setCopyRecordRouteHeadersOnSubsequentResponses( boolean copyRecordRouteHeadersOnSubsequentResponses) { this.copyRecordRouteHeadersOnSubsequentResponses = copyRecordRouteHeadersOnSubsequentResponses; } /* * (non-Javadoc) * @see org.mobicents.javax.servlet.sip.SipSessionExt#getCopyRecordRouteHeadersOnSubsequentResponses() */ public boolean getCopyRecordRouteHeadersOnSubsequentResponses() { return copyRecordRouteHeadersOnSubsequentResponses; } /** * @param sipSessionSecurity the sipSessionSecurity to set */ public void setSipSessionSecurity(SipSessionSecurity sipSessionSecurity) { this.sipSessionSecurity = sipSessionSecurity; } /** * @return the sipSessionSecurity */ public SipSessionSecurity getSipSessionSecurity() { if(sipSessionSecurity == null) { sipSessionSecurity = new SipSessionSecurity(); } return sipSessionSecurity; } }
false
true
public SipServletRequest createRequest(final String method) { if(method.equalsIgnoreCase(Request.ACK) || method.equalsIgnoreCase(Request.PRACK) || method.equalsIgnoreCase(Request.CANCEL)) { throw new IllegalArgumentException( "Can not create ACK, PRACK or CANCEL requests with this method"); } if(!isValid()) { throw new IllegalStateException("cannot create a subsequent request " + method + " because the session " + key + " is invalid"); } if(State.TERMINATED.equals(state)) { throw new IllegalStateException("cannot create a subsequent request " + method + " because the session " + key + " is in TERMINATED state"); } // if((State.INITIAL.equals(state) && hasOngoingTransaction())) { // throw new IllegalStateException("cannot create a request because the session is in INITIAL state with ongoing transactions"); // } if(logger.isDebugEnabled()) { logger.debug("dialog associated with this session to create the new request " + method + " within that dialog "+ sessionCreatingDialog); } SipServletRequestImpl sipServletRequest = null; if(sessionCreatingDialog != null && DialogState.TERMINATED.equals(sessionCreatingDialog.getState()) && !method.equalsIgnoreCase(Request.BYE)) { // Fix for Issue http://code.google.com/p/mobicents/issues/detail?id=2230 BYE is routed to unexpected IP // MSS should throw an IllegalStateException when a subsequent request is being created on a TERMINATED dialog // don't do it on the BYE method as a 408 within a dialog could have make the dialog TERMINATED and MSS should allow the app to create the subsequent BYE from any thread throw new IllegalStateException("cannot create a subsequent request " + method + " because the dialog " + sessionCreatingDialog + " for session " + key + " is in TERMINATED state"); } if(this.sessionCreatingDialog != null && !DialogState.TERMINATED.equals(sessionCreatingDialog.getState())) { if(logger.isDebugEnabled()) { logger.debug("dialog " + sessionCreatingDialog + " used to create the new request " + method); } try { final Request methodRequest = this.sessionCreatingDialog.createRequest(method); if(methodRequest.getHeader(ContactHeader.NAME) != null) { // if a sip load balancer is present in front of the server, the contact header is the one from the sip lb // so that the subsequent requests can be failed over try { ContactHeader contactHeader = null; FromHeader from = (FromHeader) methodRequest.getHeader(FromHeader.NAME); String displayName = from.getAddress().getDisplayName(); String userName = null; javax.sip.address.URI uri = from.getAddress().getURI(); if(uri.isSipURI()) { userName = ((javax.sip.address.SipURI)uri).getUser(); } if(sipFactory.isUseLoadBalancer()) { SipLoadBalancer loadBalancerToUse = sipFactory.getLoadBalancerToUse(); javax.sip.address.SipURI sipURI = SipFactories.addressFactory.createSipURI(userName, loadBalancerToUse.getAddress().getHostAddress()); sipURI.setHost(loadBalancerToUse.getAddress().getHostAddress()); sipURI.setPort(loadBalancerToUse.getSipPort()); // TODO: Is this enough or we must specify the transport somewhere? // We can leave it like this. It will be updated if needed in the send() method sipURI.setTransportParam(ListeningPoint.UDP); javax.sip.address.Address contactAddress = SipFactories.addressFactory.createAddress(sipURI); contactHeader = SipFactories.headerFactory.createContactHeader(contactAddress); } else { contactHeader = JainSipUtils.createContactHeader(sipFactory.getSipNetworkInterfaceManager(), methodRequest, displayName, userName, outboundInterface); } methodRequest.setHeader(contactHeader); } catch (Exception e) { logger.error("Can not create contact header for subsequent request " + method + " for session " + key, e); } } // Fix for Issue 1130 (http://code.google.com/p/mobicents/issues/detail?id=1130) : // NullPointerException when sending request to client which support both UDP and TCP transport // before removing the via header we store the transport into its app data ListIterator<ViaHeader> viaHeaders = methodRequest.getHeaders(ViaHeader.NAME); if(viaHeaders != null && viaHeaders.hasNext()) { ViaHeader viaHeader = viaHeaders.next(); ((MessageExt)methodRequest).setApplicationData(viaHeader.getTransport()); } //Issue 112 fix by folsson methodRequest.removeHeader(ViaHeader.NAME); //if a SUBSCRIBE or BYE is sent for exemple, it will reuse the prexisiting dialog sipServletRequest = new SipServletRequestImpl( methodRequest, this.sipFactory, this, null, sessionCreatingDialog, false); } catch (SipException e) { logger.error("Cannot create the " + method + " request from the dialog " + sessionCreatingDialog,e); throw new IllegalArgumentException("Cannot create the " + method + " request from the dialog " + sessionCreatingDialog + " for sip session " + key,e); } } else { //case where other requests are sent with the same session like REGISTER or for challenge requests if(sessionCreatingTransactionRequest != null) { if(!isSessionCreatingTransactionServer) { if(logger.isDebugEnabled()) { logger.debug("orignal tx for creating susbequent request " + method + " on session " + key +" was a Client Tx"); } Request request = (Request) sessionCreatingTransactionRequest.getMessage().clone(); // Issue 1524 : Caused by: java.text.ParseException: CSEQ method mismatch with Request-Line javax.sip.address.URI requestUri = (javax.sip.address.URI) request.getRequestURI().clone(); ((SIPRequest)request).setMethod(method); ((SIPRequest)request).setRequestURI(requestUri); ((SIPMessage)request).setApplicationData(null); final CSeqHeader cSeqHeader = (CSeqHeader) request.getHeader((CSeqHeader.NAME)); try { cSeqHeader.setSeqNumber(cSeqHeader.getSeqNumber() + 1l); cSeqHeader.setMethod(method); } catch (InvalidArgumentException e) { logger.error("Cannot increment the Cseq header to the new " + method + " on the susbequent request to create on session " + key,e); throw new IllegalArgumentException("Cannot create the " + method + " on the susbequent request to create on session " + key,e); } catch (ParseException e) { throw new IllegalArgumentException("Cannot set the " + method + " on the susbequent request to create on session " + key,e); } // Fix for Issue 1130 (http://code.google.com/p/mobicents/issues/detail?id=1130) : // NullPointerException when sending request to client which support both UDP and TCP transport // before removing the ViaHeader we store the transport into its app data ListIterator<ViaHeader> viaHeaders = request.getHeaders(ViaHeader.NAME); if(viaHeaders != null && viaHeaders.hasNext()) { ViaHeader viaHeader = viaHeaders.next(); ((MessageExt)request).setApplicationData(viaHeader.getTransport()); } request.removeHeader(ViaHeader.NAME); final SipNetworkInterfaceManager sipNetworkInterfaceManager = sipFactory.getSipNetworkInterfaceManager(); final SipProvider sipProvider = sipNetworkInterfaceManager.findMatchingListeningPoint( JainSipUtils.findTransport(request), false).getSipProvider(); final SipApplicationDispatcher sipApplicationDispatcher = sipFactory.getSipApplicationDispatcher(); final String branch = JainSipUtils.createBranch(getSipApplicationSession().getKey().getId(), sipApplicationDispatcher.getHashFromApplicationName(getKey().getApplicationName())); ViaHeader viaHeader = JainSipUtils.createViaHeader( sipNetworkInterfaceManager, request, branch, outboundInterface); request.addHeader(viaHeader); sipServletRequest = new SipServletRequestImpl( request, this.sipFactory, this, null, sessionCreatingDialog, true); // Fix for Issue http://code.google.com/p/mobicents/issues/detail?id=2230 BYE is routed to unexpected IP if(sessionCreatingDialog != null && sessionCreatingDialog.getRemoteTarget() != null) { SipUri sipUri = (SipUri) sessionCreatingDialog.getRemoteTarget().getURI().clone(); sipUri.clearUriParms(); if(logger.isDebugEnabled()) { logger.debug("setting request uri to " + sipUri); } request.setRequestURI(sipUri); } } else { if(logger.isDebugEnabled()) { logger.debug("orignal tx for creating susbequent request " + method + " on session " + key +" was a Server Tx"); } try { // copying original params and call id final Request originalRequest = (Request) sessionCreatingTransactionRequest.getMessage(); final FromHeader fromHeader = (FromHeader) originalRequest.getHeader(FromHeader.NAME); final ToHeader toHeader = (ToHeader) originalRequest.getHeader(ToHeader.NAME); final AddressImpl currentLocalParty = (AddressImpl)this.getLocalParty().clone(); final AddressImpl currentRemoteParty = (AddressImpl)this.getRemoteParty().clone(); ((Parameters)currentRemoteParty .getAddress().getURI()).removeParameter("tag"); ((Parameters)currentLocalParty .getAddress().getURI()).removeParameter("tag"); final String originalCallId = ((CallIdHeader)originalRequest.getHeader(CallIdHeader.NAME)).getCallId(); sipServletRequest =(SipServletRequestImpl) sipFactory.createRequest( getSipApplicationSession(), method, currentLocalParty, currentRemoteParty, handlerServlet, originalCallId, fromHeader.getTag()); final Request request = ((Request)sipServletRequest.getMessage()); sipServletRequest.getSipSession().setCseq(((CSeqHeader)request.getHeader(CSeqHeader.NAME)).getSeqNumber()); final Map<String, String> fromParameters = new HashMap<String, String>(); final Iterator<String> fromParameterNames = fromHeader.getParameterNames(); while (fromParameterNames.hasNext()) { String parameterName = (String) fromParameterNames.next(); if(sessionCreatingDialog != null || !SipFactoryImpl.FORBIDDEN_PARAMS.contains(parameterName)) { fromParameters.put(parameterName, fromHeader.getParameter(parameterName)); } } final Map<String, String> toParameters = new HashMap<String, String>(); final Iterator<String> toParameterNames = toHeader.getParameterNames(); while (toParameterNames.hasNext()) { String parameterName = (String) toParameterNames.next(); if(sessionCreatingDialog != null || !SipFactoryImpl.FORBIDDEN_PARAMS.contains(parameterName)) { toParameters.put(parameterName, toHeader.getParameter(parameterName)); } } final ToHeader newTo = (ToHeader) request.getHeader(ToHeader.NAME); for (Entry<String, String> fromParameter : fromParameters.entrySet()) { String value = fromParameter.getValue(); if(value == null) { value = ""; } newTo.setParameter(fromParameter.getKey(), value); } final FromHeader newFrom = (FromHeader) request.getHeader(FromHeader.NAME); for (Entry<String, String> toParameter : toParameters.entrySet()) { String value = toParameter.getValue(); if(value == null) { value = ""; } newFrom.setParameter(toParameter.getKey(), value); } // Fix for Issue http://code.google.com/p/mobicents/issues/detail?id=2230 BYE is routed to unexpected IP if(sessionCreatingDialog != null && sessionCreatingDialog.getRemoteTarget() != null) { SipUri sipUri = (SipUri) sessionCreatingDialog.getRemoteTarget().getURI().clone(); sipUri.clearUriParms(); if(logger.isDebugEnabled()) { logger.debug("setting request uri to " + sipUri); } request.setRequestURI(sipUri); } } catch (ParseException e) { throw new IllegalArgumentException("Problem setting param on the newly created susbequent request " + sipServletRequest,e); } } if(sipSessionSecurity != null && sipSessionSecurity.getNextNonce() != null) { sipServletRequest.updateAuthorizationHeadersWithNextNonce(); } return sipServletRequest; } else { String errorMessage = "Couldn't create the subsequent request " + method + " for this session " + key + ", isValid " + isValid() + ", session state " + state + " , sessionCreatingDialog = " + sessionCreatingDialog; if(sessionCreatingDialog != null) { errorMessage += " , dialog state " + sessionCreatingDialog.getState(); } errorMessage += " , sessionCreatingTransactionRequest = " + sessionCreatingTransactionRequest; throw new IllegalStateException(errorMessage); } } //Application Routing : //removing the route headers and adding them back again except the one //corresponding to the app that is creating the subsequent request //avoid going through the same app that created the subsequent request Request request = (Request) sipServletRequest.getMessage(); final ListIterator<RouteHeader> routeHeaders = request.getHeaders(RouteHeader.NAME); request.removeHeader(RouteHeader.NAME); while (routeHeaders.hasNext()) { RouteHeader routeHeader = routeHeaders.next(); String routeAppNameHashed = ((javax.sip.address.SipURI)routeHeader .getAddress().getURI()). getParameter(MessageDispatcher.RR_PARAM_APPLICATION_NAME); String routeAppName = null; if(routeAppNameHashed != null) { routeAppName = sipFactory.getSipApplicationDispatcher().getApplicationNameFromHash(routeAppNameHashed); } if(routeAppName == null || !routeAppName.equals(getKey().getApplicationName())) { request.addHeader(routeHeader); } } if(sipSessionSecurity != null && sipSessionSecurity.getNextNonce() != null) { sipServletRequest.updateAuthorizationHeadersWithNextNonce(); } return sipServletRequest; }
public SipServletRequest createRequest(final String method) { if(method.equalsIgnoreCase(Request.ACK) || method.equalsIgnoreCase(Request.PRACK) || method.equalsIgnoreCase(Request.CANCEL)) { throw new IllegalArgumentException( "Can not create ACK, PRACK or CANCEL requests with this method"); } if(!isValid()) { throw new IllegalStateException("cannot create a subsequent request " + method + " because the session " + key + " is invalid"); } if(State.TERMINATED.equals(state)) { throw new IllegalStateException("cannot create a subsequent request " + method + " because the session " + key + " is in TERMINATED state"); } // if((State.INITIAL.equals(state) && hasOngoingTransaction())) { // throw new IllegalStateException("cannot create a request because the session is in INITIAL state with ongoing transactions"); // } if(logger.isDebugEnabled()) { logger.debug("dialog associated with this session to create the new request " + method + " within that dialog "+ sessionCreatingDialog); if(sessionCreatingDialog != null) { logger.debug("dialog state " + sessionCreatingDialog.getState() + " for that dialog "+ sessionCreatingDialog); } } SipServletRequestImpl sipServletRequest = null; // Fix for Issue http://code.google.com/p/mobicents/issues/detail?id=2230 BYE is routed to unexpected IP // MSS should throw an IllegalStateException when a subsequent request is being created on a TERMINATED dialog // don't do it on the BYE method as a 408 within a dialog could have make the dialog TERMINATED and MSS should allow the app to create the subsequent BYE from any thread if(sessionCreatingDialog != null && DialogState.TERMINATED.equals(sessionCreatingDialog.getState()) && !method.equalsIgnoreCase(Request.BYE)) { // don't do it for authentication as the dialog will go back to TERMINATED state, so we should allow to create challenge requests if(sessionCreatingTransactionRequest == null || sessionCreatingTransactionRequest.getLastFinalResponse() == null || (sessionCreatingTransactionRequest.getLastFinalResponse().getStatus() != 401 && sessionCreatingTransactionRequest.getLastFinalResponse().getStatus() != 407)) { throw new IllegalStateException("cannot create a subsequent request " + method + " because the dialog " + sessionCreatingDialog + " for session " + key + " is in TERMINATED state"); } } if(this.sessionCreatingDialog != null && !DialogState.TERMINATED.equals(sessionCreatingDialog.getState())) { if(logger.isDebugEnabled()) { logger.debug("dialog " + sessionCreatingDialog + " used to create the new request " + method); } try { final Request methodRequest = this.sessionCreatingDialog.createRequest(method); if(methodRequest.getHeader(ContactHeader.NAME) != null) { // if a sip load balancer is present in front of the server, the contact header is the one from the sip lb // so that the subsequent requests can be failed over try { ContactHeader contactHeader = null; FromHeader from = (FromHeader) methodRequest.getHeader(FromHeader.NAME); String displayName = from.getAddress().getDisplayName(); String userName = null; javax.sip.address.URI uri = from.getAddress().getURI(); if(uri.isSipURI()) { userName = ((javax.sip.address.SipURI)uri).getUser(); } if(sipFactory.isUseLoadBalancer()) { SipLoadBalancer loadBalancerToUse = sipFactory.getLoadBalancerToUse(); javax.sip.address.SipURI sipURI = SipFactories.addressFactory.createSipURI(userName, loadBalancerToUse.getAddress().getHostAddress()); sipURI.setHost(loadBalancerToUse.getAddress().getHostAddress()); sipURI.setPort(loadBalancerToUse.getSipPort()); // TODO: Is this enough or we must specify the transport somewhere? // We can leave it like this. It will be updated if needed in the send() method sipURI.setTransportParam(ListeningPoint.UDP); javax.sip.address.Address contactAddress = SipFactories.addressFactory.createAddress(sipURI); contactHeader = SipFactories.headerFactory.createContactHeader(contactAddress); } else { contactHeader = JainSipUtils.createContactHeader(sipFactory.getSipNetworkInterfaceManager(), methodRequest, displayName, userName, outboundInterface); } methodRequest.setHeader(contactHeader); } catch (Exception e) { logger.error("Can not create contact header for subsequent request " + method + " for session " + key, e); } } // Fix for Issue 1130 (http://code.google.com/p/mobicents/issues/detail?id=1130) : // NullPointerException when sending request to client which support both UDP and TCP transport // before removing the via header we store the transport into its app data ListIterator<ViaHeader> viaHeaders = methodRequest.getHeaders(ViaHeader.NAME); if(viaHeaders != null && viaHeaders.hasNext()) { ViaHeader viaHeader = viaHeaders.next(); ((MessageExt)methodRequest).setApplicationData(viaHeader.getTransport()); } //Issue 112 fix by folsson methodRequest.removeHeader(ViaHeader.NAME); //if a SUBSCRIBE or BYE is sent for exemple, it will reuse the prexisiting dialog sipServletRequest = new SipServletRequestImpl( methodRequest, this.sipFactory, this, null, sessionCreatingDialog, false); } catch (SipException e) { logger.error("Cannot create the " + method + " request from the dialog " + sessionCreatingDialog,e); throw new IllegalArgumentException("Cannot create the " + method + " request from the dialog " + sessionCreatingDialog + " for sip session " + key,e); } } else { //case where other requests are sent with the same session like REGISTER or for challenge requests if(sessionCreatingTransactionRequest != null) { if(!isSessionCreatingTransactionServer) { if(logger.isDebugEnabled()) { logger.debug("orignal tx for creating susbequent request " + method + " on session " + key +" was a Client Tx"); } Request request = (Request) sessionCreatingTransactionRequest.getMessage().clone(); // Issue 1524 : Caused by: java.text.ParseException: CSEQ method mismatch with Request-Line javax.sip.address.URI requestUri = (javax.sip.address.URI) request.getRequestURI().clone(); ((SIPRequest)request).setMethod(method); ((SIPRequest)request).setRequestURI(requestUri); ((SIPMessage)request).setApplicationData(null); final CSeqHeader cSeqHeader = (CSeqHeader) request.getHeader((CSeqHeader.NAME)); try { cSeqHeader.setSeqNumber(cSeqHeader.getSeqNumber() + 1l); cSeqHeader.setMethod(method); } catch (InvalidArgumentException e) { logger.error("Cannot increment the Cseq header to the new " + method + " on the susbequent request to create on session " + key,e); throw new IllegalArgumentException("Cannot create the " + method + " on the susbequent request to create on session " + key,e); } catch (ParseException e) { throw new IllegalArgumentException("Cannot set the " + method + " on the susbequent request to create on session " + key,e); } // Fix for Issue 1130 (http://code.google.com/p/mobicents/issues/detail?id=1130) : // NullPointerException when sending request to client which support both UDP and TCP transport // before removing the ViaHeader we store the transport into its app data ListIterator<ViaHeader> viaHeaders = request.getHeaders(ViaHeader.NAME); if(viaHeaders != null && viaHeaders.hasNext()) { ViaHeader viaHeader = viaHeaders.next(); ((MessageExt)request).setApplicationData(viaHeader.getTransport()); } request.removeHeader(ViaHeader.NAME); final SipNetworkInterfaceManager sipNetworkInterfaceManager = sipFactory.getSipNetworkInterfaceManager(); final SipProvider sipProvider = sipNetworkInterfaceManager.findMatchingListeningPoint( JainSipUtils.findTransport(request), false).getSipProvider(); final SipApplicationDispatcher sipApplicationDispatcher = sipFactory.getSipApplicationDispatcher(); final String branch = JainSipUtils.createBranch(getSipApplicationSession().getKey().getId(), sipApplicationDispatcher.getHashFromApplicationName(getKey().getApplicationName())); ViaHeader viaHeader = JainSipUtils.createViaHeader( sipNetworkInterfaceManager, request, branch, outboundInterface); request.addHeader(viaHeader); sipServletRequest = new SipServletRequestImpl( request, this.sipFactory, this, null, sessionCreatingDialog, true); // Fix for Issue http://code.google.com/p/mobicents/issues/detail?id=2230 BYE is routed to unexpected IP if(sessionCreatingDialog != null && sessionCreatingDialog.getRemoteTarget() != null) { SipUri sipUri = (SipUri) sessionCreatingDialog.getRemoteTarget().getURI().clone(); sipUri.clearUriParms(); if(logger.isDebugEnabled()) { logger.debug("setting request uri to " + sipUri); } request.setRequestURI(sipUri); } } else { if(logger.isDebugEnabled()) { logger.debug("orignal tx for creating susbequent request " + method + " on session " + key +" was a Server Tx"); } try { // copying original params and call id final Request originalRequest = (Request) sessionCreatingTransactionRequest.getMessage(); final FromHeader fromHeader = (FromHeader) originalRequest.getHeader(FromHeader.NAME); final ToHeader toHeader = (ToHeader) originalRequest.getHeader(ToHeader.NAME); final AddressImpl currentLocalParty = (AddressImpl)this.getLocalParty().clone(); final AddressImpl currentRemoteParty = (AddressImpl)this.getRemoteParty().clone(); ((Parameters)currentRemoteParty .getAddress().getURI()).removeParameter("tag"); ((Parameters)currentLocalParty .getAddress().getURI()).removeParameter("tag"); final String originalCallId = ((CallIdHeader)originalRequest.getHeader(CallIdHeader.NAME)).getCallId(); sipServletRequest =(SipServletRequestImpl) sipFactory.createRequest( getSipApplicationSession(), method, currentLocalParty, currentRemoteParty, handlerServlet, originalCallId, fromHeader.getTag()); final Request request = ((Request)sipServletRequest.getMessage()); sipServletRequest.getSipSession().setCseq(((CSeqHeader)request.getHeader(CSeqHeader.NAME)).getSeqNumber()); final Map<String, String> fromParameters = new HashMap<String, String>(); final Iterator<String> fromParameterNames = fromHeader.getParameterNames(); while (fromParameterNames.hasNext()) { String parameterName = (String) fromParameterNames.next(); if(sessionCreatingDialog != null || !SipFactoryImpl.FORBIDDEN_PARAMS.contains(parameterName)) { fromParameters.put(parameterName, fromHeader.getParameter(parameterName)); } } final Map<String, String> toParameters = new HashMap<String, String>(); final Iterator<String> toParameterNames = toHeader.getParameterNames(); while (toParameterNames.hasNext()) { String parameterName = (String) toParameterNames.next(); if(sessionCreatingDialog != null || !SipFactoryImpl.FORBIDDEN_PARAMS.contains(parameterName)) { toParameters.put(parameterName, toHeader.getParameter(parameterName)); } } final ToHeader newTo = (ToHeader) request.getHeader(ToHeader.NAME); for (Entry<String, String> fromParameter : fromParameters.entrySet()) { String value = fromParameter.getValue(); if(value == null) { value = ""; } newTo.setParameter(fromParameter.getKey(), value); } final FromHeader newFrom = (FromHeader) request.getHeader(FromHeader.NAME); for (Entry<String, String> toParameter : toParameters.entrySet()) { String value = toParameter.getValue(); if(value == null) { value = ""; } newFrom.setParameter(toParameter.getKey(), value); } // Fix for Issue http://code.google.com/p/mobicents/issues/detail?id=2230 BYE is routed to unexpected IP if(sessionCreatingDialog != null && sessionCreatingDialog.getRemoteTarget() != null) { SipUri sipUri = (SipUri) sessionCreatingDialog.getRemoteTarget().getURI().clone(); sipUri.clearUriParms(); if(logger.isDebugEnabled()) { logger.debug("setting request uri to " + sipUri); } request.setRequestURI(sipUri); } } catch (ParseException e) { throw new IllegalArgumentException("Problem setting param on the newly created susbequent request " + sipServletRequest,e); } } if(sipSessionSecurity != null && sipSessionSecurity.getNextNonce() != null) { sipServletRequest.updateAuthorizationHeadersWithNextNonce(); } return sipServletRequest; } else { String errorMessage = "Couldn't create the subsequent request " + method + " for this session " + key + ", isValid " + isValid() + ", session state " + state + " , sessionCreatingDialog = " + sessionCreatingDialog; if(sessionCreatingDialog != null) { errorMessage += " , dialog state " + sessionCreatingDialog.getState(); } errorMessage += " , sessionCreatingTransactionRequest = " + sessionCreatingTransactionRequest; throw new IllegalStateException(errorMessage); } } //Application Routing : //removing the route headers and adding them back again except the one //corresponding to the app that is creating the subsequent request //avoid going through the same app that created the subsequent request Request request = (Request) sipServletRequest.getMessage(); final ListIterator<RouteHeader> routeHeaders = request.getHeaders(RouteHeader.NAME); request.removeHeader(RouteHeader.NAME); while (routeHeaders.hasNext()) { RouteHeader routeHeader = routeHeaders.next(); String routeAppNameHashed = ((javax.sip.address.SipURI)routeHeader .getAddress().getURI()). getParameter(MessageDispatcher.RR_PARAM_APPLICATION_NAME); String routeAppName = null; if(routeAppNameHashed != null) { routeAppName = sipFactory.getSipApplicationDispatcher().getApplicationNameFromHash(routeAppNameHashed); } if(routeAppName == null || !routeAppName.equals(getKey().getApplicationName())) { request.addHeader(routeHeader); } } if(sipSessionSecurity != null && sipSessionSecurity.getNextNonce() != null) { sipServletRequest.updateAuthorizationHeadersWithNextNonce(); } return sipServletRequest; }
diff --git a/src/main/org/jboss/jms/server/remoting/JMSWireFormat.java b/src/main/org/jboss/jms/server/remoting/JMSWireFormat.java index 625792607..06034a534 100644 --- a/src/main/org/jboss/jms/server/remoting/JMSWireFormat.java +++ b/src/main/org/jboss/jms/server/remoting/JMSWireFormat.java @@ -1,358 +1,358 @@ /* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.jms.server.remoting; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.util.List; import java.util.Map; import org.jboss.jms.wireformat.ClientDelivery; import org.jboss.jms.wireformat.ConnectionFactoryUpdate; import org.jboss.jms.wireformat.NullResponse; import org.jboss.jms.wireformat.PacketSupport; import org.jboss.jms.wireformat.PolledCallbacksDelivery; import org.jboss.jms.wireformat.RequestSupport; import org.jboss.jms.wireformat.ResponseSupport; import org.jboss.jms.wireformat.SerializedPacket; import org.jboss.logging.Logger; import org.jboss.remoting.InvocationRequest; import org.jboss.remoting.InvocationResponse; import org.jboss.remoting.callback.Callback; import org.jboss.remoting.invocation.InternalInvocation; import org.jboss.remoting.invocation.OnewayInvocation; import org.jboss.remoting.marshal.Marshaller; import org.jboss.remoting.marshal.UnMarshaller; /** * * A JMSWireFormat. * * We do not use Java or JBoss serialization to send data over the wire. * Serialization adds considerable overhead in terms of the amount of data sent (it adds class information * plus block data information) which significantly degrades performance. * * Instead we define a customer wire format that minimises the * amount of data sent. * * The only exception to this rule is when sending an ObjectMessage which contains a user * defined object whose type is only known at run-time. In this case we use serialization. * * * @author <a href="[email protected]">Tim Fox</a> * @author <a href="[email protected]">Ovidiu Feodorov</a> * @version <tt>$Revision$</tt> * * $Id$ */ public class JMSWireFormat implements Marshaller, UnMarshaller { // Constants ------------------------------------------------------------------------------------ private static final long serialVersionUID = -7646123424863782043L; private static final Logger log = Logger.getLogger(JMSWireFormat.class); // Static --------------------------------------------------------------------------------------- // Attributes ----------------------------------------------------------------------------------- protected boolean trace; // Constructors --------------------------------------------------------------------------------- public JMSWireFormat() { trace = log.isTraceEnabled(); } // Marshaller implementation -------------------------------------------------------------------- public void write(Object obj, OutputStream out) throws IOException { if (trace) { log.trace("Writing " + obj); } DataOutputStream dos; if (out instanceof DataOutputStream) { //For non HTTP transports - we should ALWAYS be passed a DataOutputStream //We do this by specifying socket wrapper classes on the locator uri dos = (DataOutputStream)out; if (trace) { log.trace("Stream is a DataOutputStream"); } } else { // Further sanity check if (out instanceof ObjectOutputStream) { throw new IllegalArgumentException("Invalid stream - are you sure you have " + "configured socket wrappers?"); } // This would be the case for the HTTP transport for example. Wrap the stream. //FIXME - remoting should be fixed to allow socket wrappers to be specified for //all transports - not just socket //until then we have no choice but to create a wrapping stream on every invocation //for HTTP transport dos = new DataOutputStream(out); if (trace) { log.trace("Stream is NOT a DataOutputStream - must be using HTTP transport"); } } try { PacketSupport packet = null; if (obj instanceof InvocationRequest) { InvocationRequest req = (InvocationRequest)obj; Object param = req.getParameter(); if (param instanceof PacketSupport) { // A JBM invocation packet = (PacketSupport)param; if (trace) { log.trace("JBM Request"); } } else if (param instanceof OnewayInvocation) { if (trace) { log.trace("It's a OnewayInvocation"); } // This is fucking horrendous - remoting should not force us to deal with // its internal objects // Hmmm... hidden somewhere in the depths of this crap there must be the callback, // The search begins.... OnewayInvocation oneWay = (OnewayInvocation)param; param = oneWay.getParameters()[0]; if (param instanceof RequestSupport) { //A JBM invocation being sent one way (e.g. changeRate) if (trace) { log.trace("JBM oneway request"); } packet = (PacketSupport)param; } else if (param instanceof InternalInvocation) { InternalInvocation ii = (InternalInvocation)param; Object[] params = ii.getParameters(); if (trace) { log.trace("Params is " + params); } if (params != null && params.length > 0 && params[0] instanceof Callback) { Callback callback = (Callback) params[0]; if (trace) { log.trace("It's a callback: " + callback); } if (callback.getParameter() instanceof ClientDelivery) { // Whooooppee!! found the callback. Hurrah for remoting! // What a simple and intuitive API ;) packet = (ClientDelivery)callback.getParameter(); if (trace) { log.trace("Message delivery callback"); } } else if (callback.getParameter() instanceof ConnectionFactoryUpdate) { packet = (ConnectionFactoryUpdate)callback.getParameter(); if (trace) { log.trace("Connection factory update callback"); } } } } else { throw new IllegalArgumentException("Invalid request param " + param); } } else { //Some other remoting internal thing, e.g. PING, DISCONNECT, add listener etc packet = new SerializedPacket(req); } } else if (obj instanceof InvocationResponse) { InvocationResponse resp = (InvocationResponse)obj; Object param = resp.getResult(); if (param instanceof ResponseSupport) { // A JBM invocation response packet = (ResponseSupport)param; if (trace) { log.trace("JBM Response"); } } else if (param instanceof List) { // List of polled Callbacks, this is how messages are delivered when using // polled callbacks e.g. the HTTP transport // Sanity check if (((List)param).isEmpty()) { - log.error("Got a polled callback list - but it is empty!!! " + + log.warn("Got a polled callback list - but it is empty!!! " + "See http://jira.jboss.org/jira/browse/JBMESSAGING-818"); } packet = new PolledCallbacksDelivery((List)param, resp.getSessionId()); } else if (param == null) { // Null response packet = new NullResponse(); if (trace) { log.trace("Null Response"); } } else { // Return value from some remoting internal invocation e.g. PONG - return value from PING packet = new SerializedPacket(obj); } } else { //Actually this should never occur packet = new SerializedPacket(obj); } if (trace) { log.trace("Writing packet: " + packet); } packet.write(dos); if (trace) { log.trace("Wrote packet"); } } catch (Exception e) { log.error("Failed to write packet", e); IOException e2 = new IOException(e.getMessage()); e2.setStackTrace(e.getStackTrace()); throw e2; } } public Marshaller cloneMarshaller() throws CloneNotSupportedException { return this; } // UnMarshaller implementation ------------------------------------------------------------------ public Object read(InputStream in, Map map) throws IOException, ClassNotFoundException { if (trace) { log.trace("Reading"); } DataInputStream dis; if (in instanceof DataInputStream) { //For non HTTP transports - we should ALWAYS be passed a DataInputStream //We do this by specifying socket wrapper classes on the locator uri dis = (DataInputStream)in; if (trace) { log.trace("Stream is already DataInputStream :)"); } } else { // Further sanity check if (in instanceof ObjectInputStream) { throw new IllegalArgumentException("Invalid stream - are you sure you have " + "configured socket wrappers?"); } // This would be the case for the HTTP transport for example. Wrap the stream //FIXME Ideally remoting would let us wrap this before invoking the marshaller // but this does not appear to be possible dis = new DataInputStream(in); if (trace) { log.trace("Stream is NOT DataInputStream - must be using HTTP transport"); } } int id = dis.readInt(); PacketSupport packet = PacketSupport.createPacket(id); if (trace) { log.trace("Created packet " + packet); } try { if (trace) { log.trace("Reading packet"); } packet.read(dis); if (trace) { log.trace("Read packet"); } } catch (Exception e) { IOException e2 = new IOException(e.getMessage()); e2.setStackTrace(e.getStackTrace()); throw e2; } Object payload = packet.getPayload(); if (trace) { log.trace("Returning payload: " + payload); } return payload; } public UnMarshaller cloneUnMarshaller() throws CloneNotSupportedException { return this; } public void setClassLoader(ClassLoader classloader) { } // Public --------------------------------------------------------------------------------------- // Package protected ---------------------------------------------------------------------------- // Protected ------------------------------------------------------------------------------------ // Private -------------------------------------------------------------------------------------- // Inner classes -------------------------------------------------------------------------------- }
true
true
public void write(Object obj, OutputStream out) throws IOException { if (trace) { log.trace("Writing " + obj); } DataOutputStream dos; if (out instanceof DataOutputStream) { //For non HTTP transports - we should ALWAYS be passed a DataOutputStream //We do this by specifying socket wrapper classes on the locator uri dos = (DataOutputStream)out; if (trace) { log.trace("Stream is a DataOutputStream"); } } else { // Further sanity check if (out instanceof ObjectOutputStream) { throw new IllegalArgumentException("Invalid stream - are you sure you have " + "configured socket wrappers?"); } // This would be the case for the HTTP transport for example. Wrap the stream. //FIXME - remoting should be fixed to allow socket wrappers to be specified for //all transports - not just socket //until then we have no choice but to create a wrapping stream on every invocation //for HTTP transport dos = new DataOutputStream(out); if (trace) { log.trace("Stream is NOT a DataOutputStream - must be using HTTP transport"); } } try { PacketSupport packet = null; if (obj instanceof InvocationRequest) { InvocationRequest req = (InvocationRequest)obj; Object param = req.getParameter(); if (param instanceof PacketSupport) { // A JBM invocation packet = (PacketSupport)param; if (trace) { log.trace("JBM Request"); } } else if (param instanceof OnewayInvocation) { if (trace) { log.trace("It's a OnewayInvocation"); } // This is fucking horrendous - remoting should not force us to deal with // its internal objects // Hmmm... hidden somewhere in the depths of this crap there must be the callback, // The search begins.... OnewayInvocation oneWay = (OnewayInvocation)param; param = oneWay.getParameters()[0]; if (param instanceof RequestSupport) { //A JBM invocation being sent one way (e.g. changeRate) if (trace) { log.trace("JBM oneway request"); } packet = (PacketSupport)param; } else if (param instanceof InternalInvocation) { InternalInvocation ii = (InternalInvocation)param; Object[] params = ii.getParameters(); if (trace) { log.trace("Params is " + params); } if (params != null && params.length > 0 && params[0] instanceof Callback) { Callback callback = (Callback) params[0]; if (trace) { log.trace("It's a callback: " + callback); } if (callback.getParameter() instanceof ClientDelivery) { // Whooooppee!! found the callback. Hurrah for remoting! // What a simple and intuitive API ;) packet = (ClientDelivery)callback.getParameter(); if (trace) { log.trace("Message delivery callback"); } } else if (callback.getParameter() instanceof ConnectionFactoryUpdate) { packet = (ConnectionFactoryUpdate)callback.getParameter(); if (trace) { log.trace("Connection factory update callback"); } } } } else { throw new IllegalArgumentException("Invalid request param " + param); } } else { //Some other remoting internal thing, e.g. PING, DISCONNECT, add listener etc packet = new SerializedPacket(req); } } else if (obj instanceof InvocationResponse) { InvocationResponse resp = (InvocationResponse)obj; Object param = resp.getResult(); if (param instanceof ResponseSupport) { // A JBM invocation response packet = (ResponseSupport)param; if (trace) { log.trace("JBM Response"); } } else if (param instanceof List) { // List of polled Callbacks, this is how messages are delivered when using // polled callbacks e.g. the HTTP transport // Sanity check if (((List)param).isEmpty()) { log.error("Got a polled callback list - but it is empty!!! " + "See http://jira.jboss.org/jira/browse/JBMESSAGING-818"); } packet = new PolledCallbacksDelivery((List)param, resp.getSessionId()); } else if (param == null) { // Null response packet = new NullResponse(); if (trace) { log.trace("Null Response"); } } else { // Return value from some remoting internal invocation e.g. PONG - return value from PING packet = new SerializedPacket(obj); } } else { //Actually this should never occur packet = new SerializedPacket(obj); } if (trace) { log.trace("Writing packet: " + packet); } packet.write(dos); if (trace) { log.trace("Wrote packet"); } } catch (Exception e) { log.error("Failed to write packet", e); IOException e2 = new IOException(e.getMessage()); e2.setStackTrace(e.getStackTrace()); throw e2; } }
public void write(Object obj, OutputStream out) throws IOException { if (trace) { log.trace("Writing " + obj); } DataOutputStream dos; if (out instanceof DataOutputStream) { //For non HTTP transports - we should ALWAYS be passed a DataOutputStream //We do this by specifying socket wrapper classes on the locator uri dos = (DataOutputStream)out; if (trace) { log.trace("Stream is a DataOutputStream"); } } else { // Further sanity check if (out instanceof ObjectOutputStream) { throw new IllegalArgumentException("Invalid stream - are you sure you have " + "configured socket wrappers?"); } // This would be the case for the HTTP transport for example. Wrap the stream. //FIXME - remoting should be fixed to allow socket wrappers to be specified for //all transports - not just socket //until then we have no choice but to create a wrapping stream on every invocation //for HTTP transport dos = new DataOutputStream(out); if (trace) { log.trace("Stream is NOT a DataOutputStream - must be using HTTP transport"); } } try { PacketSupport packet = null; if (obj instanceof InvocationRequest) { InvocationRequest req = (InvocationRequest)obj; Object param = req.getParameter(); if (param instanceof PacketSupport) { // A JBM invocation packet = (PacketSupport)param; if (trace) { log.trace("JBM Request"); } } else if (param instanceof OnewayInvocation) { if (trace) { log.trace("It's a OnewayInvocation"); } // This is fucking horrendous - remoting should not force us to deal with // its internal objects // Hmmm... hidden somewhere in the depths of this crap there must be the callback, // The search begins.... OnewayInvocation oneWay = (OnewayInvocation)param; param = oneWay.getParameters()[0]; if (param instanceof RequestSupport) { //A JBM invocation being sent one way (e.g. changeRate) if (trace) { log.trace("JBM oneway request"); } packet = (PacketSupport)param; } else if (param instanceof InternalInvocation) { InternalInvocation ii = (InternalInvocation)param; Object[] params = ii.getParameters(); if (trace) { log.trace("Params is " + params); } if (params != null && params.length > 0 && params[0] instanceof Callback) { Callback callback = (Callback) params[0]; if (trace) { log.trace("It's a callback: " + callback); } if (callback.getParameter() instanceof ClientDelivery) { // Whooooppee!! found the callback. Hurrah for remoting! // What a simple and intuitive API ;) packet = (ClientDelivery)callback.getParameter(); if (trace) { log.trace("Message delivery callback"); } } else if (callback.getParameter() instanceof ConnectionFactoryUpdate) { packet = (ConnectionFactoryUpdate)callback.getParameter(); if (trace) { log.trace("Connection factory update callback"); } } } } else { throw new IllegalArgumentException("Invalid request param " + param); } } else { //Some other remoting internal thing, e.g. PING, DISCONNECT, add listener etc packet = new SerializedPacket(req); } } else if (obj instanceof InvocationResponse) { InvocationResponse resp = (InvocationResponse)obj; Object param = resp.getResult(); if (param instanceof ResponseSupport) { // A JBM invocation response packet = (ResponseSupport)param; if (trace) { log.trace("JBM Response"); } } else if (param instanceof List) { // List of polled Callbacks, this is how messages are delivered when using // polled callbacks e.g. the HTTP transport // Sanity check if (((List)param).isEmpty()) { log.warn("Got a polled callback list - but it is empty!!! " + "See http://jira.jboss.org/jira/browse/JBMESSAGING-818"); } packet = new PolledCallbacksDelivery((List)param, resp.getSessionId()); } else if (param == null) { // Null response packet = new NullResponse(); if (trace) { log.trace("Null Response"); } } else { // Return value from some remoting internal invocation e.g. PONG - return value from PING packet = new SerializedPacket(obj); } } else { //Actually this should never occur packet = new SerializedPacket(obj); } if (trace) { log.trace("Writing packet: " + packet); } packet.write(dos); if (trace) { log.trace("Wrote packet"); } } catch (Exception e) { log.error("Failed to write packet", e); IOException e2 = new IOException(e.getMessage()); e2.setStackTrace(e.getStackTrace()); throw e2; } }
diff --git a/org.nelfin.othello/test/iago/SmartPlayerTestAbstract.java b/org.nelfin.othello/test/iago/SmartPlayerTestAbstract.java index ead7fe3..7e1690a 100644 --- a/org.nelfin.othello/test/iago/SmartPlayerTestAbstract.java +++ b/org.nelfin.othello/test/iago/SmartPlayerTestAbstract.java @@ -1,33 +1,39 @@ package iago; import iago.players.Player; import iago.players.Player.PlayerType; import org.junit.Test; public abstract class SmartPlayerTestAbstract extends PlayerTestAbstract { protected Player smartWhitePlayer, smartBlackPlayer; //This is a solved game, white (2nd player) wins by 8 @Test public void testPerfectPlay() { Board small4x4Board = new Board(DebugFunctions.make4x4OthelloString()); Boolean blacksTurn = true; Move nextMove = new Move(0,0); - while(!nextMove.equals(new Move(-1,-1))) + int consecutivePasses = 0; + while(consecutivePasses < 2) { if(blacksTurn) { nextMove = smartBlackPlayer.chooseMove(small4x4Board); }else{ nextMove = smartWhitePlayer.chooseMove(small4x4Board); } - //apply the move - small4x4Board.apply(nextMove, blacksTurn?PlayerType.BLACK:PlayerType.WHITE, true); + if (nextMove.equals(Move.NO_MOVE)) { + consecutivePasses++; + } else { + //apply the move + small4x4Board.apply(nextMove, blacksTurn?PlayerType.BLACK:PlayerType.WHITE, true); + consecutivePasses = 0; + } blacksTurn = !blacksTurn; } - assertEquals(small4x4Board.scoreBoard(PlayerType.WHITE),8); + assertEquals(8, small4x4Board.scoreBoard(PlayerType.WHITE)); } }
false
true
public void testPerfectPlay() { Board small4x4Board = new Board(DebugFunctions.make4x4OthelloString()); Boolean blacksTurn = true; Move nextMove = new Move(0,0); while(!nextMove.equals(new Move(-1,-1))) { if(blacksTurn) { nextMove = smartBlackPlayer.chooseMove(small4x4Board); }else{ nextMove = smartWhitePlayer.chooseMove(small4x4Board); } //apply the move small4x4Board.apply(nextMove, blacksTurn?PlayerType.BLACK:PlayerType.WHITE, true); blacksTurn = !blacksTurn; } assertEquals(small4x4Board.scoreBoard(PlayerType.WHITE),8); }
public void testPerfectPlay() { Board small4x4Board = new Board(DebugFunctions.make4x4OthelloString()); Boolean blacksTurn = true; Move nextMove = new Move(0,0); int consecutivePasses = 0; while(consecutivePasses < 2) { if(blacksTurn) { nextMove = smartBlackPlayer.chooseMove(small4x4Board); }else{ nextMove = smartWhitePlayer.chooseMove(small4x4Board); } if (nextMove.equals(Move.NO_MOVE)) { consecutivePasses++; } else { //apply the move small4x4Board.apply(nextMove, blacksTurn?PlayerType.BLACK:PlayerType.WHITE, true); consecutivePasses = 0; } blacksTurn = !blacksTurn; } assertEquals(8, small4x4Board.scoreBoard(PlayerType.WHITE)); }
diff --git a/trunk/src/om/stdcomponent/RadioBoxComponent.java b/trunk/src/om/stdcomponent/RadioBoxComponent.java index 149ce69..e3170b9 100644 --- a/trunk/src/om/stdcomponent/RadioBoxComponent.java +++ b/trunk/src/om/stdcomponent/RadioBoxComponent.java @@ -1,248 +1,248 @@ /* OpenMark online assessment system Copyright (C) 2007 The Open University This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package om.stdcomponent; import java.awt.Color; import om.*; import om.question.ActionParams; import om.stdquestion.*; import org.w3c.dom.Element; import util.xml.XML; /** A radiobox component. Consists of an actual radiobox with a coloured box that surrounds the radiobox and its content. The user can click anywhere in the box to toggle the check. (Consequently, the radiobox should not contain components that might require user input, as this behaviour is likely to break them.) <p/> If included within a {@link LayoutGridComponent}, the radiobox can automatically size itself to match other radioboxes on the same grid row. <h2>XML usage</h2> &lt;radiobox &gt;...&lt;/radiobox&gt; <h2>Properties</h2> <table border="1"> <tr><th>Property</th><th>Values</th><th>Effect</th></tr> <tr><td>id</td><td>(string)</td><td>Specifies unique ID</td></tr> <tr><td>group</td><td>(string)</td><td>Specifies radio group</td></tr> <tr><td>display</td><td>(boolean)</td><td>Includes in/removes from output</td></tr> <tr><td>enabled</td><td>(boolean)</td><td>Activates/deactivates this control</td></tr> <tr><td>checked</td><td>(boolean)</td><td>Whether or not the box is checked</td></tr> <tr><td>highlight</td><td>(boolean)</td><td>Whether to use the highlight colours for box</td></tr> </table> */ //TODO Maybe merge radiobox with checkbox? //TODO Maybe use label tag for accessibillity etc. public class RadioBoxComponent extends QComponent { /** Property name for being highlighted (boolean) */ public static final String PROPERTY_HIGHLIGHT="highlight"; /** Property name for value of radiobox (boolean) */ public final static String PROPERTY_CHECKED="checked"; /** Property name for radio groups (string) */ public final static String PROPERTY_GROUP="group"; /** @return Tag name (introspected; this may be replaced by a 1.5 annotation) */ public static String getTagName() { return "radiobox"; } @Override protected void defineProperties() throws OmDeveloperException { super.defineProperties(); defineBoolean(PROPERTY_CHECKED); defineBoolean(PROPERTY_HIGHLIGHT); setBoolean(PROPERTY_CHECKED,false); defineString(PROPERTY_GROUP); setString(PROPERTY_GROUP,"_rg"); } @Override protected void produceVisibleOutput(QContent qc,boolean bInit,boolean bPlain) throws OmException { Element eOuterBox=qc.createElement("div"); qc.addInlineXHTML(eOuterBox); if(!bPlain) { eOuterBox.setAttribute("class","radiobox"); eOuterBox.setAttribute("id",QDocument.ID_PREFIX+getID()); eOuterBox.setAttribute("onclick","radioBoxOnClick('rb_"+getID()+"','"+QDocument.ID_PREFIX+"');"); if(isHighlight()) { eOuterBox.setAttribute("style", "background-color:"+convertHash("innerbg")+";" + "border-color:"+convertHash("text")+";"); } else { eOuterBox.setAttribute("style", "background-color:"+convertHash("innerbg")+";" + "border-color:"+convertHash("innerbg")+";"); } } Element eInput=XML.createChild(eOuterBox,"input"); eInput.setAttribute("type","radio"); - eInput.setAttribute("value",QDocument.ID_PREFIX+getID()); - eInput.setAttribute("name",getString("group")); + eInput.setAttribute("value",getID()); + eInput.setAttribute("name",QDocument.ID_PREFIX+getString(PROPERTY_GROUP)); if(!bPlain) { eInput.setAttribute("class","radioboxcheck"); eInput.setAttribute("id",QDocument.ID_PREFIX+"rb_"+getID()); // eInput.setAttribute("onclick","radioBoxOnClick('rb_"+getID()+"');"); } if(isChecked()) eInput.setAttribute("checked","yes"); if(!isEnabled()) eInput.setAttribute("disabled","yes"); if(!bPlain) { Element eContents=XML.createChild(eOuterBox,"div"); eContents.setAttribute("class","radioboxcontents"); qc.setParent(eContents); } else { // Add a space, then add content direct to outer box (avoids having it // appear on different line, prob. doesn't make any diff for screenreaders // but whatever) XML.createText(eOuterBox," "); qc.setParent(eOuterBox); } qc.addTextEquivalent("[Radio button: "); produceChildOutput(qc,bInit,bPlain); qc.addTextEquivalent("]"); qc.unsetParent(); if(shouldFillParent() && !bPlain) { Element eScript=XML.createChild(eOuterBox,"script"); eScript.setAttribute("type","text/javascript"); XML.createText(eScript,"addOnLoad(function() { radioBoxFix('"+getID()+"','"+QDocument.ID_PREFIX+"');});"); } if(isEnabled()) qc.informFocusable(eInput.getAttribute("id"),bPlain); } /** @return True if the radiobox was checked */ public boolean isChecked() { try { return getBoolean(PROPERTY_CHECKED); } catch(OmDeveloperException e) { throw new OmUnexpectedException(e); } } /** * Checks the radiobox. * @param bChecked True to check it, false to uncheck */ public void setChecked(boolean bChecked) { try { setBoolean(PROPERTY_CHECKED,bChecked); } catch(OmDeveloperException e) { throw new OmUnexpectedException(e); } } /** @return True if the radiobox is highlighted */ public boolean isHighlight() { try { if(isPropertySet(PROPERTY_HIGHLIGHT)) return getBoolean(PROPERTY_HIGHLIGHT); else // Default behaviour is to highlight when disabled and checked, this // means that the selected radioboxes are shown more clearly alongside // 'you got this wrong' pages return isChecked() && !isEnabled(); } catch(OmDeveloperException e) { throw new OmUnexpectedException(e); } } /** * Sets the highlight value. * @param bHighlight True to highlight, false to unhighlight */ public void setHighlight(boolean bHighlight) { try { setBoolean(PROPERTY_HIGHLIGHT,bHighlight); } catch(OmDeveloperException e) { throw new OmUnexpectedException(e); } } @Override protected void formSetValue(String sValue,ActionParams ap) throws OmException { if(!isEnabled()) return; } @Override protected void formAllValuesSet(ActionParams ap) throws OmException { if(!isEnabled()) return; String group = getString("group"); if(ap.hasParameter(group)) { String radioChoice = ap.getParameter(group); boolean checked = radioChoice.equals(getID()); setChecked(checked); } } @Override protected Color getChildBackground(QComponent qcChild) { try { return convertRGB("innerbg"); } catch(OmDeveloperException ode) { throw new OmUnexpectedException(ode); } } }
true
true
protected void produceVisibleOutput(QContent qc,boolean bInit,boolean bPlain) throws OmException { Element eOuterBox=qc.createElement("div"); qc.addInlineXHTML(eOuterBox); if(!bPlain) { eOuterBox.setAttribute("class","radiobox"); eOuterBox.setAttribute("id",QDocument.ID_PREFIX+getID()); eOuterBox.setAttribute("onclick","radioBoxOnClick('rb_"+getID()+"','"+QDocument.ID_PREFIX+"');"); if(isHighlight()) { eOuterBox.setAttribute("style", "background-color:"+convertHash("innerbg")+";" + "border-color:"+convertHash("text")+";"); } else { eOuterBox.setAttribute("style", "background-color:"+convertHash("innerbg")+";" + "border-color:"+convertHash("innerbg")+";"); } } Element eInput=XML.createChild(eOuterBox,"input"); eInput.setAttribute("type","radio"); eInput.setAttribute("value",QDocument.ID_PREFIX+getID()); eInput.setAttribute("name",getString("group")); if(!bPlain) { eInput.setAttribute("class","radioboxcheck"); eInput.setAttribute("id",QDocument.ID_PREFIX+"rb_"+getID()); // eInput.setAttribute("onclick","radioBoxOnClick('rb_"+getID()+"');"); } if(isChecked()) eInput.setAttribute("checked","yes"); if(!isEnabled()) eInput.setAttribute("disabled","yes"); if(!bPlain) { Element eContents=XML.createChild(eOuterBox,"div"); eContents.setAttribute("class","radioboxcontents"); qc.setParent(eContents); } else { // Add a space, then add content direct to outer box (avoids having it // appear on different line, prob. doesn't make any diff for screenreaders // but whatever) XML.createText(eOuterBox," "); qc.setParent(eOuterBox); } qc.addTextEquivalent("[Radio button: "); produceChildOutput(qc,bInit,bPlain); qc.addTextEquivalent("]"); qc.unsetParent(); if(shouldFillParent() && !bPlain) { Element eScript=XML.createChild(eOuterBox,"script"); eScript.setAttribute("type","text/javascript"); XML.createText(eScript,"addOnLoad(function() { radioBoxFix('"+getID()+"','"+QDocument.ID_PREFIX+"');});"); } if(isEnabled()) qc.informFocusable(eInput.getAttribute("id"),bPlain); }
protected void produceVisibleOutput(QContent qc,boolean bInit,boolean bPlain) throws OmException { Element eOuterBox=qc.createElement("div"); qc.addInlineXHTML(eOuterBox); if(!bPlain) { eOuterBox.setAttribute("class","radiobox"); eOuterBox.setAttribute("id",QDocument.ID_PREFIX+getID()); eOuterBox.setAttribute("onclick","radioBoxOnClick('rb_"+getID()+"','"+QDocument.ID_PREFIX+"');"); if(isHighlight()) { eOuterBox.setAttribute("style", "background-color:"+convertHash("innerbg")+";" + "border-color:"+convertHash("text")+";"); } else { eOuterBox.setAttribute("style", "background-color:"+convertHash("innerbg")+";" + "border-color:"+convertHash("innerbg")+";"); } } Element eInput=XML.createChild(eOuterBox,"input"); eInput.setAttribute("type","radio"); eInput.setAttribute("value",getID()); eInput.setAttribute("name",QDocument.ID_PREFIX+getString(PROPERTY_GROUP)); if(!bPlain) { eInput.setAttribute("class","radioboxcheck"); eInput.setAttribute("id",QDocument.ID_PREFIX+"rb_"+getID()); // eInput.setAttribute("onclick","radioBoxOnClick('rb_"+getID()+"');"); } if(isChecked()) eInput.setAttribute("checked","yes"); if(!isEnabled()) eInput.setAttribute("disabled","yes"); if(!bPlain) { Element eContents=XML.createChild(eOuterBox,"div"); eContents.setAttribute("class","radioboxcontents"); qc.setParent(eContents); } else { // Add a space, then add content direct to outer box (avoids having it // appear on different line, prob. doesn't make any diff for screenreaders // but whatever) XML.createText(eOuterBox," "); qc.setParent(eOuterBox); } qc.addTextEquivalent("[Radio button: "); produceChildOutput(qc,bInit,bPlain); qc.addTextEquivalent("]"); qc.unsetParent(); if(shouldFillParent() && !bPlain) { Element eScript=XML.createChild(eOuterBox,"script"); eScript.setAttribute("type","text/javascript"); XML.createText(eScript,"addOnLoad(function() { radioBoxFix('"+getID()+"','"+QDocument.ID_PREFIX+"');});"); } if(isEnabled()) qc.informFocusable(eInput.getAttribute("id"),bPlain); }
diff --git a/src/main/java/ru/mystamps/web/validation/jsr303/NotEmptyFileValidator.java b/src/main/java/ru/mystamps/web/validation/jsr303/NotEmptyFileValidator.java index 1bcc1856..66643189 100644 --- a/src/main/java/ru/mystamps/web/validation/jsr303/NotEmptyFileValidator.java +++ b/src/main/java/ru/mystamps/web/validation/jsr303/NotEmptyFileValidator.java @@ -1,46 +1,46 @@ /* * Copyright (C) 2009-2012 Slava Semushin <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package ru.mystamps.web.validation.jsr303; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import org.springframework.web.multipart.MultipartFile; public class NotEmptyFileValidator implements ConstraintValidator<NotEmptyFile, MultipartFile> { @Override public void initialize(NotEmptyFile annotation) { // Intentionally empty: nothing to initialize } @Override public boolean isValid(MultipartFile file, ConstraintValidatorContext ctx) { if (file == null) { return true; } - if (file.getSize() == 0) { // NOPMD + if (file.isEmpty()) { return false; } return true; } }
true
true
public boolean isValid(MultipartFile file, ConstraintValidatorContext ctx) { if (file == null) { return true; } if (file.getSize() == 0) { // NOPMD return false; } return true; }
public boolean isValid(MultipartFile file, ConstraintValidatorContext ctx) { if (file == null) { return true; } if (file.isEmpty()) { return false; } return true; }
diff --git a/libraries/javalib/java/io/RandomAccessFile.java b/libraries/javalib/java/io/RandomAccessFile.java index 135b82a95..a3dd096ea 100644 --- a/libraries/javalib/java/io/RandomAccessFile.java +++ b/libraries/javalib/java/io/RandomAccessFile.java @@ -1,265 +1,265 @@ /* * Java core library component. * * Copyright (c) 1997, 1998 * Transvirtual Technologies, Inc. All rights reserved. * * See the file "license.terms" for information on usage and redistribution * of this file. */ package java.io; import kaffe.util.UTF8; public class RandomAccessFile implements DataOutput, DataInput { private FileDescriptor fd = new FileDescriptor(); static { System.loadLibrary("io"); } public RandomAccessFile(File file, String mode) throws IOException { this(file.getPath(), mode); } public RandomAccessFile(String name, String mode) throws FileNotFoundException { boolean writable; if (mode.equalsIgnoreCase("r")) writable=false; else if (mode.equalsIgnoreCase("rw")) writable=true; else throw new IllegalArgumentException(); System.getSecurityManager().checkRead(name); if (writable) { System.getSecurityManager().checkWrite(name); } open(name, writable); } native public void close() throws IOException; final public FileDescriptor getFD() throws IOException { return fd; } native public long getFilePointer() throws IOException; native public long length() throws IOException; native private void open(String name, boolean rw); native public int read() throws IOException; public int read(byte b[]) throws IOException { return read(b, 0, b.length); } public int read(byte b[], int off, int len) throws IOException { int total = 0; while (total < len) { int got = readBytes(b, off + total, len - total); if (got == -1) { break; } total += got; } if (len > 0 && total == 0) { return -1; } return total; } final public boolean readBoolean() throws IOException { return (readByte()==0); } final public byte readByte() throws IOException { int value = read(); if (value == -1) { throw new EOFException(); } return (byte)value; } native private int readBytes(byte bytes[], int off, int len); final public char readChar() throws IOException { int b1=readUnsignedByte(); int b2=readUnsignedByte(); return (char )((b1 << 8) | b2); } final public double readDouble() throws IOException { return Double.longBitsToDouble(readLong()); } final public float readFloat() throws IOException { return Float.intBitsToFloat(readInt()); } final public void readFully(byte b[]) throws IOException { readFully(b, 0, b.length); } final public void readFully(byte b[], int off, int len) throws IOException { int got = read(b, off, len); if (got != len) { throw new EOFException(); } } final public int readInt() throws IOException { int b1=readUnsignedByte(); int b2=readUnsignedByte(); int b3=readUnsignedByte(); int b4=readUnsignedByte(); return (b1 << 24) | (b2 << 16) + (b3 << 8) + b4; } final public String readLine() throws IOException { final StringBuffer buffer = new StringBuffer(); int nread = 0; while (true) { final int data = read(); final char ch = (char) (data & 0xff); if (data == -1) break; nread++; if (ch == '\n') break; if (ch == '\r') { // Check for '\r\n' final int data2 = read(); - final char ch2 = (char) (data & 0xff); + final char ch2 = (char) (data2 & 0xff); if (data2 != -1 && ch2 != '\n') seek(getFilePointer() - 1); break; } buffer.append(ch); } return (nread == 0) ? null : buffer.toString(); } final public long readLong() throws IOException { int i1=readInt(); /* b1-4 */ int i2=readInt(); /* b5-8 */ return ((long)i1 << 32) + (((long)i2) & 0xffffffffL); } final public short readShort() throws IOException { int b1=readUnsignedByte(); int b2=readUnsignedByte(); return (short)((b1 << 8)|b2); } final public String readUTF() throws IOException { return UTF8.decode(this, readUnsignedShort()); } final public int readUnsignedByte() throws IOException { return (int)readByte() & 0xFF; } final public int readUnsignedShort() throws IOException { int b1=readUnsignedByte(); int b2=readUnsignedByte(); return (b1 << 8) | b2; } native public void seek(long pos) throws IOException; public int skipBytes(int n) throws IOException { long pos = getFilePointer(); seek(pos+(long)n); return n; } public void write(byte b[]) throws IOException { writeBytes(b, 0, b.length); } public void write(byte b[], int off, int len) throws IOException { writeBytes(b, off, len); } native public void write(int b) throws IOException; final public void writeBoolean(boolean v) throws IOException { if (v==true) writeByte(1); else writeByte(0); } final public void writeByte(int v) throws IOException { write(v); } final public void writeBytes(String s) throws IOException { char[] c = s.toCharArray(); byte[] b = new byte[c.length]; for (int pos = 0; pos < c.length; pos++) { b[pos] = (byte)(c[pos] & 0xFF); } write(b, 0, b.length); } native private void writeBytes(byte bytes[], int off, int len); final public void writeChar(int v) throws IOException { writeByte((v & 0xFF00) >> 8); writeByte((v & 0x00FF)); } final public void writeChars(String s) throws IOException { for (int pos=0; pos<s.length(); pos++) { writeChar(s.charAt(pos)); } } final public void writeDouble(double v) throws IOException { writeLong(Double.doubleToLongBits(v)); } final public void writeFloat(float v) throws IOException { writeInt(Float.floatToIntBits(v)); } final public void writeInt(int v) throws IOException { byte b[] = new byte[4]; int i, shift; for (i = 0, shift = 24; i < 4; i++, shift -= 8) b[i] = (byte)(0xFF & (v >> shift)); write(b, 0, 4); } final public void writeLong(long v) throws IOException { int hiInt=(int )(v >> 32); int loInt=(int )(v & 0xFFFFFFFF); writeInt(hiInt); writeInt(loInt); } final public void writeShort(int v) throws IOException { writeChar(v); } final public void writeUTF(String str) throws IOException { byte[] data = UTF8.encode(str); if (data.length > 0xffff) { throw new UTFDataFormatException("String too long"); } synchronized(this) { writeShort(data.length); write(data, 0, data.length); } } }
true
true
final public String readLine() throws IOException { final StringBuffer buffer = new StringBuffer(); int nread = 0; while (true) { final int data = read(); final char ch = (char) (data & 0xff); if (data == -1) break; nread++; if (ch == '\n') break; if (ch == '\r') { // Check for '\r\n' final int data2 = read(); final char ch2 = (char) (data & 0xff); if (data2 != -1 && ch2 != '\n') seek(getFilePointer() - 1); break; } buffer.append(ch); }
final public String readLine() throws IOException { final StringBuffer buffer = new StringBuffer(); int nread = 0; while (true) { final int data = read(); final char ch = (char) (data & 0xff); if (data == -1) break; nread++; if (ch == '\n') break; if (ch == '\r') { // Check for '\r\n' final int data2 = read(); final char ch2 = (char) (data2 & 0xff); if (data2 != -1 && ch2 != '\n') seek(getFilePointer() - 1); break; } buffer.append(ch); }
diff --git a/geogebra/geogebra/kernel/arithmetic/ExpressionNode.java b/geogebra/geogebra/kernel/arithmetic/ExpressionNode.java index c08b17793..36021f832 100644 --- a/geogebra/geogebra/kernel/arithmetic/ExpressionNode.java +++ b/geogebra/geogebra/kernel/arithmetic/ExpressionNode.java @@ -1,2465 +1,2465 @@ /* GeoGebra - Dynamic Mathematics for Schools Copyright Markus Hohenwarter and GeoGebra Inc., http://www.geogebra.org This file is part of GeoGebra. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation. */ /* * ExpressionNode.java * * binary tree node for ExpressionValues (NumberValues, VectorValues) * * Created on 03. Oktober 2001, 09:37 */ package geogebra.kernel.arithmetic; import geogebra.kernel.GeoElement; import geogebra.kernel.GeoFunction; import geogebra.kernel.Kernel; import geogebra.kernel.arithmetic3D.Vector3DValue; import geogebra.main.Application; import java.util.HashSet; import java.util.Iterator; /** * Tree node for expressions like "3*a - b/5" * @author Markus * @version */ public class ExpressionNode extends ValidExpression implements ExpressionValue, ExpressionNodeConstants { public Application app; public Kernel kernel; public ExpressionValue left, right; public int operation = NO_OPERATION; public boolean forceVector = false, forcePoint = false; public boolean holdsLaTeXtext = false; // for leaf mode public boolean leaf = false; public ExpressionNode(){}; /** Creates new ExpressionNode */ public ExpressionNode(Kernel kernel, ExpressionValue left, int operation, ExpressionValue right) { this.kernel = kernel; app = kernel.getApplication(); this.operation = operation; setLeft(left); if (right != null) { setRight(right); } else { // set dummy value setRight(new MyDouble(kernel, Double.NaN)); } } /** for only one leaf */ // for wrapping ExpressionValues as ValidExpression public ExpressionNode(Kernel kernel, ExpressionValue leaf) { this.kernel = kernel; app = kernel.getApplication(); setLeft(leaf); this.leaf = true; } // copy constructor: NO deep copy of subtrees is done here! // this is needed for translation of functions public ExpressionNode(ExpressionNode node) { kernel = node.kernel; app = node.app; leaf = node.leaf; operation = node.operation; setLeft(node.left); setRight(node.right); } public Kernel getKernel() { return kernel; } final public int getOperation() { return operation; } public void setOperation(int op) { operation = op; } public void setHoldsLaTeXtext(boolean flag) { holdsLaTeXtext = flag; } final public ExpressionValue getLeft() { return left; } final public void setLeft(ExpressionValue l) { left = l; left.setInTree(true); // needed fot list operations eg k=2 then k {1,2} } public ExpressionNode getLeftTree() { if (left.isExpressionNode()) return (ExpressionNode) left; else return new ExpressionNode(kernel, left); } final public ExpressionValue getRight() { return right; } final public void setRight(ExpressionValue r) { right = r; right.setInTree(true); // needed for list operations eg k=2 then k {1,2} leaf = operation == NO_OPERATION; // right is a dummy MyDouble by default } public ExpressionNode getRightTree() { if (right == null) return null; if (right.isExpressionNode()) return (ExpressionNode) right; else return new ExpressionNode(kernel, right); } public ExpressionValue deepCopy(Kernel kernel) { return getCopy(kernel); } /** copy the whole tree structure except leafs */ public ExpressionNode getCopy(Kernel kernel) { //Application.debug("getCopy() input: " + this); ExpressionNode newNode = null; ExpressionValue lev = null, rev = null; if (left != null) lev = copy(left, kernel); if (right != null) rev = copy(right, kernel); if (lev != null) { newNode = new ExpressionNode(kernel, lev, operation, rev); newNode.leaf = leaf; } else // something went wrong return null; // set member vars that are not set by constructors newNode.forceVector = forceVector; newNode.forcePoint = forcePoint; //Application.debug("getCopy() output: " + newNode); return newNode; } /** deep copy except for GeoElements */ public static ExpressionValue copy(ExpressionValue ev, Kernel kernel) { if (ev == null) return null; ExpressionValue ret = null; //Application.debug("copy ExpressionValue input: " + ev); if (ev.isExpressionNode()) { ExpressionNode en = (ExpressionNode) ev; ret = en.getCopy(kernel); } // deep copy else if (ev.isPolynomialInstance() || ev.isConstant() || ev instanceof Command) { ret = ev.deepCopy(kernel); } else { ret = ev; } //Application.debug("copy ExpressionValue output: " + ev); return ret; } /** * Replaces all ExpressionNodes in tree that are leafs (=wrappers) by their leaf * objects (of type ExpressionValue). */ final public void simplifyLeafs() { if (left.isExpressionNode()) { ExpressionNode node = (ExpressionNode) left; if (node.leaf) { left = node.left; simplifyLeafs(); } } if (right != null) { if (right.isExpressionNode()) { ExpressionNode node = (ExpressionNode) right; if (node.leaf) { right = node.left; simplifyLeafs(); } } } } /** * Replaces all Command objects in tree by their evaluated GeoElement * objects. */ final private void simplifyAndEvalCommands() { // don't evaluate any commands for the CAS here if (kernel.isResolveVariablesForCASactive()) return; if (left.isExpressionNode()) { ((ExpressionNode) left).simplifyAndEvalCommands(); } else if (left instanceof Command) { left = ((Command) left).evaluate(); } if (right != null) { if (right.isExpressionNode()) { ((ExpressionNode) right).simplifyAndEvalCommands(); } else if (right instanceof Command) { right = ((Command) right).evaluate(); } } } /** * Replaces all constant parts in tree by their values */ final public void simplifyConstantIntegers() { if (left.isExpressionNode()) { ExpressionNode node = (ExpressionNode) left; if (left.isConstant()) { ExpressionValue eval = node.evaluate(); if (eval.isNumberValue()) { // we only simplify numbers that have integer values if (kernel.isInteger(((NumberValue) eval).getDouble())) left = eval; } else { left = eval; } } else node.simplifyConstantIntegers(); } if (right != null && right.isExpressionNode()) { ExpressionNode node = (ExpressionNode) right; if (right.isConstant()) { ExpressionValue eval = node.evaluate(); if (eval.isNumberValue()) { // we only simplify numbers that have integer values if (kernel.isInteger(((NumberValue) eval).getDouble())) right = eval; } else { right = eval; } } else node.simplifyConstantIntegers(); } } /** * Expands equation expressions like (3*x + 2 = 5) / 2 to (3*x + 2)/2 = 5/2. */ final public ExpressionValue expandEquationExpressions() { if (leaf) return this; if (left.isExpressionNode()) { left = ((ExpressionNode) left).expandEquationExpressions(); } if (right.isExpressionNode()) { right = ((ExpressionNode) right).expandEquationExpressions(); } switch (operation) { case PLUS: case MINUS: case MULTIPLY: case DIVIDE: // equ <operation> val if (left instanceof Equation) { ((Equation) left).applyOperation(operation, right, false); leaf = true; right = null; } // val <operation> equ else if (right instanceof Equation) { ((Equation) right).applyOperation(operation, left, true); left = right; right = null; leaf = true; } break; } return this; } // used for 3D /* protected ExpressionValue evaluate(ExpressionValue v){ return v.evaluate(); } */ /** * interface ExpressionValue implementation */ public ExpressionValue evaluate() { return kernel.getExpressionNodeEvaluator().evaluate(this); } /** * * @param lt * @param rt * @return false if not defined */ private MyBoolean evalEquals(ExpressionValue lt, ExpressionValue rt) { // booleans if (lt.isBooleanValue() && rt.isBooleanValue()) return new MyBoolean( ((BooleanValue)lt).getBoolean() == ((BooleanValue)rt).getBoolean() ); // nummber == number else if (lt.isNumberValue() && rt.isNumberValue()) return new MyBoolean( kernel.isEqual( ((NumberValue)lt).getDouble(), ((NumberValue)rt).getDouble() ) ); // needed for eg If[""=="a",0,1] // when lt and rt are MyStringBuffers else if (lt.isTextValue() && rt.isTextValue()) { String strL = ((TextValue)lt).toValueString(); String strR = ((TextValue)rt).toValueString(); // needed for eg Sequence[If[Element[list1,i]=="b",0,1],i,i,i] if (strL == null || strR == null) return new MyBoolean(false); return new MyBoolean(strL.equals(strR)); } else if (lt.isGeoElement() && rt.isGeoElement()) { GeoElement geo1 = (GeoElement) lt; GeoElement geo2 = (GeoElement) rt; return new MyBoolean(geo1.isEqual(geo2)); } else if (lt.isVectorValue() && rt.isVectorValue()) { VectorValue vec1 = (VectorValue) lt; VectorValue vec2 = (VectorValue) rt; return new MyBoolean(vec1.getVector().equals(vec2.getVector())); } /* // Michael Borcherds 2008-05-01 // replaced following code with one line: if (geo1.isGeoPoint() && geo2.isGeoPoint()) { return new MyBoolean(((GeoPoint)geo1).equals((GeoPoint) geo2)); } else if (geo1.isGeoLine() && geo2.isGeoLine()) { return new MyBoolean(((GeoLine)geo1).equals((GeoLine) geo2)); } else if (geo1.isGeoConic() && geo2.isGeoConic()) { return new MyBoolean(((GeoConic)geo1).equals((GeoConic) geo2)); } else if (geo1.isGeoVector() && geo2.isGeoVector()) { return new MyBoolean(((GeoVector)geo1).equals((GeoVector) geo2)); } else if (geo1.isGeoList() && geo2.isGeoList()) { // Michael Borcherds 2008-04-12 return new MyBoolean(((GeoList)geo1).equals((GeoList) geo2)); }*/ return new MyBoolean(false); } /** * look for Variable objects in the tree and replace them * by their resolved GeoElement */ public void resolveVariables() { doResolveVariables(); simplifyAndEvalCommands(); simplifyLeafs(); } private void doResolveVariables() { // resolve left wing if (left.isVariable()) { left = ((Variable) left).resolveAsExpressionValue(); } else left.resolveVariables(); // resolve right wing if (right != null) { if (right.isVariable()) { right = ((Variable) right).resolveAsExpressionValue(); } else right.resolveVariables(); } } /** * Looks for Variable objects that hold String var in the tree and * replaces them by their newOb. * public void replaceSpecificVariable(String var, ExpressionValue newOb) { // left wing if (left.isVariable()) { if (var.equals(((Variable) left).getName())) left = newOb; } else if (left.isExpressionNode()) { ((ExpressionNode) left).replaceSpecificVariable(var, newOb); } // right wing if (right != null) { if (right.isVariable()) { if (var.equals(((Variable) right).getName())) right = newOb; } else if (right.isExpressionNode()) { ((ExpressionNode) right).replaceSpecificVariable(var, newOb); } } } */ /** * look for GeoFunction objects in the tree and replace them * by FUNCTION ExpressionNodes. This makes operations like * f + g possible by changing this to f(x) + g(x) * public void wrapGeoFunctionsAsExpressionNode() { Polynomial polyX = new Polynomial(kernel, "x"); // left wing if (left.isExpressionNode()) { ((ExpressionNode)left).wrapGeoFunctionsAsExpressionNode(); } else if (left instanceof GeoFunction) { left = new ExpressionNode(kernel, left, ExpressionNode.FUNCTION, polyX); } // resolve right wing if (right != null) { if (right.isExpressionNode()) { ((ExpressionNode)right).wrapGeoFunctionsAsExpressionNode(); } else if (right instanceof GeoFunction) { right = new ExpressionNode(kernel, right, ExpressionNode.FUNCTION, polyX); } } }*/ /** * returns true if there is at least one Polynomial in the tree */ public boolean includesPolynomial() { if (left.isExpressionNode()) { if (((ExpressionNode)left).includesPolynomial()) return true; } else if (left.isPolynomialInstance()) return true; if (right != null) { if (right.isExpressionNode()) { if (((ExpressionNode)right).includesPolynomial()) return true; } else if (right.isPolynomialInstance()) return true; } return false; } /** * Returns whether this ExpressionNode should evaluate to a GeoVector. * This method returns true when all GeoElements in this tree are GeoVectors and * there are no other constanct VectorValues (i.e. constant points) */ public boolean shouldEvaluateToGeoVector() { boolean evalToVector = false; if (left.isExpressionNode()) { evalToVector = (((ExpressionNode)left).shouldEvaluateToGeoVector()); } else if (left.isGeoElement()) { GeoElement geo = (GeoElement) left; evalToVector = geo.isGeoVector() || geo.isNumberValue(); } else if (left.isNumberValue()) { evalToVector = true; } if (right != null && evalToVector) { if (right.isExpressionNode()) { evalToVector = ((ExpressionNode)right).shouldEvaluateToGeoVector(); } else if (right.isGeoElement()) { GeoElement geo = (GeoElement) right; evalToVector = geo.isGeoVector() || geo.isNumberValue(); } else if (right.isNumberValue()) { evalToVector = true; } } return evalToVector; } /** * Returns true if this tree contains only Polynomials that * return true for isX() */ final public boolean isFunctionInX() { boolean isFunction = true; if (left.isExpressionNode()) { isFunction = ((ExpressionNode)left).isFunctionInX(); } else if (left.isPolynomialInstance()) { isFunction = ((Polynomial) left).isX(); } if (!isFunction) return false; if (right != null) { if (right.isExpressionNode()) { isFunction =((ExpressionNode)right).isFunctionInX(); }else if (right.isPolynomialInstance()) { isFunction = ((Polynomial) right).isX(); } } return isFunction; } /** * Returns true if this tree includes a division by val */ final public boolean includesDivisionBy(ExpressionValue val) { if (operation == DIVIDE) { if (right.contains(val)) return true; if (left.isExpressionNode() && ((ExpressionNode) left).includesDivisionBy(val)) return true; } else { if (left.isExpressionNode() && ((ExpressionNode) left).includesDivisionBy(val)) return true; if (right != null && right.isExpressionNode() && ((ExpressionNode) right).includesDivisionBy(val)) return true; } return false; } /** * Replaces all Polynomials in tree by function variable * @return number of replacements done */ int replacePolynomials(FunctionVariable x) { int replacements = 0; // left tree if (left.isExpressionNode()) { replacements += ((ExpressionNode) left).replacePolynomials( x); } else if (left.isPolynomialInstance()) { left = x; replacements++; } // right tree if (right != null) { if (right.isExpressionNode()) { replacements += ((ExpressionNode) right).replacePolynomials(x); } else if (right.isPolynomialInstance()) { right = x; replacements++; } } return replacements; } /** * Replaces every oldOb by newOb in this tree * @return resulting expression node */ public ExpressionNode replace(ExpressionValue oldOb, ExpressionValue newOb) { if (this == oldOb) { if (newOb.isExpressionNode()) return (ExpressionNode) newOb; else return new ExpressionNode(kernel, newOb); } // left tree if (left == oldOb) { left = newOb; } else if (left.isExpressionNode()) { left = ((ExpressionNode) left).replace(oldOb, newOb); } // right tree if (right != null) { if (right == oldOb) { right = newOb; } else if (right.isExpressionNode()) { right = ((ExpressionNode) right).replace(oldOb, newOb); } } return this; } /** * Replaces geo and all its dependent geos in this tree by * copies of their values. */ public void replaceChildrenByValues(GeoElement geo) { // left tree if (left.isGeoElement()) { GeoElement treeGeo = (GeoElement) left; if (left == geo || treeGeo.isChildOf(geo)) { left = treeGeo.copyInternal(treeGeo.getConstruction()); } } else if (left.isExpressionNode()) { ((ExpressionNode) left).replaceChildrenByValues(geo); } // handle command arguments else if (left instanceof Command) { ((Command) left).replaceChildrenByValues(geo); } // right tree if (right != null) { if (right.isGeoElement()) { GeoElement treeGeo = (GeoElement) right; if (right == geo || treeGeo.isChildOf(geo)) { right = treeGeo.copyInternal(treeGeo.getConstruction()); } } else if (right.isExpressionNode()) { ((ExpressionNode) right).replaceChildrenByValues(geo); } // handle command arguments else if (right instanceof Command) { ((Command) right).replaceChildrenByValues(geo); } } } /** * Returns true when the given object is found in this expression tree. */ final public boolean contains(ExpressionValue ev) { if (leaf) return left.contains(ev); else return left.contains(ev) || right.contains(ev); } /** * transfers every non-polynomial in this tree to a polynomial. * This is needed to enable polynomial simplification by evaluate() */ final void makePolynomialTree() { // transfer left subtree if (left.isExpressionNode()) { ((ExpressionNode)left).makePolynomialTree(); } else if (!(left.isPolynomialInstance()) ) { left = new Polynomial(kernel, new Term(kernel, left, "")); } // transfer right subtree if (right != null) { if (right.isExpressionNode()) { ((ExpressionNode)right).makePolynomialTree(); } else if (!(right.isPolynomialInstance()) ) { right = new Polynomial(kernel, new Term(kernel, right, "")); } } } /** returns true, if there are no variable objects * in the subtree */ final public boolean isConstant() { if (isLeaf()) return left.isConstant(); else return left.isConstant() && right.isConstant(); } /* * * returns true, if all variables are angles (GeoAngle) * or if a number followed by '�' or "rad" was entered (e.g. * 30� or 20 rad) * final public boolean isAngle() { // check if evaluation states that this is an angle // get MyDouble of evaluation ExpressionValue ev = evaluate(); if (ev instanceof MyDouble) { if (((MyDouble)ev).isAngle()) return true; } else return false; // only a number can be an angle // all veriables must be angles GeoElement [] vars = getGeoElementVariables(); if (vars == null || vars.length == 0) return false; for (int i=0; i < vars.length; i++) { if (!(vars[i] instanceof GeoAngle)) return false; } return true; } */ /** * returns true, if no variable is a point (GeoPoint) */ final public boolean isVectorValue() { if (forcePoint) return false; if (forceVector) return true; return shouldEvaluateToGeoVector(); } public void setForceVector() { // this expression should be considered as a vector, not a point forceVector = true; } final public boolean isForcedVector() { return forceVector; } public void setForcePoint() { // this expression should be considered as a point, not a vector forcePoint = true; } final public boolean isForcedPoint() { return forcePoint; } /** * Returns whether this tree has any operations */ final public boolean hasOperations() { if (leaf) { if (left.isExpressionNode()) { ((ExpressionNode)left).hasOperations(); } else return false; } return (right != null); } /** * Returns all GeoElement objects in the subtree */ final public HashSet getVariables() { if (leaf) return left.getVariables(); HashSet leftVars = left.getVariables(); HashSet rightVars = right.getVariables(); if (leftVars == null) { return rightVars; } else if (rightVars == null) { return leftVars; } else { leftVars.addAll(rightVars); return leftVars; } } final public GeoElement [] getGeoElementVariables() { HashSet varset = getVariables(); if (varset == null) return null; Iterator i = varset.iterator(); GeoElement [] ret = new GeoElement[varset.size()]; int j=0; while (i.hasNext()) { ret[j++] = (GeoElement) i.next(); } return ret; } final public boolean isLeaf() { return leaf; //|| operation == NO_OPERATION; } final public boolean isSingleGeoElement() { return leaf && left.isGeoElement(); } final public GeoElement getSingleGeoElement() { return (GeoElement) left; } public boolean isSingleVariable() { return (isLeaf() && (left instanceof Variable)); } /** * Returns a string representation of this node that can be used with * the given CAS, e.g. "*" and "^" are always printed. * @param symbolic: true for variable names, false for values of variables * @param STRING_TYPE: e.g. ExpressionNode.STRING_TYPE_JASYMCA */ final public String getCASstring(int STRING_TYPE, boolean symbolic) { int oldPrintForm = kernel.getCASPrintForm(); kernel.setCASPrintForm(STRING_TYPE); String ret = printCASstring(symbolic); kernel.setCASPrintForm(oldPrintForm); return ret; } private String printCASstring(boolean symbolic) { String ret = null; if (leaf) { // leaf is GeoElement or not /* if (symbolic) { if (left.isGeoElement()) ret = ((GeoElement) left).getLabel(); else if (left.isExpressionNode()) ret = ((ExpressionNode)left).printJSCLString(symbolic); else ret = left.toString(); } else { ret = left.toValueString(); } */ if (symbolic && left.isGeoElement()) ret = ((GeoElement)left).getLabel(); else if (left.isExpressionNode()) ret = ((ExpressionNode)left).printCASstring(symbolic); else ret = symbolic ? left.toString() : left.toValueString(); } // STANDARD case: no leaf else { // expression node String leftStr = null, rightStr = null; if (symbolic && left.isGeoElement()) { leftStr = ((GeoElement)left).getLabel(); } else if (left.isExpressionNode()) { leftStr = ((ExpressionNode)left).printCASstring(symbolic); } else { leftStr = symbolic ? left.toString() : left.toValueString(); } if (right != null) { if (symbolic && right.isGeoElement()) { rightStr = ((GeoElement)right).getLabel(); } else if (right.isExpressionNode()) { rightStr = ((ExpressionNode)right).printCASstring(symbolic); } else { rightStr = symbolic ? right.toString() : right.toValueString(); } } ret = operationToString(leftStr, rightStr, !symbolic); } return ret; } /** * Returns a string representation of this node. */ final public String toString() { if (leaf) { // leaf is GeoElement or not if (left.isGeoElement()) return ((GeoElement)left).getLabel(); else return left.toString(); } // expression node String leftStr = null, rightStr = null; if (left.isGeoElement()) { leftStr = ((GeoElement)left).getLabel(); } else { leftStr = left.toString(); } if (right != null) { if (right.isGeoElement()) { rightStr = ((GeoElement)right).getLabel(); } else { rightStr = right.toString(); } } return operationToString(leftStr, rightStr, false); } /** like toString() but with current values of variables */ final public String toValueString() { if (isLeaf()) { // leaf is GeoElement or not if (left != null) return left.toValueString(); } // expression node String leftStr = left.toValueString(); String rightStr = null; if (right != null) { rightStr = right.toValueString(); } return operationToString(leftStr, rightStr, true); } /** * Returns a string representation of this node in LaTeX syntax. * Note: the resulting string may contain special unicode characters like * greek characters or special signs for integer exponents. These sould be * handled afterwards! * @param symbolic: true for variable names, false for values of variables */ final public String toLaTeXString(boolean symbolic) { if (isLeaf()) { // leaf is GeoElement or not if (left != null) return left.toLaTeXString(symbolic); } // expression node String leftStr = left.toLaTeXString(symbolic); String rightStr = null; if (right != null) { rightStr = right.toLaTeXString(symbolic); } // build latex string int oldPrintForm = kernel.getCASPrintForm(); kernel.setCASPrintForm(STRING_TYPE_LATEX); String ret = operationToString(leftStr, rightStr,!symbolic); kernel.setCASPrintForm(oldPrintForm); return ret; } /** * Returns a string representation of this node. * Note: STRING_TYPE is used for LaTeX, MathPiper, Jasymca conform output, valueForm is used * by toValueString(), forLaTeX is used for LaTeX output * */ final private String operationToString(String leftStr, String rightStr, boolean valueForm) { ExpressionValue leftEval; StringBuilder sb = new StringBuilder(); int STRING_TYPE = kernel.getCASPrintForm(); switch (operation) { case NOT: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\neg "); break; case STRING_TYPE_MATH_PIPER: sb.append("Not "); break; default: sb.append(strNOT); } if (left.isLeaf()) { sb.append(leftStr); } else { sb.append('('); sb.append(leftStr); sb.append(')'); } break; case OR: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\vee"); break; case STRING_TYPE_MATH_PIPER: sb.append("Or"); break; default: sb.append(strOR); } sb.append(' '); sb.append(rightStr); break; case AND: if (left.isLeaf() || opID(left) >= AND) { sb.append(leftStr); } else { sb.append('('); sb.append(leftStr); sb.append(')'); } sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\wedge"); break; case STRING_TYPE_MATH_PIPER: sb.append("And"); break; default: sb.append(strAND); } sb.append(' '); if (right.isLeaf() || opID(right) >= AND) { sb.append(rightStr); } else { sb.append('('); sb.append(rightStr); sb.append(')'); } break; case EQUAL_BOOLEAN: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: case STRING_TYPE_MATH_PIPER: case STRING_TYPE_JASYMCA: sb.append("="); break; default: sb.append(strEQUAL_BOOLEAN); } sb.append(' '); sb.append(rightStr); break; case NOT_EQUAL: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\neq"); break; case STRING_TYPE_MATH_PIPER: sb.append("!="); break; default: sb.append(strNOT_EQUAL); } sb.append(' '); sb.append(rightStr); break; case IS_ELEMENT_OF: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\in"); break; default: sb.append(strIS_ELEMENT_OF); } sb.append(' '); sb.append(rightStr); break; case CONTAINS: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\subseteq"); break; default: sb.append(strCONTAINS); } sb.append(' '); sb.append(rightStr); break; case CONTAINS_STRICT: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\subset"); break; default: sb.append(strCONTAINS_STRICT); } sb.append(' '); sb.append(rightStr); break; case LESS: sb.append(leftStr); sb.append(" < "); sb.append(rightStr); break; case GREATER: sb.append(leftStr); sb.append(" > "); sb.append(rightStr); break; case LESS_EQUAL: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\leq"); break; case STRING_TYPE_MATH_PIPER: sb.append("<="); break; default: sb.append(strLESS_EQUAL); } sb.append(' '); sb.append(rightStr); break; case GREATER_EQUAL: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\geq"); break; case STRING_TYPE_MATH_PIPER: sb.append(">="); break; default: sb.append(strGREATER_EQUAL); } sb.append(' '); sb.append(rightStr); break; case PARALLEL: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\parallel"); break; default: sb.append(strPARALLEL); } sb.append(' '); sb.append(rightStr); break; case PERPENDICULAR: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\perp"); break; default: sb.append(strPERPENDICULAR); } sb.append(' '); sb.append(rightStr); break; case VECTORPRODUCT: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\times"); break; default: sb.append(strVECTORPRODUCT); } sb.append(' '); sb.append(rightStr); break; case PLUS: switch (STRING_TYPE) { case STRING_TYPE_JASYMCA: case STRING_TYPE_MATH_PIPER: sb.append('('); sb.append(leftStr); sb.append(") + ("); sb.append(rightStr); sb.append(')'); break; default: // TODO: remove // System.out.println("PLUS: left: " + leftStr + " " + isEqualString(left, 0, !valueForm) + // ", right: " + isEqualString(left, 0, !valueForm) + " " + rightStr); // check for 0 if (isEqualString(left, 0, !valueForm)) { if (right.isLeaf() || opID(right) >= PLUS) { sb.append(rightStr); } else { sb.append('('); sb.append(rightStr); sb.append(')'); } break; } else if (isEqualString(right, 0, !valueForm)) { if (left.isLeaf() || opID(left) >= PLUS) { sb.append(leftStr); } else { sb.append('('); sb.append(leftStr); sb.append(')'); } break; } // we need parantheses around right text // if right is not a leaf expression or // it is a leaf GeoElement without a label (i.e. it is calculated somehow) if (left.isTextValue() && ( !right.isLeaf() || (right.isGeoElement() && !((GeoElement) right).isLabelSet()) ) ) { sb.append(leftStr); sb.append(" + ("); sb.append(rightStr); sb.append(')'); } else { sb.append(leftStr); if (rightStr.charAt(0) == '-') { // convert + - to - sb.append(" - "); sb.append(rightStr.substring(1)); } else { sb.append(" + "); sb.append(rightStr); } } break; } break; case MINUS: switch (STRING_TYPE) { case STRING_TYPE_JASYMCA: case STRING_TYPE_MATH_PIPER: sb.append('('); sb.append(leftStr); sb.append(") - ("); sb.append(rightStr); sb.append(')'); break; default: sb.append(leftStr); // check for 0 at right if (rightStr.equals("0")) { break; } if (right.isLeaf() || opID(right) >= MULTIPLY) { // not +, - if (rightStr.charAt(0) == '-') { // convert - - to + sb.append(" + "); sb.append(rightStr.substring(1)); } else { sb.append(" - "); sb.append(rightStr); } } else { sb.append(" - ("); sb.append(rightStr); sb.append(')'); } break; } break; case MULTIPLY: switch (STRING_TYPE) { case STRING_TYPE_JASYMCA: case STRING_TYPE_MATH_PIPER: sb.append('('); sb.append(leftStr); sb.append(") * ("); sb.append(rightStr); sb.append(')'); break; default: // check for 1 at left if (isEqualString(left, 1, !valueForm)) { if (right.isLeaf() || opID(right) >= MULTIPLY) { sb.append(rightStr); } else { sb.append('('); sb.append(rightStr); sb.append(')'); } break; } // check for 0 at right else if (isEqualString(right, 1, !valueForm)) { if (left.isLeaf() || opID(left) >= MULTIPLY) { sb.append(leftStr); } else { sb.append('('); sb.append(leftStr); sb.append(')'); } break; } // check for 0 at left - else if (isEqualString(left, 0, !valueForm)) { + else if (valueForm && isEqualString(left, 0, !valueForm)) { sb.append("0"); break; } // check for 0 at right - else if (isEqualString(right, 0, !valueForm)) { + else if (valueForm && isEqualString(right, 0, !valueForm)) { sb.append("0"); break; } // check for degree sign at right else if (rightStr.equals("1\u00b0") || rightStr.equals("\u00b0")) { sb.append(leftStr); sb.append("\u00b0"); break; } boolean nounary = true; // left wing if (left.isLeaf() || opID(left) >= MULTIPLY) { // not +, - if (isEqualString(left, -1, !valueForm)) { // unary minus nounary = false; sb.append('-'); } else { sb.append(leftStr); } } else { sb.append('('); sb.append(leftStr); sb.append(')'); } // right wing int opIDright = opID(right); if (right.isLeaf() || opIDright >= MULTIPLY) { // not +, - // two digits colide: insert * if (nounary) { if (Character.isDigit(rightStr.charAt(0)) && Character.isDigit(sb.charAt(sb.length() - 1)) ) { sb.append(" * "); } else { switch (STRING_TYPE) { case STRING_TYPE_GEOGEBRA_XML: sb.append(" * "); break; default: sb.append(' '); // space instead of '*' } } } // show parentheses around these cases if (rightStr.charAt(0) == '-' // 2 (-5) or -(-5) || !nounary && opIDright <= DIVIDE) // -(x * a) or -(x / a) { sb.append('('); sb.append(rightStr); sb.append(')'); } else sb.append(rightStr); } else { if (nounary) { switch (STRING_TYPE) { case STRING_TYPE_GEOGEBRA_XML: sb.append(" * "); break; default: sb.append(' '); // space instead of '*' } } sb.append('('); sb.append(rightStr); sb.append(')'); } } break; case DIVIDE: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\frac{"); sb.append(leftStr); sb.append("}{"); sb.append(rightStr); sb.append("}"); break; case STRING_TYPE_JASYMCA: case STRING_TYPE_MATH_PIPER: sb.append('('); sb.append(leftStr); sb.append(")/("); sb.append(rightStr); sb.append(')'); break; default: // check for 1 in denominator if (isEqualString(right, 1, !valueForm)) { sb.append(leftStr); break; } // left wing if (left.isLeaf()|| opID(left) >= DIVIDE) { // not +, -, * sb.append(leftStr); } else { sb.append('('); sb.append(leftStr); sb.append(')'); } sb.append(" / "); // right wing if (right.isLeaf() || opID(right) >= POWER) // not +, -, *, / sb.append(rightStr); else { sb.append('('); sb.append(rightStr); sb.append(')'); } } break; case POWER: switch (STRING_TYPE) { case STRING_TYPE_JASYMCA: case STRING_TYPE_MATH_PIPER: sb.append('('); sb.append(leftStr); sb.append(')'); break; default: /* removed Michael Borcherds 2009-02-08 * doesn't work eg m=1 g(x) = (x - 1)^m (x - 3) */ // check for 1 in exponent if (isEqualString(right, 1, !valueForm)) { sb.append(leftStr); break; } // left wing if (leftStr.charAt(0) != '-' && // no unary (left.isLeaf() || opID(left) > POWER)) { // not +, -, *, /, ^ sb.append(leftStr); } else { sb.append('('); sb.append(leftStr); sb.append(')'); } break; } // right wing switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append('^'); sb.append('{'); sb.append(rightStr); sb.append('}'); break; case STRING_TYPE_JASYMCA: case STRING_TYPE_GEOGEBRA_XML: case STRING_TYPE_MATH_PIPER: sb.append('^'); sb.append('('); sb.append(rightStr); sb.append(')'); break; default: if (right.isLeaf() || opID(right) > POWER) { // not +, -, *, /, ^ /* // Michael Borcherds 2008-05-14 // display powers over 9 as unicode superscript try { int i = Integer.parseInt(rightStr); String index=""; if (i<0) { sb.append('\u207B'); // superscript minus sign i=-i; } if (i==0) sb.append('\u2070'); // zero else while (i>0) { switch (i%10) { case 0: index="\u2070"+index; break; case 1: index="\u00b9"+index; break; case 2: index="\u00b2"+index; break; case 3: index="\u00b3"+index; break; case 4: index="\u2074"+index; break; case 5: index="\u2075"+index; break; case 6: index="\u2076"+index; break; case 7: index="\u2077"+index; break; case 8: index="\u2078"+index; break; case 9: index="\u2079"+index; break; } i=i/10; } sb.append(index); } catch (Exception e) { sb.append('^'); sb.append(rightStr); }*/ if (rightStr.length() == 1) { switch (rightStr.charAt(0)) { case '0': sb.append('\u2070'); break; case '1': sb.append('\u00b9'); break; case '2': sb.append('\u00b2'); break; case '3': sb.append('\u00b3'); break; case '4': sb.append('\u2074'); break; case '5': sb.append('\u2075'); break; case '6': sb.append('\u2076'); break; case '7': sb.append('\u2077'); break; case '8': sb.append('\u2078'); break; case '9': sb.append('\u2079'); break; default: sb.append('^'); sb.append(rightStr); } } else { sb.append('^'); sb.append(rightStr); } } else { sb.append('^'); sb.append('('); sb.append(rightStr); sb.append(')'); } } break; case FACTORIAL: if (leftStr.charAt(0) != '-' && // no unary left.isLeaf() || opID(left) > POWER) { // not +, -, *, /, ^ sb.append(leftStr); } else { sb.append('('); sb.append(leftStr); sb.append(')'); } sb.append('!'); break; case COS: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\cos("); break; case STRING_TYPE_MATH_PIPER: sb.append("Cos("); break; default: sb.append("cos("); } sb.append(leftStr); sb.append(')'); break; case SIN: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\sin("); break; case STRING_TYPE_MATH_PIPER: sb.append("Sin("); break; default: sb.append("sin("); } sb.append(leftStr); sb.append(')'); break; case TAN: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\tan("); break; case STRING_TYPE_MATH_PIPER: sb.append("Tan("); break; default: sb.append("tan("); } sb.append(leftStr); sb.append(')'); break; case ARCCOS: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\arccos("); break; case STRING_TYPE_MATH_PIPER: sb.append("ArcCos("); break; default: sb.append("acos("); } sb.append(leftStr); sb.append(')'); break; case ARCSIN: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\arcsin("); break; case STRING_TYPE_MATH_PIPER: sb.append("ArcSin("); break; default: sb.append("asin("); } sb.append(leftStr); sb.append(')'); break; case ARCTAN: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\arctan("); break; case STRING_TYPE_MATH_PIPER: sb.append("ArcTan("); break; default: sb.append("atan("); } sb.append(leftStr); sb.append(')'); break; case COSH: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\cosh("); break; case STRING_TYPE_MATH_PIPER: sb.append("Cosh("); break; default: sb.append("cosh("); } sb.append(leftStr); sb.append(')'); break; case SINH: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\sinh("); break; case STRING_TYPE_MATH_PIPER: sb.append("Sinh("); break; default: sb.append("sinh("); } sb.append(leftStr); sb.append(')'); break; case TANH: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\tanh("); break; case STRING_TYPE_MATH_PIPER: sb.append("Tanh("); break; default: sb.append("tanh("); } sb.append(leftStr); sb.append(')'); break; case ACOSH: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\mathrm{acosh}("); break; case STRING_TYPE_MATH_PIPER: sb.append("ArcCosh("); break; default: sb.append("acosh("); } sb.append(leftStr); sb.append(')'); break; case ASINH: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\mathrm{asinh}("); break; case STRING_TYPE_MATH_PIPER: sb.append("ArcSinh("); break; default: sb.append("asinh("); } sb.append(leftStr); sb.append(')'); break; case ATANH: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\mathrm{atanh}("); break; case STRING_TYPE_MATH_PIPER: sb.append("ArcTanh("); break; default: sb.append("atanh("); } sb.append(leftStr); sb.append(')'); break; case EXP: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("e^{"); sb.append(leftStr); sb.append('}'); break; case STRING_TYPE_MATH_PIPER: sb.append("Exp("); sb.append(leftStr); sb.append(')'); break; case STRING_TYPE_JASYMCA: case STRING_TYPE_GEOGEBRA_XML: sb.append("exp("); sb.append(leftStr); sb.append(')'); break; default: sb.append(Kernel.EULER_STRING); if (left.isLeaf()) { sb.append("^"); sb.append(leftStr); } else { sb.append("^("); sb.append(leftStr); sb.append(')'); } break; } break; case LOG: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\log("); break; case STRING_TYPE_MATH_PIPER: sb.append("Ln("); break; case STRING_TYPE_JASYMCA: case STRING_TYPE_GEOGEBRA_XML: sb.append("log("); break; default: sb.append("ln("); break; } sb.append(leftStr); sb.append(')'); break; case LOG10: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\log_{10}("); sb.append(leftStr); sb.append(')'); break; case STRING_TYPE_MATH_PIPER: sb.append("Ln("); sb.append(leftStr); sb.append(")/Ln(10)"); break; case STRING_TYPE_JASYMCA: sb.append("log("); sb.append(leftStr); sb.append(")/log(10)"); break; default: sb.append("lg("); sb.append(leftStr); sb.append(')'); break; } break; case LOG2: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\log_{2}("); sb.append(leftStr); sb.append(')'); break; case STRING_TYPE_MATH_PIPER: sb.append("Ln("); sb.append(leftStr); sb.append(")/Ln(2)"); break; case STRING_TYPE_JASYMCA: sb.append("log("); sb.append(leftStr); sb.append(")/log(2)"); break; default: sb.append("ld("); sb.append(leftStr); sb.append(')'); break; } break; case SQRT: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\sqrt{"); sb.append(leftStr); sb.append('}'); break; case STRING_TYPE_MATH_PIPER: sb.append("Sqrt("); sb.append(leftStr); sb.append(')'); break; default: sb.append("sqrt("); sb.append(leftStr); sb.append(')'); } break; case CBRT: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\sqrt[3]{"); sb.append(leftStr); sb.append('}'); break; case STRING_TYPE_MATH_PIPER: sb.append("("); sb.append(leftStr); sb.append(")^(1/3)"); break; default: sb.append("cbrt("); sb.append(leftStr); sb.append(')'); } break; case ABS: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\left|"); sb.append(leftStr); sb.append("\\right|"); break; case STRING_TYPE_MATH_PIPER: sb.append("Abs("); sb.append(leftStr); sb.append(')'); break; default: sb.append("abs("); sb.append(leftStr); sb.append(')'); } break; case SGN: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\mathrm{sgn}("); break; case STRING_TYPE_MATH_PIPER: sb.append("Sign("); break; case STRING_TYPE_JASYMCA: sb.append("sign("); break; default: sb.append("sgn("); } sb.append(leftStr); sb.append(')'); break; case FLOOR: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\lfloor"); sb.append(leftStr); sb.append("\\rfloor"); break; case STRING_TYPE_MATH_PIPER: sb.append("Floor("); sb.append(leftStr); sb.append(')'); break; default: sb.append("floor("); sb.append(leftStr); sb.append(')'); } break; case CEIL: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\lceil"); sb.append(leftStr); sb.append("\\rceil"); break; case STRING_TYPE_MATH_PIPER: sb.append("Ceil("); sb.append(leftStr); sb.append(')'); break; default: sb.append("ceil("); sb.append(leftStr); sb.append(')'); } break; case ROUND: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\mathrm{round}("); break; case STRING_TYPE_MATH_PIPER: sb.append("Round("); break; default: sb.append("round("); } sb.append(leftStr); sb.append(')'); break; case GAMMA: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\Gamma("); break; case STRING_TYPE_MATH_PIPER: sb.append("Gamma("); break; default: sb.append("gamma("); } sb.append(leftStr); sb.append(')'); break; case RANDOM: if (valueForm) sb.append(leftStr); else sb.append("random()"); break; case XCOORD: if (valueForm && (leftEval = left.evaluate()).isVectorValue()) { sb.append(kernel.format(((VectorValue)leftEval).getVector().getX())); } else if (valueForm && (leftEval = left.evaluate()).isVector3DValue()) { sb.append(kernel.format(((Vector3DValue)leftEval).getPointAsDouble()[0])); } else { switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\mathrm{x}("); sb.append(leftStr); sb.append(')'); break; case STRING_TYPE_JASYMCA: case STRING_TYPE_MATH_PIPER: // note: see GeoGebraCAS.insertSpecialChars() sb.append("x"); sb.append(UNICODE_PREFIX); sb.append("40"); // decimal unicode for ( sb.append(UNICODE_DELIMITER); sb.append(leftStr); sb.append(UNICODE_PREFIX); sb.append("41"); // decimal unicode for ) sb.append(UNICODE_DELIMITER); break; default: sb.append("x("); sb.append(leftStr); sb.append(')'); } } break; case YCOORD: if (valueForm && (leftEval = left.evaluate()).isVectorValue()) { sb.append(kernel.format(((VectorValue)leftEval).getVector().getY())); } else if (valueForm && (leftEval = left.evaluate()).isVector3DValue()) { sb.append(kernel.format(((Vector3DValue)leftEval).getPointAsDouble()[1])); } else { switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\mathrm{y}("); sb.append(leftStr); sb.append(')'); break; case STRING_TYPE_JASYMCA: case STRING_TYPE_MATH_PIPER: // note: see GeoGebraCAS.insertSpecialChars() sb.append("y"); sb.append(UNICODE_PREFIX); sb.append("40"); // decimal unicode for ( sb.append(UNICODE_DELIMITER); sb.append(leftStr); sb.append(UNICODE_PREFIX); sb.append("41"); // decimal unicode for ) sb.append(UNICODE_DELIMITER); break; default: sb.append("y("); sb.append(leftStr); sb.append(')'); } } break; case ZCOORD: if (valueForm && (leftEval = left.evaluate()).isVector3DValue()) { sb.append(kernel.format(((Vector3DValue)leftEval).getPointAsDouble()[2])); } else { switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\mathrm{z}("); sb.append(leftStr); sb.append(')'); break; //case STRING_TYPE_JASYMCA: case STRING_TYPE_MATH_PIPER: // note: see GeoGebraCAS.insertSpecialChars() sb.append("z"); sb.append(UNICODE_PREFIX); sb.append("40"); // decimal unicode for ( sb.append(UNICODE_DELIMITER); sb.append(leftStr); sb.append(UNICODE_PREFIX); sb.append("41"); // decimal unicode for ) sb.append(UNICODE_DELIMITER); break; default: sb.append("z("); sb.append(leftStr); sb.append(')'); } } break; case FUNCTION: // GeoFunction and GeoFunctionConditional should not be expanded if (left.isGeoElement() && ((GeoElement)left).isGeoFunction()) { GeoFunction geo = (GeoFunction)left; if (geo.isLabelSet()) { sb.append(geo.getLabel()); sb.append('('); sb.append(rightStr); sb.append(')'); } else { // inline function: replace function var by right side FunctionVariable var = geo.getFunction().getFunctionVariable(); String oldVarStr = var.toString(); var.setVarString(rightStr); sb.append(geo.getLabel()); var.setVarString(oldVarStr); } } else if (valueForm && left.isExpressionNode()) { ExpressionNode en = (ExpressionNode) left; // left could contain $ nodes to wrap a GeoElement // e.g. A1(x) = x^2 and B1(x) = $A$1(x) // value form of B1 is x^2 and NOT x^2(x) switch (en.operation) { case $VAR_ROW: case $VAR_COL: case $VAR_ROW_COL: sb.append(leftStr); break; default: sb.append(leftStr); sb.append('('); sb.append(rightStr); sb.append(')'); break; } } else { // standard case if we get here sb.append(leftStr); sb.append('('); sb.append(rightStr); sb.append(')'); } break; case VEC_FUNCTION: // GeoCurveables should not be expanded if (left.isGeoElement() && ((GeoElement)left).isGeoCurveable()) { sb.append(((GeoElement)left).getLabel()); } else sb.append(leftStr); sb.append('('); sb.append(rightStr); sb.append(')'); break; case DERIVATIVE: // e.g. f'' // labeled GeoElements should not be expanded if (left.isGeoElement() && ((GeoElement)left).isLabelSet()) { sb.append(((GeoElement)left).getLabel()); } else sb.append(leftStr); if (right.isNumberValue()) { int order = (int) Math.round(((MyDouble)right).getDouble()); for (;order > 0; order--) sb.append('\''); } else sb.append(right); break; case $VAR_ROW: // e.g. A$1 if (valueForm) { // GeoElement value sb.append(leftStr); } else { // $ for row GeoElement geo = (GeoElement)left; if (geo.getSpreadsheetCoords() != null) { sb.append(geo.getSpreadsheetLabelWithDollars(false, true)); } else { sb.append(leftStr); } } break; case $VAR_COL: // e.g. $A1 if (valueForm) { // GeoElement value sb.append(leftStr); } else { // $ for row GeoElement geo = (GeoElement)left; if (geo.getSpreadsheetCoords() != null) { sb.append(geo.getSpreadsheetLabelWithDollars(true, false)); } else { sb.append(leftStr); } } break; case $VAR_ROW_COL: // e.g. $A$1 if (valueForm) { // GeoElement value sb.append(leftStr); } else { // $ for row GeoElement geo = (GeoElement)left; if (geo.getSpreadsheetCoords() != null) { sb.append(geo.getSpreadsheetLabelWithDollars(true, true)); } else { sb.append(leftStr); } } break; default: sb.append("unhandled operation " + operation); } return sb.toString(); } // return operation number static public int opID(ExpressionValue ev) { if (ev.isExpressionNode()) return ((ExpressionNode)ev).operation; else return -1; } public boolean isNumberValue() { return evaluate().isNumberValue(); } public boolean isBooleanValue() { return evaluate().isBooleanValue(); } public boolean isListValue() { return evaluate().isListValue(); } public boolean isPolynomialInstance() { //return evaluate().isPolynomial(); return false; } public boolean isTextValue() { // should be efficient as it is used in operationToString() if (leaf) return left.isTextValue(); else return (operation == PLUS && (left.isTextValue() || right.isTextValue())); } final public boolean isExpressionNode() { return true; } public boolean isVector3DValue() { return false; } public static boolean isEqual(ExpressionValue ev1, ExpressionValue ev2) { if (ev1.isNumberValue() && ev2.isNumberValue()) { return Kernel.isEqual( ((NumberValue)ev1).getDouble(), ((NumberValue)ev2).getDouble(), Kernel.EPSILON); } else if (ev1.isTextValue() && ev2.isTextValue()) { return ((TextValue)ev1).toString().equals(((TextValue)ev2).toString()); } else if (ev1.isGeoElement() && ev2.isGeoElement()) { return ((GeoElement)ev1).isEqual(((GeoElement)ev2)); } else return false; } /** * Returns whether the given expression will give the same String output * as val. * @param symbolic: whether we should use the value (true) or the label (false) of ev when * it is a GeoElement */ final public static boolean isEqualString(ExpressionValue ev, double val, boolean symbolic) { if (ev.isLeaf() && ev instanceof NumberValue) { // function variables need to be kept if (ev instanceof FunctionVariable) { return false; } // check if ev is a labeled GeoElement if (symbolic) { if (ev.isGeoElement()) { // labeled GeoElement GeoElement geo = (GeoElement) ev; if (geo.isLabelSet() || geo.isLocalVariable() || !geo.isIndependent()) return false; } } NumberValue nv = (NumberValue) ev; return nv.getDouble() == val; } return false; } }
false
true
final private String operationToString(String leftStr, String rightStr, boolean valueForm) { ExpressionValue leftEval; StringBuilder sb = new StringBuilder(); int STRING_TYPE = kernel.getCASPrintForm(); switch (operation) { case NOT: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\neg "); break; case STRING_TYPE_MATH_PIPER: sb.append("Not "); break; default: sb.append(strNOT); } if (left.isLeaf()) { sb.append(leftStr); } else { sb.append('('); sb.append(leftStr); sb.append(')'); } break; case OR: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\vee"); break; case STRING_TYPE_MATH_PIPER: sb.append("Or"); break; default: sb.append(strOR); } sb.append(' '); sb.append(rightStr); break; case AND: if (left.isLeaf() || opID(left) >= AND) { sb.append(leftStr); } else { sb.append('('); sb.append(leftStr); sb.append(')'); } sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\wedge"); break; case STRING_TYPE_MATH_PIPER: sb.append("And"); break; default: sb.append(strAND); } sb.append(' '); if (right.isLeaf() || opID(right) >= AND) { sb.append(rightStr); } else { sb.append('('); sb.append(rightStr); sb.append(')'); } break; case EQUAL_BOOLEAN: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: case STRING_TYPE_MATH_PIPER: case STRING_TYPE_JASYMCA: sb.append("="); break; default: sb.append(strEQUAL_BOOLEAN); } sb.append(' '); sb.append(rightStr); break; case NOT_EQUAL: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\neq"); break; case STRING_TYPE_MATH_PIPER: sb.append("!="); break; default: sb.append(strNOT_EQUAL); } sb.append(' '); sb.append(rightStr); break; case IS_ELEMENT_OF: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\in"); break; default: sb.append(strIS_ELEMENT_OF); } sb.append(' '); sb.append(rightStr); break; case CONTAINS: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\subseteq"); break; default: sb.append(strCONTAINS); } sb.append(' '); sb.append(rightStr); break; case CONTAINS_STRICT: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\subset"); break; default: sb.append(strCONTAINS_STRICT); } sb.append(' '); sb.append(rightStr); break; case LESS: sb.append(leftStr); sb.append(" < "); sb.append(rightStr); break; case GREATER: sb.append(leftStr); sb.append(" > "); sb.append(rightStr); break; case LESS_EQUAL: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\leq"); break; case STRING_TYPE_MATH_PIPER: sb.append("<="); break; default: sb.append(strLESS_EQUAL); } sb.append(' '); sb.append(rightStr); break; case GREATER_EQUAL: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\geq"); break; case STRING_TYPE_MATH_PIPER: sb.append(">="); break; default: sb.append(strGREATER_EQUAL); } sb.append(' '); sb.append(rightStr); break; case PARALLEL: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\parallel"); break; default: sb.append(strPARALLEL); } sb.append(' '); sb.append(rightStr); break; case PERPENDICULAR: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\perp"); break; default: sb.append(strPERPENDICULAR); } sb.append(' '); sb.append(rightStr); break; case VECTORPRODUCT: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\times"); break; default: sb.append(strVECTORPRODUCT); } sb.append(' '); sb.append(rightStr); break; case PLUS: switch (STRING_TYPE) { case STRING_TYPE_JASYMCA: case STRING_TYPE_MATH_PIPER: sb.append('('); sb.append(leftStr); sb.append(") + ("); sb.append(rightStr); sb.append(')'); break; default: // TODO: remove // System.out.println("PLUS: left: " + leftStr + " " + isEqualString(left, 0, !valueForm) + // ", right: " + isEqualString(left, 0, !valueForm) + " " + rightStr); // check for 0 if (isEqualString(left, 0, !valueForm)) { if (right.isLeaf() || opID(right) >= PLUS) { sb.append(rightStr); } else { sb.append('('); sb.append(rightStr); sb.append(')'); } break; } else if (isEqualString(right, 0, !valueForm)) { if (left.isLeaf() || opID(left) >= PLUS) { sb.append(leftStr); } else { sb.append('('); sb.append(leftStr); sb.append(')'); } break; } // we need parantheses around right text // if right is not a leaf expression or // it is a leaf GeoElement without a label (i.e. it is calculated somehow) if (left.isTextValue() && ( !right.isLeaf() || (right.isGeoElement() && !((GeoElement) right).isLabelSet()) ) ) { sb.append(leftStr); sb.append(" + ("); sb.append(rightStr); sb.append(')'); } else { sb.append(leftStr); if (rightStr.charAt(0) == '-') { // convert + - to - sb.append(" - "); sb.append(rightStr.substring(1)); } else { sb.append(" + "); sb.append(rightStr); } } break; } break; case MINUS: switch (STRING_TYPE) { case STRING_TYPE_JASYMCA: case STRING_TYPE_MATH_PIPER: sb.append('('); sb.append(leftStr); sb.append(") - ("); sb.append(rightStr); sb.append(')'); break; default: sb.append(leftStr); // check for 0 at right if (rightStr.equals("0")) { break; } if (right.isLeaf() || opID(right) >= MULTIPLY) { // not +, - if (rightStr.charAt(0) == '-') { // convert - - to + sb.append(" + "); sb.append(rightStr.substring(1)); } else { sb.append(" - "); sb.append(rightStr); } } else { sb.append(" - ("); sb.append(rightStr); sb.append(')'); } break; } break; case MULTIPLY: switch (STRING_TYPE) { case STRING_TYPE_JASYMCA: case STRING_TYPE_MATH_PIPER: sb.append('('); sb.append(leftStr); sb.append(") * ("); sb.append(rightStr); sb.append(')'); break; default: // check for 1 at left if (isEqualString(left, 1, !valueForm)) { if (right.isLeaf() || opID(right) >= MULTIPLY) { sb.append(rightStr); } else { sb.append('('); sb.append(rightStr); sb.append(')'); } break; } // check for 0 at right else if (isEqualString(right, 1, !valueForm)) { if (left.isLeaf() || opID(left) >= MULTIPLY) { sb.append(leftStr); } else { sb.append('('); sb.append(leftStr); sb.append(')'); } break; } // check for 0 at left else if (isEqualString(left, 0, !valueForm)) { sb.append("0"); break; } // check for 0 at right else if (isEqualString(right, 0, !valueForm)) { sb.append("0"); break; } // check for degree sign at right else if (rightStr.equals("1\u00b0") || rightStr.equals("\u00b0")) { sb.append(leftStr); sb.append("\u00b0"); break; } boolean nounary = true; // left wing if (left.isLeaf() || opID(left) >= MULTIPLY) { // not +, - if (isEqualString(left, -1, !valueForm)) { // unary minus nounary = false; sb.append('-'); } else { sb.append(leftStr); } } else { sb.append('('); sb.append(leftStr); sb.append(')'); } // right wing int opIDright = opID(right); if (right.isLeaf() || opIDright >= MULTIPLY) { // not +, - // two digits colide: insert * if (nounary) { if (Character.isDigit(rightStr.charAt(0)) && Character.isDigit(sb.charAt(sb.length() - 1)) ) { sb.append(" * "); } else { switch (STRING_TYPE) { case STRING_TYPE_GEOGEBRA_XML: sb.append(" * "); break; default: sb.append(' '); // space instead of '*' } } } // show parentheses around these cases if (rightStr.charAt(0) == '-' // 2 (-5) or -(-5) || !nounary && opIDright <= DIVIDE) // -(x * a) or -(x / a) { sb.append('('); sb.append(rightStr); sb.append(')'); } else sb.append(rightStr); } else { if (nounary) { switch (STRING_TYPE) { case STRING_TYPE_GEOGEBRA_XML: sb.append(" * "); break; default: sb.append(' '); // space instead of '*' } } sb.append('('); sb.append(rightStr); sb.append(')'); } } break; case DIVIDE: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\frac{"); sb.append(leftStr); sb.append("}{"); sb.append(rightStr); sb.append("}"); break; case STRING_TYPE_JASYMCA: case STRING_TYPE_MATH_PIPER: sb.append('('); sb.append(leftStr); sb.append(")/("); sb.append(rightStr); sb.append(')'); break; default: // check for 1 in denominator if (isEqualString(right, 1, !valueForm)) { sb.append(leftStr); break; } // left wing if (left.isLeaf()|| opID(left) >= DIVIDE) { // not +, -, * sb.append(leftStr); } else { sb.append('('); sb.append(leftStr); sb.append(')'); } sb.append(" / "); // right wing if (right.isLeaf() || opID(right) >= POWER) // not +, -, *, / sb.append(rightStr); else { sb.append('('); sb.append(rightStr); sb.append(')'); } } break; case POWER: switch (STRING_TYPE) { case STRING_TYPE_JASYMCA: case STRING_TYPE_MATH_PIPER: sb.append('('); sb.append(leftStr); sb.append(')'); break; default: /* removed Michael Borcherds 2009-02-08 * doesn't work eg m=1 g(x) = (x - 1)^m (x - 3) */ // check for 1 in exponent if (isEqualString(right, 1, !valueForm)) { sb.append(leftStr); break; } // left wing if (leftStr.charAt(0) != '-' && // no unary (left.isLeaf() || opID(left) > POWER)) { // not +, -, *, /, ^ sb.append(leftStr); } else { sb.append('('); sb.append(leftStr); sb.append(')'); } break; } // right wing switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append('^'); sb.append('{'); sb.append(rightStr); sb.append('}'); break; case STRING_TYPE_JASYMCA: case STRING_TYPE_GEOGEBRA_XML: case STRING_TYPE_MATH_PIPER: sb.append('^'); sb.append('('); sb.append(rightStr); sb.append(')'); break; default: if (right.isLeaf() || opID(right) > POWER) { // not +, -, *, /, ^ /* // Michael Borcherds 2008-05-14 // display powers over 9 as unicode superscript try { int i = Integer.parseInt(rightStr); String index=""; if (i<0) { sb.append('\u207B'); // superscript minus sign i=-i; } if (i==0) sb.append('\u2070'); // zero else while (i>0) { switch (i%10) { case 0: index="\u2070"+index; break; case 1: index="\u00b9"+index; break; case 2: index="\u00b2"+index; break; case 3: index="\u00b3"+index; break; case 4: index="\u2074"+index; break; case 5: index="\u2075"+index; break; case 6: index="\u2076"+index; break; case 7: index="\u2077"+index; break; case 8: index="\u2078"+index; break; case 9: index="\u2079"+index; break; } i=i/10; } sb.append(index); } catch (Exception e) { sb.append('^'); sb.append(rightStr); }*/ if (rightStr.length() == 1) { switch (rightStr.charAt(0)) { case '0': sb.append('\u2070'); break; case '1': sb.append('\u00b9'); break; case '2': sb.append('\u00b2'); break; case '3': sb.append('\u00b3'); break; case '4': sb.append('\u2074'); break; case '5': sb.append('\u2075'); break; case '6': sb.append('\u2076'); break; case '7': sb.append('\u2077'); break; case '8': sb.append('\u2078'); break; case '9': sb.append('\u2079'); break; default: sb.append('^'); sb.append(rightStr); } } else { sb.append('^'); sb.append(rightStr); } } else { sb.append('^'); sb.append('('); sb.append(rightStr); sb.append(')'); } } break; case FACTORIAL: if (leftStr.charAt(0) != '-' && // no unary left.isLeaf() || opID(left) > POWER) { // not +, -, *, /, ^ sb.append(leftStr); } else { sb.append('('); sb.append(leftStr); sb.append(')'); } sb.append('!'); break; case COS: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\cos("); break; case STRING_TYPE_MATH_PIPER: sb.append("Cos("); break; default: sb.append("cos("); } sb.append(leftStr); sb.append(')'); break; case SIN: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\sin("); break; case STRING_TYPE_MATH_PIPER: sb.append("Sin("); break; default: sb.append("sin("); } sb.append(leftStr); sb.append(')'); break; case TAN: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\tan("); break; case STRING_TYPE_MATH_PIPER: sb.append("Tan("); break; default: sb.append("tan("); } sb.append(leftStr); sb.append(')'); break; case ARCCOS: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\arccos("); break; case STRING_TYPE_MATH_PIPER: sb.append("ArcCos("); break; default: sb.append("acos("); } sb.append(leftStr); sb.append(')'); break; case ARCSIN: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\arcsin("); break; case STRING_TYPE_MATH_PIPER: sb.append("ArcSin("); break; default: sb.append("asin("); } sb.append(leftStr); sb.append(')'); break; case ARCTAN: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\arctan("); break; case STRING_TYPE_MATH_PIPER: sb.append("ArcTan("); break; default: sb.append("atan("); } sb.append(leftStr); sb.append(')'); break; case COSH: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\cosh("); break; case STRING_TYPE_MATH_PIPER: sb.append("Cosh("); break; default: sb.append("cosh("); } sb.append(leftStr); sb.append(')'); break; case SINH: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\sinh("); break; case STRING_TYPE_MATH_PIPER: sb.append("Sinh("); break; default: sb.append("sinh("); } sb.append(leftStr); sb.append(')'); break; case TANH: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\tanh("); break; case STRING_TYPE_MATH_PIPER: sb.append("Tanh("); break; default: sb.append("tanh("); } sb.append(leftStr); sb.append(')'); break; case ACOSH: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\mathrm{acosh}("); break; case STRING_TYPE_MATH_PIPER: sb.append("ArcCosh("); break; default: sb.append("acosh("); } sb.append(leftStr); sb.append(')'); break; case ASINH: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\mathrm{asinh}("); break; case STRING_TYPE_MATH_PIPER: sb.append("ArcSinh("); break; default: sb.append("asinh("); } sb.append(leftStr); sb.append(')'); break; case ATANH: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\mathrm{atanh}("); break; case STRING_TYPE_MATH_PIPER: sb.append("ArcTanh("); break; default: sb.append("atanh("); } sb.append(leftStr); sb.append(')'); break; case EXP: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("e^{"); sb.append(leftStr); sb.append('}'); break; case STRING_TYPE_MATH_PIPER: sb.append("Exp("); sb.append(leftStr); sb.append(')'); break; case STRING_TYPE_JASYMCA: case STRING_TYPE_GEOGEBRA_XML: sb.append("exp("); sb.append(leftStr); sb.append(')'); break; default: sb.append(Kernel.EULER_STRING); if (left.isLeaf()) { sb.append("^"); sb.append(leftStr); } else { sb.append("^("); sb.append(leftStr); sb.append(')'); } break; } break; case LOG: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\log("); break; case STRING_TYPE_MATH_PIPER: sb.append("Ln("); break; case STRING_TYPE_JASYMCA: case STRING_TYPE_GEOGEBRA_XML: sb.append("log("); break; default: sb.append("ln("); break; } sb.append(leftStr); sb.append(')'); break; case LOG10: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\log_{10}("); sb.append(leftStr); sb.append(')'); break; case STRING_TYPE_MATH_PIPER: sb.append("Ln("); sb.append(leftStr); sb.append(")/Ln(10)"); break; case STRING_TYPE_JASYMCA: sb.append("log("); sb.append(leftStr); sb.append(")/log(10)"); break; default: sb.append("lg("); sb.append(leftStr); sb.append(')'); break; } break; case LOG2: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\log_{2}("); sb.append(leftStr); sb.append(')'); break; case STRING_TYPE_MATH_PIPER: sb.append("Ln("); sb.append(leftStr); sb.append(")/Ln(2)"); break; case STRING_TYPE_JASYMCA: sb.append("log("); sb.append(leftStr); sb.append(")/log(2)"); break; default: sb.append("ld("); sb.append(leftStr); sb.append(')'); break; } break; case SQRT: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\sqrt{"); sb.append(leftStr); sb.append('}'); break; case STRING_TYPE_MATH_PIPER: sb.append("Sqrt("); sb.append(leftStr); sb.append(')'); break; default: sb.append("sqrt("); sb.append(leftStr); sb.append(')'); } break; case CBRT: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\sqrt[3]{"); sb.append(leftStr); sb.append('}'); break; case STRING_TYPE_MATH_PIPER: sb.append("("); sb.append(leftStr); sb.append(")^(1/3)"); break; default: sb.append("cbrt("); sb.append(leftStr); sb.append(')'); } break; case ABS: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\left|"); sb.append(leftStr); sb.append("\\right|"); break; case STRING_TYPE_MATH_PIPER: sb.append("Abs("); sb.append(leftStr); sb.append(')'); break; default: sb.append("abs("); sb.append(leftStr); sb.append(')'); } break; case SGN: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\mathrm{sgn}("); break; case STRING_TYPE_MATH_PIPER: sb.append("Sign("); break; case STRING_TYPE_JASYMCA: sb.append("sign("); break; default: sb.append("sgn("); } sb.append(leftStr); sb.append(')'); break; case FLOOR: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\lfloor"); sb.append(leftStr); sb.append("\\rfloor"); break; case STRING_TYPE_MATH_PIPER: sb.append("Floor("); sb.append(leftStr); sb.append(')'); break; default: sb.append("floor("); sb.append(leftStr); sb.append(')'); } break; case CEIL: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\lceil"); sb.append(leftStr); sb.append("\\rceil"); break; case STRING_TYPE_MATH_PIPER: sb.append("Ceil("); sb.append(leftStr); sb.append(')'); break; default: sb.append("ceil("); sb.append(leftStr); sb.append(')'); } break; case ROUND: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\mathrm{round}("); break; case STRING_TYPE_MATH_PIPER: sb.append("Round("); break; default: sb.append("round("); } sb.append(leftStr); sb.append(')'); break; case GAMMA: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\Gamma("); break; case STRING_TYPE_MATH_PIPER: sb.append("Gamma("); break; default: sb.append("gamma("); } sb.append(leftStr); sb.append(')'); break; case RANDOM: if (valueForm) sb.append(leftStr); else sb.append("random()"); break; case XCOORD: if (valueForm && (leftEval = left.evaluate()).isVectorValue()) { sb.append(kernel.format(((VectorValue)leftEval).getVector().getX())); } else if (valueForm && (leftEval = left.evaluate()).isVector3DValue()) { sb.append(kernel.format(((Vector3DValue)leftEval).getPointAsDouble()[0])); } else { switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\mathrm{x}("); sb.append(leftStr); sb.append(')'); break; case STRING_TYPE_JASYMCA: case STRING_TYPE_MATH_PIPER: // note: see GeoGebraCAS.insertSpecialChars() sb.append("x"); sb.append(UNICODE_PREFIX); sb.append("40"); // decimal unicode for ( sb.append(UNICODE_DELIMITER); sb.append(leftStr); sb.append(UNICODE_PREFIX); sb.append("41"); // decimal unicode for ) sb.append(UNICODE_DELIMITER); break; default: sb.append("x("); sb.append(leftStr); sb.append(')'); } } break; case YCOORD: if (valueForm && (leftEval = left.evaluate()).isVectorValue()) { sb.append(kernel.format(((VectorValue)leftEval).getVector().getY())); } else if (valueForm && (leftEval = left.evaluate()).isVector3DValue()) { sb.append(kernel.format(((Vector3DValue)leftEval).getPointAsDouble()[1])); } else { switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\mathrm{y}("); sb.append(leftStr); sb.append(')'); break; case STRING_TYPE_JASYMCA: case STRING_TYPE_MATH_PIPER: // note: see GeoGebraCAS.insertSpecialChars() sb.append("y"); sb.append(UNICODE_PREFIX); sb.append("40"); // decimal unicode for ( sb.append(UNICODE_DELIMITER); sb.append(leftStr); sb.append(UNICODE_PREFIX); sb.append("41"); // decimal unicode for ) sb.append(UNICODE_DELIMITER); break; default: sb.append("y("); sb.append(leftStr); sb.append(')'); } } break; case ZCOORD: if (valueForm && (leftEval = left.evaluate()).isVector3DValue()) { sb.append(kernel.format(((Vector3DValue)leftEval).getPointAsDouble()[2])); } else { switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\mathrm{z}("); sb.append(leftStr); sb.append(')'); break; //case STRING_TYPE_JASYMCA: case STRING_TYPE_MATH_PIPER: // note: see GeoGebraCAS.insertSpecialChars() sb.append("z"); sb.append(UNICODE_PREFIX); sb.append("40"); // decimal unicode for ( sb.append(UNICODE_DELIMITER); sb.append(leftStr); sb.append(UNICODE_PREFIX); sb.append("41"); // decimal unicode for ) sb.append(UNICODE_DELIMITER); break; default: sb.append("z("); sb.append(leftStr); sb.append(')'); } } break; case FUNCTION: // GeoFunction and GeoFunctionConditional should not be expanded if (left.isGeoElement() && ((GeoElement)left).isGeoFunction()) { GeoFunction geo = (GeoFunction)left; if (geo.isLabelSet()) { sb.append(geo.getLabel()); sb.append('('); sb.append(rightStr); sb.append(')'); } else { // inline function: replace function var by right side FunctionVariable var = geo.getFunction().getFunctionVariable(); String oldVarStr = var.toString(); var.setVarString(rightStr); sb.append(geo.getLabel()); var.setVarString(oldVarStr); } } else if (valueForm && left.isExpressionNode()) { ExpressionNode en = (ExpressionNode) left; // left could contain $ nodes to wrap a GeoElement // e.g. A1(x) = x^2 and B1(x) = $A$1(x) // value form of B1 is x^2 and NOT x^2(x) switch (en.operation) { case $VAR_ROW: case $VAR_COL: case $VAR_ROW_COL: sb.append(leftStr); break; default: sb.append(leftStr); sb.append('('); sb.append(rightStr); sb.append(')'); break; } } else { // standard case if we get here sb.append(leftStr); sb.append('('); sb.append(rightStr); sb.append(')'); } break; case VEC_FUNCTION: // GeoCurveables should not be expanded if (left.isGeoElement() && ((GeoElement)left).isGeoCurveable()) { sb.append(((GeoElement)left).getLabel()); } else sb.append(leftStr); sb.append('('); sb.append(rightStr); sb.append(')'); break; case DERIVATIVE: // e.g. f'' // labeled GeoElements should not be expanded if (left.isGeoElement() && ((GeoElement)left).isLabelSet()) { sb.append(((GeoElement)left).getLabel()); } else sb.append(leftStr); if (right.isNumberValue()) { int order = (int) Math.round(((MyDouble)right).getDouble()); for (;order > 0; order--) sb.append('\''); } else sb.append(right); break; case $VAR_ROW: // e.g. A$1 if (valueForm) { // GeoElement value sb.append(leftStr); } else { // $ for row GeoElement geo = (GeoElement)left; if (geo.getSpreadsheetCoords() != null) { sb.append(geo.getSpreadsheetLabelWithDollars(false, true)); } else { sb.append(leftStr); } } break; case $VAR_COL: // e.g. $A1 if (valueForm) { // GeoElement value sb.append(leftStr); } else { // $ for row GeoElement geo = (GeoElement)left; if (geo.getSpreadsheetCoords() != null) { sb.append(geo.getSpreadsheetLabelWithDollars(true, false)); } else { sb.append(leftStr); } } break; case $VAR_ROW_COL: // e.g. $A$1 if (valueForm) { // GeoElement value sb.append(leftStr); } else { // $ for row GeoElement geo = (GeoElement)left; if (geo.getSpreadsheetCoords() != null) { sb.append(geo.getSpreadsheetLabelWithDollars(true, true)); } else { sb.append(leftStr); } } break; default: sb.append("unhandled operation " + operation); } return sb.toString(); }
final private String operationToString(String leftStr, String rightStr, boolean valueForm) { ExpressionValue leftEval; StringBuilder sb = new StringBuilder(); int STRING_TYPE = kernel.getCASPrintForm(); switch (operation) { case NOT: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\neg "); break; case STRING_TYPE_MATH_PIPER: sb.append("Not "); break; default: sb.append(strNOT); } if (left.isLeaf()) { sb.append(leftStr); } else { sb.append('('); sb.append(leftStr); sb.append(')'); } break; case OR: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\vee"); break; case STRING_TYPE_MATH_PIPER: sb.append("Or"); break; default: sb.append(strOR); } sb.append(' '); sb.append(rightStr); break; case AND: if (left.isLeaf() || opID(left) >= AND) { sb.append(leftStr); } else { sb.append('('); sb.append(leftStr); sb.append(')'); } sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\wedge"); break; case STRING_TYPE_MATH_PIPER: sb.append("And"); break; default: sb.append(strAND); } sb.append(' '); if (right.isLeaf() || opID(right) >= AND) { sb.append(rightStr); } else { sb.append('('); sb.append(rightStr); sb.append(')'); } break; case EQUAL_BOOLEAN: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: case STRING_TYPE_MATH_PIPER: case STRING_TYPE_JASYMCA: sb.append("="); break; default: sb.append(strEQUAL_BOOLEAN); } sb.append(' '); sb.append(rightStr); break; case NOT_EQUAL: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\neq"); break; case STRING_TYPE_MATH_PIPER: sb.append("!="); break; default: sb.append(strNOT_EQUAL); } sb.append(' '); sb.append(rightStr); break; case IS_ELEMENT_OF: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\in"); break; default: sb.append(strIS_ELEMENT_OF); } sb.append(' '); sb.append(rightStr); break; case CONTAINS: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\subseteq"); break; default: sb.append(strCONTAINS); } sb.append(' '); sb.append(rightStr); break; case CONTAINS_STRICT: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\subset"); break; default: sb.append(strCONTAINS_STRICT); } sb.append(' '); sb.append(rightStr); break; case LESS: sb.append(leftStr); sb.append(" < "); sb.append(rightStr); break; case GREATER: sb.append(leftStr); sb.append(" > "); sb.append(rightStr); break; case LESS_EQUAL: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\leq"); break; case STRING_TYPE_MATH_PIPER: sb.append("<="); break; default: sb.append(strLESS_EQUAL); } sb.append(' '); sb.append(rightStr); break; case GREATER_EQUAL: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\geq"); break; case STRING_TYPE_MATH_PIPER: sb.append(">="); break; default: sb.append(strGREATER_EQUAL); } sb.append(' '); sb.append(rightStr); break; case PARALLEL: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\parallel"); break; default: sb.append(strPARALLEL); } sb.append(' '); sb.append(rightStr); break; case PERPENDICULAR: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\perp"); break; default: sb.append(strPERPENDICULAR); } sb.append(' '); sb.append(rightStr); break; case VECTORPRODUCT: sb.append(leftStr); sb.append(' '); switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\times"); break; default: sb.append(strVECTORPRODUCT); } sb.append(' '); sb.append(rightStr); break; case PLUS: switch (STRING_TYPE) { case STRING_TYPE_JASYMCA: case STRING_TYPE_MATH_PIPER: sb.append('('); sb.append(leftStr); sb.append(") + ("); sb.append(rightStr); sb.append(')'); break; default: // TODO: remove // System.out.println("PLUS: left: " + leftStr + " " + isEqualString(left, 0, !valueForm) + // ", right: " + isEqualString(left, 0, !valueForm) + " " + rightStr); // check for 0 if (isEqualString(left, 0, !valueForm)) { if (right.isLeaf() || opID(right) >= PLUS) { sb.append(rightStr); } else { sb.append('('); sb.append(rightStr); sb.append(')'); } break; } else if (isEqualString(right, 0, !valueForm)) { if (left.isLeaf() || opID(left) >= PLUS) { sb.append(leftStr); } else { sb.append('('); sb.append(leftStr); sb.append(')'); } break; } // we need parantheses around right text // if right is not a leaf expression or // it is a leaf GeoElement without a label (i.e. it is calculated somehow) if (left.isTextValue() && ( !right.isLeaf() || (right.isGeoElement() && !((GeoElement) right).isLabelSet()) ) ) { sb.append(leftStr); sb.append(" + ("); sb.append(rightStr); sb.append(')'); } else { sb.append(leftStr); if (rightStr.charAt(0) == '-') { // convert + - to - sb.append(" - "); sb.append(rightStr.substring(1)); } else { sb.append(" + "); sb.append(rightStr); } } break; } break; case MINUS: switch (STRING_TYPE) { case STRING_TYPE_JASYMCA: case STRING_TYPE_MATH_PIPER: sb.append('('); sb.append(leftStr); sb.append(") - ("); sb.append(rightStr); sb.append(')'); break; default: sb.append(leftStr); // check for 0 at right if (rightStr.equals("0")) { break; } if (right.isLeaf() || opID(right) >= MULTIPLY) { // not +, - if (rightStr.charAt(0) == '-') { // convert - - to + sb.append(" + "); sb.append(rightStr.substring(1)); } else { sb.append(" - "); sb.append(rightStr); } } else { sb.append(" - ("); sb.append(rightStr); sb.append(')'); } break; } break; case MULTIPLY: switch (STRING_TYPE) { case STRING_TYPE_JASYMCA: case STRING_TYPE_MATH_PIPER: sb.append('('); sb.append(leftStr); sb.append(") * ("); sb.append(rightStr); sb.append(')'); break; default: // check for 1 at left if (isEqualString(left, 1, !valueForm)) { if (right.isLeaf() || opID(right) >= MULTIPLY) { sb.append(rightStr); } else { sb.append('('); sb.append(rightStr); sb.append(')'); } break; } // check for 0 at right else if (isEqualString(right, 1, !valueForm)) { if (left.isLeaf() || opID(left) >= MULTIPLY) { sb.append(leftStr); } else { sb.append('('); sb.append(leftStr); sb.append(')'); } break; } // check for 0 at left else if (valueForm && isEqualString(left, 0, !valueForm)) { sb.append("0"); break; } // check for 0 at right else if (valueForm && isEqualString(right, 0, !valueForm)) { sb.append("0"); break; } // check for degree sign at right else if (rightStr.equals("1\u00b0") || rightStr.equals("\u00b0")) { sb.append(leftStr); sb.append("\u00b0"); break; } boolean nounary = true; // left wing if (left.isLeaf() || opID(left) >= MULTIPLY) { // not +, - if (isEqualString(left, -1, !valueForm)) { // unary minus nounary = false; sb.append('-'); } else { sb.append(leftStr); } } else { sb.append('('); sb.append(leftStr); sb.append(')'); } // right wing int opIDright = opID(right); if (right.isLeaf() || opIDright >= MULTIPLY) { // not +, - // two digits colide: insert * if (nounary) { if (Character.isDigit(rightStr.charAt(0)) && Character.isDigit(sb.charAt(sb.length() - 1)) ) { sb.append(" * "); } else { switch (STRING_TYPE) { case STRING_TYPE_GEOGEBRA_XML: sb.append(" * "); break; default: sb.append(' '); // space instead of '*' } } } // show parentheses around these cases if (rightStr.charAt(0) == '-' // 2 (-5) or -(-5) || !nounary && opIDright <= DIVIDE) // -(x * a) or -(x / a) { sb.append('('); sb.append(rightStr); sb.append(')'); } else sb.append(rightStr); } else { if (nounary) { switch (STRING_TYPE) { case STRING_TYPE_GEOGEBRA_XML: sb.append(" * "); break; default: sb.append(' '); // space instead of '*' } } sb.append('('); sb.append(rightStr); sb.append(')'); } } break; case DIVIDE: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\frac{"); sb.append(leftStr); sb.append("}{"); sb.append(rightStr); sb.append("}"); break; case STRING_TYPE_JASYMCA: case STRING_TYPE_MATH_PIPER: sb.append('('); sb.append(leftStr); sb.append(")/("); sb.append(rightStr); sb.append(')'); break; default: // check for 1 in denominator if (isEqualString(right, 1, !valueForm)) { sb.append(leftStr); break; } // left wing if (left.isLeaf()|| opID(left) >= DIVIDE) { // not +, -, * sb.append(leftStr); } else { sb.append('('); sb.append(leftStr); sb.append(')'); } sb.append(" / "); // right wing if (right.isLeaf() || opID(right) >= POWER) // not +, -, *, / sb.append(rightStr); else { sb.append('('); sb.append(rightStr); sb.append(')'); } } break; case POWER: switch (STRING_TYPE) { case STRING_TYPE_JASYMCA: case STRING_TYPE_MATH_PIPER: sb.append('('); sb.append(leftStr); sb.append(')'); break; default: /* removed Michael Borcherds 2009-02-08 * doesn't work eg m=1 g(x) = (x - 1)^m (x - 3) */ // check for 1 in exponent if (isEqualString(right, 1, !valueForm)) { sb.append(leftStr); break; } // left wing if (leftStr.charAt(0) != '-' && // no unary (left.isLeaf() || opID(left) > POWER)) { // not +, -, *, /, ^ sb.append(leftStr); } else { sb.append('('); sb.append(leftStr); sb.append(')'); } break; } // right wing switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append('^'); sb.append('{'); sb.append(rightStr); sb.append('}'); break; case STRING_TYPE_JASYMCA: case STRING_TYPE_GEOGEBRA_XML: case STRING_TYPE_MATH_PIPER: sb.append('^'); sb.append('('); sb.append(rightStr); sb.append(')'); break; default: if (right.isLeaf() || opID(right) > POWER) { // not +, -, *, /, ^ /* // Michael Borcherds 2008-05-14 // display powers over 9 as unicode superscript try { int i = Integer.parseInt(rightStr); String index=""; if (i<0) { sb.append('\u207B'); // superscript minus sign i=-i; } if (i==0) sb.append('\u2070'); // zero else while (i>0) { switch (i%10) { case 0: index="\u2070"+index; break; case 1: index="\u00b9"+index; break; case 2: index="\u00b2"+index; break; case 3: index="\u00b3"+index; break; case 4: index="\u2074"+index; break; case 5: index="\u2075"+index; break; case 6: index="\u2076"+index; break; case 7: index="\u2077"+index; break; case 8: index="\u2078"+index; break; case 9: index="\u2079"+index; break; } i=i/10; } sb.append(index); } catch (Exception e) { sb.append('^'); sb.append(rightStr); }*/ if (rightStr.length() == 1) { switch (rightStr.charAt(0)) { case '0': sb.append('\u2070'); break; case '1': sb.append('\u00b9'); break; case '2': sb.append('\u00b2'); break; case '3': sb.append('\u00b3'); break; case '4': sb.append('\u2074'); break; case '5': sb.append('\u2075'); break; case '6': sb.append('\u2076'); break; case '7': sb.append('\u2077'); break; case '8': sb.append('\u2078'); break; case '9': sb.append('\u2079'); break; default: sb.append('^'); sb.append(rightStr); } } else { sb.append('^'); sb.append(rightStr); } } else { sb.append('^'); sb.append('('); sb.append(rightStr); sb.append(')'); } } break; case FACTORIAL: if (leftStr.charAt(0) != '-' && // no unary left.isLeaf() || opID(left) > POWER) { // not +, -, *, /, ^ sb.append(leftStr); } else { sb.append('('); sb.append(leftStr); sb.append(')'); } sb.append('!'); break; case COS: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\cos("); break; case STRING_TYPE_MATH_PIPER: sb.append("Cos("); break; default: sb.append("cos("); } sb.append(leftStr); sb.append(')'); break; case SIN: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\sin("); break; case STRING_TYPE_MATH_PIPER: sb.append("Sin("); break; default: sb.append("sin("); } sb.append(leftStr); sb.append(')'); break; case TAN: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\tan("); break; case STRING_TYPE_MATH_PIPER: sb.append("Tan("); break; default: sb.append("tan("); } sb.append(leftStr); sb.append(')'); break; case ARCCOS: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\arccos("); break; case STRING_TYPE_MATH_PIPER: sb.append("ArcCos("); break; default: sb.append("acos("); } sb.append(leftStr); sb.append(')'); break; case ARCSIN: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\arcsin("); break; case STRING_TYPE_MATH_PIPER: sb.append("ArcSin("); break; default: sb.append("asin("); } sb.append(leftStr); sb.append(')'); break; case ARCTAN: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\arctan("); break; case STRING_TYPE_MATH_PIPER: sb.append("ArcTan("); break; default: sb.append("atan("); } sb.append(leftStr); sb.append(')'); break; case COSH: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\cosh("); break; case STRING_TYPE_MATH_PIPER: sb.append("Cosh("); break; default: sb.append("cosh("); } sb.append(leftStr); sb.append(')'); break; case SINH: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\sinh("); break; case STRING_TYPE_MATH_PIPER: sb.append("Sinh("); break; default: sb.append("sinh("); } sb.append(leftStr); sb.append(')'); break; case TANH: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\tanh("); break; case STRING_TYPE_MATH_PIPER: sb.append("Tanh("); break; default: sb.append("tanh("); } sb.append(leftStr); sb.append(')'); break; case ACOSH: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\mathrm{acosh}("); break; case STRING_TYPE_MATH_PIPER: sb.append("ArcCosh("); break; default: sb.append("acosh("); } sb.append(leftStr); sb.append(')'); break; case ASINH: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\mathrm{asinh}("); break; case STRING_TYPE_MATH_PIPER: sb.append("ArcSinh("); break; default: sb.append("asinh("); } sb.append(leftStr); sb.append(')'); break; case ATANH: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\mathrm{atanh}("); break; case STRING_TYPE_MATH_PIPER: sb.append("ArcTanh("); break; default: sb.append("atanh("); } sb.append(leftStr); sb.append(')'); break; case EXP: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("e^{"); sb.append(leftStr); sb.append('}'); break; case STRING_TYPE_MATH_PIPER: sb.append("Exp("); sb.append(leftStr); sb.append(')'); break; case STRING_TYPE_JASYMCA: case STRING_TYPE_GEOGEBRA_XML: sb.append("exp("); sb.append(leftStr); sb.append(')'); break; default: sb.append(Kernel.EULER_STRING); if (left.isLeaf()) { sb.append("^"); sb.append(leftStr); } else { sb.append("^("); sb.append(leftStr); sb.append(')'); } break; } break; case LOG: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\log("); break; case STRING_TYPE_MATH_PIPER: sb.append("Ln("); break; case STRING_TYPE_JASYMCA: case STRING_TYPE_GEOGEBRA_XML: sb.append("log("); break; default: sb.append("ln("); break; } sb.append(leftStr); sb.append(')'); break; case LOG10: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\log_{10}("); sb.append(leftStr); sb.append(')'); break; case STRING_TYPE_MATH_PIPER: sb.append("Ln("); sb.append(leftStr); sb.append(")/Ln(10)"); break; case STRING_TYPE_JASYMCA: sb.append("log("); sb.append(leftStr); sb.append(")/log(10)"); break; default: sb.append("lg("); sb.append(leftStr); sb.append(')'); break; } break; case LOG2: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\log_{2}("); sb.append(leftStr); sb.append(')'); break; case STRING_TYPE_MATH_PIPER: sb.append("Ln("); sb.append(leftStr); sb.append(")/Ln(2)"); break; case STRING_TYPE_JASYMCA: sb.append("log("); sb.append(leftStr); sb.append(")/log(2)"); break; default: sb.append("ld("); sb.append(leftStr); sb.append(')'); break; } break; case SQRT: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\sqrt{"); sb.append(leftStr); sb.append('}'); break; case STRING_TYPE_MATH_PIPER: sb.append("Sqrt("); sb.append(leftStr); sb.append(')'); break; default: sb.append("sqrt("); sb.append(leftStr); sb.append(')'); } break; case CBRT: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\sqrt[3]{"); sb.append(leftStr); sb.append('}'); break; case STRING_TYPE_MATH_PIPER: sb.append("("); sb.append(leftStr); sb.append(")^(1/3)"); break; default: sb.append("cbrt("); sb.append(leftStr); sb.append(')'); } break; case ABS: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\left|"); sb.append(leftStr); sb.append("\\right|"); break; case STRING_TYPE_MATH_PIPER: sb.append("Abs("); sb.append(leftStr); sb.append(')'); break; default: sb.append("abs("); sb.append(leftStr); sb.append(')'); } break; case SGN: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\mathrm{sgn}("); break; case STRING_TYPE_MATH_PIPER: sb.append("Sign("); break; case STRING_TYPE_JASYMCA: sb.append("sign("); break; default: sb.append("sgn("); } sb.append(leftStr); sb.append(')'); break; case FLOOR: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\lfloor"); sb.append(leftStr); sb.append("\\rfloor"); break; case STRING_TYPE_MATH_PIPER: sb.append("Floor("); sb.append(leftStr); sb.append(')'); break; default: sb.append("floor("); sb.append(leftStr); sb.append(')'); } break; case CEIL: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\lceil"); sb.append(leftStr); sb.append("\\rceil"); break; case STRING_TYPE_MATH_PIPER: sb.append("Ceil("); sb.append(leftStr); sb.append(')'); break; default: sb.append("ceil("); sb.append(leftStr); sb.append(')'); } break; case ROUND: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\mathrm{round}("); break; case STRING_TYPE_MATH_PIPER: sb.append("Round("); break; default: sb.append("round("); } sb.append(leftStr); sb.append(')'); break; case GAMMA: switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\Gamma("); break; case STRING_TYPE_MATH_PIPER: sb.append("Gamma("); break; default: sb.append("gamma("); } sb.append(leftStr); sb.append(')'); break; case RANDOM: if (valueForm) sb.append(leftStr); else sb.append("random()"); break; case XCOORD: if (valueForm && (leftEval = left.evaluate()).isVectorValue()) { sb.append(kernel.format(((VectorValue)leftEval).getVector().getX())); } else if (valueForm && (leftEval = left.evaluate()).isVector3DValue()) { sb.append(kernel.format(((Vector3DValue)leftEval).getPointAsDouble()[0])); } else { switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\mathrm{x}("); sb.append(leftStr); sb.append(')'); break; case STRING_TYPE_JASYMCA: case STRING_TYPE_MATH_PIPER: // note: see GeoGebraCAS.insertSpecialChars() sb.append("x"); sb.append(UNICODE_PREFIX); sb.append("40"); // decimal unicode for ( sb.append(UNICODE_DELIMITER); sb.append(leftStr); sb.append(UNICODE_PREFIX); sb.append("41"); // decimal unicode for ) sb.append(UNICODE_DELIMITER); break; default: sb.append("x("); sb.append(leftStr); sb.append(')'); } } break; case YCOORD: if (valueForm && (leftEval = left.evaluate()).isVectorValue()) { sb.append(kernel.format(((VectorValue)leftEval).getVector().getY())); } else if (valueForm && (leftEval = left.evaluate()).isVector3DValue()) { sb.append(kernel.format(((Vector3DValue)leftEval).getPointAsDouble()[1])); } else { switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\mathrm{y}("); sb.append(leftStr); sb.append(')'); break; case STRING_TYPE_JASYMCA: case STRING_TYPE_MATH_PIPER: // note: see GeoGebraCAS.insertSpecialChars() sb.append("y"); sb.append(UNICODE_PREFIX); sb.append("40"); // decimal unicode for ( sb.append(UNICODE_DELIMITER); sb.append(leftStr); sb.append(UNICODE_PREFIX); sb.append("41"); // decimal unicode for ) sb.append(UNICODE_DELIMITER); break; default: sb.append("y("); sb.append(leftStr); sb.append(')'); } } break; case ZCOORD: if (valueForm && (leftEval = left.evaluate()).isVector3DValue()) { sb.append(kernel.format(((Vector3DValue)leftEval).getPointAsDouble()[2])); } else { switch (STRING_TYPE) { case STRING_TYPE_LATEX: sb.append("\\mathrm{z}("); sb.append(leftStr); sb.append(')'); break; //case STRING_TYPE_JASYMCA: case STRING_TYPE_MATH_PIPER: // note: see GeoGebraCAS.insertSpecialChars() sb.append("z"); sb.append(UNICODE_PREFIX); sb.append("40"); // decimal unicode for ( sb.append(UNICODE_DELIMITER); sb.append(leftStr); sb.append(UNICODE_PREFIX); sb.append("41"); // decimal unicode for ) sb.append(UNICODE_DELIMITER); break; default: sb.append("z("); sb.append(leftStr); sb.append(')'); } } break; case FUNCTION: // GeoFunction and GeoFunctionConditional should not be expanded if (left.isGeoElement() && ((GeoElement)left).isGeoFunction()) { GeoFunction geo = (GeoFunction)left; if (geo.isLabelSet()) { sb.append(geo.getLabel()); sb.append('('); sb.append(rightStr); sb.append(')'); } else { // inline function: replace function var by right side FunctionVariable var = geo.getFunction().getFunctionVariable(); String oldVarStr = var.toString(); var.setVarString(rightStr); sb.append(geo.getLabel()); var.setVarString(oldVarStr); } } else if (valueForm && left.isExpressionNode()) { ExpressionNode en = (ExpressionNode) left; // left could contain $ nodes to wrap a GeoElement // e.g. A1(x) = x^2 and B1(x) = $A$1(x) // value form of B1 is x^2 and NOT x^2(x) switch (en.operation) { case $VAR_ROW: case $VAR_COL: case $VAR_ROW_COL: sb.append(leftStr); break; default: sb.append(leftStr); sb.append('('); sb.append(rightStr); sb.append(')'); break; } } else { // standard case if we get here sb.append(leftStr); sb.append('('); sb.append(rightStr); sb.append(')'); } break; case VEC_FUNCTION: // GeoCurveables should not be expanded if (left.isGeoElement() && ((GeoElement)left).isGeoCurveable()) { sb.append(((GeoElement)left).getLabel()); } else sb.append(leftStr); sb.append('('); sb.append(rightStr); sb.append(')'); break; case DERIVATIVE: // e.g. f'' // labeled GeoElements should not be expanded if (left.isGeoElement() && ((GeoElement)left).isLabelSet()) { sb.append(((GeoElement)left).getLabel()); } else sb.append(leftStr); if (right.isNumberValue()) { int order = (int) Math.round(((MyDouble)right).getDouble()); for (;order > 0; order--) sb.append('\''); } else sb.append(right); break; case $VAR_ROW: // e.g. A$1 if (valueForm) { // GeoElement value sb.append(leftStr); } else { // $ for row GeoElement geo = (GeoElement)left; if (geo.getSpreadsheetCoords() != null) { sb.append(geo.getSpreadsheetLabelWithDollars(false, true)); } else { sb.append(leftStr); } } break; case $VAR_COL: // e.g. $A1 if (valueForm) { // GeoElement value sb.append(leftStr); } else { // $ for row GeoElement geo = (GeoElement)left; if (geo.getSpreadsheetCoords() != null) { sb.append(geo.getSpreadsheetLabelWithDollars(true, false)); } else { sb.append(leftStr); } } break; case $VAR_ROW_COL: // e.g. $A$1 if (valueForm) { // GeoElement value sb.append(leftStr); } else { // $ for row GeoElement geo = (GeoElement)left; if (geo.getSpreadsheetCoords() != null) { sb.append(geo.getSpreadsheetLabelWithDollars(true, true)); } else { sb.append(leftStr); } } break; default: sb.append("unhandled operation " + operation); } return sb.toString(); }
diff --git a/bundles/org.eclipse.wst.xml.xpath2.processor/src/org/eclipse/wst/xml/xpath2/processor/internal/types/ElementType.java b/bundles/org.eclipse.wst.xml.xpath2.processor/src/org/eclipse/wst/xml/xpath2/processor/internal/types/ElementType.java index f4aa1ed..9a48c6f 100644 --- a/bundles/org.eclipse.wst.xml.xpath2.processor/src/org/eclipse/wst/xml/xpath2/processor/internal/types/ElementType.java +++ b/bundles/org.eclipse.wst.xml.xpath2.processor/src/org/eclipse/wst/xml/xpath2/processor/internal/types/ElementType.java @@ -1,193 +1,193 @@ /******************************************************************************* * Copyright (c) 2005, 2009 Andrea Bittau, University College London, and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Andrea Bittau - initial API and implementation from the PsychoPath XPath 2.0 * Mukul Gandhi - bug 276134 - improvements to schema aware primitive type support * for attribute/element nodes * David Carver - bug 281186 - implementation of fn:id and fn:idref *******************************************************************************/ package org.eclipse.wst.xml.xpath2.processor.internal.types; import org.apache.xerces.dom.PSVIElementNSImpl; import org.apache.xerces.xs.XSTypeDefinition; import org.eclipse.wst.xml.xpath2.processor.ResultSequence; import org.eclipse.wst.xml.xpath2.processor.ResultSequenceFactory; import org.eclipse.wst.xml.xpath2.processor.function.XSCtrLibrary; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.w3c.dom.TypeInfo; /** * A representation of the ElementType datatype */ public class ElementType extends NodeType { private Element _value; private String _string_value; // constructor only usefull for string_type() // XXX needs to be fixed in future /** * Initialises to a null element */ public ElementType() { this(null, 0); } /** * Initialises according to the supplied parameters * * @param v * The element being represented * @param doc_order * The document order */ public ElementType(Element v, int doc_order) { super(v, doc_order); _value = v; _string_value = null; } /** * Retrieves the actual element value being represented * * @return Actual element value being represented */ public Element value() { return _value; } /** * Retrieves the datatype's full pathname * * @return "element" which is the datatype's full pathname */ @Override public String string_type() { return "element"; } /** * Retrieves a String representation of the element being stored * * @return String representation of the element being stored */ @Override public String string_value() { // XXX can we cache ? if (_string_value != null) return _string_value; _string_value = textnode_strings(_value); return _string_value; } /** * Creates a new ResultSequence consisting of the element stored * * @return New ResultSequence consisting of the element stored */ @Override public ResultSequence typed_value() { ResultSequence rs = ResultSequenceFactory.create_new(); PSVIElementNSImpl psviElem = (PSVIElementNSImpl)_value; XSTypeDefinition typeDef = psviElem.getTypeDefinition(); - if (typeDef != null && typeDef.getNamespace().equals(XSCtrLibrary.XML_SCHEMA_NS)) { + if (XSCtrLibrary.XML_SCHEMA_NS.equals(typeDef.getNamespace())) { Object schemaTypeValue = getTypedValueForPrimitiveType(typeDef); if (schemaTypeValue != null) { rs.add((AnyType)schemaTypeValue); } else { rs.add(new XSUntypedAtomic(string_value())); } } else { rs.add(new XSUntypedAtomic(string_value())); } return rs; } // recursively concatenate TextNode strings /** * Recursively concatenate TextNode strings * * @param node * Node to recurse * @return String representation of the node supplied */ public static String textnode_strings(Node node) { String result = ""; if (node.getNodeType() == Node.TEXT_NODE) { Text tn = (Text) node; result += tn.getData(); } NodeList nl = node.getChildNodes(); // concatenate children for (int i = 0; i < nl.getLength(); i++) { Node n = nl.item(i); result += textnode_strings(n); } return result; } /** * Retrieves the name of the node * * @return QName representation of the name of the node */ @Override public QName node_name() { QName name = new QName(_value.getPrefix(), _value.getLocalName(), _value.getNamespaceURI()); return name; } @Override public ResultSequence nilled() { ResultSequence rs = ResultSequenceFactory.create_new(); // XXX PSVI !!! rs.add(new XSBoolean(false)); return rs; } /** * @since 1.1 */ @Override public boolean isID() { return isElementType(SCHEMA_TYPE_ID); } /** * @since 1.1 */ @Override public boolean isIDREF() { return isElementType(SCHEMA_TYPE_IDREF); } protected boolean isElementType(String typeName) { TypeInfo typeInfo = _value.getSchemaTypeInfo(); return isType(typeInfo, typeName); } }
true
true
public ResultSequence typed_value() { ResultSequence rs = ResultSequenceFactory.create_new(); PSVIElementNSImpl psviElem = (PSVIElementNSImpl)_value; XSTypeDefinition typeDef = psviElem.getTypeDefinition(); if (typeDef != null && typeDef.getNamespace().equals(XSCtrLibrary.XML_SCHEMA_NS)) { Object schemaTypeValue = getTypedValueForPrimitiveType(typeDef); if (schemaTypeValue != null) { rs.add((AnyType)schemaTypeValue); } else { rs.add(new XSUntypedAtomic(string_value())); } } else { rs.add(new XSUntypedAtomic(string_value())); } return rs; }
public ResultSequence typed_value() { ResultSequence rs = ResultSequenceFactory.create_new(); PSVIElementNSImpl psviElem = (PSVIElementNSImpl)_value; XSTypeDefinition typeDef = psviElem.getTypeDefinition(); if (XSCtrLibrary.XML_SCHEMA_NS.equals(typeDef.getNamespace())) { Object schemaTypeValue = getTypedValueForPrimitiveType(typeDef); if (schemaTypeValue != null) { rs.add((AnyType)schemaTypeValue); } else { rs.add(new XSUntypedAtomic(string_value())); } } else { rs.add(new XSUntypedAtomic(string_value())); } return rs; }
diff --git a/openejb/examples/webservice-attachments/src/test/java/org/superbiz/attachment/AttachmentTest.java b/openejb/examples/webservice-attachments/src/test/java/org/superbiz/attachment/AttachmentTest.java index 96c654637..b9cf8f13e 100644 --- a/openejb/examples/webservice-attachments/src/test/java/org/superbiz/attachment/AttachmentTest.java +++ b/openejb/examples/webservice-attachments/src/test/java/org/superbiz/attachment/AttachmentTest.java @@ -1,86 +1,86 @@ /** * 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.superbiz.attachment; import junit.framework.TestCase; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.mail.util.ByteArrayDataSource; import javax.naming.Context; import javax.naming.InitialContext; import javax.xml.namespace.QName; import javax.xml.ws.BindingProvider; import javax.xml.ws.Service; import javax.xml.ws.soap.SOAPBinding; import java.net.URL; import java.util.Properties; public class AttachmentTest extends TestCase { //START SNIPPET: setup private InitialContext initialContext; protected void setUp() throws Exception { Properties properties = new Properties(); properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.core.LocalInitialContextFactory"); properties.setProperty("openejb.embedded.remotable", "true"); initialContext = new InitialContext(properties); } //END SNIPPET: setup /** * Create a webservice client using wsdl url * * @throws Exception */ //START SNIPPET: webservice public void testAttachmentViaWsInterface() throws Exception { Service service = Service.create( - new URL("http://127.0.0.1:4204/webservice-attachements/AttachmentImpl?wsdl"), + new URL("http://127.0.0.1:4204/webservice-attachments/AttachmentImpl?wsdl"), new QName("http://superbiz.org/wsdl", "AttachmentWsService")); assertNotNull(service); AttachmentWs ws = service.getPort(AttachmentWs.class); // retrieve the SOAPBinding SOAPBinding binding = (SOAPBinding) ((BindingProvider) ws).getBinding(); binding.setMTOMEnabled(true); String request = "[email protected]"; // Byte array String response = ws.stringFromBytes(request.getBytes()); assertEquals(request, response); // Data Source DataSource source = new ByteArrayDataSource(request.getBytes(), "text/plain; charset=UTF-8"); // not yet supported ! // response = ws.stringFromDataSource(source); // assertEquals(request, response); // Data Handler response = ws.stringFromDataHandler(new DataHandler(source)); assertEquals(request, response); } //END SNIPPET: webservice }
true
true
public void testAttachmentViaWsInterface() throws Exception { Service service = Service.create( new URL("http://127.0.0.1:4204/webservice-attachements/AttachmentImpl?wsdl"), new QName("http://superbiz.org/wsdl", "AttachmentWsService")); assertNotNull(service); AttachmentWs ws = service.getPort(AttachmentWs.class); // retrieve the SOAPBinding SOAPBinding binding = (SOAPBinding) ((BindingProvider) ws).getBinding(); binding.setMTOMEnabled(true); String request = "[email protected]"; // Byte array String response = ws.stringFromBytes(request.getBytes()); assertEquals(request, response); // Data Source DataSource source = new ByteArrayDataSource(request.getBytes(), "text/plain; charset=UTF-8"); // not yet supported ! // response = ws.stringFromDataSource(source); // assertEquals(request, response); // Data Handler response = ws.stringFromDataHandler(new DataHandler(source)); assertEquals(request, response); }
public void testAttachmentViaWsInterface() throws Exception { Service service = Service.create( new URL("http://127.0.0.1:4204/webservice-attachments/AttachmentImpl?wsdl"), new QName("http://superbiz.org/wsdl", "AttachmentWsService")); assertNotNull(service); AttachmentWs ws = service.getPort(AttachmentWs.class); // retrieve the SOAPBinding SOAPBinding binding = (SOAPBinding) ((BindingProvider) ws).getBinding(); binding.setMTOMEnabled(true); String request = "[email protected]"; // Byte array String response = ws.stringFromBytes(request.getBytes()); assertEquals(request, response); // Data Source DataSource source = new ByteArrayDataSource(request.getBytes(), "text/plain; charset=UTF-8"); // not yet supported ! // response = ws.stringFromDataSource(source); // assertEquals(request, response); // Data Handler response = ws.stringFromDataHandler(new DataHandler(source)); assertEquals(request, response); }
diff --git a/pmd/regress/test/net/sourceforge/pmd/rules/basic/BasicRulesTest.java b/pmd/regress/test/net/sourceforge/pmd/rules/basic/BasicRulesTest.java index bbf3d89b3..01e62f99a 100644 --- a/pmd/regress/test/net/sourceforge/pmd/rules/basic/BasicRulesTest.java +++ b/pmd/regress/test/net/sourceforge/pmd/rules/basic/BasicRulesTest.java @@ -1,55 +1,56 @@ /** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package test.net.sourceforge.pmd.rules.basic; import org.junit.Before; import test.net.sourceforge.pmd.testframework.SimpleAggregatorTst; public class BasicRulesTest extends SimpleAggregatorTst { @Before public void setUp() { addRule("basic", "AvoidDecimalLiteralsInBigDecimalConstructor"); addRule("basic", "AvoidMultipleUnaryOperators"); addRule("basic", "AvoidThreadGroup"); addRule("basic", "AvoidUsingHardCodedIP"); // addRule("basic", "AvoidUsingHardCodedURL"); addRule("basic", "AvoidUsingOctalValues"); addRule("basic", "BigIntegerInstantiation"); addRule("basic", "BooleanInstantiation"); addRule("basic", "BrokenNullCheck"); addRule("basic", "CheckResultSet"); addRule("basic", "ClassCastExceptionWithToArray"); addRule("basic", "CollapsibleIfStatements"); addRule("basic", "DoubleCheckedLocking"); addRule("basic", "EmptyCatchBlock"); addRule("basic", "EmptyFinallyBlock"); addRule("basic", "EmptyIfStmt"); addRule("basic", "EmptyInitializer"); addRule("basic", "EmptyStatementBlock"); addRule("basic", "EmptyStatementNotInLoop"); addRule("basic", "EmptyStaticInitializer"); addRule("basic", "EmptySwitchStatements"); addRule("basic", "EmptySynchronizedBlock"); addRule("basic", "EmptyTryBlock"); addRule("basic", "EmptyWhileStmt"); addRule("basic", "ExtendsObject"); addRule("basic", "ForLoopShouldBeWhileLoop"); addRule("basic", "JumbledIncrementer"); addRule("basic", "MisplacedNullCheck"); addRule("basic", "OverrideBothEqualsAndHashcode"); addRule("basic", "ReturnFromFinallyBlock"); addRule("basic", "UnconditionalIfStatement"); addRule("basic", "UnnecessaryFinalModifier"); addRule("basic", "UnnecessaryReturn"); addRule("basic", "UnnecessaryConversionTemporary"); addRule("basic", "UselessOperationOnImmutable"); addRule("basic", "UselessOverridingMethod"); + addRule("basic", "UselessParentheses"); } public static junit.framework.Test suite() { return new junit.framework.JUnit4TestAdapter(BasicRulesTest.class); } }
true
true
public void setUp() { addRule("basic", "AvoidDecimalLiteralsInBigDecimalConstructor"); addRule("basic", "AvoidMultipleUnaryOperators"); addRule("basic", "AvoidThreadGroup"); addRule("basic", "AvoidUsingHardCodedIP"); // addRule("basic", "AvoidUsingHardCodedURL"); addRule("basic", "AvoidUsingOctalValues"); addRule("basic", "BigIntegerInstantiation"); addRule("basic", "BooleanInstantiation"); addRule("basic", "BrokenNullCheck"); addRule("basic", "CheckResultSet"); addRule("basic", "ClassCastExceptionWithToArray"); addRule("basic", "CollapsibleIfStatements"); addRule("basic", "DoubleCheckedLocking"); addRule("basic", "EmptyCatchBlock"); addRule("basic", "EmptyFinallyBlock"); addRule("basic", "EmptyIfStmt"); addRule("basic", "EmptyInitializer"); addRule("basic", "EmptyStatementBlock"); addRule("basic", "EmptyStatementNotInLoop"); addRule("basic", "EmptyStaticInitializer"); addRule("basic", "EmptySwitchStatements"); addRule("basic", "EmptySynchronizedBlock"); addRule("basic", "EmptyTryBlock"); addRule("basic", "EmptyWhileStmt"); addRule("basic", "ExtendsObject"); addRule("basic", "ForLoopShouldBeWhileLoop"); addRule("basic", "JumbledIncrementer"); addRule("basic", "MisplacedNullCheck"); addRule("basic", "OverrideBothEqualsAndHashcode"); addRule("basic", "ReturnFromFinallyBlock"); addRule("basic", "UnconditionalIfStatement"); addRule("basic", "UnnecessaryFinalModifier"); addRule("basic", "UnnecessaryReturn"); addRule("basic", "UnnecessaryConversionTemporary"); addRule("basic", "UselessOperationOnImmutable"); addRule("basic", "UselessOverridingMethod"); }
public void setUp() { addRule("basic", "AvoidDecimalLiteralsInBigDecimalConstructor"); addRule("basic", "AvoidMultipleUnaryOperators"); addRule("basic", "AvoidThreadGroup"); addRule("basic", "AvoidUsingHardCodedIP"); // addRule("basic", "AvoidUsingHardCodedURL"); addRule("basic", "AvoidUsingOctalValues"); addRule("basic", "BigIntegerInstantiation"); addRule("basic", "BooleanInstantiation"); addRule("basic", "BrokenNullCheck"); addRule("basic", "CheckResultSet"); addRule("basic", "ClassCastExceptionWithToArray"); addRule("basic", "CollapsibleIfStatements"); addRule("basic", "DoubleCheckedLocking"); addRule("basic", "EmptyCatchBlock"); addRule("basic", "EmptyFinallyBlock"); addRule("basic", "EmptyIfStmt"); addRule("basic", "EmptyInitializer"); addRule("basic", "EmptyStatementBlock"); addRule("basic", "EmptyStatementNotInLoop"); addRule("basic", "EmptyStaticInitializer"); addRule("basic", "EmptySwitchStatements"); addRule("basic", "EmptySynchronizedBlock"); addRule("basic", "EmptyTryBlock"); addRule("basic", "EmptyWhileStmt"); addRule("basic", "ExtendsObject"); addRule("basic", "ForLoopShouldBeWhileLoop"); addRule("basic", "JumbledIncrementer"); addRule("basic", "MisplacedNullCheck"); addRule("basic", "OverrideBothEqualsAndHashcode"); addRule("basic", "ReturnFromFinallyBlock"); addRule("basic", "UnconditionalIfStatement"); addRule("basic", "UnnecessaryFinalModifier"); addRule("basic", "UnnecessaryReturn"); addRule("basic", "UnnecessaryConversionTemporary"); addRule("basic", "UselessOperationOnImmutable"); addRule("basic", "UselessOverridingMethod"); addRule("basic", "UselessParentheses"); }
diff --git a/src/org/python/core/PyModule.java b/src/org/python/core/PyModule.java index 5ccef86c..643f3087 100644 --- a/src/org/python/core/PyModule.java +++ b/src/org/python/core/PyModule.java @@ -1,182 +1,185 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; import org.python.expose.ExposedDelete; import org.python.expose.ExposedGet; import org.python.expose.ExposedMethod; import org.python.expose.ExposedNew; import org.python.expose.ExposedSet; import org.python.expose.ExposedType; /** * The Python Module object. * */ @ExposedType(name = "module") public class PyModule extends PyObject { private final PyObject moduleDoc = new PyString( "module(name[, doc])\n" + "\n" + "Create a module object.\n" + "The name must be a string; the optional doc argument can have any type."); /** The module's mutable dictionary */ @ExposedGet public PyObject __dict__; public PyModule() { super(); } public PyModule(PyType subType) { super(subType); } public PyModule(PyType subType, String name) { super(subType); module___init__(new PyString(name), Py.None); } public PyModule(String name) { this(name, null); } public PyModule(String name, PyObject dict) { super(); __dict__ = dict; module___init__(new PyString(name), Py.None); } @ExposedNew @ExposedMethod final void module___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("__init__", args, keywords, new String[] {"name", "doc"}); PyObject name = ap.getPyObject(0); PyObject docs = ap.getPyObject(1, Py.None); module___init__(name, docs); } private void module___init__(PyObject name, PyObject doc) { ensureDict(); __dict__.__setitem__("__name__", name); __dict__.__setitem__("__doc__", doc); } public PyObject fastGetDict() { return __dict__; } public PyObject getDict() { return __dict__; } @ExposedSet(name = "__dict__") public void setDict(PyObject newDict) { throw Py.TypeError("readonly attribute"); } @ExposedDelete(name = "__dict__") public void delDict() { throw Py.TypeError("readonly attribute"); } protected PyObject impAttr(String name) { + if (__dict__ == null) { + return null; + } PyObject path = __dict__.__finditem__("__path__"); PyObject pyName = __dict__.__finditem__("__name__"); if (path == null || pyName == null) { return null; } PyObject attr = null; String fullName = (pyName.__str__().toString() + '.' + name).intern(); if (path == Py.None) { // XXX: disabled //attr = imp.loadFromClassLoader(fullName, // Py.getSystemState().getClassLoader()); } else if (path instanceof PyList) { attr = imp.find_module(name, fullName, (PyList)path); } else { throw Py.TypeError("__path__ must be list or None"); } if (attr == null) { attr = PySystemState.packageManager.lookupName(fullName); } if (attr != null) { // Allow a package component to change its own meaning PyObject found = Py.getSystemState().modules.__finditem__(fullName); if (found != null) { attr = found; } __dict__.__setitem__(name, attr); return attr; } return null; } @Override public PyObject __findattr_ex__(String name) { PyObject attr=super.__findattr_ex__(name); if (attr!=null) return attr; return impAttr(name); } public void __setattr__(String name, PyObject value) { module___setattr__(name, value); } @ExposedMethod final void module___setattr__(String name, PyObject value) { if (name != "__dict__") { ensureDict(); } super.__setattr__(name, value); } public void __delattr__(String name) { module___delattr__(name); } @ExposedMethod final void module___delattr__(String name) { super.__delattr__(name); } public String toString() { return module_toString(); } @ExposedMethod(names = {"__repr__"}) final String module_toString() { PyObject name = null; PyObject filename = null; if (__dict__ != null) { name = __dict__.__finditem__("__name__"); filename = __dict__.__finditem__("__file__"); } if (name == null) { name = new PyString("?"); } if (filename == null) { return String.format("<module '%s' (built-in)>", name); } return String.format("<module '%s' from '%s'>", name, filename); } public PyObject __dir__() { if (__dict__ == null) { throw Py.TypeError("module.__dict__ is not a dictionary"); } return __dict__.invoke("keys"); } private void ensureDict() { if (__dict__ == null) { __dict__ = new PyStringMap(); } } }
true
true
protected PyObject impAttr(String name) { PyObject path = __dict__.__finditem__("__path__"); PyObject pyName = __dict__.__finditem__("__name__"); if (path == null || pyName == null) { return null; } PyObject attr = null; String fullName = (pyName.__str__().toString() + '.' + name).intern(); if (path == Py.None) { // XXX: disabled //attr = imp.loadFromClassLoader(fullName, // Py.getSystemState().getClassLoader()); } else if (path instanceof PyList) { attr = imp.find_module(name, fullName, (PyList)path); } else { throw Py.TypeError("__path__ must be list or None"); } if (attr == null) { attr = PySystemState.packageManager.lookupName(fullName); } if (attr != null) { // Allow a package component to change its own meaning PyObject found = Py.getSystemState().modules.__finditem__(fullName); if (found != null) { attr = found; } __dict__.__setitem__(name, attr); return attr; } return null; }
protected PyObject impAttr(String name) { if (__dict__ == null) { return null; } PyObject path = __dict__.__finditem__("__path__"); PyObject pyName = __dict__.__finditem__("__name__"); if (path == null || pyName == null) { return null; } PyObject attr = null; String fullName = (pyName.__str__().toString() + '.' + name).intern(); if (path == Py.None) { // XXX: disabled //attr = imp.loadFromClassLoader(fullName, // Py.getSystemState().getClassLoader()); } else if (path instanceof PyList) { attr = imp.find_module(name, fullName, (PyList)path); } else { throw Py.TypeError("__path__ must be list or None"); } if (attr == null) { attr = PySystemState.packageManager.lookupName(fullName); } if (attr != null) { // Allow a package component to change its own meaning PyObject found = Py.getSystemState().modules.__finditem__(fullName); if (found != null) { attr = found; } __dict__.__setitem__(name, attr); return attr; } return null; }
diff --git a/src/examples/com/basho/riakcs/client/UserOperations.java b/src/examples/com/basho/riakcs/client/UserOperations.java index 357e549..8eb6371 100644 --- a/src/examples/com/basho/riakcs/client/UserOperations.java +++ b/src/examples/com/basho/riakcs/client/UserOperations.java @@ -1,46 +1,46 @@ /* * This file is provided 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 examples.com.basho.riakcs.client; import org.json.*; import com.basho.riakcs.client.api.*; public class UserOperations { public static void runIt(boolean enableDebugOutput) throws Exception { CSCredentials csCredentials= new CSCredentials(CSCredentials.class.getResourceAsStream("CSCredentials.Riak.properties")); RiakCSClient csClient= new RiakCSClient(csCredentials.getCSAccessKey(), csCredentials.getsCSSecretKey(), csCredentials.getCSEndPoint(), false); if (enableDebugOutput) csClient.enableDebugOutput(); //create new user, and get info using newly created key_id // JSONObject result= csClient.createUser("Hugo Doe", "[email protected]"); // System.out.println(result.toString(2)); // String key_id= result.getString("key_id"); // result= csClient.getUserInfo(key_id); // System.out.println(result.toString(2)); -// JSONObject userInfo= csClient.getMyUserInfo(); -// System.out.println(userInfo.toString(2)); + JSONObject userInfo= csClient.getMyUserInfo(); + System.out.println(userInfo.toString(2)); // JSONObject userInfo= csClient.getUserInfo("YT3FHHROU6I88JHIX9C3"); // use key_id from existing user // System.out.println(userInfo.toString(2)); JSONObject userList= csClient.listUsers(); System.out.println(userList.toString(2)); } }
true
true
public static void runIt(boolean enableDebugOutput) throws Exception { CSCredentials csCredentials= new CSCredentials(CSCredentials.class.getResourceAsStream("CSCredentials.Riak.properties")); RiakCSClient csClient= new RiakCSClient(csCredentials.getCSAccessKey(), csCredentials.getsCSSecretKey(), csCredentials.getCSEndPoint(), false); if (enableDebugOutput) csClient.enableDebugOutput(); //create new user, and get info using newly created key_id // JSONObject result= csClient.createUser("Hugo Doe", "[email protected]"); // System.out.println(result.toString(2)); // String key_id= result.getString("key_id"); // result= csClient.getUserInfo(key_id); // System.out.println(result.toString(2)); // JSONObject userInfo= csClient.getMyUserInfo(); // System.out.println(userInfo.toString(2)); // JSONObject userInfo= csClient.getUserInfo("YT3FHHROU6I88JHIX9C3"); // use key_id from existing user // System.out.println(userInfo.toString(2)); JSONObject userList= csClient.listUsers(); System.out.println(userList.toString(2)); }
public static void runIt(boolean enableDebugOutput) throws Exception { CSCredentials csCredentials= new CSCredentials(CSCredentials.class.getResourceAsStream("CSCredentials.Riak.properties")); RiakCSClient csClient= new RiakCSClient(csCredentials.getCSAccessKey(), csCredentials.getsCSSecretKey(), csCredentials.getCSEndPoint(), false); if (enableDebugOutput) csClient.enableDebugOutput(); //create new user, and get info using newly created key_id // JSONObject result= csClient.createUser("Hugo Doe", "[email protected]"); // System.out.println(result.toString(2)); // String key_id= result.getString("key_id"); // result= csClient.getUserInfo(key_id); // System.out.println(result.toString(2)); JSONObject userInfo= csClient.getMyUserInfo(); System.out.println(userInfo.toString(2)); // JSONObject userInfo= csClient.getUserInfo("YT3FHHROU6I88JHIX9C3"); // use key_id from existing user // System.out.println(userInfo.toString(2)); JSONObject userList= csClient.listUsers(); System.out.println(userList.toString(2)); }
diff --git a/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/WorkingCopyAction.java b/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/WorkingCopyAction.java index 557a8a991..f8cd91fb0 100644 --- a/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/WorkingCopyAction.java +++ b/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/WorkingCopyAction.java @@ -1,232 +1,232 @@ package org.apache.maven.continuum.web.action; /* * 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. */ import com.opensymphony.webwork.ServletActionContext; import com.opensymphony.webwork.views.util.UrlHelper; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.web.exception.AuthorizationRequiredException; import org.apache.maven.continuum.web.util.WorkingCopyContentGenerator; import org.codehaus.plexus.util.StringUtils; import javax.activation.MimetypesFileTypeMap; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.HashMap; import java.util.List; /** * @author <a href="mailto:[email protected]">Emmanuel Venisse</a> * @version $Id$ * @plexus.component role="com.opensymphony.xwork.Action" role-hint="workingCopy" */ public class WorkingCopyAction extends ContinuumActionSupport { /** * @plexus.requirement */ private WorkingCopyContentGenerator generator; private Project project; private int projectId; private String userDirectory; private String currentFile; private String currentFileContent; private String output; private String projectName; private File downloadFile; private String mimeType = "application/octet-stream"; private static String FILE_SEPARATOR = System.getProperty( "file.separator" ); private String projectGroupName = ""; public String execute() throws ContinuumException { try { checkViewProjectGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } List<File> files = getContinuum().getFiles( projectId, userDirectory ); project = getContinuum().getProject( projectId ); projectName = project.getName(); HashMap params = new HashMap(); params.put( "projectId", new Integer( projectId ) ); params.put( "projectName", projectName ); String baseUrl = UrlHelper.buildUrl( "/workingCopy.action", ServletActionContext.getRequest(), ServletActionContext.getResponse(), params ); String imagesBaseUrl = UrlHelper.buildUrl( "/images/", ServletActionContext.getRequest(), ServletActionContext.getResponse(), params ); imagesBaseUrl = imagesBaseUrl.substring( 0, imagesBaseUrl.indexOf( "/images/" ) + "/images/".length() ); output = generator.generate( files, baseUrl, imagesBaseUrl, getContinuum().getWorkingDirectory( projectId ) ); - if ( currentFile != null && currentFile != "" ) + if ( currentFile != null && !currentFile.equals( "" ) ) { String dir; //TODO: maybe create a plexus component for this so that additional mimetypes can be easily added MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap(); mimeTypesMap.addMimeTypes( "application/java-archive jar war ear" ); mimeTypesMap.addMimeTypes( "application/java-class class" ); mimeTypesMap.addMimeTypes( "image/png png" ); if ( FILE_SEPARATOR.equals( userDirectory ) ) { dir = userDirectory; } else { dir = FILE_SEPARATOR + userDirectory + FILE_SEPARATOR; } downloadFile = new File( getContinuum().getWorkingDirectory( projectId ) + dir + currentFile ); mimeType = mimeTypesMap.getContentType( downloadFile ); if ( ( mimeType.indexOf( "image" ) >= 0 ) || ( mimeType.indexOf( "java-archive" ) >= 0 ) || ( mimeType.indexOf( "java-class" ) >= 0 ) || ( downloadFile.length() > 100000 ) ) { return "stream"; } currentFileContent = getContinuum().getFileContent( projectId, userDirectory, currentFile ); } else { currentFileContent = ""; } return SUCCESS; } public int getProjectId() { return projectId; } public void setProjectId( int projectId ) { this.projectId = projectId; } public String getProjectName() { return projectName; } public String getUserDirectory() { return userDirectory; } public void setUserDirectory( String userDirectory ) { this.userDirectory = userDirectory; } public void setFile( String currentFile ) { this.currentFile = currentFile; } public String getOutput() { return output; } public String getFileContent() { return currentFileContent; } public InputStream getInputStream() throws ContinuumException { FileInputStream fis; try { fis = new FileInputStream( downloadFile ); } catch ( FileNotFoundException fne ) { throw new ContinuumException( "Error accessing file.", fne ); } return fis; } public String getFileLength() { return Long.toString( downloadFile.length() ); } public String getDownloadFilename() { return downloadFile.getName(); } public String getMimeType() { return this.mimeType; } public Project getProject() { return project; } public String getProjectGroupName() throws ContinuumException { if ( StringUtils.isEmpty( projectGroupName ) ) { projectGroupName = getContinuum().getProjectGroupByProjectId( projectId ).getName(); } return projectGroupName; } }
true
true
public String execute() throws ContinuumException { try { checkViewProjectGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } List<File> files = getContinuum().getFiles( projectId, userDirectory ); project = getContinuum().getProject( projectId ); projectName = project.getName(); HashMap params = new HashMap(); params.put( "projectId", new Integer( projectId ) ); params.put( "projectName", projectName ); String baseUrl = UrlHelper.buildUrl( "/workingCopy.action", ServletActionContext.getRequest(), ServletActionContext.getResponse(), params ); String imagesBaseUrl = UrlHelper.buildUrl( "/images/", ServletActionContext.getRequest(), ServletActionContext.getResponse(), params ); imagesBaseUrl = imagesBaseUrl.substring( 0, imagesBaseUrl.indexOf( "/images/" ) + "/images/".length() ); output = generator.generate( files, baseUrl, imagesBaseUrl, getContinuum().getWorkingDirectory( projectId ) ); if ( currentFile != null && currentFile != "" ) { String dir; //TODO: maybe create a plexus component for this so that additional mimetypes can be easily added MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap(); mimeTypesMap.addMimeTypes( "application/java-archive jar war ear" ); mimeTypesMap.addMimeTypes( "application/java-class class" ); mimeTypesMap.addMimeTypes( "image/png png" ); if ( FILE_SEPARATOR.equals( userDirectory ) ) { dir = userDirectory; } else { dir = FILE_SEPARATOR + userDirectory + FILE_SEPARATOR; } downloadFile = new File( getContinuum().getWorkingDirectory( projectId ) + dir + currentFile ); mimeType = mimeTypesMap.getContentType( downloadFile ); if ( ( mimeType.indexOf( "image" ) >= 0 ) || ( mimeType.indexOf( "java-archive" ) >= 0 ) || ( mimeType.indexOf( "java-class" ) >= 0 ) || ( downloadFile.length() > 100000 ) ) { return "stream"; } currentFileContent = getContinuum().getFileContent( projectId, userDirectory, currentFile ); } else { currentFileContent = ""; } return SUCCESS; }
public String execute() throws ContinuumException { try { checkViewProjectGroupAuthorization( getProjectGroupName() ); } catch ( AuthorizationRequiredException e ) { return REQUIRES_AUTHORIZATION; } List<File> files = getContinuum().getFiles( projectId, userDirectory ); project = getContinuum().getProject( projectId ); projectName = project.getName(); HashMap params = new HashMap(); params.put( "projectId", new Integer( projectId ) ); params.put( "projectName", projectName ); String baseUrl = UrlHelper.buildUrl( "/workingCopy.action", ServletActionContext.getRequest(), ServletActionContext.getResponse(), params ); String imagesBaseUrl = UrlHelper.buildUrl( "/images/", ServletActionContext.getRequest(), ServletActionContext.getResponse(), params ); imagesBaseUrl = imagesBaseUrl.substring( 0, imagesBaseUrl.indexOf( "/images/" ) + "/images/".length() ); output = generator.generate( files, baseUrl, imagesBaseUrl, getContinuum().getWorkingDirectory( projectId ) ); if ( currentFile != null && !currentFile.equals( "" ) ) { String dir; //TODO: maybe create a plexus component for this so that additional mimetypes can be easily added MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap(); mimeTypesMap.addMimeTypes( "application/java-archive jar war ear" ); mimeTypesMap.addMimeTypes( "application/java-class class" ); mimeTypesMap.addMimeTypes( "image/png png" ); if ( FILE_SEPARATOR.equals( userDirectory ) ) { dir = userDirectory; } else { dir = FILE_SEPARATOR + userDirectory + FILE_SEPARATOR; } downloadFile = new File( getContinuum().getWorkingDirectory( projectId ) + dir + currentFile ); mimeType = mimeTypesMap.getContentType( downloadFile ); if ( ( mimeType.indexOf( "image" ) >= 0 ) || ( mimeType.indexOf( "java-archive" ) >= 0 ) || ( mimeType.indexOf( "java-class" ) >= 0 ) || ( downloadFile.length() > 100000 ) ) { return "stream"; } currentFileContent = getContinuum().getFileContent( projectId, userDirectory, currentFile ); } else { currentFileContent = ""; } return SUCCESS; }
diff --git a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.esb/src/org/wso2/developerstudio/eclipse/esb/mediators/impl/AggregateMediatorImpl.java b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.esb/src/org/wso2/developerstudio/eclipse/esb/mediators/impl/AggregateMediatorImpl.java index 544de480f..e082fa7cf 100644 --- a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.esb/src/org/wso2/developerstudio/eclipse/esb/mediators/impl/AggregateMediatorImpl.java +++ b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.esb/src/org/wso2/developerstudio/eclipse/esb/mediators/impl/AggregateMediatorImpl.java @@ -1,624 +1,625 @@ /* * Copyright 2009-2010 WSO2, Inc. (http://wso2.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.developerstudio.eclipse.esb.mediators.impl; import java.util.HashMap; import java.util.Map; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.w3c.dom.Element; import org.wso2.developerstudio.eclipse.esb.NamespacedProperty; import org.wso2.developerstudio.eclipse.esb.impl.MediatorImpl; import org.wso2.developerstudio.eclipse.esb.mediators.AggregateMediator; import org.wso2.developerstudio.eclipse.esb.mediators.AggregateOnCompleteBranch; import org.wso2.developerstudio.eclipse.esb.mediators.MediatorsPackage; import org.wso2.developerstudio.eclipse.esb.util.ObjectValidator; /** * <!-- begin-user-doc --> An implementation of the model object ' * <em><b>Aggregate Mediator</b></em>'. <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link org.wso2.developerstudio.eclipse.esb.mediators.impl.AggregateMediatorImpl#getAggregateID <em>Aggregate ID</em>}</li> * <li>{@link org.wso2.developerstudio.eclipse.esb.mediators.impl.AggregateMediatorImpl#getCorrelationExpression <em>Correlation Expression</em>}</li> * <li>{@link org.wso2.developerstudio.eclipse.esb.mediators.impl.AggregateMediatorImpl#getCompletionTimeout <em>Completion Timeout</em>}</li> * <li>{@link org.wso2.developerstudio.eclipse.esb.mediators.impl.AggregateMediatorImpl#getCompletionMinMessages <em>Completion Min Messages</em>}</li> * <li>{@link org.wso2.developerstudio.eclipse.esb.mediators.impl.AggregateMediatorImpl#getCompletionMaxMessages <em>Completion Max Messages</em>}</li> * <li>{@link org.wso2.developerstudio.eclipse.esb.mediators.impl.AggregateMediatorImpl#getOnCompleteBranch <em>On Complete Branch</em>}</li> * </ul> * </p> * * @generated */ public class AggregateMediatorImpl extends MediatorImpl implements AggregateMediator { /** * The default value of the '{@link #getAggregateID() <em>Aggregate ID</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getAggregateID() * @generated * @ordered */ protected static final String AGGREGATE_ID_EDEFAULT = null; /** * The cached value of the '{@link #getAggregateID() <em>Aggregate ID</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getAggregateID() * @generated * @ordered */ protected String aggregateID = AGGREGATE_ID_EDEFAULT; /** * The cached value of the '{@link #getCorrelationExpression() * <em>Correlation Expression</em>}' containment reference. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @see #getCorrelationExpression() * @generated * @ordered */ protected NamespacedProperty correlationExpression; /** * The default value of the '{@link #getCompletionTimeout() <em>Completion Timeout</em>}' attribute. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see #getCompletionTimeout() * @generated * @ordered */ protected static final int COMPLETION_TIMEOUT_EDEFAULT = 0; /** * The cached value of the '{@link #getCompletionTimeout() <em>Completion Timeout</em>}' attribute. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see #getCompletionTimeout() * @generated * @ordered */ protected int completionTimeout = COMPLETION_TIMEOUT_EDEFAULT; /** * The default value of the '{@link #getCompletionMinMessages() <em>Completion Min Messages</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCompletionMinMessages() * @generated * @ordered */ protected static final int COMPLETION_MIN_MESSAGES_EDEFAULT = 0; /** * The cached value of the '{@link #getCompletionMinMessages() <em>Completion Min Messages</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCompletionMinMessages() * @generated * @ordered */ protected int completionMinMessages = COMPLETION_MIN_MESSAGES_EDEFAULT; /** * The default value of the '{@link #getCompletionMaxMessages() <em>Completion Max Messages</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCompletionMaxMessages() * @generated * @ordered */ protected static final int COMPLETION_MAX_MESSAGES_EDEFAULT = 0; /** * The cached value of the '{@link #getCompletionMaxMessages() <em>Completion Max Messages</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCompletionMaxMessages() * @generated * @ordered */ protected int completionMaxMessages = COMPLETION_MAX_MESSAGES_EDEFAULT; /** * The cached value of the '{@link #getOnCompleteBranch() <em>On Complete Branch</em>}' containment reference. * <!-- begin-user-doc * --> <!-- end-user-doc --> * @see #getOnCompleteBranch() * @generated * @ordered */ protected AggregateOnCompleteBranch onCompleteBranch; /** * <!-- begin-user-doc --> <!-- end-user-doc --> */ protected AggregateMediatorImpl() { super(); // Correlation expression. NamespacedProperty correlateOnExpression = getEsbFactory() .createNamespacedProperty(); correlateOnExpression.setPrettyName("Correlation Expression"); correlateOnExpression.setPropertyName("expression"); correlateOnExpression.setPropertyValue(""); setCorrelationExpression(correlateOnExpression); setOnCompleteBranch(getMediatorFactory() .createAggregateOnCompleteBranch()); //Fixing TOOLS-994. setCompletionMaxMessages(-1); setCompletionMinMessages(-1); } /** * {@inheritDoc} */ public void doLoad(Element self) throws Exception { // Load ID if(self.hasAttribute("id")){ setAggregateID(self.getAttribute("id")); } // Correlation expression. Element correlateElem = getChildElement(self, "correlateOn"); if (correlateElem != null) { getCorrelationExpression().load(correlateElem); } // Completion condition. Element completionElem = getChildElement(self, "completeCondition"); if (completionElem != null) { // Timeout. if (completionElem.hasAttribute("timeout")) { setCompletionTimeout(Integer.parseInt(completionElem .getAttribute("timeout"))); } // Message count. Element messageCountElem = getChildElement(completionElem, "messageCount"); if (messageCountElem != null) { setCompletionMaxMessages(Integer.parseInt(messageCountElem .getAttribute("max"))); setCompletionMinMessages(Integer.parseInt(messageCountElem .getAttribute("min"))); } } // OnComplete branch. loadObject(self, "onComplete", AggregateOnCompleteBranch.class, false, new ObjectHandler<AggregateOnCompleteBranch>() { public void handle(AggregateOnCompleteBranch object) { setOnCompleteBranch(object); } }); super.doLoad(self); } /** * {@inheritDoc} */ public Element doSave(Element parent) throws Exception { Element self = createChildElement(parent, "aggregate"); String correlationValue; Element completionElem; switch (getCurrentEsbVersion()){ case ESB301: // Correlation expression. If the expression is empty, don't put the tag correlationValue = getCorrelationExpression().getPropertyValue(); if (correlationValue != null && !correlationValue.trim().equals("")) { Element correlateElem = createChildElement(self, "correlateOn"); getCorrelationExpression().save(correlateElem); } // Completion condition. completionElem = createChildElement(self, "completeCondition"); { // Timeout. completionElem.setAttribute("timeout", Integer.toString(getCompletionTimeout())); // Message count. Element messageCountElem = createChildElement(completionElem, "messageCount"); messageCountElem.setAttribute("max", Integer.toString(getCompletionMaxMessages())); messageCountElem.setAttribute("min", Integer.toString(getCompletionMinMessages())); } // OnComplete branch. if (getOnCompleteBranch() != null) { getOnCompleteBranch().save(self); } if(description!=null) description.save(self); break; case ESB400: // ID - if(getAggregateID()!=""){ + //Fixing TOOLS-1137 + if(getAggregateID()!=null){ self.setAttribute("id",getAggregateID()); } // Correlation expression. If the expression is empty, don't put the tag correlationValue = getCorrelationExpression().getPropertyValue(); if (correlationValue != null && !correlationValue.trim().equals("")) { Element correlateElem = createChildElement(self, "correlateOn"); getCorrelationExpression().save(correlateElem); } // Completion condition. completionElem = createChildElement(self, "completeCondition"); { // Timeout. completionElem.setAttribute("timeout", Integer.toString(getCompletionTimeout())); // Message count. Element messageCountElem = createChildElement(completionElem, "messageCount"); messageCountElem.setAttribute("max", Integer.toString(getCompletionMaxMessages())); messageCountElem.setAttribute("min", Integer.toString(getCompletionMinMessages())); } // OnComplete branch. if (getOnCompleteBranch() != null) { getOnCompleteBranch().save(self); } if(description!=null) description.save(self); break; } return self; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return MediatorsPackage.Literals.AGGREGATE_MEDIATOR; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public int getCompletionTimeout() { return completionTimeout; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setCompletionTimeout(int newCompletionTimeout) { int oldCompletionTimeout = completionTimeout; completionTimeout = newCompletionTimeout; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MediatorsPackage.AGGREGATE_MEDIATOR__COMPLETION_TIMEOUT, oldCompletionTimeout, completionTimeout)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public int getCompletionMinMessages() { return completionMinMessages; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setCompletionMinMessages(int newCompletionMinMessages) { int oldCompletionMinMessages = completionMinMessages; completionMinMessages = newCompletionMinMessages; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MediatorsPackage.AGGREGATE_MEDIATOR__COMPLETION_MIN_MESSAGES, oldCompletionMinMessages, completionMinMessages)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public int getCompletionMaxMessages() { return completionMaxMessages; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setCompletionMaxMessages(int newCompletionMaxMessages) { int oldCompletionMaxMessages = completionMaxMessages; completionMaxMessages = newCompletionMaxMessages; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MediatorsPackage.AGGREGATE_MEDIATOR__COMPLETION_MAX_MESSAGES, oldCompletionMaxMessages, completionMaxMessages)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public NamespacedProperty getCorrelationExpression() { return correlationExpression; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public NotificationChain basicSetCorrelationExpression( NamespacedProperty newCorrelationExpression, NotificationChain msgs) { NamespacedProperty oldCorrelationExpression = correlationExpression; correlationExpression = newCorrelationExpression; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MediatorsPackage.AGGREGATE_MEDIATOR__CORRELATION_EXPRESSION, oldCorrelationExpression, newCorrelationExpression); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setCorrelationExpression( NamespacedProperty newCorrelationExpression) { if (newCorrelationExpression != correlationExpression) { NotificationChain msgs = null; if (correlationExpression != null) msgs = ((InternalEObject)correlationExpression).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - MediatorsPackage.AGGREGATE_MEDIATOR__CORRELATION_EXPRESSION, null, msgs); if (newCorrelationExpression != null) msgs = ((InternalEObject)newCorrelationExpression).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - MediatorsPackage.AGGREGATE_MEDIATOR__CORRELATION_EXPRESSION, null, msgs); msgs = basicSetCorrelationExpression(newCorrelationExpression, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MediatorsPackage.AGGREGATE_MEDIATOR__CORRELATION_EXPRESSION, newCorrelationExpression, newCorrelationExpression)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public AggregateOnCompleteBranch getOnCompleteBranch() { return onCompleteBranch; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public NotificationChain basicSetOnCompleteBranch( AggregateOnCompleteBranch newOnCompleteBranch, NotificationChain msgs) { AggregateOnCompleteBranch oldOnCompleteBranch = onCompleteBranch; onCompleteBranch = newOnCompleteBranch; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MediatorsPackage.AGGREGATE_MEDIATOR__ON_COMPLETE_BRANCH, oldOnCompleteBranch, newOnCompleteBranch); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setOnCompleteBranch( AggregateOnCompleteBranch newOnCompleteBranch) { if (newOnCompleteBranch != onCompleteBranch) { NotificationChain msgs = null; if (onCompleteBranch != null) msgs = ((InternalEObject)onCompleteBranch).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - MediatorsPackage.AGGREGATE_MEDIATOR__ON_COMPLETE_BRANCH, null, msgs); if (newOnCompleteBranch != null) msgs = ((InternalEObject)newOnCompleteBranch).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - MediatorsPackage.AGGREGATE_MEDIATOR__ON_COMPLETE_BRANCH, null, msgs); msgs = basicSetOnCompleteBranch(newOnCompleteBranch, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MediatorsPackage.AGGREGATE_MEDIATOR__ON_COMPLETE_BRANCH, newOnCompleteBranch, newOnCompleteBranch)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String getAggregateID() { return aggregateID; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setAggregateID(String newAggregateID) { String oldAggregateID = aggregateID; aggregateID = newAggregateID; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MediatorsPackage.AGGREGATE_MEDIATOR__AGGREGATE_ID, oldAggregateID, aggregateID)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case MediatorsPackage.AGGREGATE_MEDIATOR__CORRELATION_EXPRESSION: return basicSetCorrelationExpression(null, msgs); case MediatorsPackage.AGGREGATE_MEDIATOR__ON_COMPLETE_BRANCH: return basicSetOnCompleteBranch(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case MediatorsPackage.AGGREGATE_MEDIATOR__AGGREGATE_ID: return getAggregateID(); case MediatorsPackage.AGGREGATE_MEDIATOR__CORRELATION_EXPRESSION: return getCorrelationExpression(); case MediatorsPackage.AGGREGATE_MEDIATOR__COMPLETION_TIMEOUT: return getCompletionTimeout(); case MediatorsPackage.AGGREGATE_MEDIATOR__COMPLETION_MIN_MESSAGES: return getCompletionMinMessages(); case MediatorsPackage.AGGREGATE_MEDIATOR__COMPLETION_MAX_MESSAGES: return getCompletionMaxMessages(); case MediatorsPackage.AGGREGATE_MEDIATOR__ON_COMPLETE_BRANCH: return getOnCompleteBranch(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case MediatorsPackage.AGGREGATE_MEDIATOR__AGGREGATE_ID: setAggregateID((String)newValue); return; case MediatorsPackage.AGGREGATE_MEDIATOR__CORRELATION_EXPRESSION: setCorrelationExpression((NamespacedProperty)newValue); return; case MediatorsPackage.AGGREGATE_MEDIATOR__COMPLETION_TIMEOUT: setCompletionTimeout((Integer)newValue); return; case MediatorsPackage.AGGREGATE_MEDIATOR__COMPLETION_MIN_MESSAGES: setCompletionMinMessages((Integer)newValue); return; case MediatorsPackage.AGGREGATE_MEDIATOR__COMPLETION_MAX_MESSAGES: setCompletionMaxMessages((Integer)newValue); return; case MediatorsPackage.AGGREGATE_MEDIATOR__ON_COMPLETE_BRANCH: setOnCompleteBranch((AggregateOnCompleteBranch)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case MediatorsPackage.AGGREGATE_MEDIATOR__AGGREGATE_ID: setAggregateID(AGGREGATE_ID_EDEFAULT); return; case MediatorsPackage.AGGREGATE_MEDIATOR__CORRELATION_EXPRESSION: setCorrelationExpression((NamespacedProperty)null); return; case MediatorsPackage.AGGREGATE_MEDIATOR__COMPLETION_TIMEOUT: setCompletionTimeout(COMPLETION_TIMEOUT_EDEFAULT); return; case MediatorsPackage.AGGREGATE_MEDIATOR__COMPLETION_MIN_MESSAGES: setCompletionMinMessages(COMPLETION_MIN_MESSAGES_EDEFAULT); return; case MediatorsPackage.AGGREGATE_MEDIATOR__COMPLETION_MAX_MESSAGES: setCompletionMaxMessages(COMPLETION_MAX_MESSAGES_EDEFAULT); return; case MediatorsPackage.AGGREGATE_MEDIATOR__ON_COMPLETE_BRANCH: setOnCompleteBranch((AggregateOnCompleteBranch)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case MediatorsPackage.AGGREGATE_MEDIATOR__AGGREGATE_ID: return AGGREGATE_ID_EDEFAULT == null ? aggregateID != null : !AGGREGATE_ID_EDEFAULT.equals(aggregateID); case MediatorsPackage.AGGREGATE_MEDIATOR__CORRELATION_EXPRESSION: return correlationExpression != null; case MediatorsPackage.AGGREGATE_MEDIATOR__COMPLETION_TIMEOUT: return completionTimeout != COMPLETION_TIMEOUT_EDEFAULT; case MediatorsPackage.AGGREGATE_MEDIATOR__COMPLETION_MIN_MESSAGES: return completionMinMessages != COMPLETION_MIN_MESSAGES_EDEFAULT; case MediatorsPackage.AGGREGATE_MEDIATOR__COMPLETION_MAX_MESSAGES: return completionMaxMessages != COMPLETION_MAX_MESSAGES_EDEFAULT; case MediatorsPackage.AGGREGATE_MEDIATOR__ON_COMPLETE_BRANCH: return onCompleteBranch != null; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (aggregateID: "); result.append(aggregateID); result.append(", completionTimeout: "); result.append(completionTimeout); result.append(", completionMinMessages: "); result.append(completionMinMessages); result.append(", completionMaxMessages: "); result.append(completionMaxMessages); result.append(')'); return result.toString(); } public Map<String, ObjectValidator> validate() { return new HashMap<String, ObjectValidator>(); } } // AggregateMediatorImpl
true
true
public Element doSave(Element parent) throws Exception { Element self = createChildElement(parent, "aggregate"); String correlationValue; Element completionElem; switch (getCurrentEsbVersion()){ case ESB301: // Correlation expression. If the expression is empty, don't put the tag correlationValue = getCorrelationExpression().getPropertyValue(); if (correlationValue != null && !correlationValue.trim().equals("")) { Element correlateElem = createChildElement(self, "correlateOn"); getCorrelationExpression().save(correlateElem); } // Completion condition. completionElem = createChildElement(self, "completeCondition"); { // Timeout. completionElem.setAttribute("timeout", Integer.toString(getCompletionTimeout())); // Message count. Element messageCountElem = createChildElement(completionElem, "messageCount"); messageCountElem.setAttribute("max", Integer.toString(getCompletionMaxMessages())); messageCountElem.setAttribute("min", Integer.toString(getCompletionMinMessages())); } // OnComplete branch. if (getOnCompleteBranch() != null) { getOnCompleteBranch().save(self); } if(description!=null) description.save(self); break; case ESB400: // ID if(getAggregateID()!=""){ self.setAttribute("id",getAggregateID()); } // Correlation expression. If the expression is empty, don't put the tag correlationValue = getCorrelationExpression().getPropertyValue(); if (correlationValue != null && !correlationValue.trim().equals("")) { Element correlateElem = createChildElement(self, "correlateOn"); getCorrelationExpression().save(correlateElem); } // Completion condition. completionElem = createChildElement(self, "completeCondition"); { // Timeout. completionElem.setAttribute("timeout", Integer.toString(getCompletionTimeout())); // Message count. Element messageCountElem = createChildElement(completionElem, "messageCount"); messageCountElem.setAttribute("max", Integer.toString(getCompletionMaxMessages())); messageCountElem.setAttribute("min", Integer.toString(getCompletionMinMessages())); } // OnComplete branch. if (getOnCompleteBranch() != null) { getOnCompleteBranch().save(self); } if(description!=null) description.save(self); break; } return self; }
public Element doSave(Element parent) throws Exception { Element self = createChildElement(parent, "aggregate"); String correlationValue; Element completionElem; switch (getCurrentEsbVersion()){ case ESB301: // Correlation expression. If the expression is empty, don't put the tag correlationValue = getCorrelationExpression().getPropertyValue(); if (correlationValue != null && !correlationValue.trim().equals("")) { Element correlateElem = createChildElement(self, "correlateOn"); getCorrelationExpression().save(correlateElem); } // Completion condition. completionElem = createChildElement(self, "completeCondition"); { // Timeout. completionElem.setAttribute("timeout", Integer.toString(getCompletionTimeout())); // Message count. Element messageCountElem = createChildElement(completionElem, "messageCount"); messageCountElem.setAttribute("max", Integer.toString(getCompletionMaxMessages())); messageCountElem.setAttribute("min", Integer.toString(getCompletionMinMessages())); } // OnComplete branch. if (getOnCompleteBranch() != null) { getOnCompleteBranch().save(self); } if(description!=null) description.save(self); break; case ESB400: // ID //Fixing TOOLS-1137 if(getAggregateID()!=null){ self.setAttribute("id",getAggregateID()); } // Correlation expression. If the expression is empty, don't put the tag correlationValue = getCorrelationExpression().getPropertyValue(); if (correlationValue != null && !correlationValue.trim().equals("")) { Element correlateElem = createChildElement(self, "correlateOn"); getCorrelationExpression().save(correlateElem); } // Completion condition. completionElem = createChildElement(self, "completeCondition"); { // Timeout. completionElem.setAttribute("timeout", Integer.toString(getCompletionTimeout())); // Message count. Element messageCountElem = createChildElement(completionElem, "messageCount"); messageCountElem.setAttribute("max", Integer.toString(getCompletionMaxMessages())); messageCountElem.setAttribute("min", Integer.toString(getCompletionMinMessages())); } // OnComplete branch. if (getOnCompleteBranch() != null) { getOnCompleteBranch().save(self); } if(description!=null) description.save(self); break; } return self; }
diff --git a/src/main/java/de/prob/animator/CommandProcessor.java b/src/main/java/de/prob/animator/CommandProcessor.java index c487195..ce35355 100644 --- a/src/main/java/de/prob/animator/CommandProcessor.java +++ b/src/main/java/de/prob/animator/CommandProcessor.java @@ -1,57 +1,58 @@ package de.prob.animator; import java.util.Collections; import java.util.Map; import org.slf4j.Logger; import de.prob.ProBException; import de.prob.animator.command.ICommand; import de.prob.cli.ProBInstance; import de.prob.core.sablecc.node.Start; import de.prob.parser.BindingGenerator; import de.prob.parser.ISimplifiedROMap; import de.prob.parser.ProBResultParser; import de.prob.parser.ResultParserException; import de.prob.prolog.output.PrologTermStringOutput; import de.prob.prolog.term.PrologTerm; class CommandProcessor { private ProBInstance cli; private Logger logger; public ISimplifiedROMap<String, PrologTerm> sendCommand( final ICommand command) throws ProBException { PrologTermStringOutput pto = new PrologTermStringOutput(); command.writeCommand(pto); pto.printAtom("true"); final String query = pto.fullstop().toString(); String result = cli.send(query); Map<String, PrologTerm> bindings = Collections.emptyMap(); try { final Start ast = parseResult(result); bindings = BindingGenerator.createBindingMustNotFail(query, ast); } catch (ResultParserException e) { logger.error("Non well-formed answer '{}'", result); + throw new ProBException(e); } return new SimplifiedROMap<String, PrologTerm>(bindings); } private Start parseResult(final String input) throws ProBException, ResultParserException { if (input == null) return null; else return ProBResultParser.parse(input); } public void configure(final ProBInstance cli, final Logger logger) { this.cli = cli; this.logger = logger; } }
true
true
public ISimplifiedROMap<String, PrologTerm> sendCommand( final ICommand command) throws ProBException { PrologTermStringOutput pto = new PrologTermStringOutput(); command.writeCommand(pto); pto.printAtom("true"); final String query = pto.fullstop().toString(); String result = cli.send(query); Map<String, PrologTerm> bindings = Collections.emptyMap(); try { final Start ast = parseResult(result); bindings = BindingGenerator.createBindingMustNotFail(query, ast); } catch (ResultParserException e) { logger.error("Non well-formed answer '{}'", result); } return new SimplifiedROMap<String, PrologTerm>(bindings); }
public ISimplifiedROMap<String, PrologTerm> sendCommand( final ICommand command) throws ProBException { PrologTermStringOutput pto = new PrologTermStringOutput(); command.writeCommand(pto); pto.printAtom("true"); final String query = pto.fullstop().toString(); String result = cli.send(query); Map<String, PrologTerm> bindings = Collections.emptyMap(); try { final Start ast = parseResult(result); bindings = BindingGenerator.createBindingMustNotFail(query, ast); } catch (ResultParserException e) { logger.error("Non well-formed answer '{}'", result); throw new ProBException(e); } return new SimplifiedROMap<String, PrologTerm>(bindings); }
diff --git a/src/com/android/launcher3/LauncherModel.java b/src/com/android/launcher3/LauncherModel.java index 041882fd9..11aeb20b0 100644 --- a/src/com/android/launcher3/LauncherModel.java +++ b/src/com/android/launcher3/LauncherModel.java @@ -1,2861 +1,2861 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.launcher3; import android.app.SearchManager; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProviderInfo; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentProviderClient; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.Intent.ShortcutIconResource; import android.content.pm.ActivityInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Environment; import android.os.Handler; import android.os.HandlerThread; import android.os.Parcelable; import android.os.Process; import android.os.RemoteException; import android.os.SystemClock; import android.util.Log; import com.android.launcher3.InstallWidgetReceiver.WidgetMimeTypeHandlerData; import java.lang.ref.WeakReference; import java.net.URISyntaxException; import java.text.Collator; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeMap; /** * Maintains in-memory state of the Launcher. It is expected that there should be only one * LauncherModel object held in a static. Also provide APIs for updating the database state * for the Launcher. */ public class LauncherModel extends BroadcastReceiver { static final boolean DEBUG_LOADERS = false; static final String TAG = "Launcher.Model"; private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons private final boolean mAppsCanBeOnExternalStorage; private int mBatchSize; // 0 is all apps at once private int mAllAppsLoadDelay; // milliseconds between batches private final LauncherAppState mApp; private final Object mLock = new Object(); private DeferredHandler mHandler = new DeferredHandler(); private LoaderTask mLoaderTask; private boolean mIsLoaderTaskRunning; private volatile boolean mFlushingWorkerThread; // Specific runnable types that are run on the main thread deferred handler, this allows us to // clear all queued binding runnables when the Launcher activity is destroyed. private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0; private static final int MAIN_THREAD_BINDING_RUNNABLE = 1; private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader"); static { sWorkerThread.start(); } private static final Handler sWorker = new Handler(sWorkerThread.getLooper()); // We start off with everything not loaded. After that, we assume that // our monitoring of the package manager provides all updates and we never // need to do a requery. These are only ever touched from the loader thread. private boolean mWorkspaceLoaded; private boolean mAllAppsLoaded; // When we are loading pages synchronously, we can't just post the binding of items on the side // pages as this delays the rotation process. Instead, we wait for a callback from the first // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start // a normal load, we also clear this set of Runnables. static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>(); private WeakReference<Callbacks> mCallbacks; // < only access in worker thread > private AllAppsList mBgAllAppsList; // The lock that must be acquired before referencing any static bg data structures. Unlike // other locks, this one can generally be held long-term because we never expect any of these // static data structures to be referenced outside of the worker thread except on the first // load after configuration change. static final Object sBgLock = new Object(); // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by // LauncherModel to their ids static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>(); // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts // created by LauncherModel that are directly on the home screen (however, no widgets or // shortcuts within folders). static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>(); // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget() static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders() static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>(); // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>(); // sBgWorkspaceScreens is the ordered set of workspace screens. static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>(); // </ only access in worker thread > private IconCache mIconCache; private Bitmap mDefaultIcon; private static int mCellCountX; private static int mCellCountY; protected int mPreviousConfigMcc; public interface Callbacks { public boolean setLoadOnResume(); public int getCurrentWorkspaceScreen(); public void startBinding(); public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end); public void bindScreens(ArrayList<Long> orderedScreenIds); public void bindFolders(HashMap<Long,FolderInfo> folders); public void finishBindingItems(boolean upgradePath); public void bindAppWidget(LauncherAppWidgetInfo info); public void bindAllApplications(ArrayList<ApplicationInfo> apps); public void bindAppsAdded(ArrayList<ApplicationInfo> apps); public void bindAppsUpdated(ArrayList<ApplicationInfo> apps); public void bindComponentsRemoved(ArrayList<String> packageNames, ArrayList<ApplicationInfo> appInfos, boolean matchPackageNamesOnly); public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts); public boolean isAllAppsVisible(); public boolean isAllAppsButtonRank(int rank); public void bindSearchablesChanged(); public void onPageBoundSynchronously(int page); } LauncherModel(Context context, IconCache iconCache) { mAppsCanBeOnExternalStorage = !Environment.isExternalStorageEmulated(); mApp = LauncherAppState.getInstance(); mBgAllAppsList = new AllAppsList(iconCache); mIconCache = iconCache; mDefaultIcon = Utilities.createIconBitmap( mIconCache.getFullResDefaultActivityIcon(), context); final Resources res = context.getResources(); mAllAppsLoadDelay = res.getInteger(R.integer.config_allAppsBatchLoadDelay); mBatchSize = res.getInteger(R.integer.config_allAppsBatchSize); Configuration config = res.getConfiguration(); mPreviousConfigMcc = config.mcc; } /** Runs the specified runnable immediately if called from the main thread, otherwise it is * posted on the main thread handler. */ private void runOnMainThread(Runnable r) { runOnMainThread(r, 0); } private void runOnMainThread(Runnable r, int type) { if (sWorkerThread.getThreadId() == Process.myTid()) { // If we are on the worker thread, post onto the main handler mHandler.post(r); } else { r.run(); } } /** Runs the specified runnable immediately if called from the worker thread, otherwise it is * posted on the worker thread handler. */ private static void runOnWorkerThread(Runnable r) { if (sWorkerThread.getThreadId() == Process.myTid()) { r.run(); } else { // If we are not on the worker thread, then post to the worker handler sWorker.post(r); } } public Bitmap getFallbackIcon() { return Bitmap.createBitmap(mDefaultIcon); } public void unbindItemInfosAndClearQueuedBindRunnables() { if (sWorkerThread.getThreadId() == Process.myTid()) { throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " + "main thread"); } // Clear any deferred bind runnables mDeferredBindRunnables.clear(); // Remove any queued bind runnables mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE); // Unbind all the workspace items unbindWorkspaceItemsOnMainThread(); } /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */ void unbindWorkspaceItemsOnMainThread() { // Ensure that we don't use the same workspace items data structure on the main thread // by making a copy of workspace items first. final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>(); final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>(); synchronized (sBgLock) { tmpWorkspaceItems.addAll(sBgWorkspaceItems); tmpAppWidgets.addAll(sBgAppWidgets); } Runnable r = new Runnable() { @Override public void run() { for (ItemInfo item : tmpWorkspaceItems) { item.unbind(); } for (ItemInfo item : tmpAppWidgets) { item.unbind(); } } }; runOnMainThread(r); } /** * Adds an item to the DB if it was not created previously, or move it to a new * <container, screen, cellX, cellY> */ static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container, long screenId, int cellX, int cellY) { if (item.container == ItemInfo.NO_ID) { // From all apps addItemToDatabase(context, item, container, screenId, cellX, cellY, false); } else { // From somewhere else moveItemInDatabase(context, item, container, screenId, cellX, cellY); } } static void checkItemInfoLocked( final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) { ItemInfo modelItem = sBgItemsIdMap.get(itemId); if (modelItem != null && item != modelItem) { // check all the data is consistent if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) { ShortcutInfo modelShortcut = (ShortcutInfo) modelItem; ShortcutInfo shortcut = (ShortcutInfo) item; if (modelShortcut.title.toString().equals(shortcut.title.toString()) && modelShortcut.intent.filterEquals(shortcut.intent) && modelShortcut.id == shortcut.id && modelShortcut.itemType == shortcut.itemType && modelShortcut.container == shortcut.container && modelShortcut.screenId == shortcut.screenId && modelShortcut.cellX == shortcut.cellX && modelShortcut.cellY == shortcut.cellY && modelShortcut.spanX == shortcut.spanX && modelShortcut.spanY == shortcut.spanY && ((modelShortcut.dropPos == null && shortcut.dropPos == null) || (modelShortcut.dropPos != null && shortcut.dropPos != null && modelShortcut.dropPos[0] == shortcut.dropPos[0] && modelShortcut.dropPos[1] == shortcut.dropPos[1]))) { // For all intents and purposes, this is the same object return; } } // the modelItem needs to match up perfectly with item if our model is // to be consistent with the database-- for now, just require // modelItem == item or the equality check above String msg = "item: " + ((item != null) ? item.toString() : "null") + "modelItem: " + ((modelItem != null) ? modelItem.toString() : "null") + "Error: ItemInfo passed to checkItemInfo doesn't match original"; RuntimeException e = new RuntimeException(msg); if (stackTrace != null) { e.setStackTrace(stackTrace); } // TODO: something breaks this in the upgrade path //throw e; } } static void checkItemInfo(final ItemInfo item) { final StackTraceElement[] stackTrace = new Throwable().getStackTrace(); final long itemId = item.id; Runnable r = new Runnable() { public void run() { synchronized (sBgLock) { checkItemInfoLocked(itemId, item, stackTrace); } } }; runOnWorkerThread(r); } static void updateItemInDatabaseHelper(Context context, final ContentValues values, final ItemInfo item, final String callingFunction) { final long itemId = item.id; final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false); final ContentResolver cr = context.getContentResolver(); final StackTraceElement[] stackTrace = new Throwable().getStackTrace(); Runnable r = new Runnable() { public void run() { cr.update(uri, values, null, null); updateItemArrays(item, itemId, stackTrace); } }; runOnWorkerThread(r); } static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList, final ArrayList<ItemInfo> items, final String callingFunction) { final ContentResolver cr = context.getContentResolver(); final StackTraceElement[] stackTrace = new Throwable().getStackTrace(); Runnable r = new Runnable() { public void run() { ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); int count = items.size(); for (int i = 0; i < count; i++) { ItemInfo item = items.get(i); final long itemId = item.id; final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false); ContentValues values = valuesList.get(i); ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build()); updateItemArrays(item, itemId, stackTrace); } try { cr.applyBatch(LauncherProvider.AUTHORITY, ops); } catch (Exception e) { e.printStackTrace(); } } }; runOnWorkerThread(r); } static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) { // Lock on mBgLock *after* the db operation synchronized (sBgLock) { checkItemInfoLocked(itemId, item, stackTrace); if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP && item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) { // Item is in a folder, make sure this folder exists if (!sBgFolders.containsKey(item.container)) { // An items container is being set to a that of an item which is not in // the list of Folders. String msg = "item: " + item + " container being set to: " + item.container + ", not in the list of folders"; Log.e(TAG, msg); Launcher.dumpDebugLogsToConsole(); } } // Items are added/removed from the corresponding FolderInfo elsewhere, such // as in Workspace.onDrop. Here, we just add/remove them from the list of items // that are on the desktop, as appropriate ItemInfo modelItem = sBgItemsIdMap.get(itemId); if (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP || modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { switch (modelItem.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: if (!sBgWorkspaceItems.contains(modelItem)) { sBgWorkspaceItems.add(modelItem); } break; default: break; } } else { sBgWorkspaceItems.remove(modelItem); } } } public void flushWorkerThread() { mFlushingWorkerThread = true; Runnable waiter = new Runnable() { public void run() { synchronized (this) { notifyAll(); mFlushingWorkerThread = false; } } }; synchronized(waiter) { runOnWorkerThread(waiter); if (mLoaderTask != null) { synchronized(mLoaderTask) { mLoaderTask.notify(); } } boolean success = false; while (!success) { try { waiter.wait(); success = true; } catch (InterruptedException e) { } } } } /** * Move an item in the DB to a new <container, screen, cellX, cellY> */ static void moveItemInDatabase(Context context, final ItemInfo item, final long container, final long screenId, final int cellX, final int cellY) { String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY + ") --> " + "(" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")"; Launcher.sDumpLogs.add(transaction); Log.d(TAG, transaction); item.container = container; item.cellX = cellX; item.cellY = cellY; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screenId < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); } else { item.screenId = screenId; } final ContentValues values = new ContentValues(); values.put(LauncherSettings.Favorites.CONTAINER, item.container); values.put(LauncherSettings.Favorites.CELLX, item.cellX); values.put(LauncherSettings.Favorites.CELLY, item.cellY); values.put(LauncherSettings.Favorites.SCREEN, item.screenId); updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase"); } /** * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the * cellX, cellY have already been updated on the ItemInfos. */ static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items, final long container, final int screen) { ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>(); int count = items.size(); for (int i = 0; i < count; i++) { ItemInfo item = items.get(i); String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY + ") --> " + "(" + container + ", " + screen + ", " + item.cellX + ", " + item.cellY + ")"; Launcher.sDumpLogs.add(transaction); item.container = container; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screen < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX, item.cellY); } else { item.screenId = screen; } final ContentValues values = new ContentValues(); values.put(LauncherSettings.Favorites.CONTAINER, item.container); values.put(LauncherSettings.Favorites.CELLX, item.cellX); values.put(LauncherSettings.Favorites.CELLY, item.cellY); values.put(LauncherSettings.Favorites.SCREEN, item.screenId); contentValues.add(values); } updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase"); } /** * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY> */ static void modifyItemInDatabase(Context context, final ItemInfo item, final long container, final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) { String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY + ") --> " + "(" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")"; Launcher.sDumpLogs.add(transaction); Log.d(TAG, transaction); item.cellX = cellX; item.cellY = cellY; item.spanX = spanX; item.spanY = spanY; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screenId < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); } else { item.screenId = screenId; } final ContentValues values = new ContentValues(); values.put(LauncherSettings.Favorites.CONTAINER, item.container); values.put(LauncherSettings.Favorites.CELLX, item.cellX); values.put(LauncherSettings.Favorites.CELLY, item.cellY); values.put(LauncherSettings.Favorites.SPANX, item.spanX); values.put(LauncherSettings.Favorites.SPANY, item.spanY); values.put(LauncherSettings.Favorites.SCREEN, item.screenId); updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase"); } /** * Update an item to the database in a specified container. */ static void updateItemInDatabase(Context context, final ItemInfo item) { final ContentValues values = new ContentValues(); item.onAddToDatabase(values); item.updateValuesWithCoordinates(values, item.cellX, item.cellY); updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase"); } /** * Returns true if the shortcuts already exists in the database. * we identify a shortcut by its title and intent. */ static boolean shortcutExists(Context context, String title, Intent intent) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { "title", "intent" }, "title=? and intent=?", new String[] { title, intent.toUri(0) }, null); boolean result = false; try { result = c.moveToFirst(); } finally { c.close(); } return result; } /** * Returns an ItemInfo array containing all the items in the LauncherModel. * The ItemInfo.id is not set through this function. */ static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) { ArrayList<ItemInfo> items = new ArrayList<ItemInfo>(); final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER, LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY, LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null); final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY); try { while (c.moveToNext()) { ItemInfo item = new ItemInfo(); item.cellX = c.getInt(cellXIndex); item.cellY = c.getInt(cellYIndex); item.spanX = c.getInt(spanXIndex); item.spanY = c.getInt(spanYIndex); item.container = c.getInt(containerIndex); item.itemType = c.getInt(itemTypeIndex); item.screenId = c.getInt(screenIndex); items.add(item); } } catch (Exception e) { items.clear(); } finally { c.close(); } return items; } /** * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. */ FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, "_id=? and (itemType=? or itemType=?)", new String[] { String.valueOf(id), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null); try { if (c.moveToFirst()) { final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); FolderInfo folderInfo = null; switch (c.getInt(itemTypeIndex)) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: folderInfo = findOrMakeFolder(folderList, id); break; } folderInfo.title = c.getString(titleIndex); folderInfo.id = id; folderInfo.container = c.getInt(containerIndex); folderInfo.screenId = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); return folderInfo; } } finally { c.close(); } return null; } /** * Add an item to the database in a specified container. Sets the container, screen, cellX and * cellY fields of the item. Also assigns an ID to the item. */ static void addItemToDatabase(Context context, final ItemInfo item, final long container, final long screenId, final int cellX, final int cellY, final boolean notify) { item.container = container; item.cellX = cellX; item.cellY = cellY; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screenId < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); } else { item.screenId = screenId; } final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); LauncherAppState app = LauncherAppState.getInstance(); item.id = app.getLauncherProvider().generateNewItemId(); values.put(LauncherSettings.Favorites._ID, item.id); item.updateValuesWithCoordinates(values, item.cellX, item.cellY); Runnable r = new Runnable() { public void run() { String transaction = "DbDebug Add item (" + item.title + ") to db, id: " + item.id + " (" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")"; Launcher.sDumpLogs.add(transaction); Log.d(TAG, transaction); cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { checkItemInfoLocked(item.id, item, null); sBgItemsIdMap.put(item.id, item); switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sBgFolders.put(item.id, (FolderInfo) item); // Fall through case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP || item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { sBgWorkspaceItems.add(item); } else { if (!sBgFolders.containsKey(item.container)) { // Adding an item to a folder that doesn't exist. String msg = "adding item: " + item + " to a folder that " + " doesn't exist"; Log.e(TAG, msg); Launcher.dumpDebugLogsToConsole(); } } break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sBgAppWidgets.add((LauncherAppWidgetInfo) item); break; } } } }; runOnWorkerThread(r); } /** * Creates a new unique child id, for a given cell span across all layouts. */ static int getCellLayoutChildId( long container, long screen, int localCellX, int localCellY, int spanX, int spanY) { return (((int) container & 0xFF) << 24) | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF); } static int getCellCountX() { return mCellCountX; } static int getCellCountY() { return mCellCountY; } /** * Updates the model orientation helper to take into account the current layout dimensions * when performing local/canonical coordinate transformations. */ static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) { mCellCountX = shortAxisCellCount; mCellCountY = longAxisCellCount; } /** * Removes the specified item from the database * @param context * @param item */ static void deleteItemFromDatabase(Context context, final ItemInfo item) { final ContentResolver cr = context.getContentResolver(); final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false); Runnable r = new Runnable() { public void run() { String transaction = "DbDebug Delete item (" + item.title + ") from db, id: " + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY + ")"; Launcher.sDumpLogs.add(transaction); Log.d(TAG, transaction); cr.delete(uriToDelete, null, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sBgFolders.remove(item.id); for (ItemInfo info: sBgItemsIdMap.values()) { if (info.container == item.id) { // We are deleting a folder which still contains items that // think they are contained by that folder. String msg = "deleting a folder (" + item + ") which still " + "contains items (" + info + ")"; Log.e(TAG, msg); Launcher.dumpDebugLogsToConsole(); } } sBgWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: sBgWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sBgAppWidgets.remove((LauncherAppWidgetInfo) item); break; } sBgItemsIdMap.remove(item.id); sBgDbIconCache.remove(item); } } }; runOnWorkerThread(r); } /** * Update the order of the workspace screens in the database. The array list contains * a list of screen ids in the order that they should appear. */ static void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) { final ContentResolver cr = context.getContentResolver(); final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI; // Remove any negative screen ids -- these aren't persisted Iterator<Long> iter = screens.iterator(); while (iter.hasNext()) { long id = iter.next(); if (id < 0) { iter.remove(); } } Runnable r = new Runnable() { @Override public void run() { final ArrayList<Long> screensCopy = new ArrayList<Long>(); // Clear the table cr.delete(uri, null, null); int count = screens.size(); ContentValues[] values = new ContentValues[count]; for (int i = 0; i < count; i++) { ContentValues v = new ContentValues(); long screenId = screens.get(i); v.put(LauncherSettings.WorkspaceScreens._ID, screenId); v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i); screensCopy.add(screenId); values[i] = v; } cr.bulkInsert(uri, values); sBgWorkspaceScreens.clear(); sBgWorkspaceScreens.addAll(screensCopy); } }; runOnWorkerThread(r); } /** * Remove the contents of the specified folder from the database */ static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) { final ContentResolver cr = context.getContentResolver(); Runnable r = new Runnable() { public void run() { cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { sBgItemsIdMap.remove(info.id); sBgFolders.remove(info.id); sBgDbIconCache.remove(info); sBgWorkspaceItems.remove(info); } cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { for (ItemInfo childInfo : info.contents) { sBgItemsIdMap.remove(childInfo.id); sBgDbIconCache.remove(childInfo); } } } }; runOnWorkerThread(r); } /** * Set this as the current Launcher activity object for the loader. */ public void initialize(Callbacks callbacks) { synchronized (mLock) { mCallbacks = new WeakReference<Callbacks>(callbacks); } } /** * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and * ACTION_PACKAGE_CHANGED. */ @Override public void onReceive(Context context, Intent intent) { if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent); final String action = intent.getAction(); if (Intent.ACTION_PACKAGE_CHANGED.equals(action) || Intent.ACTION_PACKAGE_REMOVED.equals(action) || Intent.ACTION_PACKAGE_ADDED.equals(action)) { final String packageName = intent.getData().getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); int op = PackageUpdatedTask.OP_NONE; if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { op = PackageUpdatedTask.OP_UPDATE; } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_REMOVE; } // else, we are replacing the package, so a PACKAGE_ADDED will be sent // later, we will update the package at this time } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_ADD; } else { op = PackageUpdatedTask.OP_UPDATE; } } if (op != PackageUpdatedTask.OP_NONE) { enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName })); } } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) { // First, schedule to add these apps back in. String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages)); // Then, rebind everything. startLoaderFromBackground(); } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask( PackageUpdatedTask.OP_UNAVAILABLE, packages)); } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) { // If we have changed locale we need to clear out the labels in all apps/workspace. forceReload(); } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) { // Check if configuration change was an mcc/mnc change which would affect app resources // and we would need to clear out the labels in all apps/workspace. Same handling as // above for ACTION_LOCALE_CHANGED Configuration currentConfig = context.getResources().getConfiguration(); if (mPreviousConfigMcc != currentConfig.mcc) { Log.d(TAG, "Reload apps on config change. curr_mcc:" + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc); forceReload(); } // Update previousConfig mPreviousConfigMcc = currentConfig.mcc; } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) || SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) { if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { callbacks.bindSearchablesChanged(); } } } } private void forceReload() { resetLoadedState(true, true); // Do this here because if the launcher activity is running it will be restarted. // If it's not running startLoaderFromBackground will merely tell it that it needs // to reload. startLoaderFromBackground(); } public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) { synchronized (mLock) { // Stop any existing loaders first, so they don't set mAllAppsLoaded or // mWorkspaceLoaded to true later stopLoaderLocked(); if (resetAllAppsLoaded) mAllAppsLoaded = false; if (resetWorkspaceLoaded) mWorkspaceLoaded = false; } } /** * When the launcher is in the background, it's possible for it to miss paired * configuration changes. So whenever we trigger the loader from the background * tell the launcher that it needs to re-run the loader when it comes back instead * of doing it now. */ public void startLoaderFromBackground() { boolean runLoader = false; if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { // Only actually run the loader if they're not paused. if (!callbacks.setLoadOnResume()) { runLoader = true; } } } if (runLoader) { startLoader(false, -1); } } // If there is already a loader task running, tell it to stop. // returns true if isLaunching() was true on the old task private boolean stopLoaderLocked() { boolean isLaunching = false; LoaderTask oldTask = mLoaderTask; if (oldTask != null) { if (oldTask.isLaunching()) { isLaunching = true; } oldTask.stopLocked(); } return isLaunching; } public void startLoader(boolean isLaunching, int synchronousBindPage) { synchronized (mLock) { if (DEBUG_LOADERS) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); } // Clear any deferred bind-runnables from the synchronized load process // We must do this before any loading/binding is scheduled below. mDeferredBindRunnables.clear(); // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks != null && mCallbacks.get() != null) { // If there is already one running, tell it to stop. // also, don't downgrade isLaunching if we're already running isLaunching = isLaunching || stopLoaderLocked(); mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching); if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) { mLoaderTask.runBindSynchronousPage(synchronousBindPage); } else { sWorkerThread.setPriority(Thread.NORM_PRIORITY); sWorker.post(mLoaderTask); } } } } void bindRemainingSynchronousPages() { // Post the remaining side pages to be loaded if (!mDeferredBindRunnables.isEmpty()) { for (final Runnable r : mDeferredBindRunnables) { mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE); } mDeferredBindRunnables.clear(); } } public void stopLoader() { synchronized (mLock) { if (mLoaderTask != null) { mLoaderTask.stopLocked(); } } } public boolean isAllAppsLoaded() { return mAllAppsLoaded; } boolean isLoadingWorkspace() { synchronized (mLock) { if (mLoaderTask != null) { return mLoaderTask.isLoadingWorkspace(); } } return false; } /** * Runnable for the thread that loads the contents of the launcher: * - workspace icons * - widgets * - all apps icons */ private class LoaderTask implements Runnable { private Context mContext; private boolean mIsLaunching; private boolean mIsLoadingAndBindingWorkspace; private boolean mStopped; private boolean mLoadAndBindStepFinished; private boolean mIsUpgradePath; private HashMap<Object, CharSequence> mLabelCache; LoaderTask(Context context, boolean isLaunching) { mContext = context; mIsLaunching = isLaunching; mLabelCache = new HashMap<Object, CharSequence>(); } boolean isLaunching() { return mIsLaunching; } boolean isLoadingWorkspace() { return mIsLoadingAndBindingWorkspace; } private void loadAndBindWorkspace() { mIsLoadingAndBindingWorkspace = true; // Load the workspace if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded); } if (!mWorkspaceLoaded) { loadWorkspace(); synchronized (LoaderTask.this) { if (mStopped) { return; } mWorkspaceLoaded = true; } } // Bind the workspace bindWorkspace(-1); } private void waitForIdle() { // Wait until the either we're stopped or the other threads are done. // This way we don't start loading all apps until the workspace has settled // down. synchronized (LoaderTask.this) { final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; mHandler.postIdle(new Runnable() { public void run() { synchronized (LoaderTask.this) { mLoadAndBindStepFinished = true; if (DEBUG_LOADERS) { Log.d(TAG, "done with previous binding step"); } LoaderTask.this.notify(); } } }); while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) { try { // Just in case mFlushingWorkerThread changes but we aren't woken up, // wait no longer than 1sec at a time this.wait(1000); } catch (InterruptedException ex) { // Ignore } } if (DEBUG_LOADERS) { Log.d(TAG, "waited " + (SystemClock.uptimeMillis()-workspaceWaitTime) + "ms for previous step to finish binding"); } } } void runBindSynchronousPage(int synchronousBindPage) { if (synchronousBindPage < 0) { // Ensure that we have a valid page index to load synchronously throw new RuntimeException("Should not call runBindSynchronousPage() without " + "valid page index"); } if (!mAllAppsLoaded || !mWorkspaceLoaded) { // Ensure that we don't try and bind a specified page when the pages have not been // loaded already (we should load everything asynchronously in that case) throw new RuntimeException("Expecting AllApps and Workspace to be loaded"); } synchronized (mLock) { if (mIsLoaderTaskRunning) { // Ensure that we are never running the background loading at this point since // we also touch the background collections throw new RuntimeException("Error! Background loading is already running"); } } // XXX: Throw an exception if we are already loading (since we touch the worker thread // data structures, we can't allow any other thread to touch that data, but because // this call is synchronous, we can get away with not locking). // The LauncherModel is static in the LauncherAppState and mHandler may have queued // operations from the previous activity. We need to ensure that all queued operations // are executed before any synchronous binding work is done. mHandler.flush(); // Divide the set of loaded items into those that we are binding synchronously, and // everything else that is to be bound normally (asynchronously). bindWorkspace(synchronousBindPage); // XXX: For now, continue posting the binding of AllApps as there are other issues that // arise from that. onlyBindAllApps(); } public void run() { synchronized (mLock) { mIsLoaderTaskRunning = true; } // Optimize for end-user experience: if the Launcher is up and // running with the // All Apps interface in the foreground, load All Apps first. Otherwise, load the // workspace first (default). final Callbacks cbk = mCallbacks.get(); final boolean loadWorkspaceFirst = cbk != null ? (!cbk.isAllAppsVisible()) : true; keep_running: { // Elevate priority when Home launches for the first time to avoid // starving at boot time. Staring at a blank home is not cool. synchronized (mLock) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " + (mIsLaunching ? "DEFAULT" : "BACKGROUND")); android.os.Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } if (loadWorkspaceFirst) { if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace"); loadAndBindWorkspace(); } else { if (DEBUG_LOADERS) Log.d(TAG, "step 1: special: loading all apps"); loadAndBindAllApps(); } if (mStopped) { break keep_running; } // Whew! Hard work done. Slow us down, and wait until the UI thread has // settled down. synchronized (mLock) { if (mIsLaunching) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND"); android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); } } waitForIdle(); // second step if (loadWorkspaceFirst) { if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps"); loadAndBindAllApps(); } else { if (DEBUG_LOADERS) Log.d(TAG, "step 2: special: loading workspace"); loadAndBindWorkspace(); } // Restore the default thread priority after we are done loading items synchronized (mLock) { android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); } } // Update the saved icons if necessary if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons"); synchronized (sBgLock) { for (Object key : sBgDbIconCache.keySet()) { updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key)); } sBgDbIconCache.clear(); } // Clear out this reference, otherwise we end up holding it until all of the // callback runnables are done. mContext = null; synchronized (mLock) { // If we are still the last one to be scheduled, remove ourselves. if (mLoaderTask == this) { mLoaderTask = null; } mIsLoaderTaskRunning = false; } } public void stopLocked() { synchronized (LoaderTask.this) { mStopped = true; this.notify(); } } /** * Gets the callbacks object. If we've been stopped, or if the launcher object * has somehow been garbage collected, return null instead. Pass in the Callbacks * object that was around when the deferred message was scheduled, and if there's * a new Callbacks object around then also return null. This will save us from * calling onto it with data that will be ignored. */ Callbacks tryGetCallbacks(Callbacks oldCallbacks) { synchronized (mLock) { if (mStopped) { return null; } if (mCallbacks == null) { return null; } final Callbacks callbacks = mCallbacks.get(); if (callbacks != oldCallbacks) { return null; } if (callbacks == null) { Log.w(TAG, "no mCallbacks"); return null; } return callbacks; } } // check & update map of what's occupied; used to discard overlapping/invalid items private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) { long containerIndex = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { if (occupied.containsKey(LauncherSettings.Favorites.CONTAINER_HOTSEAT)) { if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) [(int) item.screenId][0] != null) { Log.e(TAG, "Error loading shortcut into hotseat " + item + " into position (" + item.screenId + ":" + item.cellX + "," + item.cellY + ") occupied by " + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) [(int) item.screenId][0]); return false; } } else { ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1]; items[(int) item.screenId][0] = item; occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items); return true; } } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { // Skip further checking if it is not the hotseat or workspace container return true; } if (!occupied.containsKey(item.screenId)) { ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1]; occupied.put(item.screenId, items); } ItemInfo[][] screens = occupied.get(item.screenId); // Check if any workspace icons overlap with each other for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { if (screens[x][y] != null) { Log.e(TAG, "Error loading shortcut " + item + " into cell (" + containerIndex + "-" + item.screenId + ":" + x + "," + y + ") occupied by " + screens[x][y]); return false; } } } for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { screens[x][y] = item; } } return true; } private void loadWorkspace() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; final Context context = mContext; final ContentResolver contentResolver = context.getContentResolver(); final PackageManager manager = context.getPackageManager(); final AppWidgetManager widgets = AppWidgetManager.getInstance(context); final boolean isSafeMode = manager.isSafeMode(); // Make sure the default workspace is loaded, if needed boolean loadOldDb = mApp.getLauncherProvider().shouldLoadOldDb(); Uri contentUri = loadOldDb ? LauncherSettings.Favorites.OLD_CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI; mIsUpgradePath = loadOldDb; synchronized (sBgLock) { sBgWorkspaceItems.clear(); sBgAppWidgets.clear(); sBgFolders.clear(); sBgItemsIdMap.clear(); sBgDbIconCache.clear(); sBgWorkspaceScreens.clear(); final ArrayList<Long> itemsToRemove = new ArrayList<Long>(); final Cursor c = contentResolver.query(contentUri, null, null, null, null); // +1 for the hotseat (it can be larger than the workspace) // Load workspace in reverse order to ensure that latest items are loaded first (and // before any earlier duplicates) final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>(); try { final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.INTENT); final int titleIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.TITLE); final int iconTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_TYPE); final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); final int iconPackageIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_PACKAGE); final int iconResourceIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_RESOURCE); final int containerIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.CONTAINER); final int itemTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ITEM_TYPE); final int appWidgetIdIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_ID); final int screenIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SPANY); //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); //final int displayModeIndex = c.getColumnIndexOrThrow( // LauncherSettings.Favorites.DISPLAY_MODE); ShortcutInfo info; String intentDescription; LauncherAppWidgetInfo appWidgetInfo; int container; long id; Intent intent; while (!mStopped && c.moveToNext()) { try { int itemType = c.getInt(itemTypeIndex); switch (itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: intentDescription = c.getString(intentIndex); try { intent = Intent.parseUri(intentDescription, 0); } catch (URISyntaxException e) { continue; } if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info = getShortcutInfo(manager, intent, context, c, iconIndex, titleIndex, mLabelCache); } else { info = getShortcutInfo(c, context, iconTypeIndex, iconPackageIndex, iconResourceIndex, iconIndex, titleIndex); // App shortcuts that used to be automatically added to Launcher // didn't always have the correct intent flags set, so do that // here if (intent.getAction() != null && intent.getCategories() != null && intent.getAction().equals(Intent.ACTION_MAIN) && intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) { intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); } } if (info != null) { info.intent = intent; info.id = c.getLong(idIndex); container = c.getInt(containerIndex); info.container = container; info.screenId = c.getInt(screenIndex); info.cellX = c.getInt(cellXIndex); info.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, info)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sBgWorkspaceItems.add(info); break; default: // Item is in a user folder FolderInfo folderInfo = findOrMakeFolder(sBgFolders, container); folderInfo.add(info); break; } if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT && loadOldDb) { info.screenId = permuteScreens(info.screenId); } sBgItemsIdMap.put(info.id, info); // now that we've loaded everthing re-save it with the // icon in case it disappears somehow. queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex); } else { // Failed to load the shortcut, probably because the // activity manager couldn't resolve it (maybe the app // was uninstalled), or the db row was somehow screwed up. // Delete it. id = c.getLong(idIndex); Log.e(TAG, "Error loading shortcut " + id + ", removing it"); contentResolver.delete(LauncherSettings.Favorites.getContentUri( id, false), null, null); } break; case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: id = c.getLong(idIndex); FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id); folderInfo.title = c.getString(titleIndex); folderInfo.id = id; container = c.getInt(containerIndex); folderInfo.container = container; folderInfo.screenId = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, folderInfo)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sBgWorkspaceItems.add(folderInfo); break; } if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT && loadOldDb) { folderInfo.screenId = permuteScreens(folderInfo.screenId); } sBgItemsIdMap.put(folderInfo.id, folderInfo); sBgFolders.put(folderInfo.id, folderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: // Read all Launcher-specific widget details int appWidgetId = c.getInt(appWidgetIdIndex); id = c.getLong(idIndex); final AppWidgetProviderInfo provider = widgets.getAppWidgetInfo(appWidgetId); if (!isSafeMode && (provider == null || provider.provider == null || provider.provider.getPackageName() == null)) { String log = "Deleting widget that isn't installed anymore: id=" + id + " appWidgetId=" + appWidgetId; Log.e(TAG, log); Launcher.sDumpLogs.add(log); itemsToRemove.add(id); } else { appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId, provider.provider); appWidgetInfo.id = id; appWidgetInfo.screenId = c.getInt(screenIndex); appWidgetInfo.cellX = c.getInt(cellXIndex); appWidgetInfo.cellY = c.getInt(cellYIndex); appWidgetInfo.spanX = c.getInt(spanXIndex); appWidgetInfo.spanY = c.getInt(spanYIndex); int[] minSpan = Launcher.getMinSpanForWidget(context, provider); appWidgetInfo.minSpanX = minSpan[0]; appWidgetInfo.minSpanY = minSpan[1]; container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP && container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) { Log.e(TAG, "Widget found where container != " + "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!"); continue; } if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT && loadOldDb) { appWidgetInfo.screenId = permuteScreens(appWidgetInfo.screenId); } appWidgetInfo.container = c.getInt(containerIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, appWidgetInfo)) { break; } sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo); sBgAppWidgets.add(appWidgetInfo); } break; } } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { c.close(); } if (itemsToRemove.size() > 0) { ContentProviderClient client = contentResolver.acquireContentProviderClient( LauncherSettings.Favorites.CONTENT_URI); // Remove dead items for (long id : itemsToRemove) { if (DEBUG_LOADERS) { Log.d(TAG, "Removed id = " + id); } // Don't notify content observers try { client.delete(LauncherSettings.Favorites.getContentUri(id, false), null, null); } catch (RemoteException e) { Log.w(TAG, "Could not remove id = " + id); } } } if (loadOldDb) { long maxScreenId = 0; // If we're importing we use the old screen order. for (ItemInfo item: sBgItemsIdMap.values()) { long screenId = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && !sBgWorkspaceScreens.contains(screenId)) { sBgWorkspaceScreens.add(screenId); if (screenId > maxScreenId) { maxScreenId = screenId; } } } Collections.sort(sBgWorkspaceScreens); mApp.getLauncherProvider().updateMaxScreenId(maxScreenId); updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); } else { Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI; final Cursor sc = contentResolver.query(screensUri, null, null, null, null); TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>(); try { final int idIndex = sc.getColumnIndexOrThrow( LauncherSettings.WorkspaceScreens._ID); final int rankIndex = sc.getColumnIndexOrThrow( LauncherSettings.WorkspaceScreens.SCREEN_RANK); while (sc.moveToNext()) { try { long screenId = sc.getLong(idIndex); int rank = sc.getInt(rankIndex); orderedScreens.put(rank, screenId); } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { sc.close(); } Iterator<Integer> iter = orderedScreens.keySet().iterator(); while (iter.hasNext()) { sBgWorkspaceScreens.add(orderedScreens.get(iter.next())); } // Remove any empty screens ArrayList<Long> unusedScreens = new ArrayList<Long>(); unusedScreens.addAll(sBgWorkspaceScreens); for (ItemInfo item: sBgItemsIdMap.values()) { long screenId = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && unusedScreens.contains(screenId)) { unusedScreens.remove(screenId); } } // If there are any empty screens remove them, and update. if (unusedScreens.size() != 0) { sBgWorkspaceScreens.removeAll(unusedScreens); updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); } } if (DEBUG_LOADERS) { Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); Log.d(TAG, "workspace layout: "); - Iterator<Long> iter = occupied.keySet().iterator(); int nScreens = occupied.size(); for (int y = 0; y < mCellCountY; y++) { String line = ""; + Iterator<Long> iter = occupied.keySet().iterator(); for (int s = 0; s < nScreens; s++) { long screenId = iter.next(); if (s > 0) { line += " | "; } for (int x = 0; x < mCellCountX; x++) { line += ((occupied.get(screenId)[x][y] != null) ? "#" : "."); } } Log.d(TAG, "[ " + line + " ]"); } } } } // We rearrange the screens from the old launcher // 12345 -> 34512 private long permuteScreens(long screen) { if (screen >= 2) { return screen - 2; } else { return screen + 3; } } /** Filters the set of items who are directly or indirectly (via another container) on the * specified screen. */ private void filterCurrentWorkspaceItems(int currentScreen, ArrayList<ItemInfo> allWorkspaceItems, ArrayList<ItemInfo> currentScreenItems, ArrayList<ItemInfo> otherScreenItems) { // Purge any null ItemInfos Iterator<ItemInfo> iter = allWorkspaceItems.iterator(); while (iter.hasNext()) { ItemInfo i = iter.next(); if (i == null) { iter.remove(); } } // If we aren't filtering on a screen, then the set of items to load is the full set of // items given. if (currentScreen < 0) { currentScreenItems.addAll(allWorkspaceItems); } // Order the set of items by their containers first, this allows use to walk through the // list sequentially, build up a list of containers that are in the specified screen, // as well as all items in those containers. Set<Long> itemsOnScreen = new HashSet<Long>(); Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() { @Override public int compare(ItemInfo lhs, ItemInfo rhs) { return (int) (lhs.container - rhs.container); } }); for (ItemInfo info : allWorkspaceItems) { if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { if (info.screenId == currentScreen) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { otherScreenItems.add(info); } } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { if (itemsOnScreen.contains(info.container)) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { otherScreenItems.add(info); } } } } /** Filters the set of widgets which are on the specified screen. */ private void filterCurrentAppWidgets(int currentScreen, ArrayList<LauncherAppWidgetInfo> appWidgets, ArrayList<LauncherAppWidgetInfo> currentScreenWidgets, ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) { // If we aren't filtering on a screen, then the set of items to load is the full set of // widgets given. if (currentScreen < 0) { currentScreenWidgets.addAll(appWidgets); } for (LauncherAppWidgetInfo widget : appWidgets) { if (widget == null) continue; if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && widget.screenId == currentScreen) { currentScreenWidgets.add(widget); } else { otherScreenWidgets.add(widget); } } } /** Filters the set of folders which are on the specified screen. */ private void filterCurrentFolders(int currentScreen, HashMap<Long, ItemInfo> itemsIdMap, HashMap<Long, FolderInfo> folders, HashMap<Long, FolderInfo> currentScreenFolders, HashMap<Long, FolderInfo> otherScreenFolders) { // If we aren't filtering on a screen, then the set of items to load is the full set of // widgets given. if (currentScreen < 0) { currentScreenFolders.putAll(folders); } for (long id : folders.keySet()) { ItemInfo info = itemsIdMap.get(id); FolderInfo folder = folders.get(id); if (info == null || folder == null) continue; if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && info.screenId == currentScreen) { currentScreenFolders.put(id, folder); } else { otherScreenFolders.put(id, folder); } } } /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to * right) */ private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) { // XXX: review this Collections.sort(workspaceItems, new Comparator<ItemInfo>() { @Override public int compare(ItemInfo lhs, ItemInfo rhs) { int cellCountX = LauncherModel.getCellCountX(); int cellCountY = LauncherModel.getCellCountY(); int screenOffset = cellCountX * cellCountY; int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset + lhs.cellY * cellCountX + lhs.cellX); long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset + rhs.cellY * cellCountX + rhs.cellX); return (int) (lr - rr); } }); } private void bindWorkspaceScreens(final Callbacks oldCallbacks, final ArrayList<Long> orderedScreens) { final Runnable r = new Runnable() { @Override public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindScreens(orderedScreens); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } private void bindWorkspaceItems(final Callbacks oldCallbacks, final ArrayList<ItemInfo> workspaceItems, final ArrayList<LauncherAppWidgetInfo> appWidgets, final HashMap<Long, FolderInfo> folders, ArrayList<Runnable> deferredBindRunnables) { final boolean postOnMainThread = (deferredBindRunnables != null); // Bind the workspace items int N = workspaceItems.size(); for (int i = 0; i < N; i += ITEMS_CHUNK) { final int start = i; final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); final Runnable r = new Runnable() { @Override public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindItems(workspaceItems, start, start+chunkSize); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } // Bind the folders if (!folders.isEmpty()) { final Runnable r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindFolders(folders); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } // Bind the widgets, one at a time N = appWidgets.size(); for (int i = 0; i < N; i++) { final LauncherAppWidgetInfo widget = appWidgets.get(i); final Runnable r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } } /** * Binds all loaded data to actual views on the main thread. */ private void bindWorkspace(int synchronizeBindPage) { final long t = SystemClock.uptimeMillis(); Runnable r; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher"); return; } final boolean isLoadingSynchronously = (synchronizeBindPage > -1); final int currentScreen = isLoadingSynchronously ? synchronizeBindPage : oldCallbacks.getCurrentWorkspaceScreen(); // Load all the items that are on the current page first (and in the process, unbind // all the existing workspace items before we call startBinding() below. unbindWorkspaceItemsOnMainThread(); ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>(); ArrayList<LauncherAppWidgetInfo> appWidgets = new ArrayList<LauncherAppWidgetInfo>(); HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>(); HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>(); ArrayList<Long> orderedScreenIds = new ArrayList<Long>(); synchronized (sBgLock) { workspaceItems.addAll(sBgWorkspaceItems); appWidgets.addAll(sBgAppWidgets); folders.putAll(sBgFolders); itemsIdMap.putAll(sBgItemsIdMap); orderedScreenIds.addAll(sBgWorkspaceScreens); } ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>(); ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>(); ArrayList<LauncherAppWidgetInfo> currentAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); ArrayList<LauncherAppWidgetInfo> otherAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>(); HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>(); // Separate the items that are on the current screen, and all the other remaining items filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems, otherWorkspaceItems); filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets, otherAppWidgets); filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders, otherFolders); sortWorkspaceItemsSpatially(currentWorkspaceItems); sortWorkspaceItemsSpatially(otherWorkspaceItems); // Tell the workspace that we're about to start binding items r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.startBinding(); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); bindWorkspaceScreens(oldCallbacks, orderedScreenIds); // Load items on the current page bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets, currentFolders, null); if (isLoadingSynchronously) { r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.onPageBoundSynchronously(currentScreen); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } // Load all the remaining pages (if we are loading synchronously, we want to defer this // work until after the first render) mDeferredBindRunnables.clear(); bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders, (isLoadingSynchronously ? mDeferredBindRunnables : null)); // Tell the workspace that we're done binding items r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.finishBindingItems(mIsUpgradePath); } // If we're profiling, ensure this is the last thing in the queue. if (DEBUG_LOADERS) { Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } mIsLoadingAndBindingWorkspace = false; } }; if (isLoadingSynchronously) { mDeferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } private void loadAndBindAllApps() { if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded); } if (!mAllAppsLoaded) { loadAllAppsByBatch(); synchronized (LoaderTask.this) { if (mStopped) { return; } mAllAppsLoaded = true; } } else { onlyBindAllApps(); } } private void onlyBindAllApps() { final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)"); return; } // shallow copy @SuppressWarnings("unchecked") final ArrayList<ApplicationInfo> list = (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone(); Runnable r = new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); final Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAllApplications(list); } if (DEBUG_LOADERS) { Log.d(TAG, "bound all " + list.size() + " apps from cache in " + (SystemClock.uptimeMillis()-t) + "ms"); } } }; boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid()); if (oldCallbacks.isAllAppsVisible() && isRunningOnMainThread) { r.run(); } else { mHandler.post(r); } } private void loadAllAppsByBatch() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (loadAllAppsByBatch)"); return; } final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); final PackageManager packageManager = mContext.getPackageManager(); List<ResolveInfo> apps = null; int N = Integer.MAX_VALUE; int startIndex; int i=0; int batchSize = -1; while (i < N && !mStopped) { if (i == 0) { mBgAllAppsList.clear(); final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; apps = packageManager.queryIntentActivities(mainIntent, 0); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); } if (apps == null) { return; } N = apps.size(); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities got " + N + " apps"); } if (N == 0) { // There are no apps?!? return; } if (mBatchSize == 0) { batchSize = N; } else { batchSize = mBatchSize; } final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; Collections.sort(apps, new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache)); if (DEBUG_LOADERS) { Log.d(TAG, "sort took " + (SystemClock.uptimeMillis()-sortTime) + "ms"); } } final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; startIndex = i; for (int j=0; i<N && j<batchSize; j++) { // This builds the icon bitmaps. mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i), mIconCache, mLabelCache)); i++; } final boolean first = i <= batchSize; final Callbacks callbacks = tryGetCallbacks(oldCallbacks); final ArrayList<ApplicationInfo> added = mBgAllAppsList.added; mBgAllAppsList.added = new ArrayList<ApplicationInfo>(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); if (callbacks != null) { if (first) { callbacks.bindAllApplications(added); } else { callbacks.bindAppsAdded(added); } if (DEBUG_LOADERS) { Log.d(TAG, "bound " + added.size() + " apps in " + (SystemClock.uptimeMillis() - t) + "ms"); } } else { Log.i(TAG, "not binding apps: no Launcher activity"); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in " + (SystemClock.uptimeMillis()-t2) + "ms"); } if (mAllAppsLoadDelay > 0 && i < N) { try { if (DEBUG_LOADERS) { Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms"); } Thread.sleep(mAllAppsLoadDelay); } catch (InterruptedException exc) { } } } if (DEBUG_LOADERS) { Log.d(TAG, "cached all " + N + " apps in " + (SystemClock.uptimeMillis()-t) + "ms" + (mAllAppsLoadDelay > 0 ? " (including delay)" : "")); } } public void dumpState() { synchronized (sBgLock) { Log.d(TAG, "mLoaderTask.mContext=" + mContext); Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching); Log.d(TAG, "mLoaderTask.mStopped=" + mStopped); Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished); Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size()); } } } void enqueuePackageUpdated(PackageUpdatedTask task) { sWorker.post(task); } private class PackageUpdatedTask implements Runnable { int mOp; String[] mPackages; public static final int OP_NONE = 0; public static final int OP_ADD = 1; public static final int OP_UPDATE = 2; public static final int OP_REMOVE = 3; // uninstlled public static final int OP_UNAVAILABLE = 4; // external media unmounted public PackageUpdatedTask(int op, String[] packages) { mOp = op; mPackages = packages; } public void run() { final Context context = mApp.getContext(); final String[] packages = mPackages; final int N = packages.length; switch (mOp) { case OP_ADD: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]); mBgAllAppsList.addPackage(context, packages[i]); } break; case OP_UPDATE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]); mBgAllAppsList.updatePackage(context, packages[i]); LauncherAppState app = LauncherAppState.getInstance(); WidgetPreviewLoader.removeFromDb( app.getWidgetPreviewCacheDb(), packages[i]); } break; case OP_REMOVE: case OP_UNAVAILABLE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]); mBgAllAppsList.removePackage(packages[i]); LauncherAppState app = LauncherAppState.getInstance(); WidgetPreviewLoader.removeFromDb( app.getWidgetPreviewCacheDb(), packages[i]); } break; } ArrayList<ApplicationInfo> added = null; ArrayList<ApplicationInfo> modified = null; final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>(); if (mBgAllAppsList.added.size() > 0) { added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added); mBgAllAppsList.added.clear(); } if (mBgAllAppsList.modified.size() > 0) { modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified); mBgAllAppsList.modified.clear(); } if (mBgAllAppsList.removed.size() > 0) { removedApps.addAll(mBgAllAppsList.removed); mBgAllAppsList.removed.clear(); } final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == null) { Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading."); return; } if (added != null) { final ArrayList<ApplicationInfo> addedFinal = added; mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsAdded(addedFinal); } } }); } if (modified != null) { final ArrayList<ApplicationInfo> modifiedFinal = modified; mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsUpdated(modifiedFinal); } } }); } // If a package has been removed, or an app has been removed as a result of // an update (for example), make the removed callback. if (mOp == OP_REMOVE || !removedApps.isEmpty()) { final boolean permanent = (mOp == OP_REMOVE); final ArrayList<String> removedPackageNames = new ArrayList<String>(Arrays.asList(packages)); mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindComponentsRemoved(removedPackageNames, removedApps, permanent); } } }); } final ArrayList<Object> widgetsAndShortcuts = getSortedWidgetsAndShortcuts(context); mHandler.post(new Runnable() { @Override public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindPackagesUpdated(widgetsAndShortcuts); } } }); } } // Returns a list of ResolveInfos/AppWindowInfos in sorted order public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) { PackageManager packageManager = context.getPackageManager(); final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>(); widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders()); Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT); widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0)); Collections.sort(widgetsAndShortcuts, new LauncherModel.WidgetAndShortcutNameComparator(packageManager)); return widgetsAndShortcuts; } /** * This is called from the code that adds shortcuts from the intent receiver. This * doesn't have a Cursor, but */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) { return getShortcutInfo(manager, intent, context, null, -1, -1, null); } /** * Make an ShortcutInfo object for a shortcut that is an application. * * If c is not null, then it will be used to fill in missing data like the title and icon. */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context, Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); ComponentName componentName = intent.getComponent(); if (componentName == null) { return null; } try { PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0); if (!pi.applicationInfo.enabled) { // If we return null here, the corresponding item will be removed from the launcher // db and will not appear in the workspace. return null; } } catch (NameNotFoundException e) { Log.d(TAG, "getPackInfo failed for package " + componentName.getPackageName()); } // TODO: See if the PackageManager knows about this case. If it doesn't // then return null & delete this. // the resource -- This may implicitly give us back the fallback icon, // but don't worry about that. All we're doing with usingFallbackIcon is // to avoid saving lots of copies of that in the database, and most apps // have icons anyway. // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info // via resolveActivity(). ResolveInfo resolveInfo = null; ComponentName oldComponent = intent.getComponent(); Intent newIntent = new Intent(intent.getAction(), null); newIntent.addCategory(Intent.CATEGORY_LAUNCHER); newIntent.setPackage(oldComponent.getPackageName()); List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0); for (ResolveInfo i : infos) { ComponentName cn = new ComponentName(i.activityInfo.packageName, i.activityInfo.name); if (cn.equals(oldComponent)) { resolveInfo = i; } } if (resolveInfo == null) { resolveInfo = manager.resolveActivity(intent, 0); } if (resolveInfo != null) { icon = mIconCache.getIcon(componentName, resolveInfo, labelCache); } // the db if (icon == null) { if (c != null) { icon = getIconFromCursor(c, iconIndex, context); } } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); // from the resource if (resolveInfo != null) { ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo); if (labelCache != null && labelCache.containsKey(key)) { info.title = labelCache.get(key); } else { info.title = resolveInfo.activityInfo.loadLabel(manager); if (labelCache != null) { labelCache.put(key, info.title); } } } // from the db if (info.title == null) { if (c != null) { info.title = c.getString(titleIndex); } } // fall back to the class name of the activity if (info.title == null) { info.title = componentName.getClassName(); } info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; return info; } /** * Returns the set of workspace ShortcutInfos with the specified intent. */ static ArrayList<ItemInfo> getWorkspaceShortcutItemInfosWithIntent(Intent intent) { ArrayList<ItemInfo> items = new ArrayList<ItemInfo>(); synchronized (sBgLock) { for (ItemInfo info : sBgWorkspaceItems) { if (info instanceof ShortcutInfo) { ShortcutInfo shortcut = (ShortcutInfo) info; if (shortcut.intent.toUri(0).equals(intent.toUri(0))) { items.add(shortcut); } } } } return items; } /** * Make an ShortcutInfo object for a shortcut that isn't an application. */ private ShortcutInfo getShortcutInfo(Cursor c, Context context, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; // TODO: If there's an explicit component and we can't install that, delete it. info.title = c.getString(titleIndex); int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); info.customIcon = false; // the resource try { Resources resources = packageManager.getResourcesForApplication(packageName); if (resources != null) { final int id = resources.getIdentifier(resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } } catch (Exception e) { // drop this. we have other places to look for icons } // the db if (icon == null) { icon = getIconFromCursor(c, iconIndex, context); } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } break; case LauncherSettings.Favorites.ICON_TYPE_BITMAP: icon = getIconFromCursor(c, iconIndex, context); if (icon == null) { icon = getFallbackIcon(); info.customIcon = false; info.usingFallbackIcon = true; } else { info.customIcon = true; } break; default: icon = getFallbackIcon(); info.usingFallbackIcon = true; info.customIcon = false; break; } info.setIcon(icon); return info; } Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) { @SuppressWarnings("all") // suppress dead code warning final boolean debug = false; if (debug) { Log.d(TAG, "getIconFromCursor app=" + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE))); } byte[] data = c.getBlob(iconIndex); try { return Utilities.createIconBitmap( BitmapFactory.decodeByteArray(data, 0, data.length), context); } catch (Exception e) { return null; } } ShortcutInfo addShortcut(Context context, Intent data, long container, int screen, int cellX, int cellY, boolean notify) { final ShortcutInfo info = infoFromShortcutIntent(context, data, null); if (info == null) { return null; } addItemToDatabase(context, info, container, screen, cellX, cellY, notify); return info; } /** * Attempts to find an AppWidgetProviderInfo that matches the given component. */ AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context, ComponentName component) { List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); for (AppWidgetProviderInfo info : widgets) { if (info.provider.equals(component)) { return info; } } return null; } /** * Returns a list of all the widgets that can handle configuration with a particular mimeType. */ List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) { final PackageManager packageManager = context.getPackageManager(); final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities = new ArrayList<WidgetMimeTypeHandlerData>(); final Intent supportsIntent = new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE); supportsIntent.setType(mimeType); // Create a set of widget configuration components that we can test against final List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget = new HashMap<ComponentName, AppWidgetProviderInfo>(); for (AppWidgetProviderInfo info : widgets) { configurationComponentToWidget.put(info.configure, info); } // Run through each of the intents that can handle this type of clip data, and cross // reference them with the components that are actual configuration components final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo info : activities) { final ActivityInfo activityInfo = info.activityInfo; final ComponentName infoComponent = new ComponentName(activityInfo.packageName, activityInfo.name); if (configurationComponentToWidget.containsKey(infoComponent)) { supportedConfigurationActivities.add( new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info, configurationComponentToWidget.get(infoComponent))); } } return supportedConfigurationActivities; } ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) { Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); if (intent == null) { // If the intent is null, we can't construct a valid ShortcutInfo, so we return null Log.e(TAG, "Can't construct ShorcutInfo with null intent"); return null; } Bitmap icon = null; boolean customIcon = false; ShortcutIconResource iconResource = null; if (bitmap != null && bitmap instanceof Bitmap) { icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context); customIcon = true; } else { Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (extra != null && extra instanceof ShortcutIconResource) { try { iconResource = (ShortcutIconResource) extra; final PackageManager packageManager = context.getPackageManager(); Resources resources = packageManager.getResourcesForApplication( iconResource.packageName); final int id = resources.getIdentifier(iconResource.resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } catch (Exception e) { Log.w(TAG, "Could not load shortcut icon: " + extra); } } } final ShortcutInfo info = new ShortcutInfo(); if (icon == null) { if (fallbackIcon != null) { icon = fallbackIcon; } else { icon = getFallbackIcon(); info.usingFallbackIcon = true; } } info.setIcon(icon); info.title = name; info.intent = intent; info.customIcon = customIcon; info.iconResource = iconResource; return info; } boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c, int iconIndex) { // If apps can't be on SD, don't even bother. if (!mAppsCanBeOnExternalStorage) { return false; } // If this icon doesn't have a custom icon, check to see // what's stored in the DB, and if it doesn't match what // we're going to show, store what we are going to show back // into the DB. We do this so when we're loading, if the // package manager can't find an icon (for example because // the app is on SD) then we can use that instead. if (!info.customIcon && !info.usingFallbackIcon) { cache.put(info, c.getBlob(iconIndex)); return true; } return false; } void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) { boolean needSave = false; try { if (data != null) { Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length); Bitmap loaded = info.getIcon(mIconCache); needSave = !saved.sameAs(loaded); } else { needSave = true; } } catch (Exception e) { needSave = true; } if (needSave) { Log.d(TAG, "going to save icon bitmap for info=" + info); // This is slower than is ideal, but this only happens once // or when the app is updated with a new icon. updateItemInDatabase(context, info); } } /** * Return an existing FolderInfo object if we have encountered this ID previously, * or make a new one. */ private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null) { // No placeholder -- create a new instance folderInfo = new FolderInfo(); folders.put(id, folderInfo); } return folderInfo; } public static final Comparator<ApplicationInfo> getAppNameComparator() { final Collator collator = Collator.getInstance(); return new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { int result = collator.compare(a.title.toString(), b.title.toString()); if (result == 0) { result = a.componentName.compareTo(b.componentName); } return result; } }; } public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { if (a.firstInstallTime < b.firstInstallTime) return 1; if (a.firstInstallTime > b.firstInstallTime) return -1; return 0; } }; public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() { final Collator collator = Collator.getInstance(); return new Comparator<AppWidgetProviderInfo>() { public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) { return collator.compare(a.label.toString(), b.label.toString()); } }; } static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) { if (info.activityInfo != null) { return new ComponentName(info.activityInfo.packageName, info.activityInfo.name); } else { return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name); } } public static class ShortcutNameComparator implements Comparator<ResolveInfo> { private Collator mCollator; private PackageManager mPackageManager; private HashMap<Object, CharSequence> mLabelCache; ShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, CharSequence>(); mCollator = Collator.getInstance(); } ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) { mPackageManager = pm; mLabelCache = labelCache; mCollator = Collator.getInstance(); } public final int compare(ResolveInfo a, ResolveInfo b) { CharSequence labelA, labelB; ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a); ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b); if (mLabelCache.containsKey(keyA)) { labelA = mLabelCache.get(keyA); } else { labelA = a.loadLabel(mPackageManager).toString(); mLabelCache.put(keyA, labelA); } if (mLabelCache.containsKey(keyB)) { labelB = mLabelCache.get(keyB); } else { labelB = b.loadLabel(mPackageManager).toString(); mLabelCache.put(keyB, labelB); } return mCollator.compare(labelA, labelB); } }; public static class WidgetAndShortcutNameComparator implements Comparator<Object> { private Collator mCollator; private PackageManager mPackageManager; private HashMap<Object, String> mLabelCache; WidgetAndShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, String>(); mCollator = Collator.getInstance(); } public final int compare(Object a, Object b) { String labelA, labelB; if (mLabelCache.containsKey(a)) { labelA = mLabelCache.get(a); } else { labelA = (a instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) a).label : ((ResolveInfo) a).loadLabel(mPackageManager).toString(); mLabelCache.put(a, labelA); } if (mLabelCache.containsKey(b)) { labelB = mLabelCache.get(b); } else { labelB = (b instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) b).label : ((ResolveInfo) b).loadLabel(mPackageManager).toString(); mLabelCache.put(b, labelB); } return mCollator.compare(labelA, labelB); } }; public void dumpState() { Log.d(TAG, "mCallbacks=" + mCallbacks); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified); if (mLoaderTask != null) { mLoaderTask.dumpState(); } else { Log.d(TAG, "mLoaderTask=null"); } } }
false
true
static boolean shortcutExists(Context context, String title, Intent intent) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { "title", "intent" }, "title=? and intent=?", new String[] { title, intent.toUri(0) }, null); boolean result = false; try { result = c.moveToFirst(); } finally { c.close(); } return result; } /** * Returns an ItemInfo array containing all the items in the LauncherModel. * The ItemInfo.id is not set through this function. */ static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) { ArrayList<ItemInfo> items = new ArrayList<ItemInfo>(); final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER, LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY, LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null); final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY); try { while (c.moveToNext()) { ItemInfo item = new ItemInfo(); item.cellX = c.getInt(cellXIndex); item.cellY = c.getInt(cellYIndex); item.spanX = c.getInt(spanXIndex); item.spanY = c.getInt(spanYIndex); item.container = c.getInt(containerIndex); item.itemType = c.getInt(itemTypeIndex); item.screenId = c.getInt(screenIndex); items.add(item); } } catch (Exception e) { items.clear(); } finally { c.close(); } return items; } /** * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. */ FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, "_id=? and (itemType=? or itemType=?)", new String[] { String.valueOf(id), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null); try { if (c.moveToFirst()) { final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); FolderInfo folderInfo = null; switch (c.getInt(itemTypeIndex)) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: folderInfo = findOrMakeFolder(folderList, id); break; } folderInfo.title = c.getString(titleIndex); folderInfo.id = id; folderInfo.container = c.getInt(containerIndex); folderInfo.screenId = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); return folderInfo; } } finally { c.close(); } return null; } /** * Add an item to the database in a specified container. Sets the container, screen, cellX and * cellY fields of the item. Also assigns an ID to the item. */ static void addItemToDatabase(Context context, final ItemInfo item, final long container, final long screenId, final int cellX, final int cellY, final boolean notify) { item.container = container; item.cellX = cellX; item.cellY = cellY; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screenId < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); } else { item.screenId = screenId; } final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); LauncherAppState app = LauncherAppState.getInstance(); item.id = app.getLauncherProvider().generateNewItemId(); values.put(LauncherSettings.Favorites._ID, item.id); item.updateValuesWithCoordinates(values, item.cellX, item.cellY); Runnable r = new Runnable() { public void run() { String transaction = "DbDebug Add item (" + item.title + ") to db, id: " + item.id + " (" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")"; Launcher.sDumpLogs.add(transaction); Log.d(TAG, transaction); cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { checkItemInfoLocked(item.id, item, null); sBgItemsIdMap.put(item.id, item); switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sBgFolders.put(item.id, (FolderInfo) item); // Fall through case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP || item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { sBgWorkspaceItems.add(item); } else { if (!sBgFolders.containsKey(item.container)) { // Adding an item to a folder that doesn't exist. String msg = "adding item: " + item + " to a folder that " + " doesn't exist"; Log.e(TAG, msg); Launcher.dumpDebugLogsToConsole(); } } break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sBgAppWidgets.add((LauncherAppWidgetInfo) item); break; } } } }; runOnWorkerThread(r); } /** * Creates a new unique child id, for a given cell span across all layouts. */ static int getCellLayoutChildId( long container, long screen, int localCellX, int localCellY, int spanX, int spanY) { return (((int) container & 0xFF) << 24) | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF); } static int getCellCountX() { return mCellCountX; } static int getCellCountY() { return mCellCountY; } /** * Updates the model orientation helper to take into account the current layout dimensions * when performing local/canonical coordinate transformations. */ static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) { mCellCountX = shortAxisCellCount; mCellCountY = longAxisCellCount; } /** * Removes the specified item from the database * @param context * @param item */ static void deleteItemFromDatabase(Context context, final ItemInfo item) { final ContentResolver cr = context.getContentResolver(); final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false); Runnable r = new Runnable() { public void run() { String transaction = "DbDebug Delete item (" + item.title + ") from db, id: " + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY + ")"; Launcher.sDumpLogs.add(transaction); Log.d(TAG, transaction); cr.delete(uriToDelete, null, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sBgFolders.remove(item.id); for (ItemInfo info: sBgItemsIdMap.values()) { if (info.container == item.id) { // We are deleting a folder which still contains items that // think they are contained by that folder. String msg = "deleting a folder (" + item + ") which still " + "contains items (" + info + ")"; Log.e(TAG, msg); Launcher.dumpDebugLogsToConsole(); } } sBgWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: sBgWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sBgAppWidgets.remove((LauncherAppWidgetInfo) item); break; } sBgItemsIdMap.remove(item.id); sBgDbIconCache.remove(item); } } }; runOnWorkerThread(r); } /** * Update the order of the workspace screens in the database. The array list contains * a list of screen ids in the order that they should appear. */ static void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) { final ContentResolver cr = context.getContentResolver(); final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI; // Remove any negative screen ids -- these aren't persisted Iterator<Long> iter = screens.iterator(); while (iter.hasNext()) { long id = iter.next(); if (id < 0) { iter.remove(); } } Runnable r = new Runnable() { @Override public void run() { final ArrayList<Long> screensCopy = new ArrayList<Long>(); // Clear the table cr.delete(uri, null, null); int count = screens.size(); ContentValues[] values = new ContentValues[count]; for (int i = 0; i < count; i++) { ContentValues v = new ContentValues(); long screenId = screens.get(i); v.put(LauncherSettings.WorkspaceScreens._ID, screenId); v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i); screensCopy.add(screenId); values[i] = v; } cr.bulkInsert(uri, values); sBgWorkspaceScreens.clear(); sBgWorkspaceScreens.addAll(screensCopy); } }; runOnWorkerThread(r); } /** * Remove the contents of the specified folder from the database */ static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) { final ContentResolver cr = context.getContentResolver(); Runnable r = new Runnable() { public void run() { cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { sBgItemsIdMap.remove(info.id); sBgFolders.remove(info.id); sBgDbIconCache.remove(info); sBgWorkspaceItems.remove(info); } cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { for (ItemInfo childInfo : info.contents) { sBgItemsIdMap.remove(childInfo.id); sBgDbIconCache.remove(childInfo); } } } }; runOnWorkerThread(r); } /** * Set this as the current Launcher activity object for the loader. */ public void initialize(Callbacks callbacks) { synchronized (mLock) { mCallbacks = new WeakReference<Callbacks>(callbacks); } } /** * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and * ACTION_PACKAGE_CHANGED. */ @Override public void onReceive(Context context, Intent intent) { if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent); final String action = intent.getAction(); if (Intent.ACTION_PACKAGE_CHANGED.equals(action) || Intent.ACTION_PACKAGE_REMOVED.equals(action) || Intent.ACTION_PACKAGE_ADDED.equals(action)) { final String packageName = intent.getData().getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); int op = PackageUpdatedTask.OP_NONE; if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { op = PackageUpdatedTask.OP_UPDATE; } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_REMOVE; } // else, we are replacing the package, so a PACKAGE_ADDED will be sent // later, we will update the package at this time } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_ADD; } else { op = PackageUpdatedTask.OP_UPDATE; } } if (op != PackageUpdatedTask.OP_NONE) { enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName })); } } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) { // First, schedule to add these apps back in. String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages)); // Then, rebind everything. startLoaderFromBackground(); } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask( PackageUpdatedTask.OP_UNAVAILABLE, packages)); } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) { // If we have changed locale we need to clear out the labels in all apps/workspace. forceReload(); } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) { // Check if configuration change was an mcc/mnc change which would affect app resources // and we would need to clear out the labels in all apps/workspace. Same handling as // above for ACTION_LOCALE_CHANGED Configuration currentConfig = context.getResources().getConfiguration(); if (mPreviousConfigMcc != currentConfig.mcc) { Log.d(TAG, "Reload apps on config change. curr_mcc:" + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc); forceReload(); } // Update previousConfig mPreviousConfigMcc = currentConfig.mcc; } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) || SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) { if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { callbacks.bindSearchablesChanged(); } } } } private void forceReload() { resetLoadedState(true, true); // Do this here because if the launcher activity is running it will be restarted. // If it's not running startLoaderFromBackground will merely tell it that it needs // to reload. startLoaderFromBackground(); } public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) { synchronized (mLock) { // Stop any existing loaders first, so they don't set mAllAppsLoaded or // mWorkspaceLoaded to true later stopLoaderLocked(); if (resetAllAppsLoaded) mAllAppsLoaded = false; if (resetWorkspaceLoaded) mWorkspaceLoaded = false; } } /** * When the launcher is in the background, it's possible for it to miss paired * configuration changes. So whenever we trigger the loader from the background * tell the launcher that it needs to re-run the loader when it comes back instead * of doing it now. */ public void startLoaderFromBackground() { boolean runLoader = false; if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { // Only actually run the loader if they're not paused. if (!callbacks.setLoadOnResume()) { runLoader = true; } } } if (runLoader) { startLoader(false, -1); } } // If there is already a loader task running, tell it to stop. // returns true if isLaunching() was true on the old task private boolean stopLoaderLocked() { boolean isLaunching = false; LoaderTask oldTask = mLoaderTask; if (oldTask != null) { if (oldTask.isLaunching()) { isLaunching = true; } oldTask.stopLocked(); } return isLaunching; } public void startLoader(boolean isLaunching, int synchronousBindPage) { synchronized (mLock) { if (DEBUG_LOADERS) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); } // Clear any deferred bind-runnables from the synchronized load process // We must do this before any loading/binding is scheduled below. mDeferredBindRunnables.clear(); // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks != null && mCallbacks.get() != null) { // If there is already one running, tell it to stop. // also, don't downgrade isLaunching if we're already running isLaunching = isLaunching || stopLoaderLocked(); mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching); if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) { mLoaderTask.runBindSynchronousPage(synchronousBindPage); } else { sWorkerThread.setPriority(Thread.NORM_PRIORITY); sWorker.post(mLoaderTask); } } } } void bindRemainingSynchronousPages() { // Post the remaining side pages to be loaded if (!mDeferredBindRunnables.isEmpty()) { for (final Runnable r : mDeferredBindRunnables) { mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE); } mDeferredBindRunnables.clear(); } } public void stopLoader() { synchronized (mLock) { if (mLoaderTask != null) { mLoaderTask.stopLocked(); } } } public boolean isAllAppsLoaded() { return mAllAppsLoaded; } boolean isLoadingWorkspace() { synchronized (mLock) { if (mLoaderTask != null) { return mLoaderTask.isLoadingWorkspace(); } } return false; } /** * Runnable for the thread that loads the contents of the launcher: * - workspace icons * - widgets * - all apps icons */ private class LoaderTask implements Runnable { private Context mContext; private boolean mIsLaunching; private boolean mIsLoadingAndBindingWorkspace; private boolean mStopped; private boolean mLoadAndBindStepFinished; private boolean mIsUpgradePath; private HashMap<Object, CharSequence> mLabelCache; LoaderTask(Context context, boolean isLaunching) { mContext = context; mIsLaunching = isLaunching; mLabelCache = new HashMap<Object, CharSequence>(); } boolean isLaunching() { return mIsLaunching; } boolean isLoadingWorkspace() { return mIsLoadingAndBindingWorkspace; } private void loadAndBindWorkspace() { mIsLoadingAndBindingWorkspace = true; // Load the workspace if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded); } if (!mWorkspaceLoaded) { loadWorkspace(); synchronized (LoaderTask.this) { if (mStopped) { return; } mWorkspaceLoaded = true; } } // Bind the workspace bindWorkspace(-1); } private void waitForIdle() { // Wait until the either we're stopped or the other threads are done. // This way we don't start loading all apps until the workspace has settled // down. synchronized (LoaderTask.this) { final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; mHandler.postIdle(new Runnable() { public void run() { synchronized (LoaderTask.this) { mLoadAndBindStepFinished = true; if (DEBUG_LOADERS) { Log.d(TAG, "done with previous binding step"); } LoaderTask.this.notify(); } } }); while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) { try { // Just in case mFlushingWorkerThread changes but we aren't woken up, // wait no longer than 1sec at a time this.wait(1000); } catch (InterruptedException ex) { // Ignore } } if (DEBUG_LOADERS) { Log.d(TAG, "waited " + (SystemClock.uptimeMillis()-workspaceWaitTime) + "ms for previous step to finish binding"); } } } void runBindSynchronousPage(int synchronousBindPage) { if (synchronousBindPage < 0) { // Ensure that we have a valid page index to load synchronously throw new RuntimeException("Should not call runBindSynchronousPage() without " + "valid page index"); } if (!mAllAppsLoaded || !mWorkspaceLoaded) { // Ensure that we don't try and bind a specified page when the pages have not been // loaded already (we should load everything asynchronously in that case) throw new RuntimeException("Expecting AllApps and Workspace to be loaded"); } synchronized (mLock) { if (mIsLoaderTaskRunning) { // Ensure that we are never running the background loading at this point since // we also touch the background collections throw new RuntimeException("Error! Background loading is already running"); } } // XXX: Throw an exception if we are already loading (since we touch the worker thread // data structures, we can't allow any other thread to touch that data, but because // this call is synchronous, we can get away with not locking). // The LauncherModel is static in the LauncherAppState and mHandler may have queued // operations from the previous activity. We need to ensure that all queued operations // are executed before any synchronous binding work is done. mHandler.flush(); // Divide the set of loaded items into those that we are binding synchronously, and // everything else that is to be bound normally (asynchronously). bindWorkspace(synchronousBindPage); // XXX: For now, continue posting the binding of AllApps as there are other issues that // arise from that. onlyBindAllApps(); } public void run() { synchronized (mLock) { mIsLoaderTaskRunning = true; } // Optimize for end-user experience: if the Launcher is up and // running with the // All Apps interface in the foreground, load All Apps first. Otherwise, load the // workspace first (default). final Callbacks cbk = mCallbacks.get(); final boolean loadWorkspaceFirst = cbk != null ? (!cbk.isAllAppsVisible()) : true; keep_running: { // Elevate priority when Home launches for the first time to avoid // starving at boot time. Staring at a blank home is not cool. synchronized (mLock) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " + (mIsLaunching ? "DEFAULT" : "BACKGROUND")); android.os.Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } if (loadWorkspaceFirst) { if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace"); loadAndBindWorkspace(); } else { if (DEBUG_LOADERS) Log.d(TAG, "step 1: special: loading all apps"); loadAndBindAllApps(); } if (mStopped) { break keep_running; } // Whew! Hard work done. Slow us down, and wait until the UI thread has // settled down. synchronized (mLock) { if (mIsLaunching) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND"); android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); } } waitForIdle(); // second step if (loadWorkspaceFirst) { if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps"); loadAndBindAllApps(); } else { if (DEBUG_LOADERS) Log.d(TAG, "step 2: special: loading workspace"); loadAndBindWorkspace(); } // Restore the default thread priority after we are done loading items synchronized (mLock) { android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); } } // Update the saved icons if necessary if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons"); synchronized (sBgLock) { for (Object key : sBgDbIconCache.keySet()) { updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key)); } sBgDbIconCache.clear(); } // Clear out this reference, otherwise we end up holding it until all of the // callback runnables are done. mContext = null; synchronized (mLock) { // If we are still the last one to be scheduled, remove ourselves. if (mLoaderTask == this) { mLoaderTask = null; } mIsLoaderTaskRunning = false; } } public void stopLocked() { synchronized (LoaderTask.this) { mStopped = true; this.notify(); } } /** * Gets the callbacks object. If we've been stopped, or if the launcher object * has somehow been garbage collected, return null instead. Pass in the Callbacks * object that was around when the deferred message was scheduled, and if there's * a new Callbacks object around then also return null. This will save us from * calling onto it with data that will be ignored. */ Callbacks tryGetCallbacks(Callbacks oldCallbacks) { synchronized (mLock) { if (mStopped) { return null; } if (mCallbacks == null) { return null; } final Callbacks callbacks = mCallbacks.get(); if (callbacks != oldCallbacks) { return null; } if (callbacks == null) { Log.w(TAG, "no mCallbacks"); return null; } return callbacks; } } // check & update map of what's occupied; used to discard overlapping/invalid items private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) { long containerIndex = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { if (occupied.containsKey(LauncherSettings.Favorites.CONTAINER_HOTSEAT)) { if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) [(int) item.screenId][0] != null) { Log.e(TAG, "Error loading shortcut into hotseat " + item + " into position (" + item.screenId + ":" + item.cellX + "," + item.cellY + ") occupied by " + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) [(int) item.screenId][0]); return false; } } else { ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1]; items[(int) item.screenId][0] = item; occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items); return true; } } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { // Skip further checking if it is not the hotseat or workspace container return true; } if (!occupied.containsKey(item.screenId)) { ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1]; occupied.put(item.screenId, items); } ItemInfo[][] screens = occupied.get(item.screenId); // Check if any workspace icons overlap with each other for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { if (screens[x][y] != null) { Log.e(TAG, "Error loading shortcut " + item + " into cell (" + containerIndex + "-" + item.screenId + ":" + x + "," + y + ") occupied by " + screens[x][y]); return false; } } } for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { screens[x][y] = item; } } return true; } private void loadWorkspace() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; final Context context = mContext; final ContentResolver contentResolver = context.getContentResolver(); final PackageManager manager = context.getPackageManager(); final AppWidgetManager widgets = AppWidgetManager.getInstance(context); final boolean isSafeMode = manager.isSafeMode(); // Make sure the default workspace is loaded, if needed boolean loadOldDb = mApp.getLauncherProvider().shouldLoadOldDb(); Uri contentUri = loadOldDb ? LauncherSettings.Favorites.OLD_CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI; mIsUpgradePath = loadOldDb; synchronized (sBgLock) { sBgWorkspaceItems.clear(); sBgAppWidgets.clear(); sBgFolders.clear(); sBgItemsIdMap.clear(); sBgDbIconCache.clear(); sBgWorkspaceScreens.clear(); final ArrayList<Long> itemsToRemove = new ArrayList<Long>(); final Cursor c = contentResolver.query(contentUri, null, null, null, null); // +1 for the hotseat (it can be larger than the workspace) // Load workspace in reverse order to ensure that latest items are loaded first (and // before any earlier duplicates) final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>(); try { final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.INTENT); final int titleIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.TITLE); final int iconTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_TYPE); final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); final int iconPackageIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_PACKAGE); final int iconResourceIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_RESOURCE); final int containerIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.CONTAINER); final int itemTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ITEM_TYPE); final int appWidgetIdIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_ID); final int screenIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SPANY); //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); //final int displayModeIndex = c.getColumnIndexOrThrow( // LauncherSettings.Favorites.DISPLAY_MODE); ShortcutInfo info; String intentDescription; LauncherAppWidgetInfo appWidgetInfo; int container; long id; Intent intent; while (!mStopped && c.moveToNext()) { try { int itemType = c.getInt(itemTypeIndex); switch (itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: intentDescription = c.getString(intentIndex); try { intent = Intent.parseUri(intentDescription, 0); } catch (URISyntaxException e) { continue; } if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info = getShortcutInfo(manager, intent, context, c, iconIndex, titleIndex, mLabelCache); } else { info = getShortcutInfo(c, context, iconTypeIndex, iconPackageIndex, iconResourceIndex, iconIndex, titleIndex); // App shortcuts that used to be automatically added to Launcher // didn't always have the correct intent flags set, so do that // here if (intent.getAction() != null && intent.getCategories() != null && intent.getAction().equals(Intent.ACTION_MAIN) && intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) { intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); } } if (info != null) { info.intent = intent; info.id = c.getLong(idIndex); container = c.getInt(containerIndex); info.container = container; info.screenId = c.getInt(screenIndex); info.cellX = c.getInt(cellXIndex); info.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, info)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sBgWorkspaceItems.add(info); break; default: // Item is in a user folder FolderInfo folderInfo = findOrMakeFolder(sBgFolders, container); folderInfo.add(info); break; } if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT && loadOldDb) { info.screenId = permuteScreens(info.screenId); } sBgItemsIdMap.put(info.id, info); // now that we've loaded everthing re-save it with the // icon in case it disappears somehow. queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex); } else { // Failed to load the shortcut, probably because the // activity manager couldn't resolve it (maybe the app // was uninstalled), or the db row was somehow screwed up. // Delete it. id = c.getLong(idIndex); Log.e(TAG, "Error loading shortcut " + id + ", removing it"); contentResolver.delete(LauncherSettings.Favorites.getContentUri( id, false), null, null); } break; case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: id = c.getLong(idIndex); FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id); folderInfo.title = c.getString(titleIndex); folderInfo.id = id; container = c.getInt(containerIndex); folderInfo.container = container; folderInfo.screenId = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, folderInfo)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sBgWorkspaceItems.add(folderInfo); break; } if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT && loadOldDb) { folderInfo.screenId = permuteScreens(folderInfo.screenId); } sBgItemsIdMap.put(folderInfo.id, folderInfo); sBgFolders.put(folderInfo.id, folderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: // Read all Launcher-specific widget details int appWidgetId = c.getInt(appWidgetIdIndex); id = c.getLong(idIndex); final AppWidgetProviderInfo provider = widgets.getAppWidgetInfo(appWidgetId); if (!isSafeMode && (provider == null || provider.provider == null || provider.provider.getPackageName() == null)) { String log = "Deleting widget that isn't installed anymore: id=" + id + " appWidgetId=" + appWidgetId; Log.e(TAG, log); Launcher.sDumpLogs.add(log); itemsToRemove.add(id); } else { appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId, provider.provider); appWidgetInfo.id = id; appWidgetInfo.screenId = c.getInt(screenIndex); appWidgetInfo.cellX = c.getInt(cellXIndex); appWidgetInfo.cellY = c.getInt(cellYIndex); appWidgetInfo.spanX = c.getInt(spanXIndex); appWidgetInfo.spanY = c.getInt(spanYIndex); int[] minSpan = Launcher.getMinSpanForWidget(context, provider); appWidgetInfo.minSpanX = minSpan[0]; appWidgetInfo.minSpanY = minSpan[1]; container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP && container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) { Log.e(TAG, "Widget found where container != " + "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!"); continue; } if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT && loadOldDb) { appWidgetInfo.screenId = permuteScreens(appWidgetInfo.screenId); } appWidgetInfo.container = c.getInt(containerIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, appWidgetInfo)) { break; } sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo); sBgAppWidgets.add(appWidgetInfo); } break; } } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { c.close(); } if (itemsToRemove.size() > 0) { ContentProviderClient client = contentResolver.acquireContentProviderClient( LauncherSettings.Favorites.CONTENT_URI); // Remove dead items for (long id : itemsToRemove) { if (DEBUG_LOADERS) { Log.d(TAG, "Removed id = " + id); } // Don't notify content observers try { client.delete(LauncherSettings.Favorites.getContentUri(id, false), null, null); } catch (RemoteException e) { Log.w(TAG, "Could not remove id = " + id); } } } if (loadOldDb) { long maxScreenId = 0; // If we're importing we use the old screen order. for (ItemInfo item: sBgItemsIdMap.values()) { long screenId = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && !sBgWorkspaceScreens.contains(screenId)) { sBgWorkspaceScreens.add(screenId); if (screenId > maxScreenId) { maxScreenId = screenId; } } } Collections.sort(sBgWorkspaceScreens); mApp.getLauncherProvider().updateMaxScreenId(maxScreenId); updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); } else { Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI; final Cursor sc = contentResolver.query(screensUri, null, null, null, null); TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>(); try { final int idIndex = sc.getColumnIndexOrThrow( LauncherSettings.WorkspaceScreens._ID); final int rankIndex = sc.getColumnIndexOrThrow( LauncherSettings.WorkspaceScreens.SCREEN_RANK); while (sc.moveToNext()) { try { long screenId = sc.getLong(idIndex); int rank = sc.getInt(rankIndex); orderedScreens.put(rank, screenId); } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { sc.close(); } Iterator<Integer> iter = orderedScreens.keySet().iterator(); while (iter.hasNext()) { sBgWorkspaceScreens.add(orderedScreens.get(iter.next())); } // Remove any empty screens ArrayList<Long> unusedScreens = new ArrayList<Long>(); unusedScreens.addAll(sBgWorkspaceScreens); for (ItemInfo item: sBgItemsIdMap.values()) { long screenId = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && unusedScreens.contains(screenId)) { unusedScreens.remove(screenId); } } // If there are any empty screens remove them, and update. if (unusedScreens.size() != 0) { sBgWorkspaceScreens.removeAll(unusedScreens); updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); } } if (DEBUG_LOADERS) { Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); Log.d(TAG, "workspace layout: "); Iterator<Long> iter = occupied.keySet().iterator(); int nScreens = occupied.size(); for (int y = 0; y < mCellCountY; y++) { String line = ""; for (int s = 0; s < nScreens; s++) { long screenId = iter.next(); if (s > 0) { line += " | "; } for (int x = 0; x < mCellCountX; x++) { line += ((occupied.get(screenId)[x][y] != null) ? "#" : "."); } } Log.d(TAG, "[ " + line + " ]"); } } } } // We rearrange the screens from the old launcher // 12345 -> 34512 private long permuteScreens(long screen) { if (screen >= 2) { return screen - 2; } else { return screen + 3; } } /** Filters the set of items who are directly or indirectly (via another container) on the * specified screen. */ private void filterCurrentWorkspaceItems(int currentScreen, ArrayList<ItemInfo> allWorkspaceItems, ArrayList<ItemInfo> currentScreenItems, ArrayList<ItemInfo> otherScreenItems) { // Purge any null ItemInfos Iterator<ItemInfo> iter = allWorkspaceItems.iterator(); while (iter.hasNext()) { ItemInfo i = iter.next(); if (i == null) { iter.remove(); } } // If we aren't filtering on a screen, then the set of items to load is the full set of // items given. if (currentScreen < 0) { currentScreenItems.addAll(allWorkspaceItems); } // Order the set of items by their containers first, this allows use to walk through the // list sequentially, build up a list of containers that are in the specified screen, // as well as all items in those containers. Set<Long> itemsOnScreen = new HashSet<Long>(); Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() { @Override public int compare(ItemInfo lhs, ItemInfo rhs) { return (int) (lhs.container - rhs.container); } }); for (ItemInfo info : allWorkspaceItems) { if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { if (info.screenId == currentScreen) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { otherScreenItems.add(info); } } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { if (itemsOnScreen.contains(info.container)) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { otherScreenItems.add(info); } } } } /** Filters the set of widgets which are on the specified screen. */ private void filterCurrentAppWidgets(int currentScreen, ArrayList<LauncherAppWidgetInfo> appWidgets, ArrayList<LauncherAppWidgetInfo> currentScreenWidgets, ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) { // If we aren't filtering on a screen, then the set of items to load is the full set of // widgets given. if (currentScreen < 0) { currentScreenWidgets.addAll(appWidgets); } for (LauncherAppWidgetInfo widget : appWidgets) { if (widget == null) continue; if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && widget.screenId == currentScreen) { currentScreenWidgets.add(widget); } else { otherScreenWidgets.add(widget); } } } /** Filters the set of folders which are on the specified screen. */ private void filterCurrentFolders(int currentScreen, HashMap<Long, ItemInfo> itemsIdMap, HashMap<Long, FolderInfo> folders, HashMap<Long, FolderInfo> currentScreenFolders, HashMap<Long, FolderInfo> otherScreenFolders) { // If we aren't filtering on a screen, then the set of items to load is the full set of // widgets given. if (currentScreen < 0) { currentScreenFolders.putAll(folders); } for (long id : folders.keySet()) { ItemInfo info = itemsIdMap.get(id); FolderInfo folder = folders.get(id); if (info == null || folder == null) continue; if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && info.screenId == currentScreen) { currentScreenFolders.put(id, folder); } else { otherScreenFolders.put(id, folder); } } } /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to * right) */ private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) { // XXX: review this Collections.sort(workspaceItems, new Comparator<ItemInfo>() { @Override public int compare(ItemInfo lhs, ItemInfo rhs) { int cellCountX = LauncherModel.getCellCountX(); int cellCountY = LauncherModel.getCellCountY(); int screenOffset = cellCountX * cellCountY; int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset + lhs.cellY * cellCountX + lhs.cellX); long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset + rhs.cellY * cellCountX + rhs.cellX); return (int) (lr - rr); } }); } private void bindWorkspaceScreens(final Callbacks oldCallbacks, final ArrayList<Long> orderedScreens) { final Runnable r = new Runnable() { @Override public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindScreens(orderedScreens); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } private void bindWorkspaceItems(final Callbacks oldCallbacks, final ArrayList<ItemInfo> workspaceItems, final ArrayList<LauncherAppWidgetInfo> appWidgets, final HashMap<Long, FolderInfo> folders, ArrayList<Runnable> deferredBindRunnables) { final boolean postOnMainThread = (deferredBindRunnables != null); // Bind the workspace items int N = workspaceItems.size(); for (int i = 0; i < N; i += ITEMS_CHUNK) { final int start = i; final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); final Runnable r = new Runnable() { @Override public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindItems(workspaceItems, start, start+chunkSize); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } // Bind the folders if (!folders.isEmpty()) { final Runnable r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindFolders(folders); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } // Bind the widgets, one at a time N = appWidgets.size(); for (int i = 0; i < N; i++) { final LauncherAppWidgetInfo widget = appWidgets.get(i); final Runnable r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } } /** * Binds all loaded data to actual views on the main thread. */ private void bindWorkspace(int synchronizeBindPage) { final long t = SystemClock.uptimeMillis(); Runnable r; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher"); return; } final boolean isLoadingSynchronously = (synchronizeBindPage > -1); final int currentScreen = isLoadingSynchronously ? synchronizeBindPage : oldCallbacks.getCurrentWorkspaceScreen(); // Load all the items that are on the current page first (and in the process, unbind // all the existing workspace items before we call startBinding() below. unbindWorkspaceItemsOnMainThread(); ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>(); ArrayList<LauncherAppWidgetInfo> appWidgets = new ArrayList<LauncherAppWidgetInfo>(); HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>(); HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>(); ArrayList<Long> orderedScreenIds = new ArrayList<Long>(); synchronized (sBgLock) { workspaceItems.addAll(sBgWorkspaceItems); appWidgets.addAll(sBgAppWidgets); folders.putAll(sBgFolders); itemsIdMap.putAll(sBgItemsIdMap); orderedScreenIds.addAll(sBgWorkspaceScreens); } ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>(); ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>(); ArrayList<LauncherAppWidgetInfo> currentAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); ArrayList<LauncherAppWidgetInfo> otherAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>(); HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>(); // Separate the items that are on the current screen, and all the other remaining items filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems, otherWorkspaceItems); filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets, otherAppWidgets); filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders, otherFolders); sortWorkspaceItemsSpatially(currentWorkspaceItems); sortWorkspaceItemsSpatially(otherWorkspaceItems); // Tell the workspace that we're about to start binding items r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.startBinding(); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); bindWorkspaceScreens(oldCallbacks, orderedScreenIds); // Load items on the current page bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets, currentFolders, null); if (isLoadingSynchronously) { r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.onPageBoundSynchronously(currentScreen); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } // Load all the remaining pages (if we are loading synchronously, we want to defer this // work until after the first render) mDeferredBindRunnables.clear(); bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders, (isLoadingSynchronously ? mDeferredBindRunnables : null)); // Tell the workspace that we're done binding items r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.finishBindingItems(mIsUpgradePath); } // If we're profiling, ensure this is the last thing in the queue. if (DEBUG_LOADERS) { Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } mIsLoadingAndBindingWorkspace = false; } }; if (isLoadingSynchronously) { mDeferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } private void loadAndBindAllApps() { if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded); } if (!mAllAppsLoaded) { loadAllAppsByBatch(); synchronized (LoaderTask.this) { if (mStopped) { return; } mAllAppsLoaded = true; } } else { onlyBindAllApps(); } } private void onlyBindAllApps() { final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)"); return; } // shallow copy @SuppressWarnings("unchecked") final ArrayList<ApplicationInfo> list = (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone(); Runnable r = new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); final Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAllApplications(list); } if (DEBUG_LOADERS) { Log.d(TAG, "bound all " + list.size() + " apps from cache in " + (SystemClock.uptimeMillis()-t) + "ms"); } } }; boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid()); if (oldCallbacks.isAllAppsVisible() && isRunningOnMainThread) { r.run(); } else { mHandler.post(r); } } private void loadAllAppsByBatch() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (loadAllAppsByBatch)"); return; } final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); final PackageManager packageManager = mContext.getPackageManager(); List<ResolveInfo> apps = null; int N = Integer.MAX_VALUE; int startIndex; int i=0; int batchSize = -1; while (i < N && !mStopped) { if (i == 0) { mBgAllAppsList.clear(); final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; apps = packageManager.queryIntentActivities(mainIntent, 0); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); } if (apps == null) { return; } N = apps.size(); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities got " + N + " apps"); } if (N == 0) { // There are no apps?!? return; } if (mBatchSize == 0) { batchSize = N; } else { batchSize = mBatchSize; } final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; Collections.sort(apps, new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache)); if (DEBUG_LOADERS) { Log.d(TAG, "sort took " + (SystemClock.uptimeMillis()-sortTime) + "ms"); } } final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; startIndex = i; for (int j=0; i<N && j<batchSize; j++) { // This builds the icon bitmaps. mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i), mIconCache, mLabelCache)); i++; } final boolean first = i <= batchSize; final Callbacks callbacks = tryGetCallbacks(oldCallbacks); final ArrayList<ApplicationInfo> added = mBgAllAppsList.added; mBgAllAppsList.added = new ArrayList<ApplicationInfo>(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); if (callbacks != null) { if (first) { callbacks.bindAllApplications(added); } else { callbacks.bindAppsAdded(added); } if (DEBUG_LOADERS) { Log.d(TAG, "bound " + added.size() + " apps in " + (SystemClock.uptimeMillis() - t) + "ms"); } } else { Log.i(TAG, "not binding apps: no Launcher activity"); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in " + (SystemClock.uptimeMillis()-t2) + "ms"); } if (mAllAppsLoadDelay > 0 && i < N) { try { if (DEBUG_LOADERS) { Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms"); } Thread.sleep(mAllAppsLoadDelay); } catch (InterruptedException exc) { } } } if (DEBUG_LOADERS) { Log.d(TAG, "cached all " + N + " apps in " + (SystemClock.uptimeMillis()-t) + "ms" + (mAllAppsLoadDelay > 0 ? " (including delay)" : "")); } } public void dumpState() { synchronized (sBgLock) { Log.d(TAG, "mLoaderTask.mContext=" + mContext); Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching); Log.d(TAG, "mLoaderTask.mStopped=" + mStopped); Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished); Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size()); } } } void enqueuePackageUpdated(PackageUpdatedTask task) { sWorker.post(task); } private class PackageUpdatedTask implements Runnable { int mOp; String[] mPackages; public static final int OP_NONE = 0; public static final int OP_ADD = 1; public static final int OP_UPDATE = 2; public static final int OP_REMOVE = 3; // uninstlled public static final int OP_UNAVAILABLE = 4; // external media unmounted public PackageUpdatedTask(int op, String[] packages) { mOp = op; mPackages = packages; } public void run() { final Context context = mApp.getContext(); final String[] packages = mPackages; final int N = packages.length; switch (mOp) { case OP_ADD: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]); mBgAllAppsList.addPackage(context, packages[i]); } break; case OP_UPDATE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]); mBgAllAppsList.updatePackage(context, packages[i]); LauncherAppState app = LauncherAppState.getInstance(); WidgetPreviewLoader.removeFromDb( app.getWidgetPreviewCacheDb(), packages[i]); } break; case OP_REMOVE: case OP_UNAVAILABLE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]); mBgAllAppsList.removePackage(packages[i]); LauncherAppState app = LauncherAppState.getInstance(); WidgetPreviewLoader.removeFromDb( app.getWidgetPreviewCacheDb(), packages[i]); } break; } ArrayList<ApplicationInfo> added = null; ArrayList<ApplicationInfo> modified = null; final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>(); if (mBgAllAppsList.added.size() > 0) { added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added); mBgAllAppsList.added.clear(); } if (mBgAllAppsList.modified.size() > 0) { modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified); mBgAllAppsList.modified.clear(); } if (mBgAllAppsList.removed.size() > 0) { removedApps.addAll(mBgAllAppsList.removed); mBgAllAppsList.removed.clear(); } final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == null) { Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading."); return; } if (added != null) { final ArrayList<ApplicationInfo> addedFinal = added; mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsAdded(addedFinal); } } }); } if (modified != null) { final ArrayList<ApplicationInfo> modifiedFinal = modified; mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsUpdated(modifiedFinal); } } }); } // If a package has been removed, or an app has been removed as a result of // an update (for example), make the removed callback. if (mOp == OP_REMOVE || !removedApps.isEmpty()) { final boolean permanent = (mOp == OP_REMOVE); final ArrayList<String> removedPackageNames = new ArrayList<String>(Arrays.asList(packages)); mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindComponentsRemoved(removedPackageNames, removedApps, permanent); } } }); } final ArrayList<Object> widgetsAndShortcuts = getSortedWidgetsAndShortcuts(context); mHandler.post(new Runnable() { @Override public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindPackagesUpdated(widgetsAndShortcuts); } } }); } } // Returns a list of ResolveInfos/AppWindowInfos in sorted order public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) { PackageManager packageManager = context.getPackageManager(); final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>(); widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders()); Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT); widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0)); Collections.sort(widgetsAndShortcuts, new LauncherModel.WidgetAndShortcutNameComparator(packageManager)); return widgetsAndShortcuts; } /** * This is called from the code that adds shortcuts from the intent receiver. This * doesn't have a Cursor, but */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) { return getShortcutInfo(manager, intent, context, null, -1, -1, null); } /** * Make an ShortcutInfo object for a shortcut that is an application. * * If c is not null, then it will be used to fill in missing data like the title and icon. */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context, Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); ComponentName componentName = intent.getComponent(); if (componentName == null) { return null; } try { PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0); if (!pi.applicationInfo.enabled) { // If we return null here, the corresponding item will be removed from the launcher // db and will not appear in the workspace. return null; } } catch (NameNotFoundException e) { Log.d(TAG, "getPackInfo failed for package " + componentName.getPackageName()); } // TODO: See if the PackageManager knows about this case. If it doesn't // then return null & delete this. // the resource -- This may implicitly give us back the fallback icon, // but don't worry about that. All we're doing with usingFallbackIcon is // to avoid saving lots of copies of that in the database, and most apps // have icons anyway. // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info // via resolveActivity(). ResolveInfo resolveInfo = null; ComponentName oldComponent = intent.getComponent(); Intent newIntent = new Intent(intent.getAction(), null); newIntent.addCategory(Intent.CATEGORY_LAUNCHER); newIntent.setPackage(oldComponent.getPackageName()); List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0); for (ResolveInfo i : infos) { ComponentName cn = new ComponentName(i.activityInfo.packageName, i.activityInfo.name); if (cn.equals(oldComponent)) { resolveInfo = i; } } if (resolveInfo == null) { resolveInfo = manager.resolveActivity(intent, 0); } if (resolveInfo != null) { icon = mIconCache.getIcon(componentName, resolveInfo, labelCache); } // the db if (icon == null) { if (c != null) { icon = getIconFromCursor(c, iconIndex, context); } } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); // from the resource if (resolveInfo != null) { ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo); if (labelCache != null && labelCache.containsKey(key)) { info.title = labelCache.get(key); } else { info.title = resolveInfo.activityInfo.loadLabel(manager); if (labelCache != null) { labelCache.put(key, info.title); } } } // from the db if (info.title == null) { if (c != null) { info.title = c.getString(titleIndex); } } // fall back to the class name of the activity if (info.title == null) { info.title = componentName.getClassName(); } info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; return info; } /** * Returns the set of workspace ShortcutInfos with the specified intent. */ static ArrayList<ItemInfo> getWorkspaceShortcutItemInfosWithIntent(Intent intent) { ArrayList<ItemInfo> items = new ArrayList<ItemInfo>(); synchronized (sBgLock) { for (ItemInfo info : sBgWorkspaceItems) { if (info instanceof ShortcutInfo) { ShortcutInfo shortcut = (ShortcutInfo) info; if (shortcut.intent.toUri(0).equals(intent.toUri(0))) { items.add(shortcut); } } } } return items; } /** * Make an ShortcutInfo object for a shortcut that isn't an application. */ private ShortcutInfo getShortcutInfo(Cursor c, Context context, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; // TODO: If there's an explicit component and we can't install that, delete it. info.title = c.getString(titleIndex); int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); info.customIcon = false; // the resource try { Resources resources = packageManager.getResourcesForApplication(packageName); if (resources != null) { final int id = resources.getIdentifier(resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } } catch (Exception e) { // drop this. we have other places to look for icons } // the db if (icon == null) { icon = getIconFromCursor(c, iconIndex, context); } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } break; case LauncherSettings.Favorites.ICON_TYPE_BITMAP: icon = getIconFromCursor(c, iconIndex, context); if (icon == null) { icon = getFallbackIcon(); info.customIcon = false; info.usingFallbackIcon = true; } else { info.customIcon = true; } break; default: icon = getFallbackIcon(); info.usingFallbackIcon = true; info.customIcon = false; break; } info.setIcon(icon); return info; } Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) { @SuppressWarnings("all") // suppress dead code warning final boolean debug = false; if (debug) { Log.d(TAG, "getIconFromCursor app=" + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE))); } byte[] data = c.getBlob(iconIndex); try { return Utilities.createIconBitmap( BitmapFactory.decodeByteArray(data, 0, data.length), context); } catch (Exception e) { return null; } } ShortcutInfo addShortcut(Context context, Intent data, long container, int screen, int cellX, int cellY, boolean notify) { final ShortcutInfo info = infoFromShortcutIntent(context, data, null); if (info == null) { return null; } addItemToDatabase(context, info, container, screen, cellX, cellY, notify); return info; } /** * Attempts to find an AppWidgetProviderInfo that matches the given component. */ AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context, ComponentName component) { List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); for (AppWidgetProviderInfo info : widgets) { if (info.provider.equals(component)) { return info; } } return null; } /** * Returns a list of all the widgets that can handle configuration with a particular mimeType. */ List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) { final PackageManager packageManager = context.getPackageManager(); final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities = new ArrayList<WidgetMimeTypeHandlerData>(); final Intent supportsIntent = new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE); supportsIntent.setType(mimeType); // Create a set of widget configuration components that we can test against final List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget = new HashMap<ComponentName, AppWidgetProviderInfo>(); for (AppWidgetProviderInfo info : widgets) { configurationComponentToWidget.put(info.configure, info); } // Run through each of the intents that can handle this type of clip data, and cross // reference them with the components that are actual configuration components final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo info : activities) { final ActivityInfo activityInfo = info.activityInfo; final ComponentName infoComponent = new ComponentName(activityInfo.packageName, activityInfo.name); if (configurationComponentToWidget.containsKey(infoComponent)) { supportedConfigurationActivities.add( new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info, configurationComponentToWidget.get(infoComponent))); } } return supportedConfigurationActivities; } ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) { Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); if (intent == null) { // If the intent is null, we can't construct a valid ShortcutInfo, so we return null Log.e(TAG, "Can't construct ShorcutInfo with null intent"); return null; } Bitmap icon = null; boolean customIcon = false; ShortcutIconResource iconResource = null; if (bitmap != null && bitmap instanceof Bitmap) { icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context); customIcon = true; } else { Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (extra != null && extra instanceof ShortcutIconResource) { try { iconResource = (ShortcutIconResource) extra; final PackageManager packageManager = context.getPackageManager(); Resources resources = packageManager.getResourcesForApplication( iconResource.packageName); final int id = resources.getIdentifier(iconResource.resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } catch (Exception e) { Log.w(TAG, "Could not load shortcut icon: " + extra); } } } final ShortcutInfo info = new ShortcutInfo(); if (icon == null) { if (fallbackIcon != null) { icon = fallbackIcon; } else { icon = getFallbackIcon(); info.usingFallbackIcon = true; } } info.setIcon(icon); info.title = name; info.intent = intent; info.customIcon = customIcon; info.iconResource = iconResource; return info; } boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c, int iconIndex) { // If apps can't be on SD, don't even bother. if (!mAppsCanBeOnExternalStorage) { return false; } // If this icon doesn't have a custom icon, check to see // what's stored in the DB, and if it doesn't match what // we're going to show, store what we are going to show back // into the DB. We do this so when we're loading, if the // package manager can't find an icon (for example because // the app is on SD) then we can use that instead. if (!info.customIcon && !info.usingFallbackIcon) { cache.put(info, c.getBlob(iconIndex)); return true; } return false; } void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) { boolean needSave = false; try { if (data != null) { Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length); Bitmap loaded = info.getIcon(mIconCache); needSave = !saved.sameAs(loaded); } else { needSave = true; } } catch (Exception e) { needSave = true; } if (needSave) { Log.d(TAG, "going to save icon bitmap for info=" + info); // This is slower than is ideal, but this only happens once // or when the app is updated with a new icon. updateItemInDatabase(context, info); } } /** * Return an existing FolderInfo object if we have encountered this ID previously, * or make a new one. */ private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null) { // No placeholder -- create a new instance folderInfo = new FolderInfo(); folders.put(id, folderInfo); } return folderInfo; } public static final Comparator<ApplicationInfo> getAppNameComparator() { final Collator collator = Collator.getInstance(); return new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { int result = collator.compare(a.title.toString(), b.title.toString()); if (result == 0) { result = a.componentName.compareTo(b.componentName); } return result; } }; } public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { if (a.firstInstallTime < b.firstInstallTime) return 1; if (a.firstInstallTime > b.firstInstallTime) return -1; return 0; } }; public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() { final Collator collator = Collator.getInstance(); return new Comparator<AppWidgetProviderInfo>() { public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) { return collator.compare(a.label.toString(), b.label.toString()); } }; } static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) { if (info.activityInfo != null) { return new ComponentName(info.activityInfo.packageName, info.activityInfo.name); } else { return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name); } } public static class ShortcutNameComparator implements Comparator<ResolveInfo> { private Collator mCollator; private PackageManager mPackageManager; private HashMap<Object, CharSequence> mLabelCache; ShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, CharSequence>(); mCollator = Collator.getInstance(); } ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) { mPackageManager = pm; mLabelCache = labelCache; mCollator = Collator.getInstance(); } public final int compare(ResolveInfo a, ResolveInfo b) { CharSequence labelA, labelB; ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a); ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b); if (mLabelCache.containsKey(keyA)) { labelA = mLabelCache.get(keyA); } else { labelA = a.loadLabel(mPackageManager).toString(); mLabelCache.put(keyA, labelA); } if (mLabelCache.containsKey(keyB)) { labelB = mLabelCache.get(keyB); } else { labelB = b.loadLabel(mPackageManager).toString(); mLabelCache.put(keyB, labelB); } return mCollator.compare(labelA, labelB); } }; public static class WidgetAndShortcutNameComparator implements Comparator<Object> { private Collator mCollator; private PackageManager mPackageManager; private HashMap<Object, String> mLabelCache; WidgetAndShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, String>(); mCollator = Collator.getInstance(); } public final int compare(Object a, Object b) { String labelA, labelB; if (mLabelCache.containsKey(a)) { labelA = mLabelCache.get(a); } else { labelA = (a instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) a).label : ((ResolveInfo) a).loadLabel(mPackageManager).toString(); mLabelCache.put(a, labelA); } if (mLabelCache.containsKey(b)) { labelB = mLabelCache.get(b); } else { labelB = (b instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) b).label : ((ResolveInfo) b).loadLabel(mPackageManager).toString(); mLabelCache.put(b, labelB); } return mCollator.compare(labelA, labelB); } }; public void dumpState() { Log.d(TAG, "mCallbacks=" + mCallbacks); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified); if (mLoaderTask != null) { mLoaderTask.dumpState(); } else { Log.d(TAG, "mLoaderTask=null"); } } }
static boolean shortcutExists(Context context, String title, Intent intent) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { "title", "intent" }, "title=? and intent=?", new String[] { title, intent.toUri(0) }, null); boolean result = false; try { result = c.moveToFirst(); } finally { c.close(); } return result; } /** * Returns an ItemInfo array containing all the items in the LauncherModel. * The ItemInfo.id is not set through this function. */ static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) { ArrayList<ItemInfo> items = new ArrayList<ItemInfo>(); final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER, LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY, LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null); final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY); try { while (c.moveToNext()) { ItemInfo item = new ItemInfo(); item.cellX = c.getInt(cellXIndex); item.cellY = c.getInt(cellYIndex); item.spanX = c.getInt(spanXIndex); item.spanY = c.getInt(spanYIndex); item.container = c.getInt(containerIndex); item.itemType = c.getInt(itemTypeIndex); item.screenId = c.getInt(screenIndex); items.add(item); } } catch (Exception e) { items.clear(); } finally { c.close(); } return items; } /** * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. */ FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, "_id=? and (itemType=? or itemType=?)", new String[] { String.valueOf(id), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null); try { if (c.moveToFirst()) { final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); FolderInfo folderInfo = null; switch (c.getInt(itemTypeIndex)) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: folderInfo = findOrMakeFolder(folderList, id); break; } folderInfo.title = c.getString(titleIndex); folderInfo.id = id; folderInfo.container = c.getInt(containerIndex); folderInfo.screenId = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); return folderInfo; } } finally { c.close(); } return null; } /** * Add an item to the database in a specified container. Sets the container, screen, cellX and * cellY fields of the item. Also assigns an ID to the item. */ static void addItemToDatabase(Context context, final ItemInfo item, final long container, final long screenId, final int cellX, final int cellY, final boolean notify) { item.container = container; item.cellX = cellX; item.cellY = cellY; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screenId < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); } else { item.screenId = screenId; } final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); LauncherAppState app = LauncherAppState.getInstance(); item.id = app.getLauncherProvider().generateNewItemId(); values.put(LauncherSettings.Favorites._ID, item.id); item.updateValuesWithCoordinates(values, item.cellX, item.cellY); Runnable r = new Runnable() { public void run() { String transaction = "DbDebug Add item (" + item.title + ") to db, id: " + item.id + " (" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")"; Launcher.sDumpLogs.add(transaction); Log.d(TAG, transaction); cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { checkItemInfoLocked(item.id, item, null); sBgItemsIdMap.put(item.id, item); switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sBgFolders.put(item.id, (FolderInfo) item); // Fall through case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP || item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { sBgWorkspaceItems.add(item); } else { if (!sBgFolders.containsKey(item.container)) { // Adding an item to a folder that doesn't exist. String msg = "adding item: " + item + " to a folder that " + " doesn't exist"; Log.e(TAG, msg); Launcher.dumpDebugLogsToConsole(); } } break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sBgAppWidgets.add((LauncherAppWidgetInfo) item); break; } } } }; runOnWorkerThread(r); } /** * Creates a new unique child id, for a given cell span across all layouts. */ static int getCellLayoutChildId( long container, long screen, int localCellX, int localCellY, int spanX, int spanY) { return (((int) container & 0xFF) << 24) | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF); } static int getCellCountX() { return mCellCountX; } static int getCellCountY() { return mCellCountY; } /** * Updates the model orientation helper to take into account the current layout dimensions * when performing local/canonical coordinate transformations. */ static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) { mCellCountX = shortAxisCellCount; mCellCountY = longAxisCellCount; } /** * Removes the specified item from the database * @param context * @param item */ static void deleteItemFromDatabase(Context context, final ItemInfo item) { final ContentResolver cr = context.getContentResolver(); final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false); Runnable r = new Runnable() { public void run() { String transaction = "DbDebug Delete item (" + item.title + ") from db, id: " + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY + ")"; Launcher.sDumpLogs.add(transaction); Log.d(TAG, transaction); cr.delete(uriToDelete, null, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sBgFolders.remove(item.id); for (ItemInfo info: sBgItemsIdMap.values()) { if (info.container == item.id) { // We are deleting a folder which still contains items that // think they are contained by that folder. String msg = "deleting a folder (" + item + ") which still " + "contains items (" + info + ")"; Log.e(TAG, msg); Launcher.dumpDebugLogsToConsole(); } } sBgWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: sBgWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sBgAppWidgets.remove((LauncherAppWidgetInfo) item); break; } sBgItemsIdMap.remove(item.id); sBgDbIconCache.remove(item); } } }; runOnWorkerThread(r); } /** * Update the order of the workspace screens in the database. The array list contains * a list of screen ids in the order that they should appear. */ static void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) { final ContentResolver cr = context.getContentResolver(); final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI; // Remove any negative screen ids -- these aren't persisted Iterator<Long> iter = screens.iterator(); while (iter.hasNext()) { long id = iter.next(); if (id < 0) { iter.remove(); } } Runnable r = new Runnable() { @Override public void run() { final ArrayList<Long> screensCopy = new ArrayList<Long>(); // Clear the table cr.delete(uri, null, null); int count = screens.size(); ContentValues[] values = new ContentValues[count]; for (int i = 0; i < count; i++) { ContentValues v = new ContentValues(); long screenId = screens.get(i); v.put(LauncherSettings.WorkspaceScreens._ID, screenId); v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i); screensCopy.add(screenId); values[i] = v; } cr.bulkInsert(uri, values); sBgWorkspaceScreens.clear(); sBgWorkspaceScreens.addAll(screensCopy); } }; runOnWorkerThread(r); } /** * Remove the contents of the specified folder from the database */ static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) { final ContentResolver cr = context.getContentResolver(); Runnable r = new Runnable() { public void run() { cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { sBgItemsIdMap.remove(info.id); sBgFolders.remove(info.id); sBgDbIconCache.remove(info); sBgWorkspaceItems.remove(info); } cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { for (ItemInfo childInfo : info.contents) { sBgItemsIdMap.remove(childInfo.id); sBgDbIconCache.remove(childInfo); } } } }; runOnWorkerThread(r); } /** * Set this as the current Launcher activity object for the loader. */ public void initialize(Callbacks callbacks) { synchronized (mLock) { mCallbacks = new WeakReference<Callbacks>(callbacks); } } /** * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and * ACTION_PACKAGE_CHANGED. */ @Override public void onReceive(Context context, Intent intent) { if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent); final String action = intent.getAction(); if (Intent.ACTION_PACKAGE_CHANGED.equals(action) || Intent.ACTION_PACKAGE_REMOVED.equals(action) || Intent.ACTION_PACKAGE_ADDED.equals(action)) { final String packageName = intent.getData().getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); int op = PackageUpdatedTask.OP_NONE; if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { op = PackageUpdatedTask.OP_UPDATE; } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_REMOVE; } // else, we are replacing the package, so a PACKAGE_ADDED will be sent // later, we will update the package at this time } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_ADD; } else { op = PackageUpdatedTask.OP_UPDATE; } } if (op != PackageUpdatedTask.OP_NONE) { enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName })); } } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) { // First, schedule to add these apps back in. String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages)); // Then, rebind everything. startLoaderFromBackground(); } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask( PackageUpdatedTask.OP_UNAVAILABLE, packages)); } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) { // If we have changed locale we need to clear out the labels in all apps/workspace. forceReload(); } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) { // Check if configuration change was an mcc/mnc change which would affect app resources // and we would need to clear out the labels in all apps/workspace. Same handling as // above for ACTION_LOCALE_CHANGED Configuration currentConfig = context.getResources().getConfiguration(); if (mPreviousConfigMcc != currentConfig.mcc) { Log.d(TAG, "Reload apps on config change. curr_mcc:" + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc); forceReload(); } // Update previousConfig mPreviousConfigMcc = currentConfig.mcc; } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) || SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) { if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { callbacks.bindSearchablesChanged(); } } } } private void forceReload() { resetLoadedState(true, true); // Do this here because if the launcher activity is running it will be restarted. // If it's not running startLoaderFromBackground will merely tell it that it needs // to reload. startLoaderFromBackground(); } public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) { synchronized (mLock) { // Stop any existing loaders first, so they don't set mAllAppsLoaded or // mWorkspaceLoaded to true later stopLoaderLocked(); if (resetAllAppsLoaded) mAllAppsLoaded = false; if (resetWorkspaceLoaded) mWorkspaceLoaded = false; } } /** * When the launcher is in the background, it's possible for it to miss paired * configuration changes. So whenever we trigger the loader from the background * tell the launcher that it needs to re-run the loader when it comes back instead * of doing it now. */ public void startLoaderFromBackground() { boolean runLoader = false; if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { // Only actually run the loader if they're not paused. if (!callbacks.setLoadOnResume()) { runLoader = true; } } } if (runLoader) { startLoader(false, -1); } } // If there is already a loader task running, tell it to stop. // returns true if isLaunching() was true on the old task private boolean stopLoaderLocked() { boolean isLaunching = false; LoaderTask oldTask = mLoaderTask; if (oldTask != null) { if (oldTask.isLaunching()) { isLaunching = true; } oldTask.stopLocked(); } return isLaunching; } public void startLoader(boolean isLaunching, int synchronousBindPage) { synchronized (mLock) { if (DEBUG_LOADERS) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); } // Clear any deferred bind-runnables from the synchronized load process // We must do this before any loading/binding is scheduled below. mDeferredBindRunnables.clear(); // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks != null && mCallbacks.get() != null) { // If there is already one running, tell it to stop. // also, don't downgrade isLaunching if we're already running isLaunching = isLaunching || stopLoaderLocked(); mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching); if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) { mLoaderTask.runBindSynchronousPage(synchronousBindPage); } else { sWorkerThread.setPriority(Thread.NORM_PRIORITY); sWorker.post(mLoaderTask); } } } } void bindRemainingSynchronousPages() { // Post the remaining side pages to be loaded if (!mDeferredBindRunnables.isEmpty()) { for (final Runnable r : mDeferredBindRunnables) { mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE); } mDeferredBindRunnables.clear(); } } public void stopLoader() { synchronized (mLock) { if (mLoaderTask != null) { mLoaderTask.stopLocked(); } } } public boolean isAllAppsLoaded() { return mAllAppsLoaded; } boolean isLoadingWorkspace() { synchronized (mLock) { if (mLoaderTask != null) { return mLoaderTask.isLoadingWorkspace(); } } return false; } /** * Runnable for the thread that loads the contents of the launcher: * - workspace icons * - widgets * - all apps icons */ private class LoaderTask implements Runnable { private Context mContext; private boolean mIsLaunching; private boolean mIsLoadingAndBindingWorkspace; private boolean mStopped; private boolean mLoadAndBindStepFinished; private boolean mIsUpgradePath; private HashMap<Object, CharSequence> mLabelCache; LoaderTask(Context context, boolean isLaunching) { mContext = context; mIsLaunching = isLaunching; mLabelCache = new HashMap<Object, CharSequence>(); } boolean isLaunching() { return mIsLaunching; } boolean isLoadingWorkspace() { return mIsLoadingAndBindingWorkspace; } private void loadAndBindWorkspace() { mIsLoadingAndBindingWorkspace = true; // Load the workspace if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded); } if (!mWorkspaceLoaded) { loadWorkspace(); synchronized (LoaderTask.this) { if (mStopped) { return; } mWorkspaceLoaded = true; } } // Bind the workspace bindWorkspace(-1); } private void waitForIdle() { // Wait until the either we're stopped or the other threads are done. // This way we don't start loading all apps until the workspace has settled // down. synchronized (LoaderTask.this) { final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; mHandler.postIdle(new Runnable() { public void run() { synchronized (LoaderTask.this) { mLoadAndBindStepFinished = true; if (DEBUG_LOADERS) { Log.d(TAG, "done with previous binding step"); } LoaderTask.this.notify(); } } }); while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) { try { // Just in case mFlushingWorkerThread changes but we aren't woken up, // wait no longer than 1sec at a time this.wait(1000); } catch (InterruptedException ex) { // Ignore } } if (DEBUG_LOADERS) { Log.d(TAG, "waited " + (SystemClock.uptimeMillis()-workspaceWaitTime) + "ms for previous step to finish binding"); } } } void runBindSynchronousPage(int synchronousBindPage) { if (synchronousBindPage < 0) { // Ensure that we have a valid page index to load synchronously throw new RuntimeException("Should not call runBindSynchronousPage() without " + "valid page index"); } if (!mAllAppsLoaded || !mWorkspaceLoaded) { // Ensure that we don't try and bind a specified page when the pages have not been // loaded already (we should load everything asynchronously in that case) throw new RuntimeException("Expecting AllApps and Workspace to be loaded"); } synchronized (mLock) { if (mIsLoaderTaskRunning) { // Ensure that we are never running the background loading at this point since // we also touch the background collections throw new RuntimeException("Error! Background loading is already running"); } } // XXX: Throw an exception if we are already loading (since we touch the worker thread // data structures, we can't allow any other thread to touch that data, but because // this call is synchronous, we can get away with not locking). // The LauncherModel is static in the LauncherAppState and mHandler may have queued // operations from the previous activity. We need to ensure that all queued operations // are executed before any synchronous binding work is done. mHandler.flush(); // Divide the set of loaded items into those that we are binding synchronously, and // everything else that is to be bound normally (asynchronously). bindWorkspace(synchronousBindPage); // XXX: For now, continue posting the binding of AllApps as there are other issues that // arise from that. onlyBindAllApps(); } public void run() { synchronized (mLock) { mIsLoaderTaskRunning = true; } // Optimize for end-user experience: if the Launcher is up and // running with the // All Apps interface in the foreground, load All Apps first. Otherwise, load the // workspace first (default). final Callbacks cbk = mCallbacks.get(); final boolean loadWorkspaceFirst = cbk != null ? (!cbk.isAllAppsVisible()) : true; keep_running: { // Elevate priority when Home launches for the first time to avoid // starving at boot time. Staring at a blank home is not cool. synchronized (mLock) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " + (mIsLaunching ? "DEFAULT" : "BACKGROUND")); android.os.Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } if (loadWorkspaceFirst) { if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace"); loadAndBindWorkspace(); } else { if (DEBUG_LOADERS) Log.d(TAG, "step 1: special: loading all apps"); loadAndBindAllApps(); } if (mStopped) { break keep_running; } // Whew! Hard work done. Slow us down, and wait until the UI thread has // settled down. synchronized (mLock) { if (mIsLaunching) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND"); android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); } } waitForIdle(); // second step if (loadWorkspaceFirst) { if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps"); loadAndBindAllApps(); } else { if (DEBUG_LOADERS) Log.d(TAG, "step 2: special: loading workspace"); loadAndBindWorkspace(); } // Restore the default thread priority after we are done loading items synchronized (mLock) { android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); } } // Update the saved icons if necessary if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons"); synchronized (sBgLock) { for (Object key : sBgDbIconCache.keySet()) { updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key)); } sBgDbIconCache.clear(); } // Clear out this reference, otherwise we end up holding it until all of the // callback runnables are done. mContext = null; synchronized (mLock) { // If we are still the last one to be scheduled, remove ourselves. if (mLoaderTask == this) { mLoaderTask = null; } mIsLoaderTaskRunning = false; } } public void stopLocked() { synchronized (LoaderTask.this) { mStopped = true; this.notify(); } } /** * Gets the callbacks object. If we've been stopped, or if the launcher object * has somehow been garbage collected, return null instead. Pass in the Callbacks * object that was around when the deferred message was scheduled, and if there's * a new Callbacks object around then also return null. This will save us from * calling onto it with data that will be ignored. */ Callbacks tryGetCallbacks(Callbacks oldCallbacks) { synchronized (mLock) { if (mStopped) { return null; } if (mCallbacks == null) { return null; } final Callbacks callbacks = mCallbacks.get(); if (callbacks != oldCallbacks) { return null; } if (callbacks == null) { Log.w(TAG, "no mCallbacks"); return null; } return callbacks; } } // check & update map of what's occupied; used to discard overlapping/invalid items private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) { long containerIndex = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { if (occupied.containsKey(LauncherSettings.Favorites.CONTAINER_HOTSEAT)) { if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) [(int) item.screenId][0] != null) { Log.e(TAG, "Error loading shortcut into hotseat " + item + " into position (" + item.screenId + ":" + item.cellX + "," + item.cellY + ") occupied by " + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) [(int) item.screenId][0]); return false; } } else { ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1]; items[(int) item.screenId][0] = item; occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items); return true; } } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { // Skip further checking if it is not the hotseat or workspace container return true; } if (!occupied.containsKey(item.screenId)) { ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1]; occupied.put(item.screenId, items); } ItemInfo[][] screens = occupied.get(item.screenId); // Check if any workspace icons overlap with each other for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { if (screens[x][y] != null) { Log.e(TAG, "Error loading shortcut " + item + " into cell (" + containerIndex + "-" + item.screenId + ":" + x + "," + y + ") occupied by " + screens[x][y]); return false; } } } for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { screens[x][y] = item; } } return true; } private void loadWorkspace() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; final Context context = mContext; final ContentResolver contentResolver = context.getContentResolver(); final PackageManager manager = context.getPackageManager(); final AppWidgetManager widgets = AppWidgetManager.getInstance(context); final boolean isSafeMode = manager.isSafeMode(); // Make sure the default workspace is loaded, if needed boolean loadOldDb = mApp.getLauncherProvider().shouldLoadOldDb(); Uri contentUri = loadOldDb ? LauncherSettings.Favorites.OLD_CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI; mIsUpgradePath = loadOldDb; synchronized (sBgLock) { sBgWorkspaceItems.clear(); sBgAppWidgets.clear(); sBgFolders.clear(); sBgItemsIdMap.clear(); sBgDbIconCache.clear(); sBgWorkspaceScreens.clear(); final ArrayList<Long> itemsToRemove = new ArrayList<Long>(); final Cursor c = contentResolver.query(contentUri, null, null, null, null); // +1 for the hotseat (it can be larger than the workspace) // Load workspace in reverse order to ensure that latest items are loaded first (and // before any earlier duplicates) final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>(); try { final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.INTENT); final int titleIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.TITLE); final int iconTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_TYPE); final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); final int iconPackageIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_PACKAGE); final int iconResourceIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_RESOURCE); final int containerIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.CONTAINER); final int itemTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ITEM_TYPE); final int appWidgetIdIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_ID); final int screenIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SPANY); //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); //final int displayModeIndex = c.getColumnIndexOrThrow( // LauncherSettings.Favorites.DISPLAY_MODE); ShortcutInfo info; String intentDescription; LauncherAppWidgetInfo appWidgetInfo; int container; long id; Intent intent; while (!mStopped && c.moveToNext()) { try { int itemType = c.getInt(itemTypeIndex); switch (itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: intentDescription = c.getString(intentIndex); try { intent = Intent.parseUri(intentDescription, 0); } catch (URISyntaxException e) { continue; } if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info = getShortcutInfo(manager, intent, context, c, iconIndex, titleIndex, mLabelCache); } else { info = getShortcutInfo(c, context, iconTypeIndex, iconPackageIndex, iconResourceIndex, iconIndex, titleIndex); // App shortcuts that used to be automatically added to Launcher // didn't always have the correct intent flags set, so do that // here if (intent.getAction() != null && intent.getCategories() != null && intent.getAction().equals(Intent.ACTION_MAIN) && intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) { intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); } } if (info != null) { info.intent = intent; info.id = c.getLong(idIndex); container = c.getInt(containerIndex); info.container = container; info.screenId = c.getInt(screenIndex); info.cellX = c.getInt(cellXIndex); info.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, info)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sBgWorkspaceItems.add(info); break; default: // Item is in a user folder FolderInfo folderInfo = findOrMakeFolder(sBgFolders, container); folderInfo.add(info); break; } if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT && loadOldDb) { info.screenId = permuteScreens(info.screenId); } sBgItemsIdMap.put(info.id, info); // now that we've loaded everthing re-save it with the // icon in case it disappears somehow. queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex); } else { // Failed to load the shortcut, probably because the // activity manager couldn't resolve it (maybe the app // was uninstalled), or the db row was somehow screwed up. // Delete it. id = c.getLong(idIndex); Log.e(TAG, "Error loading shortcut " + id + ", removing it"); contentResolver.delete(LauncherSettings.Favorites.getContentUri( id, false), null, null); } break; case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: id = c.getLong(idIndex); FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id); folderInfo.title = c.getString(titleIndex); folderInfo.id = id; container = c.getInt(containerIndex); folderInfo.container = container; folderInfo.screenId = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, folderInfo)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sBgWorkspaceItems.add(folderInfo); break; } if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT && loadOldDb) { folderInfo.screenId = permuteScreens(folderInfo.screenId); } sBgItemsIdMap.put(folderInfo.id, folderInfo); sBgFolders.put(folderInfo.id, folderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: // Read all Launcher-specific widget details int appWidgetId = c.getInt(appWidgetIdIndex); id = c.getLong(idIndex); final AppWidgetProviderInfo provider = widgets.getAppWidgetInfo(appWidgetId); if (!isSafeMode && (provider == null || provider.provider == null || provider.provider.getPackageName() == null)) { String log = "Deleting widget that isn't installed anymore: id=" + id + " appWidgetId=" + appWidgetId; Log.e(TAG, log); Launcher.sDumpLogs.add(log); itemsToRemove.add(id); } else { appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId, provider.provider); appWidgetInfo.id = id; appWidgetInfo.screenId = c.getInt(screenIndex); appWidgetInfo.cellX = c.getInt(cellXIndex); appWidgetInfo.cellY = c.getInt(cellYIndex); appWidgetInfo.spanX = c.getInt(spanXIndex); appWidgetInfo.spanY = c.getInt(spanYIndex); int[] minSpan = Launcher.getMinSpanForWidget(context, provider); appWidgetInfo.minSpanX = minSpan[0]; appWidgetInfo.minSpanY = minSpan[1]; container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP && container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) { Log.e(TAG, "Widget found where container != " + "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!"); continue; } if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT && loadOldDb) { appWidgetInfo.screenId = permuteScreens(appWidgetInfo.screenId); } appWidgetInfo.container = c.getInt(containerIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, appWidgetInfo)) { break; } sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo); sBgAppWidgets.add(appWidgetInfo); } break; } } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { c.close(); } if (itemsToRemove.size() > 0) { ContentProviderClient client = contentResolver.acquireContentProviderClient( LauncherSettings.Favorites.CONTENT_URI); // Remove dead items for (long id : itemsToRemove) { if (DEBUG_LOADERS) { Log.d(TAG, "Removed id = " + id); } // Don't notify content observers try { client.delete(LauncherSettings.Favorites.getContentUri(id, false), null, null); } catch (RemoteException e) { Log.w(TAG, "Could not remove id = " + id); } } } if (loadOldDb) { long maxScreenId = 0; // If we're importing we use the old screen order. for (ItemInfo item: sBgItemsIdMap.values()) { long screenId = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && !sBgWorkspaceScreens.contains(screenId)) { sBgWorkspaceScreens.add(screenId); if (screenId > maxScreenId) { maxScreenId = screenId; } } } Collections.sort(sBgWorkspaceScreens); mApp.getLauncherProvider().updateMaxScreenId(maxScreenId); updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); } else { Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI; final Cursor sc = contentResolver.query(screensUri, null, null, null, null); TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>(); try { final int idIndex = sc.getColumnIndexOrThrow( LauncherSettings.WorkspaceScreens._ID); final int rankIndex = sc.getColumnIndexOrThrow( LauncherSettings.WorkspaceScreens.SCREEN_RANK); while (sc.moveToNext()) { try { long screenId = sc.getLong(idIndex); int rank = sc.getInt(rankIndex); orderedScreens.put(rank, screenId); } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { sc.close(); } Iterator<Integer> iter = orderedScreens.keySet().iterator(); while (iter.hasNext()) { sBgWorkspaceScreens.add(orderedScreens.get(iter.next())); } // Remove any empty screens ArrayList<Long> unusedScreens = new ArrayList<Long>(); unusedScreens.addAll(sBgWorkspaceScreens); for (ItemInfo item: sBgItemsIdMap.values()) { long screenId = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && unusedScreens.contains(screenId)) { unusedScreens.remove(screenId); } } // If there are any empty screens remove them, and update. if (unusedScreens.size() != 0) { sBgWorkspaceScreens.removeAll(unusedScreens); updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); } } if (DEBUG_LOADERS) { Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); Log.d(TAG, "workspace layout: "); int nScreens = occupied.size(); for (int y = 0; y < mCellCountY; y++) { String line = ""; Iterator<Long> iter = occupied.keySet().iterator(); for (int s = 0; s < nScreens; s++) { long screenId = iter.next(); if (s > 0) { line += " | "; } for (int x = 0; x < mCellCountX; x++) { line += ((occupied.get(screenId)[x][y] != null) ? "#" : "."); } } Log.d(TAG, "[ " + line + " ]"); } } } } // We rearrange the screens from the old launcher // 12345 -> 34512 private long permuteScreens(long screen) { if (screen >= 2) { return screen - 2; } else { return screen + 3; } } /** Filters the set of items who are directly or indirectly (via another container) on the * specified screen. */ private void filterCurrentWorkspaceItems(int currentScreen, ArrayList<ItemInfo> allWorkspaceItems, ArrayList<ItemInfo> currentScreenItems, ArrayList<ItemInfo> otherScreenItems) { // Purge any null ItemInfos Iterator<ItemInfo> iter = allWorkspaceItems.iterator(); while (iter.hasNext()) { ItemInfo i = iter.next(); if (i == null) { iter.remove(); } } // If we aren't filtering on a screen, then the set of items to load is the full set of // items given. if (currentScreen < 0) { currentScreenItems.addAll(allWorkspaceItems); } // Order the set of items by their containers first, this allows use to walk through the // list sequentially, build up a list of containers that are in the specified screen, // as well as all items in those containers. Set<Long> itemsOnScreen = new HashSet<Long>(); Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() { @Override public int compare(ItemInfo lhs, ItemInfo rhs) { return (int) (lhs.container - rhs.container); } }); for (ItemInfo info : allWorkspaceItems) { if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { if (info.screenId == currentScreen) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { otherScreenItems.add(info); } } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { if (itemsOnScreen.contains(info.container)) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { otherScreenItems.add(info); } } } } /** Filters the set of widgets which are on the specified screen. */ private void filterCurrentAppWidgets(int currentScreen, ArrayList<LauncherAppWidgetInfo> appWidgets, ArrayList<LauncherAppWidgetInfo> currentScreenWidgets, ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) { // If we aren't filtering on a screen, then the set of items to load is the full set of // widgets given. if (currentScreen < 0) { currentScreenWidgets.addAll(appWidgets); } for (LauncherAppWidgetInfo widget : appWidgets) { if (widget == null) continue; if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && widget.screenId == currentScreen) { currentScreenWidgets.add(widget); } else { otherScreenWidgets.add(widget); } } } /** Filters the set of folders which are on the specified screen. */ private void filterCurrentFolders(int currentScreen, HashMap<Long, ItemInfo> itemsIdMap, HashMap<Long, FolderInfo> folders, HashMap<Long, FolderInfo> currentScreenFolders, HashMap<Long, FolderInfo> otherScreenFolders) { // If we aren't filtering on a screen, then the set of items to load is the full set of // widgets given. if (currentScreen < 0) { currentScreenFolders.putAll(folders); } for (long id : folders.keySet()) { ItemInfo info = itemsIdMap.get(id); FolderInfo folder = folders.get(id); if (info == null || folder == null) continue; if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && info.screenId == currentScreen) { currentScreenFolders.put(id, folder); } else { otherScreenFolders.put(id, folder); } } } /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to * right) */ private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) { // XXX: review this Collections.sort(workspaceItems, new Comparator<ItemInfo>() { @Override public int compare(ItemInfo lhs, ItemInfo rhs) { int cellCountX = LauncherModel.getCellCountX(); int cellCountY = LauncherModel.getCellCountY(); int screenOffset = cellCountX * cellCountY; int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset + lhs.cellY * cellCountX + lhs.cellX); long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset + rhs.cellY * cellCountX + rhs.cellX); return (int) (lr - rr); } }); } private void bindWorkspaceScreens(final Callbacks oldCallbacks, final ArrayList<Long> orderedScreens) { final Runnable r = new Runnable() { @Override public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindScreens(orderedScreens); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } private void bindWorkspaceItems(final Callbacks oldCallbacks, final ArrayList<ItemInfo> workspaceItems, final ArrayList<LauncherAppWidgetInfo> appWidgets, final HashMap<Long, FolderInfo> folders, ArrayList<Runnable> deferredBindRunnables) { final boolean postOnMainThread = (deferredBindRunnables != null); // Bind the workspace items int N = workspaceItems.size(); for (int i = 0; i < N; i += ITEMS_CHUNK) { final int start = i; final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); final Runnable r = new Runnable() { @Override public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindItems(workspaceItems, start, start+chunkSize); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } // Bind the folders if (!folders.isEmpty()) { final Runnable r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindFolders(folders); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } // Bind the widgets, one at a time N = appWidgets.size(); for (int i = 0; i < N; i++) { final LauncherAppWidgetInfo widget = appWidgets.get(i); final Runnable r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } } /** * Binds all loaded data to actual views on the main thread. */ private void bindWorkspace(int synchronizeBindPage) { final long t = SystemClock.uptimeMillis(); Runnable r; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher"); return; } final boolean isLoadingSynchronously = (synchronizeBindPage > -1); final int currentScreen = isLoadingSynchronously ? synchronizeBindPage : oldCallbacks.getCurrentWorkspaceScreen(); // Load all the items that are on the current page first (and in the process, unbind // all the existing workspace items before we call startBinding() below. unbindWorkspaceItemsOnMainThread(); ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>(); ArrayList<LauncherAppWidgetInfo> appWidgets = new ArrayList<LauncherAppWidgetInfo>(); HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>(); HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>(); ArrayList<Long> orderedScreenIds = new ArrayList<Long>(); synchronized (sBgLock) { workspaceItems.addAll(sBgWorkspaceItems); appWidgets.addAll(sBgAppWidgets); folders.putAll(sBgFolders); itemsIdMap.putAll(sBgItemsIdMap); orderedScreenIds.addAll(sBgWorkspaceScreens); } ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>(); ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>(); ArrayList<LauncherAppWidgetInfo> currentAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); ArrayList<LauncherAppWidgetInfo> otherAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>(); HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>(); // Separate the items that are on the current screen, and all the other remaining items filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems, otherWorkspaceItems); filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets, otherAppWidgets); filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders, otherFolders); sortWorkspaceItemsSpatially(currentWorkspaceItems); sortWorkspaceItemsSpatially(otherWorkspaceItems); // Tell the workspace that we're about to start binding items r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.startBinding(); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); bindWorkspaceScreens(oldCallbacks, orderedScreenIds); // Load items on the current page bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets, currentFolders, null); if (isLoadingSynchronously) { r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.onPageBoundSynchronously(currentScreen); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } // Load all the remaining pages (if we are loading synchronously, we want to defer this // work until after the first render) mDeferredBindRunnables.clear(); bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders, (isLoadingSynchronously ? mDeferredBindRunnables : null)); // Tell the workspace that we're done binding items r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.finishBindingItems(mIsUpgradePath); } // If we're profiling, ensure this is the last thing in the queue. if (DEBUG_LOADERS) { Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } mIsLoadingAndBindingWorkspace = false; } }; if (isLoadingSynchronously) { mDeferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } private void loadAndBindAllApps() { if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded); } if (!mAllAppsLoaded) { loadAllAppsByBatch(); synchronized (LoaderTask.this) { if (mStopped) { return; } mAllAppsLoaded = true; } } else { onlyBindAllApps(); } } private void onlyBindAllApps() { final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)"); return; } // shallow copy @SuppressWarnings("unchecked") final ArrayList<ApplicationInfo> list = (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone(); Runnable r = new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); final Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAllApplications(list); } if (DEBUG_LOADERS) { Log.d(TAG, "bound all " + list.size() + " apps from cache in " + (SystemClock.uptimeMillis()-t) + "ms"); } } }; boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid()); if (oldCallbacks.isAllAppsVisible() && isRunningOnMainThread) { r.run(); } else { mHandler.post(r); } } private void loadAllAppsByBatch() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (loadAllAppsByBatch)"); return; } final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); final PackageManager packageManager = mContext.getPackageManager(); List<ResolveInfo> apps = null; int N = Integer.MAX_VALUE; int startIndex; int i=0; int batchSize = -1; while (i < N && !mStopped) { if (i == 0) { mBgAllAppsList.clear(); final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; apps = packageManager.queryIntentActivities(mainIntent, 0); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); } if (apps == null) { return; } N = apps.size(); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities got " + N + " apps"); } if (N == 0) { // There are no apps?!? return; } if (mBatchSize == 0) { batchSize = N; } else { batchSize = mBatchSize; } final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; Collections.sort(apps, new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache)); if (DEBUG_LOADERS) { Log.d(TAG, "sort took " + (SystemClock.uptimeMillis()-sortTime) + "ms"); } } final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; startIndex = i; for (int j=0; i<N && j<batchSize; j++) { // This builds the icon bitmaps. mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i), mIconCache, mLabelCache)); i++; } final boolean first = i <= batchSize; final Callbacks callbacks = tryGetCallbacks(oldCallbacks); final ArrayList<ApplicationInfo> added = mBgAllAppsList.added; mBgAllAppsList.added = new ArrayList<ApplicationInfo>(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); if (callbacks != null) { if (first) { callbacks.bindAllApplications(added); } else { callbacks.bindAppsAdded(added); } if (DEBUG_LOADERS) { Log.d(TAG, "bound " + added.size() + " apps in " + (SystemClock.uptimeMillis() - t) + "ms"); } } else { Log.i(TAG, "not binding apps: no Launcher activity"); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in " + (SystemClock.uptimeMillis()-t2) + "ms"); } if (mAllAppsLoadDelay > 0 && i < N) { try { if (DEBUG_LOADERS) { Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms"); } Thread.sleep(mAllAppsLoadDelay); } catch (InterruptedException exc) { } } } if (DEBUG_LOADERS) { Log.d(TAG, "cached all " + N + " apps in " + (SystemClock.uptimeMillis()-t) + "ms" + (mAllAppsLoadDelay > 0 ? " (including delay)" : "")); } } public void dumpState() { synchronized (sBgLock) { Log.d(TAG, "mLoaderTask.mContext=" + mContext); Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching); Log.d(TAG, "mLoaderTask.mStopped=" + mStopped); Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished); Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size()); } } } void enqueuePackageUpdated(PackageUpdatedTask task) { sWorker.post(task); } private class PackageUpdatedTask implements Runnable { int mOp; String[] mPackages; public static final int OP_NONE = 0; public static final int OP_ADD = 1; public static final int OP_UPDATE = 2; public static final int OP_REMOVE = 3; // uninstlled public static final int OP_UNAVAILABLE = 4; // external media unmounted public PackageUpdatedTask(int op, String[] packages) { mOp = op; mPackages = packages; } public void run() { final Context context = mApp.getContext(); final String[] packages = mPackages; final int N = packages.length; switch (mOp) { case OP_ADD: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]); mBgAllAppsList.addPackage(context, packages[i]); } break; case OP_UPDATE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]); mBgAllAppsList.updatePackage(context, packages[i]); LauncherAppState app = LauncherAppState.getInstance(); WidgetPreviewLoader.removeFromDb( app.getWidgetPreviewCacheDb(), packages[i]); } break; case OP_REMOVE: case OP_UNAVAILABLE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]); mBgAllAppsList.removePackage(packages[i]); LauncherAppState app = LauncherAppState.getInstance(); WidgetPreviewLoader.removeFromDb( app.getWidgetPreviewCacheDb(), packages[i]); } break; } ArrayList<ApplicationInfo> added = null; ArrayList<ApplicationInfo> modified = null; final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>(); if (mBgAllAppsList.added.size() > 0) { added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added); mBgAllAppsList.added.clear(); } if (mBgAllAppsList.modified.size() > 0) { modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified); mBgAllAppsList.modified.clear(); } if (mBgAllAppsList.removed.size() > 0) { removedApps.addAll(mBgAllAppsList.removed); mBgAllAppsList.removed.clear(); } final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == null) { Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading."); return; } if (added != null) { final ArrayList<ApplicationInfo> addedFinal = added; mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsAdded(addedFinal); } } }); } if (modified != null) { final ArrayList<ApplicationInfo> modifiedFinal = modified; mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsUpdated(modifiedFinal); } } }); } // If a package has been removed, or an app has been removed as a result of // an update (for example), make the removed callback. if (mOp == OP_REMOVE || !removedApps.isEmpty()) { final boolean permanent = (mOp == OP_REMOVE); final ArrayList<String> removedPackageNames = new ArrayList<String>(Arrays.asList(packages)); mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindComponentsRemoved(removedPackageNames, removedApps, permanent); } } }); } final ArrayList<Object> widgetsAndShortcuts = getSortedWidgetsAndShortcuts(context); mHandler.post(new Runnable() { @Override public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindPackagesUpdated(widgetsAndShortcuts); } } }); } } // Returns a list of ResolveInfos/AppWindowInfos in sorted order public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) { PackageManager packageManager = context.getPackageManager(); final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>(); widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders()); Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT); widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0)); Collections.sort(widgetsAndShortcuts, new LauncherModel.WidgetAndShortcutNameComparator(packageManager)); return widgetsAndShortcuts; } /** * This is called from the code that adds shortcuts from the intent receiver. This * doesn't have a Cursor, but */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) { return getShortcutInfo(manager, intent, context, null, -1, -1, null); } /** * Make an ShortcutInfo object for a shortcut that is an application. * * If c is not null, then it will be used to fill in missing data like the title and icon. */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context, Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); ComponentName componentName = intent.getComponent(); if (componentName == null) { return null; } try { PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0); if (!pi.applicationInfo.enabled) { // If we return null here, the corresponding item will be removed from the launcher // db and will not appear in the workspace. return null; } } catch (NameNotFoundException e) { Log.d(TAG, "getPackInfo failed for package " + componentName.getPackageName()); } // TODO: See if the PackageManager knows about this case. If it doesn't // then return null & delete this. // the resource -- This may implicitly give us back the fallback icon, // but don't worry about that. All we're doing with usingFallbackIcon is // to avoid saving lots of copies of that in the database, and most apps // have icons anyway. // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info // via resolveActivity(). ResolveInfo resolveInfo = null; ComponentName oldComponent = intent.getComponent(); Intent newIntent = new Intent(intent.getAction(), null); newIntent.addCategory(Intent.CATEGORY_LAUNCHER); newIntent.setPackage(oldComponent.getPackageName()); List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0); for (ResolveInfo i : infos) { ComponentName cn = new ComponentName(i.activityInfo.packageName, i.activityInfo.name); if (cn.equals(oldComponent)) { resolveInfo = i; } } if (resolveInfo == null) { resolveInfo = manager.resolveActivity(intent, 0); } if (resolveInfo != null) { icon = mIconCache.getIcon(componentName, resolveInfo, labelCache); } // the db if (icon == null) { if (c != null) { icon = getIconFromCursor(c, iconIndex, context); } } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); // from the resource if (resolveInfo != null) { ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo); if (labelCache != null && labelCache.containsKey(key)) { info.title = labelCache.get(key); } else { info.title = resolveInfo.activityInfo.loadLabel(manager); if (labelCache != null) { labelCache.put(key, info.title); } } } // from the db if (info.title == null) { if (c != null) { info.title = c.getString(titleIndex); } } // fall back to the class name of the activity if (info.title == null) { info.title = componentName.getClassName(); } info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; return info; } /** * Returns the set of workspace ShortcutInfos with the specified intent. */ static ArrayList<ItemInfo> getWorkspaceShortcutItemInfosWithIntent(Intent intent) { ArrayList<ItemInfo> items = new ArrayList<ItemInfo>(); synchronized (sBgLock) { for (ItemInfo info : sBgWorkspaceItems) { if (info instanceof ShortcutInfo) { ShortcutInfo shortcut = (ShortcutInfo) info; if (shortcut.intent.toUri(0).equals(intent.toUri(0))) { items.add(shortcut); } } } } return items; } /** * Make an ShortcutInfo object for a shortcut that isn't an application. */ private ShortcutInfo getShortcutInfo(Cursor c, Context context, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; // TODO: If there's an explicit component and we can't install that, delete it. info.title = c.getString(titleIndex); int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); info.customIcon = false; // the resource try { Resources resources = packageManager.getResourcesForApplication(packageName); if (resources != null) { final int id = resources.getIdentifier(resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } } catch (Exception e) { // drop this. we have other places to look for icons } // the db if (icon == null) { icon = getIconFromCursor(c, iconIndex, context); } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } break; case LauncherSettings.Favorites.ICON_TYPE_BITMAP: icon = getIconFromCursor(c, iconIndex, context); if (icon == null) { icon = getFallbackIcon(); info.customIcon = false; info.usingFallbackIcon = true; } else { info.customIcon = true; } break; default: icon = getFallbackIcon(); info.usingFallbackIcon = true; info.customIcon = false; break; } info.setIcon(icon); return info; } Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) { @SuppressWarnings("all") // suppress dead code warning final boolean debug = false; if (debug) { Log.d(TAG, "getIconFromCursor app=" + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE))); } byte[] data = c.getBlob(iconIndex); try { return Utilities.createIconBitmap( BitmapFactory.decodeByteArray(data, 0, data.length), context); } catch (Exception e) { return null; } } ShortcutInfo addShortcut(Context context, Intent data, long container, int screen, int cellX, int cellY, boolean notify) { final ShortcutInfo info = infoFromShortcutIntent(context, data, null); if (info == null) { return null; } addItemToDatabase(context, info, container, screen, cellX, cellY, notify); return info; } /** * Attempts to find an AppWidgetProviderInfo that matches the given component. */ AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context, ComponentName component) { List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); for (AppWidgetProviderInfo info : widgets) { if (info.provider.equals(component)) { return info; } } return null; } /** * Returns a list of all the widgets that can handle configuration with a particular mimeType. */ List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) { final PackageManager packageManager = context.getPackageManager(); final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities = new ArrayList<WidgetMimeTypeHandlerData>(); final Intent supportsIntent = new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE); supportsIntent.setType(mimeType); // Create a set of widget configuration components that we can test against final List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget = new HashMap<ComponentName, AppWidgetProviderInfo>(); for (AppWidgetProviderInfo info : widgets) { configurationComponentToWidget.put(info.configure, info); } // Run through each of the intents that can handle this type of clip data, and cross // reference them with the components that are actual configuration components final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo info : activities) { final ActivityInfo activityInfo = info.activityInfo; final ComponentName infoComponent = new ComponentName(activityInfo.packageName, activityInfo.name); if (configurationComponentToWidget.containsKey(infoComponent)) { supportedConfigurationActivities.add( new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info, configurationComponentToWidget.get(infoComponent))); } } return supportedConfigurationActivities; } ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) { Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); if (intent == null) { // If the intent is null, we can't construct a valid ShortcutInfo, so we return null Log.e(TAG, "Can't construct ShorcutInfo with null intent"); return null; } Bitmap icon = null; boolean customIcon = false; ShortcutIconResource iconResource = null; if (bitmap != null && bitmap instanceof Bitmap) { icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context); customIcon = true; } else { Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (extra != null && extra instanceof ShortcutIconResource) { try { iconResource = (ShortcutIconResource) extra; final PackageManager packageManager = context.getPackageManager(); Resources resources = packageManager.getResourcesForApplication( iconResource.packageName); final int id = resources.getIdentifier(iconResource.resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } catch (Exception e) { Log.w(TAG, "Could not load shortcut icon: " + extra); } } } final ShortcutInfo info = new ShortcutInfo(); if (icon == null) { if (fallbackIcon != null) { icon = fallbackIcon; } else { icon = getFallbackIcon(); info.usingFallbackIcon = true; } } info.setIcon(icon); info.title = name; info.intent = intent; info.customIcon = customIcon; info.iconResource = iconResource; return info; } boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c, int iconIndex) { // If apps can't be on SD, don't even bother. if (!mAppsCanBeOnExternalStorage) { return false; } // If this icon doesn't have a custom icon, check to see // what's stored in the DB, and if it doesn't match what // we're going to show, store what we are going to show back // into the DB. We do this so when we're loading, if the // package manager can't find an icon (for example because // the app is on SD) then we can use that instead. if (!info.customIcon && !info.usingFallbackIcon) { cache.put(info, c.getBlob(iconIndex)); return true; } return false; } void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) { boolean needSave = false; try { if (data != null) { Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length); Bitmap loaded = info.getIcon(mIconCache); needSave = !saved.sameAs(loaded); } else { needSave = true; } } catch (Exception e) { needSave = true; } if (needSave) { Log.d(TAG, "going to save icon bitmap for info=" + info); // This is slower than is ideal, but this only happens once // or when the app is updated with a new icon. updateItemInDatabase(context, info); } } /** * Return an existing FolderInfo object if we have encountered this ID previously, * or make a new one. */ private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null) { // No placeholder -- create a new instance folderInfo = new FolderInfo(); folders.put(id, folderInfo); } return folderInfo; } public static final Comparator<ApplicationInfo> getAppNameComparator() { final Collator collator = Collator.getInstance(); return new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { int result = collator.compare(a.title.toString(), b.title.toString()); if (result == 0) { result = a.componentName.compareTo(b.componentName); } return result; } }; } public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { if (a.firstInstallTime < b.firstInstallTime) return 1; if (a.firstInstallTime > b.firstInstallTime) return -1; return 0; } }; public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() { final Collator collator = Collator.getInstance(); return new Comparator<AppWidgetProviderInfo>() { public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) { return collator.compare(a.label.toString(), b.label.toString()); } }; } static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) { if (info.activityInfo != null) { return new ComponentName(info.activityInfo.packageName, info.activityInfo.name); } else { return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name); } } public static class ShortcutNameComparator implements Comparator<ResolveInfo> { private Collator mCollator; private PackageManager mPackageManager; private HashMap<Object, CharSequence> mLabelCache; ShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, CharSequence>(); mCollator = Collator.getInstance(); } ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) { mPackageManager = pm; mLabelCache = labelCache; mCollator = Collator.getInstance(); } public final int compare(ResolveInfo a, ResolveInfo b) { CharSequence labelA, labelB; ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a); ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b); if (mLabelCache.containsKey(keyA)) { labelA = mLabelCache.get(keyA); } else { labelA = a.loadLabel(mPackageManager).toString(); mLabelCache.put(keyA, labelA); } if (mLabelCache.containsKey(keyB)) { labelB = mLabelCache.get(keyB); } else { labelB = b.loadLabel(mPackageManager).toString(); mLabelCache.put(keyB, labelB); } return mCollator.compare(labelA, labelB); } }; public static class WidgetAndShortcutNameComparator implements Comparator<Object> { private Collator mCollator; private PackageManager mPackageManager; private HashMap<Object, String> mLabelCache; WidgetAndShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, String>(); mCollator = Collator.getInstance(); } public final int compare(Object a, Object b) { String labelA, labelB; if (mLabelCache.containsKey(a)) { labelA = mLabelCache.get(a); } else { labelA = (a instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) a).label : ((ResolveInfo) a).loadLabel(mPackageManager).toString(); mLabelCache.put(a, labelA); } if (mLabelCache.containsKey(b)) { labelB = mLabelCache.get(b); } else { labelB = (b instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) b).label : ((ResolveInfo) b).loadLabel(mPackageManager).toString(); mLabelCache.put(b, labelB); } return mCollator.compare(labelA, labelB); } }; public void dumpState() { Log.d(TAG, "mCallbacks=" + mCallbacks); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified); if (mLoaderTask != null) { mLoaderTask.dumpState(); } else { Log.d(TAG, "mLoaderTask=null"); } } }
diff --git a/src/MainForm.java b/src/MainForm.java index e1fed0e..ab8b927 100644 --- a/src/MainForm.java +++ b/src/MainForm.java @@ -1,489 +1,490 @@ import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableColumn; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Vector; /** * Created by IntelliJ IDEA. * User: Alla * Date: 04.01.11 * Time: 23:11 * To change this template use File | Settings | File Templates. */ public class MainForm { private JTabbedPane tabbedPane1; private JPanel mainPanel; private JTable workersTable; private JButton saveWorkersBtn; private JButton addWorkerBtn; private JButton delWorkerBtn; private JTabbedPane quarterPlan_divisions; private JTabbedPane kindWorksTabbedPane; private JButton savePlanBtn; private JButton loadPlanBtn; private JButton printPlanBtn; private JButton отчетButton; private JTable planPartTable; private JTable workersInPlanTable; private JButton addWorkBtn; private JButton delWorkBtn; private JButton addWorkerToWorkBtn; private JButton delWorkerFromWorkBtn; private JButton moveUpPlanPartBtn; private JButton moveDownPlanPartBtn; private JTabbedPane monthTabbedPane; private JComboBox quarterComboBox; private JButton monthReportBtn; private JTable monthWorksTable; private JTable monthWorkersPerWorkTable; private JTabbedPane quarterPlan_month; private JFormattedTextField yearEdit; private JButton editWorkBtn; private JButton createNewPlanBtn; public int getSelectedQuarter() { return quarterComboBox.getSelectedIndex() + 1; } public void setSelectedQuarter(int quarter) { if ((quarter > -1) && (quarter < 4)) { quarterComboBox.setSelectedIndex(quarter); } } public String getYear() { return yearEdit.getText(); } public void setYear(String year) { yearEdit.setText(year); } public Vector<Worker> getWorkers() { return workers; } // private Vector<Worker> workers = new Vector<Worker>(); public ArrayList<PlanPart> getPlan() { return plan; } private ArrayList<PlanPart> plan = new ArrayList<PlanPart>(); // public MainForm() { // Worker worker1 = new Worker("Рогов П.А.", 0.0); workers.add(worker1); Worker worker2 = new Worker("Золотов А.В.", 0.0); workers.add(worker2); workers.add(new Worker("Полулях А.В.", 0.0)); workers.add(new Worker("Горелов А.Г.", 0.0)); workers.add(new Worker("Воронин Р.М.", 0.0)); workers.add(new Worker("Гуськов С.С.", 0.0)); workers.add(new Worker("Конев Д.С.", 0.0)); workers.add(new Worker("Шумский Ю.Н.", 0.0)); workers.add(new Worker("Мироненко Н.Л.", 0.0)); workers.add(new Worker("Мармер В.В.", -1.0)); workers.add(new Worker("Зореев В.П.", -1.0)); workers.add(new Worker("Шварцман А.М.", 0.0)); workers.add(new Worker("Никитина Н.Е.", 0.0)); workers.add(new Worker("Хехнева А.В.", 0.0)); workers.add(new Worker("Конашина О.А.", 0.0)); workers.add(new Worker("Косарев В.В.", 0.0)); // plan.add(new PlanPart("Собств.работы - новые", "1. Собственные работы (по основному процессу подразделения)")); plan.add(new PlanPart("Собств.работы - продолжение", "1а). Собственные работы (завершение работ по предыдущим квартальным планам)")); plan.add(new PlanPart("Внешн.заказчик", "3. Работы по внешней кооперации (с другими организациями)")); plan.add(new PlanPart("СМК", "4. Разработка документации по СМК")); plan.add(new PlanPart("Корр.мероприятия", "5. Корректирующие и предупреждающие действия")); // plan.get(0).getWorks().add(new WorkInPlan("Работа 1", "Описание 1\nСтрока2\n]]", "10.10.2010", "", "Предоставлено \n куча \n всего \n ]]")); plan.get(0).getWorks().get(0).getWorkersInPlan().add(new WorkerInPlan(worker1, 3.5)); plan.get(0).getWorks().get(0).getWorkersInPlan().add(new WorkerInPlan(worker2, 5.5)); plan.get(0).getWorks().add(new WorkInPlan("Работа 2", "Описание 2")); plan.get(0).getWorks().add(new WorkInPlan("Работа 3", "Описание 3")); // yearEdit.setText(new SimpleDateFormat("yyyy").format(new Date())); // makePlanPartTabs(); quarterPlan_divisions.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { if (quarterPlan_divisions.getSelectedIndex() != -1) { PlanPart currPart = plan.get(quarterPlan_divisions.getSelectedIndex()); ((PlanPartModel) planPartTable.getModel()).setPlanPart(currPart); // Сбрасываем еще список работников ((WorkersInPlanTableModel) workersInPlanTable.getModel()).clearWorkInPlan(); } } }); // workersTable.setModel(new WorkersTableModel(workers)); workersTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // PlanPartModel planPartModel = new PlanPartModel(); planPartTable.setModel(planPartModel); planPartTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); planPartModel.setPlanPart(plan.get(0)); planPartTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { PlanPart currPart = plan.get(quarterPlan_divisions.getSelectedIndex()); if ((planPartTable.getSelectedRow() > -1) && (planPartTable.getSelectedRow() < currPart.getWorks().size())) { ((WorkersInPlanTableModel) workersInPlanTable.getModel()).setWorkInPlan(currPart.getWorks().get(planPartTable.getSelectedRow())); } } }); // workersInPlanTable.setModel(new WorkersInPlanTableModel()); workersInPlanTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); TableColumn workerColumn = workersInPlanTable.getColumnModel().getColumn(0); JComboBox workerSelectCB = new JComboBox(); workerSelectCB.setModel(new DefaultComboBoxModel(workers)); workerColumn.setCellEditor(new DefaultCellEditor(workerSelectCB)); // addWorkBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { PlanPart currPart = plan.get(quarterPlan_divisions.getSelectedIndex()); currPart.getWorks().add(new WorkInPlan("", "")); ((PlanPartModel) planPartTable.getModel()).fireTableDataChanged(); ((WorkersInPlanTableModel) workersInPlanTable.getModel()).clearWorkInPlan(); } }); delWorkBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (planPartTable.getSelectedRow() != -1) { if (JOptionPane.showConfirmDialog(null, "Вы уверены что хотите удалить выбранную работу?", "Удаление", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { PlanPart currPart = plan.get(quarterPlan_divisions.getSelectedIndex()); currPart.getWorks().remove(planPartTable.getSelectedRow()); ((PlanPartModel) planPartTable.getModel()).fireTableDataChanged(); ((WorkersInPlanTableModel) workersInPlanTable.getModel()).clearWorkInPlan(); } } } }); addWorkerBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { workers.add(new Worker("", 0.0)); ((WorkersTableModel) workersTable.getModel()).fireTableDataChanged(); } }); delWorkerBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if ((workersTable.getSelectedRow() != -1) && (workersTable.getSelectedRow() < workers.size())) { // Тут вначале проверим - а может у нас этот работник фигурирует в какой работе?! Worker worker = workers.get(workersTable.getSelectedRow()); boolean presentInWork = false; for (PlanPart planPart : plan) { for (WorkInPlan work : planPart.getWorks()) { for (WorkerInPlan workerInPlan : work.getWorkersInPlan()) { if (workerInPlan.getWorker() == worker) { presentInWork = true; break; } } } } if (presentInWork) { JOptionPane.showMessageDialog(null, "Работник занят в какой-то работе. Вначале удалите его из всех работ", "Удаление работника", JOptionPane.ERROR_MESSAGE); } else { if (JOptionPane.showConfirmDialog(null, "Вы уверены, что хотите удалить выбранного работника?", "Удаление работника", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { workers.remove(worker); ((WorkersTableModel) workersTable.getModel()).fireTableDataChanged(); } } } } }); // addWorkerToWorkBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { PlanPart currPart = plan.get(quarterPlan_divisions.getSelectedIndex()); if ((planPartTable.getSelectedRow() > -1) && (planPartTable.getSelectedRow() < currPart.getWorks().size())) { WorkInPlan work = currPart.getWorks().get(planPartTable.getSelectedRow()); // Теперь надо из списка работников добавить ПЕРВОГО, кого тут нет for (Worker worker : workers) { boolean found = false; for (WorkerInPlan workerInPlan : work.getWorkersInPlan()) { if (workerInPlan.getWorker() == worker) { found = true; break; } } if (!found) { work.getWorkersInPlan().add(new WorkerInPlan(worker, 0.0)); ((WorkersInPlanTableModel) workersInPlanTable.getModel()).fireTableDataChanged(); break; } } } } }); delWorkerFromWorkBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { PlanPart currPart = plan.get(quarterPlan_divisions.getSelectedIndex()); if ((planPartTable.getSelectedRow() > -1) && (planPartTable.getSelectedRow() < currPart.getWorks().size())) { WorkInPlan work = currPart.getWorks().get(planPartTable.getSelectedRow()); if ((workersInPlanTable.getSelectedRow() > -1) && (workersInPlanTable.getSelectedRow() < work.getWorkersInPlan().size())) { if (JOptionPane.showConfirmDialog(null, "Вы уверены, что хотите удалить выбранного работника из работы?", "Удаление работника из работы", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { WorkerInPlan worker = work.getWorkersInPlan().get(workersInPlanTable.getSelectedRow()); work.getWorkersInPlan().remove(worker); ((WorkersInPlanTableModel) workersInPlanTable.getModel()).fireTableDataChanged(); } } } } }); moveUpPlanPartBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { movePlanPart(-1); } }); moveDownPlanPartBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { movePlanPart(1); } }); // quarterComboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { switch (quarterComboBox.getSelectedIndex()) { case 0: { monthTabbedPane.setTitleAt(0, "Январь"); monthTabbedPane.setTitleAt(1, "Февраль"); monthTabbedPane.setTitleAt(2, "Март"); break; } case 1: { monthTabbedPane.setTitleAt(0, "Апрель"); monthTabbedPane.setTitleAt(1, "Май"); monthTabbedPane.setTitleAt(2, "Июнь"); break; } case 2: { monthTabbedPane.setTitleAt(0, "Июль"); monthTabbedPane.setTitleAt(1, "Август"); monthTabbedPane.setTitleAt(2, "Сентябрь"); break; } case 3: { monthTabbedPane.setTitleAt(0, "Октябрь"); monthTabbedPane.setTitleAt(1, "Ноябрь"); monthTabbedPane.setTitleAt(2, "Декабрь"); break; } } } }); quarterComboBox.setSelectedIndex(0); // monthTabbedPane.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { if ((monthTabbedPane.getSelectedIndex() > -1) && (monthTabbedPane.getSelectedIndex() < 4)) { ((MonthWorksTableModel) monthWorksTable.getModel()).setMonth(monthTabbedPane.getSelectedIndex()); int i = monthWorksTable.getSelectedRow(); ((MonthWorksTableModel) monthWorksTable.getModel()).fireTableDataChanged(); if (i > -1) monthWorksTable.getSelectionModel().setSelectionInterval(i, i); ((MonthWorkersTableModel) monthWorkersPerWorkTable.getModel()).setMonth(monthTabbedPane.getSelectedIndex()); } } }); monthTabbedPane.setSelectedIndex(0); // quarterPlan_month.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { if (quarterPlan_month.getSelectedIndex() != -1) { PlanPart currPart = plan.get(quarterPlan_month.getSelectedIndex()); ((MonthWorksTableModel) monthWorksTable.getModel()).setPlanPart(currPart); // Сбрасываем еще список работников ((MonthWorkersTableModel) monthWorkersPerWorkTable.getModel()).clearWorkInPlan(); } } }); // monthWorkersPerWorkTable.setModel(new MonthWorkersTableModel()); monthWorkersPerWorkTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // MonthWorksTableModel monthWorksTableModel = new MonthWorksTableModel(); monthWorksTable.setModel(monthWorksTableModel); monthWorksTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); monthWorksTableModel.setPlanPart(plan.get(0)); monthWorksTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { PlanPart currPart = plan.get(quarterPlan_month.getSelectedIndex()); if ((monthWorksTable.getSelectedRow() > -1) && (monthWorksTable.getSelectedRow() < currPart.getWorks().size())) { ((MonthWorkersTableModel) monthWorkersPerWorkTable.getModel()).setWorkInPlan(currPart.getWorks().get(monthWorksTable.getSelectedRow())); } } }); kindWorksTabbedPane.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { // Запустим обновление всего чего можно тама... ((MonthWorksTableModel) monthWorksTable.getModel()).fireTableDataChanged(); ((MonthWorkersTableModel) monthWorkersPerWorkTable.getModel()).clearWorkInPlan(); } }); // editWorkBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { PlanPart currPart = plan.get(quarterPlan_divisions.getSelectedIndex()); if ((planPartTable.getSelectedRow() > -1) && (planPartTable.getSelectedRow() < currPart.getWorks().size())) { WorkInPlan currWork = currPart.getWorks().get(planPartTable.getSelectedRow()); WorkInPlan resWork = WorkParamForm.showDialog(planPartTable, planPartTable, currWork); if (resWork != null) { currWork.setName(resWork.getName()); currWork.setDesc(resWork.getDesc()); currWork.setEndDate(resWork.getEndDate()); currWork.setReserve(resWork.getReserve()); currWork.setFinishDoc(resWork.getFinishDoc()); // Fire change ((PlanPartModel) planPartTable.getModel()).fireTableCellUpdated(planPartTable.getSelectedRow(), 0); } } } }); // savePlanBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Вначале - выбираем куда сохранять PlanUtils.savePlanToFile(); } }); loadPlanBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (PlanUtils.loadPlanFromFile()) { // Пересчитаем общую трудоемкость по всем for (Worker worker : workers) { updateTotalWorkerLabor(worker); } // Теперь еще перезапустим все модели makePlanPartTabs(); ((AbstractTableModel) workersTable.getModel()).fireTableDataChanged(); ((AbstractTableModel) planPartTable.getModel()).fireTableDataChanged(); ((AbstractTableModel) workersInPlanTable.getModel()).fireTableDataChanged(); ((AbstractTableModel) monthWorksTable.getModel()).fireTableDataChanged(); ((AbstractTableModel) monthWorkersPerWorkTable.getModel()).fireTableDataChanged(); } } }); // createNewPlanBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (JOptionPane.showConfirmDialog(null, "Вы уверены, что хотите создать новый план? Все работы текущего плана будут удалены!", "Создание нового плана", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION) { for (PlanPart part : plan) { part.getWorks().clear(); } ((PlanPartModel) planPartTable.getModel()).fireTableDataChanged(); ((WorkersInPlanTableModel) workersInPlanTable.getModel()).fireTableDataChanged(); for (Worker worker : workers) { worker.setLaborContentTotal(0.0); } ((WorkersTableModel) workersTable.getModel()).fireTableDataChanged(); } } }); printPlanBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { PlanUtils.makeQuarterPlan(); + ReportViewer.showPreview(kindWorksTabbedPane, kindWorksTabbedPane, "quarterPlan"); } catch (IOException e1) { JOptionPane.showMessageDialog(null, "Ошибка ввода-вывода"); } catch (TransformerException e1) { JOptionPane.showMessageDialog(null, "Ошибка сохранения XML документа"); } catch (ParserConfigurationException e1) { JOptionPane.showMessageDialog(null, "Ошибка работы с XML документом"); } } }); } /** * Создает табы по видам работ */ private void makePlanPartTabs() { quarterPlan_divisions.removeAll(); quarterPlan_month.removeAll(); for (PlanPart part : plan) { quarterPlan_divisions.addTab(part.getName(), null); quarterPlan_month.addTab(part.getName(), null); } } /** * Двигает выбранный элемент в planPartTable вверх или вниз * * @param moveDiff -1 - сдвинуть вверх, 1 - сдвинуть вниз. * При других значениях или при невозможности двигать - ничего не делает */ private void movePlanPart(int moveDiff) { PlanPart currPart = plan.get(quarterPlan_divisions.getSelectedIndex()); if (((moveDiff == -1) && ((planPartTable.getSelectedRow() > 0) && (planPartTable.getSelectedRow() < currPart.getWorks().size()))) || ((moveDiff == 1) && ((planPartTable.getSelectedRow() > -1) && (planPartTable.getSelectedRow() < (currPart.getWorks().size() - 1))))) { // Значит тут можно попробовать подвигать... int selPos = planPartTable.getSelectedRow(); WorkInPlan work = currPart.getWorks().get(selPos); currPart.getWorks().remove(work); currPart.getWorks().add(selPos + moveDiff, work); ((PlanPartModel) planPartTable.getModel()).fireTableDataChanged(); planPartTable.getSelectionModel().setSelectionInterval(selPos + moveDiff, selPos + moveDiff); } } public JPanel getMainPanel() { return mainPanel; } public void planPartTotalLaborChanged() { if (planPartTable.getSelectedRow() != -1) { ((PlanPartModel) planPartTable.getModel()).fireTableCellUpdated(planPartTable.getSelectedRow(), 1); } else { ((PlanPartModel) planPartTable.getModel()).fireTableDataChanged(); } } public void updateTotalWorkerLabor(Worker worker) { double total = 0; for (PlanPart planPart : plan) { for (WorkInPlan work : planPart.getWorks()) { for (WorkerInPlan workerInPlan : work.getWorkersInPlan()) { if (workerInPlan.getWorker() == worker) { total = total + workerInPlan.getLaborContent(); } } } } worker.setLaborContentTotal(total); ((WorkersTableModel) workersTable.getModel()).fireTableCellUpdated(workers.indexOf(worker), 1); } /** * Обновляет информацию о оставшейся трудоемкости в monthWorksTable */ public void updateRestLabor() { if (monthWorksTable.getSelectedRow() != -1) { ((MonthWorksTableModel) monthWorksTable.getModel()).fireTableCellUpdated(monthWorksTable.getSelectedRow(), 2); } else { ((MonthWorksTableModel) monthWorksTable.getModel()).fireTableDataChanged(); ((MonthWorkersTableModel) monthWorkersPerWorkTable.getModel()).clearWorkInPlan(); } } }
true
true
public MainForm() { // Worker worker1 = new Worker("Рогов П.А.", 0.0); workers.add(worker1); Worker worker2 = new Worker("Золотов А.В.", 0.0); workers.add(worker2); workers.add(new Worker("Полулях А.В.", 0.0)); workers.add(new Worker("Горелов А.Г.", 0.0)); workers.add(new Worker("Воронин Р.М.", 0.0)); workers.add(new Worker("Гуськов С.С.", 0.0)); workers.add(new Worker("Конев Д.С.", 0.0)); workers.add(new Worker("Шумский Ю.Н.", 0.0)); workers.add(new Worker("Мироненко Н.Л.", 0.0)); workers.add(new Worker("Мармер В.В.", -1.0)); workers.add(new Worker("Зореев В.П.", -1.0)); workers.add(new Worker("Шварцман А.М.", 0.0)); workers.add(new Worker("Никитина Н.Е.", 0.0)); workers.add(new Worker("Хехнева А.В.", 0.0)); workers.add(new Worker("Конашина О.А.", 0.0)); workers.add(new Worker("Косарев В.В.", 0.0)); // plan.add(new PlanPart("Собств.работы - новые", "1. Собственные работы (по основному процессу подразделения)")); plan.add(new PlanPart("Собств.работы - продолжение", "1а). Собственные работы (завершение работ по предыдущим квартальным планам)")); plan.add(new PlanPart("Внешн.заказчик", "3. Работы по внешней кооперации (с другими организациями)")); plan.add(new PlanPart("СМК", "4. Разработка документации по СМК")); plan.add(new PlanPart("Корр.мероприятия", "5. Корректирующие и предупреждающие действия")); // plan.get(0).getWorks().add(new WorkInPlan("Работа 1", "Описание 1\nСтрока2\n]]", "10.10.2010", "", "Предоставлено \n куча \n всего \n ]]")); plan.get(0).getWorks().get(0).getWorkersInPlan().add(new WorkerInPlan(worker1, 3.5)); plan.get(0).getWorks().get(0).getWorkersInPlan().add(new WorkerInPlan(worker2, 5.5)); plan.get(0).getWorks().add(new WorkInPlan("Работа 2", "Описание 2")); plan.get(0).getWorks().add(new WorkInPlan("Работа 3", "Описание 3")); // yearEdit.setText(new SimpleDateFormat("yyyy").format(new Date())); // makePlanPartTabs(); quarterPlan_divisions.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { if (quarterPlan_divisions.getSelectedIndex() != -1) { PlanPart currPart = plan.get(quarterPlan_divisions.getSelectedIndex()); ((PlanPartModel) planPartTable.getModel()).setPlanPart(currPart); // Сбрасываем еще список работников ((WorkersInPlanTableModel) workersInPlanTable.getModel()).clearWorkInPlan(); } } }); // workersTable.setModel(new WorkersTableModel(workers)); workersTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // PlanPartModel planPartModel = new PlanPartModel(); planPartTable.setModel(planPartModel); planPartTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); planPartModel.setPlanPart(plan.get(0)); planPartTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { PlanPart currPart = plan.get(quarterPlan_divisions.getSelectedIndex()); if ((planPartTable.getSelectedRow() > -1) && (planPartTable.getSelectedRow() < currPart.getWorks().size())) { ((WorkersInPlanTableModel) workersInPlanTable.getModel()).setWorkInPlan(currPart.getWorks().get(planPartTable.getSelectedRow())); } } }); // workersInPlanTable.setModel(new WorkersInPlanTableModel()); workersInPlanTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); TableColumn workerColumn = workersInPlanTable.getColumnModel().getColumn(0); JComboBox workerSelectCB = new JComboBox(); workerSelectCB.setModel(new DefaultComboBoxModel(workers)); workerColumn.setCellEditor(new DefaultCellEditor(workerSelectCB)); // addWorkBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { PlanPart currPart = plan.get(quarterPlan_divisions.getSelectedIndex()); currPart.getWorks().add(new WorkInPlan("", "")); ((PlanPartModel) planPartTable.getModel()).fireTableDataChanged(); ((WorkersInPlanTableModel) workersInPlanTable.getModel()).clearWorkInPlan(); } }); delWorkBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (planPartTable.getSelectedRow() != -1) { if (JOptionPane.showConfirmDialog(null, "Вы уверены что хотите удалить выбранную работу?", "Удаление", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { PlanPart currPart = plan.get(quarterPlan_divisions.getSelectedIndex()); currPart.getWorks().remove(planPartTable.getSelectedRow()); ((PlanPartModel) planPartTable.getModel()).fireTableDataChanged(); ((WorkersInPlanTableModel) workersInPlanTable.getModel()).clearWorkInPlan(); } } } }); addWorkerBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { workers.add(new Worker("", 0.0)); ((WorkersTableModel) workersTable.getModel()).fireTableDataChanged(); } }); delWorkerBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if ((workersTable.getSelectedRow() != -1) && (workersTable.getSelectedRow() < workers.size())) { // Тут вначале проверим - а может у нас этот работник фигурирует в какой работе?! Worker worker = workers.get(workersTable.getSelectedRow()); boolean presentInWork = false; for (PlanPart planPart : plan) { for (WorkInPlan work : planPart.getWorks()) { for (WorkerInPlan workerInPlan : work.getWorkersInPlan()) { if (workerInPlan.getWorker() == worker) { presentInWork = true; break; } } } } if (presentInWork) { JOptionPane.showMessageDialog(null, "Работник занят в какой-то работе. Вначале удалите его из всех работ", "Удаление работника", JOptionPane.ERROR_MESSAGE); } else { if (JOptionPane.showConfirmDialog(null, "Вы уверены, что хотите удалить выбранного работника?", "Удаление работника", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { workers.remove(worker); ((WorkersTableModel) workersTable.getModel()).fireTableDataChanged(); } } } } }); // addWorkerToWorkBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { PlanPart currPart = plan.get(quarterPlan_divisions.getSelectedIndex()); if ((planPartTable.getSelectedRow() > -1) && (planPartTable.getSelectedRow() < currPart.getWorks().size())) { WorkInPlan work = currPart.getWorks().get(planPartTable.getSelectedRow()); // Теперь надо из списка работников добавить ПЕРВОГО, кого тут нет for (Worker worker : workers) { boolean found = false; for (WorkerInPlan workerInPlan : work.getWorkersInPlan()) { if (workerInPlan.getWorker() == worker) { found = true; break; } } if (!found) { work.getWorkersInPlan().add(new WorkerInPlan(worker, 0.0)); ((WorkersInPlanTableModel) workersInPlanTable.getModel()).fireTableDataChanged(); break; } } } } }); delWorkerFromWorkBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { PlanPart currPart = plan.get(quarterPlan_divisions.getSelectedIndex()); if ((planPartTable.getSelectedRow() > -1) && (planPartTable.getSelectedRow() < currPart.getWorks().size())) { WorkInPlan work = currPart.getWorks().get(planPartTable.getSelectedRow()); if ((workersInPlanTable.getSelectedRow() > -1) && (workersInPlanTable.getSelectedRow() < work.getWorkersInPlan().size())) { if (JOptionPane.showConfirmDialog(null, "Вы уверены, что хотите удалить выбранного работника из работы?", "Удаление работника из работы", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { WorkerInPlan worker = work.getWorkersInPlan().get(workersInPlanTable.getSelectedRow()); work.getWorkersInPlan().remove(worker); ((WorkersInPlanTableModel) workersInPlanTable.getModel()).fireTableDataChanged(); } } } } }); moveUpPlanPartBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { movePlanPart(-1); } }); moveDownPlanPartBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { movePlanPart(1); } }); // quarterComboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { switch (quarterComboBox.getSelectedIndex()) { case 0: { monthTabbedPane.setTitleAt(0, "Январь"); monthTabbedPane.setTitleAt(1, "Февраль"); monthTabbedPane.setTitleAt(2, "Март"); break; } case 1: { monthTabbedPane.setTitleAt(0, "Апрель"); monthTabbedPane.setTitleAt(1, "Май"); monthTabbedPane.setTitleAt(2, "Июнь"); break; } case 2: { monthTabbedPane.setTitleAt(0, "Июль"); monthTabbedPane.setTitleAt(1, "Август"); monthTabbedPane.setTitleAt(2, "Сентябрь"); break; } case 3: { monthTabbedPane.setTitleAt(0, "Октябрь"); monthTabbedPane.setTitleAt(1, "Ноябрь"); monthTabbedPane.setTitleAt(2, "Декабрь"); break; } } } }); quarterComboBox.setSelectedIndex(0); // monthTabbedPane.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { if ((monthTabbedPane.getSelectedIndex() > -1) && (monthTabbedPane.getSelectedIndex() < 4)) { ((MonthWorksTableModel) monthWorksTable.getModel()).setMonth(monthTabbedPane.getSelectedIndex()); int i = monthWorksTable.getSelectedRow(); ((MonthWorksTableModel) monthWorksTable.getModel()).fireTableDataChanged(); if (i > -1) monthWorksTable.getSelectionModel().setSelectionInterval(i, i); ((MonthWorkersTableModel) monthWorkersPerWorkTable.getModel()).setMonth(monthTabbedPane.getSelectedIndex()); } } }); monthTabbedPane.setSelectedIndex(0); // quarterPlan_month.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { if (quarterPlan_month.getSelectedIndex() != -1) { PlanPart currPart = plan.get(quarterPlan_month.getSelectedIndex()); ((MonthWorksTableModel) monthWorksTable.getModel()).setPlanPart(currPart); // Сбрасываем еще список работников ((MonthWorkersTableModel) monthWorkersPerWorkTable.getModel()).clearWorkInPlan(); } } }); // monthWorkersPerWorkTable.setModel(new MonthWorkersTableModel()); monthWorkersPerWorkTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // MonthWorksTableModel monthWorksTableModel = new MonthWorksTableModel(); monthWorksTable.setModel(monthWorksTableModel); monthWorksTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); monthWorksTableModel.setPlanPart(plan.get(0)); monthWorksTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { PlanPart currPart = plan.get(quarterPlan_month.getSelectedIndex()); if ((monthWorksTable.getSelectedRow() > -1) && (monthWorksTable.getSelectedRow() < currPart.getWorks().size())) { ((MonthWorkersTableModel) monthWorkersPerWorkTable.getModel()).setWorkInPlan(currPart.getWorks().get(monthWorksTable.getSelectedRow())); } } }); kindWorksTabbedPane.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { // Запустим обновление всего чего можно тама... ((MonthWorksTableModel) monthWorksTable.getModel()).fireTableDataChanged(); ((MonthWorkersTableModel) monthWorkersPerWorkTable.getModel()).clearWorkInPlan(); } }); // editWorkBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { PlanPart currPart = plan.get(quarterPlan_divisions.getSelectedIndex()); if ((planPartTable.getSelectedRow() > -1) && (planPartTable.getSelectedRow() < currPart.getWorks().size())) { WorkInPlan currWork = currPart.getWorks().get(planPartTable.getSelectedRow()); WorkInPlan resWork = WorkParamForm.showDialog(planPartTable, planPartTable, currWork); if (resWork != null) { currWork.setName(resWork.getName()); currWork.setDesc(resWork.getDesc()); currWork.setEndDate(resWork.getEndDate()); currWork.setReserve(resWork.getReserve()); currWork.setFinishDoc(resWork.getFinishDoc()); // Fire change ((PlanPartModel) planPartTable.getModel()).fireTableCellUpdated(planPartTable.getSelectedRow(), 0); } } } }); // savePlanBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Вначале - выбираем куда сохранять PlanUtils.savePlanToFile(); } }); loadPlanBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (PlanUtils.loadPlanFromFile()) { // Пересчитаем общую трудоемкость по всем for (Worker worker : workers) { updateTotalWorkerLabor(worker); } // Теперь еще перезапустим все модели makePlanPartTabs(); ((AbstractTableModel) workersTable.getModel()).fireTableDataChanged(); ((AbstractTableModel) planPartTable.getModel()).fireTableDataChanged(); ((AbstractTableModel) workersInPlanTable.getModel()).fireTableDataChanged(); ((AbstractTableModel) monthWorksTable.getModel()).fireTableDataChanged(); ((AbstractTableModel) monthWorkersPerWorkTable.getModel()).fireTableDataChanged(); } } }); // createNewPlanBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (JOptionPane.showConfirmDialog(null, "Вы уверены, что хотите создать новый план? Все работы текущего плана будут удалены!", "Создание нового плана", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION) { for (PlanPart part : plan) { part.getWorks().clear(); } ((PlanPartModel) planPartTable.getModel()).fireTableDataChanged(); ((WorkersInPlanTableModel) workersInPlanTable.getModel()).fireTableDataChanged(); for (Worker worker : workers) { worker.setLaborContentTotal(0.0); } ((WorkersTableModel) workersTable.getModel()).fireTableDataChanged(); } } }); printPlanBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { PlanUtils.makeQuarterPlan(); } catch (IOException e1) { JOptionPane.showMessageDialog(null, "Ошибка ввода-вывода"); } catch (TransformerException e1) { JOptionPane.showMessageDialog(null, "Ошибка сохранения XML документа"); } catch (ParserConfigurationException e1) { JOptionPane.showMessageDialog(null, "Ошибка работы с XML документом"); } } }); }
public MainForm() { // Worker worker1 = new Worker("Рогов П.А.", 0.0); workers.add(worker1); Worker worker2 = new Worker("Золотов А.В.", 0.0); workers.add(worker2); workers.add(new Worker("Полулях А.В.", 0.0)); workers.add(new Worker("Горелов А.Г.", 0.0)); workers.add(new Worker("Воронин Р.М.", 0.0)); workers.add(new Worker("Гуськов С.С.", 0.0)); workers.add(new Worker("Конев Д.С.", 0.0)); workers.add(new Worker("Шумский Ю.Н.", 0.0)); workers.add(new Worker("Мироненко Н.Л.", 0.0)); workers.add(new Worker("Мармер В.В.", -1.0)); workers.add(new Worker("Зореев В.П.", -1.0)); workers.add(new Worker("Шварцман А.М.", 0.0)); workers.add(new Worker("Никитина Н.Е.", 0.0)); workers.add(new Worker("Хехнева А.В.", 0.0)); workers.add(new Worker("Конашина О.А.", 0.0)); workers.add(new Worker("Косарев В.В.", 0.0)); // plan.add(new PlanPart("Собств.работы - новые", "1. Собственные работы (по основному процессу подразделения)")); plan.add(new PlanPart("Собств.работы - продолжение", "1а). Собственные работы (завершение работ по предыдущим квартальным планам)")); plan.add(new PlanPart("Внешн.заказчик", "3. Работы по внешней кооперации (с другими организациями)")); plan.add(new PlanPart("СМК", "4. Разработка документации по СМК")); plan.add(new PlanPart("Корр.мероприятия", "5. Корректирующие и предупреждающие действия")); // plan.get(0).getWorks().add(new WorkInPlan("Работа 1", "Описание 1\nСтрока2\n]]", "10.10.2010", "", "Предоставлено \n куча \n всего \n ]]")); plan.get(0).getWorks().get(0).getWorkersInPlan().add(new WorkerInPlan(worker1, 3.5)); plan.get(0).getWorks().get(0).getWorkersInPlan().add(new WorkerInPlan(worker2, 5.5)); plan.get(0).getWorks().add(new WorkInPlan("Работа 2", "Описание 2")); plan.get(0).getWorks().add(new WorkInPlan("Работа 3", "Описание 3")); // yearEdit.setText(new SimpleDateFormat("yyyy").format(new Date())); // makePlanPartTabs(); quarterPlan_divisions.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { if (quarterPlan_divisions.getSelectedIndex() != -1) { PlanPart currPart = plan.get(quarterPlan_divisions.getSelectedIndex()); ((PlanPartModel) planPartTable.getModel()).setPlanPart(currPart); // Сбрасываем еще список работников ((WorkersInPlanTableModel) workersInPlanTable.getModel()).clearWorkInPlan(); } } }); // workersTable.setModel(new WorkersTableModel(workers)); workersTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // PlanPartModel planPartModel = new PlanPartModel(); planPartTable.setModel(planPartModel); planPartTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); planPartModel.setPlanPart(plan.get(0)); planPartTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { PlanPart currPart = plan.get(quarterPlan_divisions.getSelectedIndex()); if ((planPartTable.getSelectedRow() > -1) && (planPartTable.getSelectedRow() < currPart.getWorks().size())) { ((WorkersInPlanTableModel) workersInPlanTable.getModel()).setWorkInPlan(currPart.getWorks().get(planPartTable.getSelectedRow())); } } }); // workersInPlanTable.setModel(new WorkersInPlanTableModel()); workersInPlanTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); TableColumn workerColumn = workersInPlanTable.getColumnModel().getColumn(0); JComboBox workerSelectCB = new JComboBox(); workerSelectCB.setModel(new DefaultComboBoxModel(workers)); workerColumn.setCellEditor(new DefaultCellEditor(workerSelectCB)); // addWorkBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { PlanPart currPart = plan.get(quarterPlan_divisions.getSelectedIndex()); currPart.getWorks().add(new WorkInPlan("", "")); ((PlanPartModel) planPartTable.getModel()).fireTableDataChanged(); ((WorkersInPlanTableModel) workersInPlanTable.getModel()).clearWorkInPlan(); } }); delWorkBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (planPartTable.getSelectedRow() != -1) { if (JOptionPane.showConfirmDialog(null, "Вы уверены что хотите удалить выбранную работу?", "Удаление", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { PlanPart currPart = plan.get(quarterPlan_divisions.getSelectedIndex()); currPart.getWorks().remove(planPartTable.getSelectedRow()); ((PlanPartModel) planPartTable.getModel()).fireTableDataChanged(); ((WorkersInPlanTableModel) workersInPlanTable.getModel()).clearWorkInPlan(); } } } }); addWorkerBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { workers.add(new Worker("", 0.0)); ((WorkersTableModel) workersTable.getModel()).fireTableDataChanged(); } }); delWorkerBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if ((workersTable.getSelectedRow() != -1) && (workersTable.getSelectedRow() < workers.size())) { // Тут вначале проверим - а может у нас этот работник фигурирует в какой работе?! Worker worker = workers.get(workersTable.getSelectedRow()); boolean presentInWork = false; for (PlanPart planPart : plan) { for (WorkInPlan work : planPart.getWorks()) { for (WorkerInPlan workerInPlan : work.getWorkersInPlan()) { if (workerInPlan.getWorker() == worker) { presentInWork = true; break; } } } } if (presentInWork) { JOptionPane.showMessageDialog(null, "Работник занят в какой-то работе. Вначале удалите его из всех работ", "Удаление работника", JOptionPane.ERROR_MESSAGE); } else { if (JOptionPane.showConfirmDialog(null, "Вы уверены, что хотите удалить выбранного работника?", "Удаление работника", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { workers.remove(worker); ((WorkersTableModel) workersTable.getModel()).fireTableDataChanged(); } } } } }); // addWorkerToWorkBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { PlanPart currPart = plan.get(quarterPlan_divisions.getSelectedIndex()); if ((planPartTable.getSelectedRow() > -1) && (planPartTable.getSelectedRow() < currPart.getWorks().size())) { WorkInPlan work = currPart.getWorks().get(planPartTable.getSelectedRow()); // Теперь надо из списка работников добавить ПЕРВОГО, кого тут нет for (Worker worker : workers) { boolean found = false; for (WorkerInPlan workerInPlan : work.getWorkersInPlan()) { if (workerInPlan.getWorker() == worker) { found = true; break; } } if (!found) { work.getWorkersInPlan().add(new WorkerInPlan(worker, 0.0)); ((WorkersInPlanTableModel) workersInPlanTable.getModel()).fireTableDataChanged(); break; } } } } }); delWorkerFromWorkBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { PlanPart currPart = plan.get(quarterPlan_divisions.getSelectedIndex()); if ((planPartTable.getSelectedRow() > -1) && (planPartTable.getSelectedRow() < currPart.getWorks().size())) { WorkInPlan work = currPart.getWorks().get(planPartTable.getSelectedRow()); if ((workersInPlanTable.getSelectedRow() > -1) && (workersInPlanTable.getSelectedRow() < work.getWorkersInPlan().size())) { if (JOptionPane.showConfirmDialog(null, "Вы уверены, что хотите удалить выбранного работника из работы?", "Удаление работника из работы", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { WorkerInPlan worker = work.getWorkersInPlan().get(workersInPlanTable.getSelectedRow()); work.getWorkersInPlan().remove(worker); ((WorkersInPlanTableModel) workersInPlanTable.getModel()).fireTableDataChanged(); } } } } }); moveUpPlanPartBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { movePlanPart(-1); } }); moveDownPlanPartBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { movePlanPart(1); } }); // quarterComboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { switch (quarterComboBox.getSelectedIndex()) { case 0: { monthTabbedPane.setTitleAt(0, "Январь"); monthTabbedPane.setTitleAt(1, "Февраль"); monthTabbedPane.setTitleAt(2, "Март"); break; } case 1: { monthTabbedPane.setTitleAt(0, "Апрель"); monthTabbedPane.setTitleAt(1, "Май"); monthTabbedPane.setTitleAt(2, "Июнь"); break; } case 2: { monthTabbedPane.setTitleAt(0, "Июль"); monthTabbedPane.setTitleAt(1, "Август"); monthTabbedPane.setTitleAt(2, "Сентябрь"); break; } case 3: { monthTabbedPane.setTitleAt(0, "Октябрь"); monthTabbedPane.setTitleAt(1, "Ноябрь"); monthTabbedPane.setTitleAt(2, "Декабрь"); break; } } } }); quarterComboBox.setSelectedIndex(0); // monthTabbedPane.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { if ((monthTabbedPane.getSelectedIndex() > -1) && (monthTabbedPane.getSelectedIndex() < 4)) { ((MonthWorksTableModel) monthWorksTable.getModel()).setMonth(monthTabbedPane.getSelectedIndex()); int i = monthWorksTable.getSelectedRow(); ((MonthWorksTableModel) monthWorksTable.getModel()).fireTableDataChanged(); if (i > -1) monthWorksTable.getSelectionModel().setSelectionInterval(i, i); ((MonthWorkersTableModel) monthWorkersPerWorkTable.getModel()).setMonth(monthTabbedPane.getSelectedIndex()); } } }); monthTabbedPane.setSelectedIndex(0); // quarterPlan_month.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { if (quarterPlan_month.getSelectedIndex() != -1) { PlanPart currPart = plan.get(quarterPlan_month.getSelectedIndex()); ((MonthWorksTableModel) monthWorksTable.getModel()).setPlanPart(currPart); // Сбрасываем еще список работников ((MonthWorkersTableModel) monthWorkersPerWorkTable.getModel()).clearWorkInPlan(); } } }); // monthWorkersPerWorkTable.setModel(new MonthWorkersTableModel()); monthWorkersPerWorkTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // MonthWorksTableModel monthWorksTableModel = new MonthWorksTableModel(); monthWorksTable.setModel(monthWorksTableModel); monthWorksTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); monthWorksTableModel.setPlanPart(plan.get(0)); monthWorksTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { PlanPart currPart = plan.get(quarterPlan_month.getSelectedIndex()); if ((monthWorksTable.getSelectedRow() > -1) && (monthWorksTable.getSelectedRow() < currPart.getWorks().size())) { ((MonthWorkersTableModel) monthWorkersPerWorkTable.getModel()).setWorkInPlan(currPart.getWorks().get(monthWorksTable.getSelectedRow())); } } }); kindWorksTabbedPane.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { // Запустим обновление всего чего можно тама... ((MonthWorksTableModel) monthWorksTable.getModel()).fireTableDataChanged(); ((MonthWorkersTableModel) monthWorkersPerWorkTable.getModel()).clearWorkInPlan(); } }); // editWorkBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { PlanPart currPart = plan.get(quarterPlan_divisions.getSelectedIndex()); if ((planPartTable.getSelectedRow() > -1) && (planPartTable.getSelectedRow() < currPart.getWorks().size())) { WorkInPlan currWork = currPart.getWorks().get(planPartTable.getSelectedRow()); WorkInPlan resWork = WorkParamForm.showDialog(planPartTable, planPartTable, currWork); if (resWork != null) { currWork.setName(resWork.getName()); currWork.setDesc(resWork.getDesc()); currWork.setEndDate(resWork.getEndDate()); currWork.setReserve(resWork.getReserve()); currWork.setFinishDoc(resWork.getFinishDoc()); // Fire change ((PlanPartModel) planPartTable.getModel()).fireTableCellUpdated(planPartTable.getSelectedRow(), 0); } } } }); // savePlanBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Вначале - выбираем куда сохранять PlanUtils.savePlanToFile(); } }); loadPlanBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (PlanUtils.loadPlanFromFile()) { // Пересчитаем общую трудоемкость по всем for (Worker worker : workers) { updateTotalWorkerLabor(worker); } // Теперь еще перезапустим все модели makePlanPartTabs(); ((AbstractTableModel) workersTable.getModel()).fireTableDataChanged(); ((AbstractTableModel) planPartTable.getModel()).fireTableDataChanged(); ((AbstractTableModel) workersInPlanTable.getModel()).fireTableDataChanged(); ((AbstractTableModel) monthWorksTable.getModel()).fireTableDataChanged(); ((AbstractTableModel) monthWorkersPerWorkTable.getModel()).fireTableDataChanged(); } } }); // createNewPlanBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (JOptionPane.showConfirmDialog(null, "Вы уверены, что хотите создать новый план? Все работы текущего плана будут удалены!", "Создание нового плана", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION) { for (PlanPart part : plan) { part.getWorks().clear(); } ((PlanPartModel) planPartTable.getModel()).fireTableDataChanged(); ((WorkersInPlanTableModel) workersInPlanTable.getModel()).fireTableDataChanged(); for (Worker worker : workers) { worker.setLaborContentTotal(0.0); } ((WorkersTableModel) workersTable.getModel()).fireTableDataChanged(); } } }); printPlanBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { PlanUtils.makeQuarterPlan(); ReportViewer.showPreview(kindWorksTabbedPane, kindWorksTabbedPane, "quarterPlan"); } catch (IOException e1) { JOptionPane.showMessageDialog(null, "Ошибка ввода-вывода"); } catch (TransformerException e1) { JOptionPane.showMessageDialog(null, "Ошибка сохранения XML документа"); } catch (ParserConfigurationException e1) { JOptionPane.showMessageDialog(null, "Ошибка работы с XML документом"); } } }); }
diff --git a/src/nz/gen/wellington/guardian/android/activities/ui/ArticleImageDecorator.java b/src/nz/gen/wellington/guardian/android/activities/ui/ArticleImageDecorator.java index 3e7e2fe..744fb17 100644 --- a/src/nz/gen/wellington/guardian/android/activities/ui/ArticleImageDecorator.java +++ b/src/nz/gen/wellington/guardian/android/activities/ui/ArticleImageDecorator.java @@ -1,35 +1,35 @@ package nz.gen.wellington.guardian.android.activities.ui; import java.util.ArrayList; import java.util.List; import nz.gen.wellington.guardian.android.api.ArticleDAOFactory; import nz.gen.wellington.guardian.android.api.ImageDAO; import nz.gen.wellington.guardian.android.model.Article; import nz.gen.wellington.guardian.android.model.ImageDecoratedArticle; import android.content.Context; import android.graphics.Bitmap; public class ArticleImageDecorator { public static List<ImageDecoratedArticle> decorateNewsitemsWithThumbnails(List<Article> newsitems, Context context) { List<ImageDecoratedArticle> decorated = new ArrayList<ImageDecoratedArticle>(); ImageDAO imageDAO = ArticleDAOFactory.getImageDao(context); for (Article article : newsitems) { decorated.add(applyThumbnailIfAvailableLocally(imageDAO, article)); } return decorated; } private static ImageDecoratedArticle applyThumbnailIfAvailableLocally(ImageDAO imageDAO, Article article) { Bitmap image = null; if (article.getThumbnailUrl() != null && imageDAO.isAvailableLocally(article.getThumbnailUrl())) { image = imageDAO.getImage(article.getThumbnailUrl()); } else if (article.getMainImageUrl() != null && imageDAO.isAvailableLocally(article.getMainImageUrl())) { - image = imageDAO.getImage(article.getThumbnailUrl()); + image = imageDAO.getImage(article.getMainImageUrl()); } return new ImageDecoratedArticle(article, image); } }
true
true
private static ImageDecoratedArticle applyThumbnailIfAvailableLocally(ImageDAO imageDAO, Article article) { Bitmap image = null; if (article.getThumbnailUrl() != null && imageDAO.isAvailableLocally(article.getThumbnailUrl())) { image = imageDAO.getImage(article.getThumbnailUrl()); } else if (article.getMainImageUrl() != null && imageDAO.isAvailableLocally(article.getMainImageUrl())) { image = imageDAO.getImage(article.getThumbnailUrl()); } return new ImageDecoratedArticle(article, image); }
private static ImageDecoratedArticle applyThumbnailIfAvailableLocally(ImageDAO imageDAO, Article article) { Bitmap image = null; if (article.getThumbnailUrl() != null && imageDAO.isAvailableLocally(article.getThumbnailUrl())) { image = imageDAO.getImage(article.getThumbnailUrl()); } else if (article.getMainImageUrl() != null && imageDAO.isAvailableLocally(article.getMainImageUrl())) { image = imageDAO.getImage(article.getMainImageUrl()); } return new ImageDecoratedArticle(article, image); }
diff --git a/src/ltguide/base/configuration/Configuration.java b/src/ltguide/base/configuration/Configuration.java index a14664b..45b3461 100644 --- a/src/ltguide/base/configuration/Configuration.java +++ b/src/ltguide/base/configuration/Configuration.java @@ -1,146 +1,149 @@ package ltguide.base.configuration; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import ltguide.base.Base; import ltguide.base.Debug; import ltguide.base.utils.DirUtils; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; import org.yaml.snakeyaml.error.YAMLException; public class Configuration extends YamlConfiguration { private final File file; protected final Base plugin; protected int[] oldVersion; public Configuration(final Base instance) { this(instance, "config.yml"); } public Configuration(final Base instance, final String name) { plugin = instance; file = new File(plugin.getDataFolder(), name); } public void reload() { load(); } protected void load() { boolean loaded = false; try { load(file); loaded = true; } catch (final FileNotFoundException e) {} catch (final IOException e) { plugin.logException(e, "cannot load " + file); } catch (final InvalidConfigurationException e) { - if (e.getCause() instanceof YAMLException) plugin.severe("Config file " + file + " isn't valid! " + e.getCause()); + if (e.getCause() instanceof YAMLException) { + plugin.severe("Config file " + file + " isn't valid!"); + plugin.severe("Because: " + e.getCause()); + } else if (e.getCause() == null || e.getCause() instanceof ClassCastException) plugin.severe("Config file " + file + " isn't valid!"); else plugin.logException(e, "cannot load " + file + ": " + e.getCause().getClass()); backup("invalid"); } final InputStream inStream = plugin.getResource(file.getName()); if (inStream != null) { setDefaults(YamlConfiguration.loadConfiguration(inStream)); if (!loaded) plugin.info("Writing default configuration to " + file); } if (!loaded) { options().copyDefaults(true); save(); } else upgrade(); } public void backup(final String prefix) { try { final File dest = new File(file.getParentFile(), prefix + "-" + file.getName()); plugin.info("Copying config file to " + dest); DirUtils.copyFile(file, dest); } catch (final Exception e) { plugin.logException(e, "failed to copy config"); } } private void upgrade() { if (Debug.ON) Debug.info("upgrade() " + file); final String current = plugin.getDescription().getVersion(); String old = "UNKNOWN"; if (isSet("version-nomodify")) old = getString("version-nomodify"); if (current.equals(old)) return; oldVersion = getVersionInt(old); set("version-nomodify", current); plugin.warning("Migrating " + file + " from version " + old); backup(old); migrate(); save(); } protected void migrate() { if (Debug.ON) Debug.info("Configuration migrate()"); } public void save() { try { save(file); } catch (final IOException e) { plugin.logException(e, "could not save " + file); } } protected int[] getVersionInt(final String version) { final String[] split = version.split("\\."); final int[] num = new int[split.length]; for (int i = 0; i < split.length; i++) try { num[i] = Integer.parseInt(split[i]); } catch (final NumberFormatException e) { num[i] = 0; } return num; } protected boolean versionCompare(final int... compare) { for (int i = 0; i < compare.length && i < oldVersion.length; i++) if (oldVersion[i] > compare[i]) return false; return true; } protected void fixIntRange(final ConfigurationSection cs, final String key, final int min, final int max) { final int value = cs.getInt(key); if (value < min || value > max) { cs.set(key, getDefaultSection().getInt(cs.getCurrentPath() + "." + key)); plugin.configWarning(cs, key, value + "; valid: " + min + "-" + max); } } protected void fixBoolean(final ConfigurationSection cs, final String key) { if (!cs.isBoolean(key)) { cs.set(key, getDefaultSection().getBoolean(cs.getCurrentPath() + "." + key)); plugin.configWarning(cs, key, cs.get(key) + "; valid: true/false"); } } }
true
true
protected void load() { boolean loaded = false; try { load(file); loaded = true; } catch (final FileNotFoundException e) {} catch (final IOException e) { plugin.logException(e, "cannot load " + file); } catch (final InvalidConfigurationException e) { if (e.getCause() instanceof YAMLException) plugin.severe("Config file " + file + " isn't valid! " + e.getCause()); else if (e.getCause() == null || e.getCause() instanceof ClassCastException) plugin.severe("Config file " + file + " isn't valid!"); else plugin.logException(e, "cannot load " + file + ": " + e.getCause().getClass()); backup("invalid"); } final InputStream inStream = plugin.getResource(file.getName()); if (inStream != null) { setDefaults(YamlConfiguration.loadConfiguration(inStream)); if (!loaded) plugin.info("Writing default configuration to " + file); } if (!loaded) { options().copyDefaults(true); save(); } else upgrade(); }
protected void load() { boolean loaded = false; try { load(file); loaded = true; } catch (final FileNotFoundException e) {} catch (final IOException e) { plugin.logException(e, "cannot load " + file); } catch (final InvalidConfigurationException e) { if (e.getCause() instanceof YAMLException) { plugin.severe("Config file " + file + " isn't valid!"); plugin.severe("Because: " + e.getCause()); } else if (e.getCause() == null || e.getCause() instanceof ClassCastException) plugin.severe("Config file " + file + " isn't valid!"); else plugin.logException(e, "cannot load " + file + ": " + e.getCause().getClass()); backup("invalid"); } final InputStream inStream = plugin.getResource(file.getName()); if (inStream != null) { setDefaults(YamlConfiguration.loadConfiguration(inStream)); if (!loaded) plugin.info("Writing default configuration to " + file); } if (!loaded) { options().copyDefaults(true); save(); } else upgrade(); }
diff --git a/src/CollisionManager.java b/src/CollisionManager.java index b1fcd3f..e433111 100644 --- a/src/CollisionManager.java +++ b/src/CollisionManager.java @@ -1,37 +1,37 @@ import java.util.ArrayList; public class CollisionManager { public static boolean checkAndHandleCollisions(Bird bird, ArrayList<Entity> entities, Health birdHealth) { Boolean exit = false; for (Entity entity : entities) { if(entity.colidable) { //Bird poops on shit if(entity.boundingShape.intersects(bird.getCrap().getBoundingShape()) && bird.getCrap().isActive) { entity.handleCollision(entity); bird.getCrap().handleCollision(entity); } //Bird collision with enemies if(entity.boundingShape.intersects(bird.boundingShape)) { - if (entity.boundingShape.getX() > GLOBAL.BUFFER_RIGHT){ + if (entity.boundingShape.getX() > GLOBAL.BUFFER_RIGHT + 32){ System.out.println("Avoided a collision. WHEW!"); continue; } System.out.println("Collision detected between the bird and " + entity.getName()); birdHealth.decreaseHealth(); entity.handleCollision(bird); // if health = 0 exit game. exit = !(birdHealth.isAlive()); System.out.println("Collision: Exit? " +exit); } } } return exit; } }
true
true
public static boolean checkAndHandleCollisions(Bird bird, ArrayList<Entity> entities, Health birdHealth) { Boolean exit = false; for (Entity entity : entities) { if(entity.colidable) { //Bird poops on shit if(entity.boundingShape.intersects(bird.getCrap().getBoundingShape()) && bird.getCrap().isActive) { entity.handleCollision(entity); bird.getCrap().handleCollision(entity); } //Bird collision with enemies if(entity.boundingShape.intersects(bird.boundingShape)) { if (entity.boundingShape.getX() > GLOBAL.BUFFER_RIGHT){ System.out.println("Avoided a collision. WHEW!"); continue; } System.out.println("Collision detected between the bird and " + entity.getName()); birdHealth.decreaseHealth(); entity.handleCollision(bird); // if health = 0 exit game. exit = !(birdHealth.isAlive()); System.out.println("Collision: Exit? " +exit); } } } return exit; }
public static boolean checkAndHandleCollisions(Bird bird, ArrayList<Entity> entities, Health birdHealth) { Boolean exit = false; for (Entity entity : entities) { if(entity.colidable) { //Bird poops on shit if(entity.boundingShape.intersects(bird.getCrap().getBoundingShape()) && bird.getCrap().isActive) { entity.handleCollision(entity); bird.getCrap().handleCollision(entity); } //Bird collision with enemies if(entity.boundingShape.intersects(bird.boundingShape)) { if (entity.boundingShape.getX() > GLOBAL.BUFFER_RIGHT + 32){ System.out.println("Avoided a collision. WHEW!"); continue; } System.out.println("Collision detected between the bird and " + entity.getName()); birdHealth.decreaseHealth(); entity.handleCollision(bird); // if health = 0 exit game. exit = !(birdHealth.isAlive()); System.out.println("Collision: Exit? " +exit); } } } return exit; }
diff --git a/event-bus-toposervice/src/main/java/pegasus/eventbus/topology/service/Activator.java b/event-bus-toposervice/src/main/java/pegasus/eventbus/topology/service/Activator.java index 6735a4e..ba16d11 100755 --- a/event-bus-toposervice/src/main/java/pegasus/eventbus/topology/service/Activator.java +++ b/event-bus-toposervice/src/main/java/pegasus/eventbus/topology/service/Activator.java @@ -1,53 +1,54 @@ package pegasus.eventbus.topology.service; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pegasus.eventbus.client.EventManager; import pegasus.eventbus.topology.TopologyRegistry; public class Activator implements BundleActivator { protected static final Logger LOG = LoggerFactory.getLogger(Activator.class); private static TopologyService topologyService; public void start(BundleContext bundleContext) throws Exception { LOG.info("OSGi Starting: {}", TopologyService.class.getName()); ServiceReference eventManagerServiceReference = bundleContext.getServiceReference(EventManager.class.getName()); if (eventManagerServiceReference != null) { EventManager eventManager = (EventManager) bundleContext.getService(eventManagerServiceReference); TopologyRegistry topologyRegistry = new TopologyRegistry(); ClientRegistry clientRegistry = new ClientRegistry(); RegistrationHandler registrationHandler = new RegistrationHandler(eventManager, clientRegistry, topologyRegistry); - topologyService = new TopologyService(registrationHandler); + UnknownEventTypeHandler unknownEventTypeHandler = new UnknownEventTypeHandler(eventManager, topologyRegistry); + topologyService = new TopologyService(registrationHandler, unknownEventTypeHandler); topologyService.start(); LOG.info("OSGi Started: {}", TopologyService.class.getName()); } else { LOG.error("Unable to find EventManager service."); } } public void stop(BundleContext bundleContext) throws Exception { LOG.info("OSGi Stopping: {}", TopologyService.class.getName()); if (topologyService != null) { topologyService.stop(); } LOG.info("OSGi Stopped: {}", TopologyService.class.getName()); } }
true
true
public void start(BundleContext bundleContext) throws Exception { LOG.info("OSGi Starting: {}", TopologyService.class.getName()); ServiceReference eventManagerServiceReference = bundleContext.getServiceReference(EventManager.class.getName()); if (eventManagerServiceReference != null) { EventManager eventManager = (EventManager) bundleContext.getService(eventManagerServiceReference); TopologyRegistry topologyRegistry = new TopologyRegistry(); ClientRegistry clientRegistry = new ClientRegistry(); RegistrationHandler registrationHandler = new RegistrationHandler(eventManager, clientRegistry, topologyRegistry); topologyService = new TopologyService(registrationHandler); topologyService.start(); LOG.info("OSGi Started: {}", TopologyService.class.getName()); } else { LOG.error("Unable to find EventManager service."); } }
public void start(BundleContext bundleContext) throws Exception { LOG.info("OSGi Starting: {}", TopologyService.class.getName()); ServiceReference eventManagerServiceReference = bundleContext.getServiceReference(EventManager.class.getName()); if (eventManagerServiceReference != null) { EventManager eventManager = (EventManager) bundleContext.getService(eventManagerServiceReference); TopologyRegistry topologyRegistry = new TopologyRegistry(); ClientRegistry clientRegistry = new ClientRegistry(); RegistrationHandler registrationHandler = new RegistrationHandler(eventManager, clientRegistry, topologyRegistry); UnknownEventTypeHandler unknownEventTypeHandler = new UnknownEventTypeHandler(eventManager, topologyRegistry); topologyService = new TopologyService(registrationHandler, unknownEventTypeHandler); topologyService.start(); LOG.info("OSGi Started: {}", TopologyService.class.getName()); } else { LOG.error("Unable to find EventManager service."); } }
diff --git a/src/org/openstreetmap/josm/gui/MainApplication.java b/src/org/openstreetmap/josm/gui/MainApplication.java index cd37b8ba..fdb79fac 100644 --- a/src/org/openstreetmap/josm/gui/MainApplication.java +++ b/src/org/openstreetmap/josm/gui/MainApplication.java @@ -1,226 +1,227 @@ // License: GPL. Copyright 2007 by Immanuel Scholz and others //Licence: GPL package org.openstreetmap.josm.gui; import org.xnap.commons.i18n.I18nFactory; import static org.openstreetmap.josm.tools.I18n.i18n; import static org.openstreetmap.josm.tools.I18n.tr; import java.awt.EventQueue; import java.awt.Toolkit; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import javax.swing.JFrame; import javax.swing.JOptionPane; import org.openstreetmap.josm.Main; import org.openstreetmap.josm.plugins.PluginDownloader; import org.openstreetmap.josm.tools.BugReportExceptionHandler; import org.openstreetmap.josm.tools.ImageProvider; /** * Main window class application. * * @author imi */ public class MainApplication extends Main { /** * Allow subclassing (see JOSM.java) */ public MainApplication() {} /** * Construct an main frame, ready sized and operating. Does not * display the frame. */ public MainApplication(JFrame mainFrame, SplashScreen splash) { super(splash); mainFrame.setContentPane(contentPane); mainFrame.setJMenuBar(menu); mainFrame.setBounds(bounds); mainFrame.setIconImage(ImageProvider.get("logo.png").getImage()); mainFrame.addWindowListener(new WindowAdapter(){ @Override public void windowClosing(final WindowEvent arg0) { if (Main.breakBecauseUnsavedChanges()) return; System.exit(0); } }); mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); } /** * Main application Startup */ public static void main(final String[] argArray) { ///////////////////////////////////////////////////////////////////////// // TO ALL TRANSLATORS ///////////////////////////////////////////////////////////////////////// // Do not translate the early strings below until the locale is set up. // (By the eager loaded plugins) // // These strings cannot be translated. That's life. Really. Sorry. // // Imi. ///////////////////////////////////////////////////////////////////////// Thread.setDefaultUncaughtExceptionHandler(new BugReportExceptionHandler()); // initialize the plaform hook, and Main.determinePlatformHook(); // call the really early hook before we anything else Main.platform.preStartupHook(); // construct argument table List<String> argList = Arrays.asList(argArray); final Map<String, Collection<String>> args = new HashMap<String, Collection<String>>(); for (String arg : argArray) { if (!arg.startsWith("--")) arg = "--download="+arg; int i = arg.indexOf('='); String key = i == -1 ? arg.substring(2) : arg.substring(2,i); String value = i == -1 ? "" : arg.substring(i+1); Collection<String> v = args.get(key); if (v == null) v = new LinkedList<String>(); v.add(value); args.put(key, v); } if (argList.contains("--help") || argList.contains("-?") || argList.contains("-h")) { // TODO: put in a platformHook for system that have no console by default System.out.println(tr("Java OpenStreetMap Editor")+"\n\n"+ tr("usage")+":\n"+ "\tjava -jar josm.jar <option> <option> <option>...\n\n"+ tr("options")+":\n"+ "\t--help|-?|-h "+tr("Show this help")+"\n"+ "\t--geometry=widthxheight(+|-)x(+|-)y "+tr("Standard unix geometry argument")+"\n"+ "\t[--download=]minlat,minlon,maxlat,maxlon "+tr("Download the bounding box")+"\n"+ "\t[--download=]<url> "+tr("Download the location at the url (with lat=x&lon=y&zoom=z)")+"\n"+ "\t[--download=]<filename> "+tr("Open file (as raw gps, if .gpx)")+"\n"+ "\t--downloadgps=minlat,minlon,maxlat,maxlon "+tr("Download the bounding box as raw gps")+"\n"+ "\t--selection=<searchstring> "+tr("Select with the given search")+"\n"+ "\t--no-fullscreen "+tr("Don't launch in fullscreen mode")+"\n"+ "\t--reset-preferences "+tr("Reset the preferences to default")+"\n\n"+ "\t--language=<language> "+tr("Set the language.")+"\n\n"+ tr("examples")+":\n"+ "\tjava -jar josm.jar track1.gpx track2.gpx london.osm\n"+ "\tjava -jar josm.jar http://www.openstreetmap.org/index.html?lat=43.2&lon=11.1&zoom=13\n"+ "\tjava -jar josm.jar london.osm --selection=http://www.ostertag.name/osm/OSM_errors_node-duplicate.xml\n"+ "\tjava -jar josm.jar 43.2,11.1,43.4,11.4\n\n"+ tr("Parameters are read in the order they are specified, so make sure you load\n"+ "some data before --selection")+"\n\n"+ tr("Instead of --download=<bbox> you may specify osm://<bbox>\n")); System.exit(0); } // get the preferences. final File prefDir = new File(Main.pref.getPreferencesDir()); if (prefDir.exists()) { if(!prefDir.isDirectory()) { JOptionPane.showMessageDialog(null, tr("Cannot open preferences directory: {0}",Main.pref.getPreferencesDir())); return; } } else prefDir.mkdirs(); if (!new File(Main.pref.getPreferencesDir()+"preferences").exists()) { Main.pref.resetToDefault(); } try { if (args.containsKey("reset-preferences")) { Main.pref.resetToDefault(); } else { Main.pref.load(); } } catch (final IOException e1) { e1.printStackTrace(); String backup = Main.pref.getPreferencesDir() + "preferences.bak"; JOptionPane.showMessageDialog(null, tr("Preferences file had errors. Making backup of old one to {0}.", backup)); new File(Main.pref.getPreferencesDir() + "preferences").renameTo(new File(backup)); Main.pref.save(); } String localeName = null; //The locale to use //Check if passed as parameter if(args.containsKey("language")) localeName = (String)(args.get("language").toArray()[0]); if (localeName == null) { localeName = Main.pref.get("language", null); } if (localeName != null) { + if(localeName.equals("he")) localeName = "iw_IL"; Locale l; int i = localeName.indexOf('_'); if (i > 0) { l = new Locale(localeName.substring(0, i), localeName.substring(i + 1)); } else { l = new Locale(localeName); } Locale.setDefault(l); } try { i18n = I18nFactory.getI18n(MainApplication.class); } catch (MissingResourceException ex) { if(!Locale.getDefault().getLanguage().equals("en")) { System.out.println("Unable to find translation for the locale: " + Locale.getDefault().getDisplayName() + " reverting to English."); Locale.setDefault(Locale.ENGLISH); } } SplashScreen splash = new SplashScreen(Main.pref.getBoolean("draw.splashscreen", true)); splash.setStatus(tr("Activating updated plugins")); if (!PluginDownloader.moveUpdatedPlugins()) { JOptionPane.showMessageDialog(null, tr("Activating the updated plugins failed. Check if JOSM has the permission to overwrite the existing ones."), tr("Plugins"), JOptionPane.ERROR_MESSAGE); } // load the early plugins splash.setStatus(tr("Loading early plugins")); Main.loadPlugins(true); splash.setStatus(tr("Setting defaults")); preConstructorInit(args); splash.setStatus(tr("Creating main GUI")); JFrame mainFrame = new JFrame(tr("Java OpenStreetMap Editor")); Main.parent = mainFrame; final Main main = new MainApplication(mainFrame, splash); splash.setStatus(tr("Loading plugins")); Main.loadPlugins(false); toolbar.refreshToolbarControl(); mainFrame.setVisible(true); splash.closeSplash(); if (!args.containsKey("no-fullscreen") && !args.containsKey("geometry") && Toolkit.getDefaultToolkit().isFrameStateSupported(JFrame.MAXIMIZED_BOTH)) mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH); EventQueue.invokeLater(new Runnable(){ public void run() { main.postConstructorProcessCmdLine(args); } }); } }
true
true
public static void main(final String[] argArray) { ///////////////////////////////////////////////////////////////////////// // TO ALL TRANSLATORS ///////////////////////////////////////////////////////////////////////// // Do not translate the early strings below until the locale is set up. // (By the eager loaded plugins) // // These strings cannot be translated. That's life. Really. Sorry. // // Imi. ///////////////////////////////////////////////////////////////////////// Thread.setDefaultUncaughtExceptionHandler(new BugReportExceptionHandler()); // initialize the plaform hook, and Main.determinePlatformHook(); // call the really early hook before we anything else Main.platform.preStartupHook(); // construct argument table List<String> argList = Arrays.asList(argArray); final Map<String, Collection<String>> args = new HashMap<String, Collection<String>>(); for (String arg : argArray) { if (!arg.startsWith("--")) arg = "--download="+arg; int i = arg.indexOf('='); String key = i == -1 ? arg.substring(2) : arg.substring(2,i); String value = i == -1 ? "" : arg.substring(i+1); Collection<String> v = args.get(key); if (v == null) v = new LinkedList<String>(); v.add(value); args.put(key, v); } if (argList.contains("--help") || argList.contains("-?") || argList.contains("-h")) { // TODO: put in a platformHook for system that have no console by default System.out.println(tr("Java OpenStreetMap Editor")+"\n\n"+ tr("usage")+":\n"+ "\tjava -jar josm.jar <option> <option> <option>...\n\n"+ tr("options")+":\n"+ "\t--help|-?|-h "+tr("Show this help")+"\n"+ "\t--geometry=widthxheight(+|-)x(+|-)y "+tr("Standard unix geometry argument")+"\n"+ "\t[--download=]minlat,minlon,maxlat,maxlon "+tr("Download the bounding box")+"\n"+ "\t[--download=]<url> "+tr("Download the location at the url (with lat=x&lon=y&zoom=z)")+"\n"+ "\t[--download=]<filename> "+tr("Open file (as raw gps, if .gpx)")+"\n"+ "\t--downloadgps=minlat,minlon,maxlat,maxlon "+tr("Download the bounding box as raw gps")+"\n"+ "\t--selection=<searchstring> "+tr("Select with the given search")+"\n"+ "\t--no-fullscreen "+tr("Don't launch in fullscreen mode")+"\n"+ "\t--reset-preferences "+tr("Reset the preferences to default")+"\n\n"+ "\t--language=<language> "+tr("Set the language.")+"\n\n"+ tr("examples")+":\n"+ "\tjava -jar josm.jar track1.gpx track2.gpx london.osm\n"+ "\tjava -jar josm.jar http://www.openstreetmap.org/index.html?lat=43.2&lon=11.1&zoom=13\n"+ "\tjava -jar josm.jar london.osm --selection=http://www.ostertag.name/osm/OSM_errors_node-duplicate.xml\n"+ "\tjava -jar josm.jar 43.2,11.1,43.4,11.4\n\n"+ tr("Parameters are read in the order they are specified, so make sure you load\n"+ "some data before --selection")+"\n\n"+ tr("Instead of --download=<bbox> you may specify osm://<bbox>\n")); System.exit(0); } // get the preferences. final File prefDir = new File(Main.pref.getPreferencesDir()); if (prefDir.exists()) { if(!prefDir.isDirectory()) { JOptionPane.showMessageDialog(null, tr("Cannot open preferences directory: {0}",Main.pref.getPreferencesDir())); return; } } else prefDir.mkdirs(); if (!new File(Main.pref.getPreferencesDir()+"preferences").exists()) { Main.pref.resetToDefault(); } try { if (args.containsKey("reset-preferences")) { Main.pref.resetToDefault(); } else { Main.pref.load(); } } catch (final IOException e1) { e1.printStackTrace(); String backup = Main.pref.getPreferencesDir() + "preferences.bak"; JOptionPane.showMessageDialog(null, tr("Preferences file had errors. Making backup of old one to {0}.", backup)); new File(Main.pref.getPreferencesDir() + "preferences").renameTo(new File(backup)); Main.pref.save(); } String localeName = null; //The locale to use //Check if passed as parameter if(args.containsKey("language")) localeName = (String)(args.get("language").toArray()[0]); if (localeName == null) { localeName = Main.pref.get("language", null); } if (localeName != null) { Locale l; int i = localeName.indexOf('_'); if (i > 0) { l = new Locale(localeName.substring(0, i), localeName.substring(i + 1)); } else { l = new Locale(localeName); } Locale.setDefault(l); } try { i18n = I18nFactory.getI18n(MainApplication.class); } catch (MissingResourceException ex) { if(!Locale.getDefault().getLanguage().equals("en")) { System.out.println("Unable to find translation for the locale: " + Locale.getDefault().getDisplayName() + " reverting to English."); Locale.setDefault(Locale.ENGLISH); } } SplashScreen splash = new SplashScreen(Main.pref.getBoolean("draw.splashscreen", true)); splash.setStatus(tr("Activating updated plugins")); if (!PluginDownloader.moveUpdatedPlugins()) { JOptionPane.showMessageDialog(null, tr("Activating the updated plugins failed. Check if JOSM has the permission to overwrite the existing ones."), tr("Plugins"), JOptionPane.ERROR_MESSAGE); } // load the early plugins splash.setStatus(tr("Loading early plugins")); Main.loadPlugins(true); splash.setStatus(tr("Setting defaults")); preConstructorInit(args); splash.setStatus(tr("Creating main GUI")); JFrame mainFrame = new JFrame(tr("Java OpenStreetMap Editor")); Main.parent = mainFrame; final Main main = new MainApplication(mainFrame, splash); splash.setStatus(tr("Loading plugins")); Main.loadPlugins(false); toolbar.refreshToolbarControl(); mainFrame.setVisible(true); splash.closeSplash(); if (!args.containsKey("no-fullscreen") && !args.containsKey("geometry") && Toolkit.getDefaultToolkit().isFrameStateSupported(JFrame.MAXIMIZED_BOTH)) mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH); EventQueue.invokeLater(new Runnable(){ public void run() { main.postConstructorProcessCmdLine(args); } }); }
public static void main(final String[] argArray) { ///////////////////////////////////////////////////////////////////////// // TO ALL TRANSLATORS ///////////////////////////////////////////////////////////////////////// // Do not translate the early strings below until the locale is set up. // (By the eager loaded plugins) // // These strings cannot be translated. That's life. Really. Sorry. // // Imi. ///////////////////////////////////////////////////////////////////////// Thread.setDefaultUncaughtExceptionHandler(new BugReportExceptionHandler()); // initialize the plaform hook, and Main.determinePlatformHook(); // call the really early hook before we anything else Main.platform.preStartupHook(); // construct argument table List<String> argList = Arrays.asList(argArray); final Map<String, Collection<String>> args = new HashMap<String, Collection<String>>(); for (String arg : argArray) { if (!arg.startsWith("--")) arg = "--download="+arg; int i = arg.indexOf('='); String key = i == -1 ? arg.substring(2) : arg.substring(2,i); String value = i == -1 ? "" : arg.substring(i+1); Collection<String> v = args.get(key); if (v == null) v = new LinkedList<String>(); v.add(value); args.put(key, v); } if (argList.contains("--help") || argList.contains("-?") || argList.contains("-h")) { // TODO: put in a platformHook for system that have no console by default System.out.println(tr("Java OpenStreetMap Editor")+"\n\n"+ tr("usage")+":\n"+ "\tjava -jar josm.jar <option> <option> <option>...\n\n"+ tr("options")+":\n"+ "\t--help|-?|-h "+tr("Show this help")+"\n"+ "\t--geometry=widthxheight(+|-)x(+|-)y "+tr("Standard unix geometry argument")+"\n"+ "\t[--download=]minlat,minlon,maxlat,maxlon "+tr("Download the bounding box")+"\n"+ "\t[--download=]<url> "+tr("Download the location at the url (with lat=x&lon=y&zoom=z)")+"\n"+ "\t[--download=]<filename> "+tr("Open file (as raw gps, if .gpx)")+"\n"+ "\t--downloadgps=minlat,minlon,maxlat,maxlon "+tr("Download the bounding box as raw gps")+"\n"+ "\t--selection=<searchstring> "+tr("Select with the given search")+"\n"+ "\t--no-fullscreen "+tr("Don't launch in fullscreen mode")+"\n"+ "\t--reset-preferences "+tr("Reset the preferences to default")+"\n\n"+ "\t--language=<language> "+tr("Set the language.")+"\n\n"+ tr("examples")+":\n"+ "\tjava -jar josm.jar track1.gpx track2.gpx london.osm\n"+ "\tjava -jar josm.jar http://www.openstreetmap.org/index.html?lat=43.2&lon=11.1&zoom=13\n"+ "\tjava -jar josm.jar london.osm --selection=http://www.ostertag.name/osm/OSM_errors_node-duplicate.xml\n"+ "\tjava -jar josm.jar 43.2,11.1,43.4,11.4\n\n"+ tr("Parameters are read in the order they are specified, so make sure you load\n"+ "some data before --selection")+"\n\n"+ tr("Instead of --download=<bbox> you may specify osm://<bbox>\n")); System.exit(0); } // get the preferences. final File prefDir = new File(Main.pref.getPreferencesDir()); if (prefDir.exists()) { if(!prefDir.isDirectory()) { JOptionPane.showMessageDialog(null, tr("Cannot open preferences directory: {0}",Main.pref.getPreferencesDir())); return; } } else prefDir.mkdirs(); if (!new File(Main.pref.getPreferencesDir()+"preferences").exists()) { Main.pref.resetToDefault(); } try { if (args.containsKey("reset-preferences")) { Main.pref.resetToDefault(); } else { Main.pref.load(); } } catch (final IOException e1) { e1.printStackTrace(); String backup = Main.pref.getPreferencesDir() + "preferences.bak"; JOptionPane.showMessageDialog(null, tr("Preferences file had errors. Making backup of old one to {0}.", backup)); new File(Main.pref.getPreferencesDir() + "preferences").renameTo(new File(backup)); Main.pref.save(); } String localeName = null; //The locale to use //Check if passed as parameter if(args.containsKey("language")) localeName = (String)(args.get("language").toArray()[0]); if (localeName == null) { localeName = Main.pref.get("language", null); } if (localeName != null) { if(localeName.equals("he")) localeName = "iw_IL"; Locale l; int i = localeName.indexOf('_'); if (i > 0) { l = new Locale(localeName.substring(0, i), localeName.substring(i + 1)); } else { l = new Locale(localeName); } Locale.setDefault(l); } try { i18n = I18nFactory.getI18n(MainApplication.class); } catch (MissingResourceException ex) { if(!Locale.getDefault().getLanguage().equals("en")) { System.out.println("Unable to find translation for the locale: " + Locale.getDefault().getDisplayName() + " reverting to English."); Locale.setDefault(Locale.ENGLISH); } } SplashScreen splash = new SplashScreen(Main.pref.getBoolean("draw.splashscreen", true)); splash.setStatus(tr("Activating updated plugins")); if (!PluginDownloader.moveUpdatedPlugins()) { JOptionPane.showMessageDialog(null, tr("Activating the updated plugins failed. Check if JOSM has the permission to overwrite the existing ones."), tr("Plugins"), JOptionPane.ERROR_MESSAGE); } // load the early plugins splash.setStatus(tr("Loading early plugins")); Main.loadPlugins(true); splash.setStatus(tr("Setting defaults")); preConstructorInit(args); splash.setStatus(tr("Creating main GUI")); JFrame mainFrame = new JFrame(tr("Java OpenStreetMap Editor")); Main.parent = mainFrame; final Main main = new MainApplication(mainFrame, splash); splash.setStatus(tr("Loading plugins")); Main.loadPlugins(false); toolbar.refreshToolbarControl(); mainFrame.setVisible(true); splash.closeSplash(); if (!args.containsKey("no-fullscreen") && !args.containsKey("geometry") && Toolkit.getDefaultToolkit().isFrameStateSupported(JFrame.MAXIMIZED_BOTH)) mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH); EventQueue.invokeLater(new Runnable(){ public void run() { main.postConstructorProcessCmdLine(args); } }); }
diff --git a/libcore/tools/runner/java/dalvik/runner/Dx.java b/libcore/tools/runner/java/dalvik/runner/Dx.java index 83f126552..d36a99d28 100644 --- a/libcore/tools/runner/java/dalvik/runner/Dx.java +++ b/libcore/tools/runner/java/dalvik/runner/Dx.java @@ -1,32 +1,37 @@ /* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dalvik.runner; /** * A dx command. */ final class Dx { public void dex(String output, Classpath classpath) { + // We pass --core-library so that we can write tests in the same package they're testing, + // even when that's a core library package. If you're actually just using this tool to + // execute arbitrary code, this has the unfortunate side-effect of preventing "dx" from + // protecting you from yourself. new Command.Builder() .args("dx") + .args("--core-library") .args("--dex") .args("--output=" + output) .args(Strings.objectsToStrings(classpath.getElements())) .execute(); } }
false
true
public void dex(String output, Classpath classpath) { new Command.Builder() .args("dx") .args("--dex") .args("--output=" + output) .args(Strings.objectsToStrings(classpath.getElements())) .execute(); }
public void dex(String output, Classpath classpath) { // We pass --core-library so that we can write tests in the same package they're testing, // even when that's a core library package. If you're actually just using this tool to // execute arbitrary code, this has the unfortunate side-effect of preventing "dx" from // protecting you from yourself. new Command.Builder() .args("dx") .args("--core-library") .args("--dex") .args("--output=" + output) .args(Strings.objectsToStrings(classpath.getElements())) .execute(); }
diff --git a/src/main/groovy/ui/text/GroovyFilter.java b/src/main/groovy/ui/text/GroovyFilter.java index d7db17f6d..94b74cd0b 100644 --- a/src/main/groovy/ui/text/GroovyFilter.java +++ b/src/main/groovy/ui/text/GroovyFilter.java @@ -1,263 +1,259 @@ /* * GroovyFilter.java * * Copyright (c) 2004, 2007 Evan A Slatis * * 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 groovy.ui.text; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.KeyStroke; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultStyledDocument; import javax.swing.text.Element; import javax.swing.text.JTextComponent; import javax.swing.text.Segment; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; import javax.swing.text.StyleContext; /** * * @author hippy */ public class GroovyFilter extends StructuredSyntaxDocumentFilter { // java tab policy action private static final Action AutoTabAction = new AutoTabAction(); // Style names public static final String COMMENT = "comment"; public static final String SLASH_STAR_COMMENT = "/\\*(?s:.)*?(?:\\*/|\\z)"; public static final String SLASH_SLASH_COMMENT = "//.*"; public static final String QUOTES = "(?ms:\"{3}(?!\\\"{1,3}).*?(?:\"{3}|\\z))|(?:\"{1}(?!\\\").*?(?:\"|\\Z))"; public static final String SINGLE_QUOTES = "(?ms:'{3}(?!'{1,3}).*?(?:'{3}|\\z))|(?:'[^'].*?(?:'|\\z))"; public static final String SLASHY_QUOTES = "/[^/*].*?/"; public static final String DIGIT = "\\d+?[efld]?"; public static final String IDENT = "[\\w\\$&&[\\D]][\\w\\$]*"; public static final String OPERATION = "[\\w\\$&&[\\D]][\\w\\$]* *\\("; public static final String LEFT_PARENS = "\\("; private static final Color COMMENT_COLOR = Color.LIGHT_GRAY.darker().darker(); public static final String RESERVED_WORD = "reserved"; public static final String[] RESERVED_WORDS = {"\\babstract\\b", "\\bassert\\b", "\\bdefault\\b", "\\bif\\b", "\\bprivate\\b", "\\bthis\\b", "\\bboolean\\b", "\\bdo\\b", "\\bimplements\\b", "\\bprotected\\b", "\\bthrow\\b", "\\bbreak\\b", "\\bdouble\\b", "\\bimport\\b", "\\bpublic\\b", "\\bthrows\\b", "\\bbyte\\b", "\\belse\\b", "\\binstanceof\\b", "\\breturn\\b", "\\btransient\\b", "\\bcase\\b", "\\bextends\\b", "\\bint\\b", "\\bshort\\b", "\\btry\\b", "\\bcatch\\b", "\\bfinal\\b", "\\binterface\\b", "\\benum\\b", "\\bstatic\\b", "\\bvoid\\b", "\\bchar\\b", "\\bfinally\\b", "\\blong\\b", "\\bstrictfp\\b", "\\bvolatile\\b", "\\bclass\\b", "\\bfloat\\b", "\\bnative\\b", "\\bsuper\\b", "\\bwhile\\b", "\\bconst\\b", "\\bfor\\b", "\\bnew\\b", "\\bswitch\\b", "\\bcontinue\\b", "\\bgoto\\b", "\\bpackage\\b", "\\bdef\\b", "\\bas\\b", "\\bin\\b", "\\bsynchronized\\b", "\\bnull\\b"}; /** * Creates a new instance of GroovyFilter */ public GroovyFilter(DefaultStyledDocument doc) { super(doc); init(); } private void init() { StyleContext styleContext = StyleContext.getDefaultStyleContext(); Style defaultStyle = styleContext.getStyle(StyleContext.DEFAULT_STYLE); - StyleConstants.setFontFamily(defaultStyle, - StructuredSyntaxResources.EDITOR_FONT.getFamily()); - StyleConstants.setFontSize(defaultStyle, - StructuredSyntaxResources.EDITOR_FONT.getSize()); Style comment = styleContext.addStyle(COMMENT, defaultStyle); StyleConstants.setForeground(comment, COMMENT_COLOR); StyleConstants.setItalic(comment, true); Style quotes = styleContext.addStyle(QUOTES, defaultStyle); StyleConstants.setForeground(quotes, Color.MAGENTA.darker().darker()); Style charQuotes = styleContext.addStyle(SINGLE_QUOTES, defaultStyle); StyleConstants.setForeground(charQuotes, Color.GREEN.darker().darker()); Style slashyQuotes = styleContext.addStyle(SLASHY_QUOTES, defaultStyle); StyleConstants.setForeground(slashyQuotes, Color.ORANGE.darker()); Style digit = styleContext.addStyle(DIGIT, defaultStyle); StyleConstants.setForeground(digit, Color.RED.darker()); Style operation = styleContext.addStyle(OPERATION, defaultStyle); StyleConstants.setBold(operation, true); Style ident = styleContext.addStyle(IDENT, defaultStyle); Style reservedWords = styleContext.addStyle(RESERVED_WORD, defaultStyle); StyleConstants.setBold(reservedWords, true); StyleConstants.setForeground(reservedWords, Color.BLUE.darker().darker()); Style leftParens = styleContext.addStyle(IDENT, defaultStyle); getRootNode().putStyle(SLASH_STAR_COMMENT, comment); getRootNode().putStyle(SLASH_SLASH_COMMENT, comment); getRootNode().putStyle(QUOTES, quotes); getRootNode().putStyle(SINGLE_QUOTES, charQuotes); getRootNode().putStyle(SLASHY_QUOTES, slashyQuotes); getRootNode().putStyle(DIGIT, digit); getRootNode().putStyle(OPERATION, operation); StructuredSyntaxDocumentFilter.LexerNode node = createLexerNode(); node.putStyle(RESERVED_WORDS, reservedWords); node.putStyle(LEFT_PARENS, leftParens); getRootNode().putChild(OPERATION, node); getRootNode().putStyle(IDENT, ident); node = createLexerNode(); node.putStyle(RESERVED_WORDS, reservedWords); getRootNode().putChild(IDENT, node); } public static void installAutoTabAction(JTextComponent tComp) { tComp.getActionMap().put("GroovyFilter-autoTab", AutoTabAction); KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false); tComp.getInputMap().put(keyStroke, "GroovyFilter-autoTab"); } private static class AutoTabAction extends AbstractAction { private StyledDocument doc; private Segment segment = new Segment(); private StringBuffer buffer = new StringBuffer(); public void actionPerformed(ActionEvent ae) { JTextComponent tComp = (JTextComponent)ae.getSource(); if (tComp.getDocument() instanceof StyledDocument) { doc = (StyledDocument)tComp.getDocument(); try { doc.getText(0, doc.getLength(), segment); } catch (Exception e) { // should NEVER reach here e.printStackTrace(); } int offset = tComp.getCaretPosition(); int index = findTabLocation(offset); buffer.delete(0, buffer.length()); buffer.append('\n'); if (index > -1) { for (int i = 0; i < index + 4; i++) { buffer.append(' '); } } try { doc.insertString(offset, buffer.toString(), doc.getDefaultRootElement().getAttributes()); } catch (BadLocationException ble) { ble.printStackTrace(); } } } public int findTabLocation(int offset) { // find first { boolean cont = true; while (offset > -1 && cont) { Element el = doc.getCharacterElement(offset); Object color = el.getAttributes().getAttribute(StyleConstants.Foreground); if (!COMMENT_COLOR.equals(color)) { cont = segment.array[offset] != '{' && segment.array[offset] != '}'; } offset -= cont ? 1 : 0; } if (offset > -1 && segment.array[offset] == '{') { while (offset > -1 && !Character.isWhitespace(segment.array[offset--])){ } } int index = offset < 0 || segment.array[offset] == '}' ? -4 : 0; if (offset > -1) { Element top = doc.getDefaultRootElement(); offset = top.getElement(top.getElementIndex(offset)).getStartOffset(); while (Character.isWhitespace(segment.array[offset++])) { index++; } } return index; } } }
true
true
private void init() { StyleContext styleContext = StyleContext.getDefaultStyleContext(); Style defaultStyle = styleContext.getStyle(StyleContext.DEFAULT_STYLE); StyleConstants.setFontFamily(defaultStyle, StructuredSyntaxResources.EDITOR_FONT.getFamily()); StyleConstants.setFontSize(defaultStyle, StructuredSyntaxResources.EDITOR_FONT.getSize()); Style comment = styleContext.addStyle(COMMENT, defaultStyle); StyleConstants.setForeground(comment, COMMENT_COLOR); StyleConstants.setItalic(comment, true); Style quotes = styleContext.addStyle(QUOTES, defaultStyle); StyleConstants.setForeground(quotes, Color.MAGENTA.darker().darker()); Style charQuotes = styleContext.addStyle(SINGLE_QUOTES, defaultStyle); StyleConstants.setForeground(charQuotes, Color.GREEN.darker().darker()); Style slashyQuotes = styleContext.addStyle(SLASHY_QUOTES, defaultStyle); StyleConstants.setForeground(slashyQuotes, Color.ORANGE.darker()); Style digit = styleContext.addStyle(DIGIT, defaultStyle); StyleConstants.setForeground(digit, Color.RED.darker()); Style operation = styleContext.addStyle(OPERATION, defaultStyle); StyleConstants.setBold(operation, true); Style ident = styleContext.addStyle(IDENT, defaultStyle); Style reservedWords = styleContext.addStyle(RESERVED_WORD, defaultStyle); StyleConstants.setBold(reservedWords, true); StyleConstants.setForeground(reservedWords, Color.BLUE.darker().darker()); Style leftParens = styleContext.addStyle(IDENT, defaultStyle); getRootNode().putStyle(SLASH_STAR_COMMENT, comment); getRootNode().putStyle(SLASH_SLASH_COMMENT, comment); getRootNode().putStyle(QUOTES, quotes); getRootNode().putStyle(SINGLE_QUOTES, charQuotes); getRootNode().putStyle(SLASHY_QUOTES, slashyQuotes); getRootNode().putStyle(DIGIT, digit); getRootNode().putStyle(OPERATION, operation); StructuredSyntaxDocumentFilter.LexerNode node = createLexerNode(); node.putStyle(RESERVED_WORDS, reservedWords); node.putStyle(LEFT_PARENS, leftParens); getRootNode().putChild(OPERATION, node); getRootNode().putStyle(IDENT, ident); node = createLexerNode(); node.putStyle(RESERVED_WORDS, reservedWords); getRootNode().putChild(IDENT, node); }
private void init() { StyleContext styleContext = StyleContext.getDefaultStyleContext(); Style defaultStyle = styleContext.getStyle(StyleContext.DEFAULT_STYLE); Style comment = styleContext.addStyle(COMMENT, defaultStyle); StyleConstants.setForeground(comment, COMMENT_COLOR); StyleConstants.setItalic(comment, true); Style quotes = styleContext.addStyle(QUOTES, defaultStyle); StyleConstants.setForeground(quotes, Color.MAGENTA.darker().darker()); Style charQuotes = styleContext.addStyle(SINGLE_QUOTES, defaultStyle); StyleConstants.setForeground(charQuotes, Color.GREEN.darker().darker()); Style slashyQuotes = styleContext.addStyle(SLASHY_QUOTES, defaultStyle); StyleConstants.setForeground(slashyQuotes, Color.ORANGE.darker()); Style digit = styleContext.addStyle(DIGIT, defaultStyle); StyleConstants.setForeground(digit, Color.RED.darker()); Style operation = styleContext.addStyle(OPERATION, defaultStyle); StyleConstants.setBold(operation, true); Style ident = styleContext.addStyle(IDENT, defaultStyle); Style reservedWords = styleContext.addStyle(RESERVED_WORD, defaultStyle); StyleConstants.setBold(reservedWords, true); StyleConstants.setForeground(reservedWords, Color.BLUE.darker().darker()); Style leftParens = styleContext.addStyle(IDENT, defaultStyle); getRootNode().putStyle(SLASH_STAR_COMMENT, comment); getRootNode().putStyle(SLASH_SLASH_COMMENT, comment); getRootNode().putStyle(QUOTES, quotes); getRootNode().putStyle(SINGLE_QUOTES, charQuotes); getRootNode().putStyle(SLASHY_QUOTES, slashyQuotes); getRootNode().putStyle(DIGIT, digit); getRootNode().putStyle(OPERATION, operation); StructuredSyntaxDocumentFilter.LexerNode node = createLexerNode(); node.putStyle(RESERVED_WORDS, reservedWords); node.putStyle(LEFT_PARENS, leftParens); getRootNode().putChild(OPERATION, node); getRootNode().putStyle(IDENT, ident); node = createLexerNode(); node.putStyle(RESERVED_WORDS, reservedWords); getRootNode().putChild(IDENT, node); }
diff --git a/src/main/java/org/primefaces/mobile/renderkit/DataListRenderer.java b/src/main/java/org/primefaces/mobile/renderkit/DataListRenderer.java index a28ec6f..7b8e453 100644 --- a/src/main/java/org/primefaces/mobile/renderkit/DataListRenderer.java +++ b/src/main/java/org/primefaces/mobile/renderkit/DataListRenderer.java @@ -1,212 +1,210 @@ /* * Copyright 2009-2011 Prime Technology. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.primefaces.mobile.renderkit; import java.io.IOException; import java.util.Iterator; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import org.primefaces.component.datalist.DataList; import org.primefaces.component.separator.Separator; import org.primefaces.renderkit.CoreRenderer; import org.primefaces.util.WidgetBuilder; public class DataListRenderer extends CoreRenderer { @Override public void encodeEnd(FacesContext context, UIComponent component) throws IOException { DataList dataList = (DataList) component; if (dataList.isPaginationRequest(context)) { dataList.updatePaginationData(context, dataList); if(dataList.isLazy()) { dataList.loadLazyData(); } encodeLoadMore(context, dataList); } else { encodeMarkup(context, dataList); encodeScript(context, dataList); } } protected void encodeMarkup(FacesContext context, DataList dataList) throws IOException { if(dataList.isLazy()) { dataList.loadLazyData(); } ResponseWriter writer = context.getResponseWriter(); UIComponent header = dataList.getHeader(); UIComponent footer = dataList.getFooter(); String type = dataList.getType(); Object filterValue = dataList.getAttributes().get("filter"); Object placeholder = dataList.getAttributes().get("placeholder"); Object autodividers = dataList.getAttributes().get("autoDividers"); Object autoComplete = dataList.getAttributes().get("autoComplete"); Object icon = dataList.getAttributes().get("icon"); Object iconSplit = dataList.getAttributes().get("iconSplit"); Object swatch = (String) dataList.getAttributes().get("swatch"); Object dividerSwatch = (String) dataList.getAttributes().get("dividerSwatch"); String iconType = (iconSplit != null && Boolean.valueOf(iconSplit.toString())) ? "data-split-icon" : "data-icon"; writer.startElement("ul", dataList); writer.writeAttribute("id", dataList.getClientId(context), "id"); if(dataList.getStyle() != null) writer.writeAttribute("style", dataList.getStyle(), null); if(dataList.getStyleClass() != null) writer.writeAttribute("class", dataList.getStyleClass(), null); writer.writeAttribute("data-role", "listview", null); if(filterValue != null && Boolean.valueOf(filterValue.toString())) writer.writeAttribute("data-filter", "true", null); if(placeholder != null) writer.writeAttribute("data-filter-placeholder", placeholder, null); if(autodividers != null && Boolean.valueOf(autodividers.toString())) writer.writeAttribute("data-autodividers", "true", null); if(autoComplete != null && Boolean.valueOf(autoComplete.toString())) writer.writeAttribute("data-filter-reveal", "true", null); if(icon != null) writer.writeAttribute(iconType, icon, null); if(type != null && type.equals("inset")) writer.writeAttribute("data-inset", true, null); if(swatch != null) writer.writeAttribute("data-theme", swatch, null); if(dividerSwatch != null) writer.writeAttribute("data-divider-theme", dividerSwatch, null); if(header != null) { writer.startElement("li", null); writer.writeAttribute("data-role", "list-divider", null); header.encodeAll(context); writer.endElement("li"); } int rowCount = dataList.getRowCount(); if(dataList.getVar() != null) { - if (dataList.isPaginator() && rowCount != 0) { + if (dataList.isPaginator() && rowCount > dataList.getRows()) { rowCount = dataList.getRows(); } - for(int i = 0; i < rowCount; i++) { + for (int i = 0; i < rowCount; i++) { dataList.setRowIndex(i); - if (dataList.isRowAvailable()) { - writer.startElement("li", null); - renderChildren(context, dataList); - writer.endElement("li"); - } + writer.startElement("li", null); + renderChildren(context, dataList); + writer.endElement("li"); } } else { for(UIComponent child : dataList.getChildren()) { if(child.isRendered()) { writer.startElement("li", dataList); if(child instanceof Separator) { writer.writeAttribute("data-role", "list-divider", null); renderChildren(context, child); } else { Object iconLi = child.getAttributes().get("icon"); Object filterText = child.getAttributes().get("filterText"); if(iconLi != null) writer.writeAttribute("data-icon", iconLi, null); if (filterText != null) writer.writeAttribute("data-filtertext", filterText, null); child.encodeAll(context); } writer.endElement("li"); } } } if (footer != null) { writer.startElement("div", null); writer.writeAttribute("style", "margin-top: 20px;text-align: center;", null); footer.encodeAll(context); writer.endElement("div"); } if (dataList.isPaginator() && (dataList.getRows() < dataList.getRowCount())) { encodePaginatorButton(context, dataList); } writer.endElement("ul"); dataList.setRowIndex(-1); } protected void encodePaginatorButton(FacesContext context, DataList dataList) throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = dataList.getClientId(context) + "_btn"; Object paginatorText = (dataList.getAttributes().get("paginatorText") == null) ? "More" : dataList.getAttributes().get("paginatorText"); writer.startElement("a", dataList); writer.writeAttribute("id", clientId, null); writer.writeAttribute("data-role", "button", null); writer.writeAttribute("style", "margin-top: 20px", null); writer.writeText(paginatorText, null); writer.endElement("a"); } protected void encodeLoadMore(FacesContext context, DataList dataList) throws IOException { ResponseWriter writer = context.getResponseWriter(); for (int i = dataList.getFirst(); i < (dataList.getFirst() + dataList.getRows()); i++) { dataList.setRowIndex(i); if (dataList.isRowAvailable()) { writer.startElement("li", null); renderChildren(context, dataList); writer.endElement("li"); } } dataList.setRowIndex(-1); } protected void encodeScript(FacesContext context, DataList dataList) throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = dataList.getClientId(context); WidgetBuilder wb = getWidgetBuilder(context); wb.widget("DataList", dataList.resolveWidgetVar(), clientId, true) .attr("isPaginator", dataList.isPaginator()) .attr("scrollStep", dataList.getRows()) .attr("scrollLimit", dataList.getRowCount()); startScript(writer, clientId); writer.write(wb.build()); endScript(writer); } @Override protected void renderChildren(FacesContext context, UIComponent component) throws IOException { ResponseWriter writer = context.getResponseWriter(); for (Iterator<UIComponent> iterator = component.getChildren().iterator(); iterator.hasNext();) { UIComponent child = (UIComponent) iterator.next(); Object iconLi = child.getAttributes().get("icon"); Object filterText = child.getAttributes().get("filterText"); if (iconLi != null) { writer.writeAttribute("data-icon", iconLi, null); } if (filterText != null) { writer.writeAttribute("data-filtertext", filterText, null); } renderChild(context, child); } } @Override public void encodeChildren(FacesContext context, UIComponent component) throws IOException { //Do Nothing } @Override public boolean getRendersChildren() { return true; } }
false
true
protected void encodeMarkup(FacesContext context, DataList dataList) throws IOException { if(dataList.isLazy()) { dataList.loadLazyData(); } ResponseWriter writer = context.getResponseWriter(); UIComponent header = dataList.getHeader(); UIComponent footer = dataList.getFooter(); String type = dataList.getType(); Object filterValue = dataList.getAttributes().get("filter"); Object placeholder = dataList.getAttributes().get("placeholder"); Object autodividers = dataList.getAttributes().get("autoDividers"); Object autoComplete = dataList.getAttributes().get("autoComplete"); Object icon = dataList.getAttributes().get("icon"); Object iconSplit = dataList.getAttributes().get("iconSplit"); Object swatch = (String) dataList.getAttributes().get("swatch"); Object dividerSwatch = (String) dataList.getAttributes().get("dividerSwatch"); String iconType = (iconSplit != null && Boolean.valueOf(iconSplit.toString())) ? "data-split-icon" : "data-icon"; writer.startElement("ul", dataList); writer.writeAttribute("id", dataList.getClientId(context), "id"); if(dataList.getStyle() != null) writer.writeAttribute("style", dataList.getStyle(), null); if(dataList.getStyleClass() != null) writer.writeAttribute("class", dataList.getStyleClass(), null); writer.writeAttribute("data-role", "listview", null); if(filterValue != null && Boolean.valueOf(filterValue.toString())) writer.writeAttribute("data-filter", "true", null); if(placeholder != null) writer.writeAttribute("data-filter-placeholder", placeholder, null); if(autodividers != null && Boolean.valueOf(autodividers.toString())) writer.writeAttribute("data-autodividers", "true", null); if(autoComplete != null && Boolean.valueOf(autoComplete.toString())) writer.writeAttribute("data-filter-reveal", "true", null); if(icon != null) writer.writeAttribute(iconType, icon, null); if(type != null && type.equals("inset")) writer.writeAttribute("data-inset", true, null); if(swatch != null) writer.writeAttribute("data-theme", swatch, null); if(dividerSwatch != null) writer.writeAttribute("data-divider-theme", dividerSwatch, null); if(header != null) { writer.startElement("li", null); writer.writeAttribute("data-role", "list-divider", null); header.encodeAll(context); writer.endElement("li"); } int rowCount = dataList.getRowCount(); if(dataList.getVar() != null) { if (dataList.isPaginator() && rowCount != 0) { rowCount = dataList.getRows(); } for(int i = 0; i < rowCount; i++) { dataList.setRowIndex(i); if (dataList.isRowAvailable()) { writer.startElement("li", null); renderChildren(context, dataList); writer.endElement("li"); } } } else { for(UIComponent child : dataList.getChildren()) { if(child.isRendered()) { writer.startElement("li", dataList); if(child instanceof Separator) { writer.writeAttribute("data-role", "list-divider", null); renderChildren(context, child); } else { Object iconLi = child.getAttributes().get("icon"); Object filterText = child.getAttributes().get("filterText"); if(iconLi != null) writer.writeAttribute("data-icon", iconLi, null); if (filterText != null) writer.writeAttribute("data-filtertext", filterText, null); child.encodeAll(context); } writer.endElement("li"); } } } if (footer != null) { writer.startElement("div", null); writer.writeAttribute("style", "margin-top: 20px;text-align: center;", null); footer.encodeAll(context); writer.endElement("div"); } if (dataList.isPaginator() && (dataList.getRows() < dataList.getRowCount())) { encodePaginatorButton(context, dataList); } writer.endElement("ul"); dataList.setRowIndex(-1); }
protected void encodeMarkup(FacesContext context, DataList dataList) throws IOException { if(dataList.isLazy()) { dataList.loadLazyData(); } ResponseWriter writer = context.getResponseWriter(); UIComponent header = dataList.getHeader(); UIComponent footer = dataList.getFooter(); String type = dataList.getType(); Object filterValue = dataList.getAttributes().get("filter"); Object placeholder = dataList.getAttributes().get("placeholder"); Object autodividers = dataList.getAttributes().get("autoDividers"); Object autoComplete = dataList.getAttributes().get("autoComplete"); Object icon = dataList.getAttributes().get("icon"); Object iconSplit = dataList.getAttributes().get("iconSplit"); Object swatch = (String) dataList.getAttributes().get("swatch"); Object dividerSwatch = (String) dataList.getAttributes().get("dividerSwatch"); String iconType = (iconSplit != null && Boolean.valueOf(iconSplit.toString())) ? "data-split-icon" : "data-icon"; writer.startElement("ul", dataList); writer.writeAttribute("id", dataList.getClientId(context), "id"); if(dataList.getStyle() != null) writer.writeAttribute("style", dataList.getStyle(), null); if(dataList.getStyleClass() != null) writer.writeAttribute("class", dataList.getStyleClass(), null); writer.writeAttribute("data-role", "listview", null); if(filterValue != null && Boolean.valueOf(filterValue.toString())) writer.writeAttribute("data-filter", "true", null); if(placeholder != null) writer.writeAttribute("data-filter-placeholder", placeholder, null); if(autodividers != null && Boolean.valueOf(autodividers.toString())) writer.writeAttribute("data-autodividers", "true", null); if(autoComplete != null && Boolean.valueOf(autoComplete.toString())) writer.writeAttribute("data-filter-reveal", "true", null); if(icon != null) writer.writeAttribute(iconType, icon, null); if(type != null && type.equals("inset")) writer.writeAttribute("data-inset", true, null); if(swatch != null) writer.writeAttribute("data-theme", swatch, null); if(dividerSwatch != null) writer.writeAttribute("data-divider-theme", dividerSwatch, null); if(header != null) { writer.startElement("li", null); writer.writeAttribute("data-role", "list-divider", null); header.encodeAll(context); writer.endElement("li"); } int rowCount = dataList.getRowCount(); if(dataList.getVar() != null) { if (dataList.isPaginator() && rowCount > dataList.getRows()) { rowCount = dataList.getRows(); } for (int i = 0; i < rowCount; i++) { dataList.setRowIndex(i); writer.startElement("li", null); renderChildren(context, dataList); writer.endElement("li"); } } else { for(UIComponent child : dataList.getChildren()) { if(child.isRendered()) { writer.startElement("li", dataList); if(child instanceof Separator) { writer.writeAttribute("data-role", "list-divider", null); renderChildren(context, child); } else { Object iconLi = child.getAttributes().get("icon"); Object filterText = child.getAttributes().get("filterText"); if(iconLi != null) writer.writeAttribute("data-icon", iconLi, null); if (filterText != null) writer.writeAttribute("data-filtertext", filterText, null); child.encodeAll(context); } writer.endElement("li"); } } } if (footer != null) { writer.startElement("div", null); writer.writeAttribute("style", "margin-top: 20px;text-align: center;", null); footer.encodeAll(context); writer.endElement("div"); } if (dataList.isPaginator() && (dataList.getRows() < dataList.getRowCount())) { encodePaginatorButton(context, dataList); } writer.endElement("ul"); dataList.setRowIndex(-1); }
diff --git a/src/play/modules/jpagen/Generator.java b/src/play/modules/jpagen/Generator.java index da006e4..6b35d07 100644 --- a/src/play/modules/jpagen/Generator.java +++ b/src/play/modules/jpagen/Generator.java @@ -1,308 +1,308 @@ package play.modules.jpagen; import java.io.File; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import play.Logger; import play.Play; import play.libs.IO; import play.templates.GroovyTemplateCompiler; import play.templates.JavaExtensions; import play.templates.Template; import play.vfs.VirtualFile; public class Generator { private static List<String> keyword = new ArrayList<String>(); public static void main(String[] args) throws Exception { // Load all forbidden keywords init(); try { // init Play Framework File root = new File(System.getProperty("application.path")); Play.init(root, System.getProperty("play.id", "")); Thread.currentThread().setContextClassLoader(Play.classloader); // Load properties String driver = Play.configuration.getProperty("db.driver"); String url = Play.configuration.getProperty("db.url"); String user = Play.configuration.getProperty("db.user"); String password = Play.configuration.getProperty("db.pass", ""); String temp = Play.configuration.getProperty("db.default.schema", ""); String[] schemas = null; if (temp.length() > 0) { schemas = temp.split(","); } String mode = Play.configuration.getProperty("jpagen.mode"); if (mode == null || mode.trim().length() == 0) { throw new ExceptionInInitializerError("ERROR: Parameter jpagen.mode is mandatory!"); } if (ModeEnum.valueOf(mode.toUpperCase()) == null) { throw new ExceptionInInitializerError("ERROR: Parameter jpagen.mode provided is not supported: MYSQL or ORACLE only!"); } String packageName = Play.configuration.getProperty("jpagen.package.name", "models"); String templatePath = Play.configuration.getProperty("jpagen.template.entity", "jpagen/entity.tmpl"); String templateIdPath = Play.configuration.getProperty("jpagen.template.idClass", "jpagen/idClass.tmpl"); Logger.info("driver: %s url: %s user: %s password: %s", driver, url, user, password); // Open DB Connection SimpleDB db = new SimpleDB(driver, url, user, password); Connection con = db.getConnection(); // Entity template VirtualFile templateFile = VirtualFile.search(Play.templatesPath, templatePath); Logger.info("templateFile: %s", templateFile.getName()); GroovyTemplateCompiler compiler1 = new GroovyTemplateCompiler(); Template entityTemplate = compiler1.compile(templateFile); // Composite Key template VirtualFile templateIdFile = VirtualFile.search(Play.templatesPath, templateIdPath); Logger.info("templateIdFile: %s", templateIdFile.getName()); GroovyTemplateCompiler compiler2 = new GroovyTemplateCompiler(); Template idTemplate = compiler2.compile(templateIdFile); // Get table list from conf/table_list.conf or from metadata DatabaseMetaData meta = con.getMetaData(); List<String> tableList = new ArrayList<String>(); if (Play.getVirtualFile("conf/table_list.conf").exists()) { Logger.info("Using table_list.conf"); tableList = IO.readLines(Play.getFile("conf/table_list.conf")); Logger.info("TableList contains %s lines (including comments and empty lines)", tableList.size()); } else { Logger.info("Using metadata"); ResultSet rs = null; if (schemas != null) { for (String schema : schemas) { rs = meta.getTables(null, schema, null, new String[] { "TABLE" }); while (rs.next()) { tableList.add(schema + "." + rs.getString("TABLE_NAME")); } rs.close(); } } else { rs = meta.getTables(null, null, null, new String[] { "TABLE" }); while (rs.next()) { tableList.add(rs.getString("TABLE_NAME")); } rs.close(); } } int count = 0; int idCount = 0; int skipCount = 0; int skipIdCount = 0; // Iterate over table list for (String tableName : tableList) { if (tableName == null || tableName.trim().length() == 0 || tableName.startsWith("#")) { Logger.debug("skipping line..."); continue; } String schema = ""; if (tableName.indexOf(".") > 0) { Logger.info("tableName: %s", tableName); String[] names = tableName.split("\\."); Logger.debug("%s", Arrays.asList(names)); schema = names[0]; tableName = names[1]; }else{ Logger.info("No schema for table %s", tableName); } Logger.debug("Working on table %s", schema + "." + tableName); Table table = new Table(); table.tableName = tableName; table.packageName = packageName; - table.className = JavaExtensions.camelCase(table.tableName.replaceAll("_", " ")); + table.className = JavaExtensions.camelCase(table.tableName.toLowerCase().replaceAll("_", " ")); List<String> keys = new ArrayList<String>(); ResultSet rsKeys = meta.getPrimaryKeys(null, (schema.length() == 0 ? null : schema), tableName); while (rsKeys.next()) { String key = rsKeys.getString("COLUMN_NAME"); keys.add(key); Logger.info("Table: %s, primaryKey: %s", (schema.length() > 0 ? schema + "." : "") + tableName, key); } rsKeys.close(); if (keys.size() == 0) { table.isIdLess = true; table.extend = "Model"; } PreparedStatement ps = null; if (mode.equalsIgnoreCase(ModeEnum.MYSQL.name())) { ps = con.prepareStatement("select * from " + (schema.length() > 0 ? schema + "." : "") + tableName + " limit 0"); } if (mode.equalsIgnoreCase(ModeEnum.ORACLE.name())) { ps = con.prepareStatement("select * from " + (schema.length() > 0 ? schema + "." : "") + tableName + " where rownum < 2"); } ResultSet rs = ps.executeQuery(); ResultSetMetaData tm = rs.getMetaData(); // Setting Composite Keys class IdClass idClass = new IdClass(); idClass.className = table.className + "Id"; idClass.packageName = table.packageName; // Iterating on columns int cc = tm.getColumnCount(); for (int i = 1; i <= cc; i++) { Column column = new Column(); column.columnName = tm.getColumnName(i); column.columnType = tm.getColumnClassName(i).substring(tm.getColumnClassName(i).lastIndexOf(".") + 1); if (column.columnType.equals("[B")) { Logger.error("BLOB??? %s", tm.getColumnClassName(i)); column.columnType = "Blob"; } if (column.columnType.equals("String")) { column.max = tm.getPrecision(i); } column.columnPropertyName = JavaExtensions.camelCase(column.columnName.toLowerCase().replaceAll("_", " ")); column.columnPropertyName = normalizeColumnName(column.columnPropertyName.substring(0, 1).toLowerCase() + column.columnPropertyName.substring(1)); if (tm.isNullable(i) == tm.columnNoNulls) { column.nullable = false; } if (keys.contains(column.columnName)) { column.primary = true; if (keys.size() > 1) { idClass.keys.add(column); } } if (column.columnPropertyName.equals("id")) { table.extend = "GenericModel"; } table.columns.add(column); } rs.close(); ps.close(); // Composite Key if (keys.size() > 1) { table.idClass = table.className + "Id.class"; Logger.info("Key: %s", idClass.className); String relativePath = "app/" + packageName.replace('.', '/') + "/" + table.className + "Id.java"; if (!VirtualFile.fromRelativePath(relativePath).exists()) { File idFile = VirtualFile.fromRelativePath(relativePath).getRealFile(); Map<String, Object> params = new HashMap<String, Object>(); params.put("idClass", idClass); String output = idTemplate.render(params); IO.writeContent(output, idFile); idCount++; } else { skipIdCount++; Logger.warn("File %s already exists...NOT OVERWRITING", relativePath); } } // Entity String relativePath = "app/" + packageName.replace('.', '/') + "/" + table.className + ".java"; if (!VirtualFile.fromRelativePath(relativePath).exists()) { Map<String, Object> params = new HashMap<String, Object>(); params.put("table", table); String output = entityTemplate.render(params); File entityFile = VirtualFile.fromRelativePath(relativePath).getRealFile(); IO.writeContent(output, entityFile); count++; } else { skipCount++; Logger.warn("File %s already exists...NOT OVERWRITING", relativePath); } Logger.debug("Table done: %s", tableName); } db.close(); Logger.info("Process finished: %s Entities and %s Composite Keys generated", count, idCount); Logger.warn("%s Entities and %s Composite Keys SKIPPED", skipCount, skipIdCount); } catch (Exception e) { Logger.error(e, e.getMessage()); } System.exit(0); } private static String normalizeColumnName(String column) { if (keyword.contains(column)) { return column + "Col"; } else { return column; } } private static void init() { keyword.add("abstract"); keyword.add("assert"); keyword.add("boolean"); keyword.add("break"); keyword.add("byte"); keyword.add("case"); keyword.add("catch"); keyword.add("char"); keyword.add("class"); keyword.add("const"); keyword.add("continue"); keyword.add("default"); keyword.add("do"); keyword.add("double"); keyword.add("else"); keyword.add("entityId"); keyword.add("enum"); keyword.add("extends"); keyword.add("final"); keyword.add("finally"); keyword.add("float"); keyword.add("for"); keyword.add("goto"); keyword.add("if"); keyword.add("implements"); keyword.add("import"); keyword.add("instanceof"); keyword.add("int"); keyword.add("interface"); keyword.add("long"); keyword.add("native"); keyword.add("new"); keyword.add("package"); keyword.add("private"); keyword.add("protected"); keyword.add("public"); keyword.add("return"); keyword.add("short"); keyword.add("static"); keyword.add("strictfp"); keyword.add("super"); keyword.add("switch"); keyword.add("synchronized"); keyword.add("this"); keyword.add("throw"); keyword.add("throws"); keyword.add("transient"); keyword.add("try"); keyword.add("void"); keyword.add("volatile"); keyword.add("while"); } }
true
true
public static void main(String[] args) throws Exception { // Load all forbidden keywords init(); try { // init Play Framework File root = new File(System.getProperty("application.path")); Play.init(root, System.getProperty("play.id", "")); Thread.currentThread().setContextClassLoader(Play.classloader); // Load properties String driver = Play.configuration.getProperty("db.driver"); String url = Play.configuration.getProperty("db.url"); String user = Play.configuration.getProperty("db.user"); String password = Play.configuration.getProperty("db.pass", ""); String temp = Play.configuration.getProperty("db.default.schema", ""); String[] schemas = null; if (temp.length() > 0) { schemas = temp.split(","); } String mode = Play.configuration.getProperty("jpagen.mode"); if (mode == null || mode.trim().length() == 0) { throw new ExceptionInInitializerError("ERROR: Parameter jpagen.mode is mandatory!"); } if (ModeEnum.valueOf(mode.toUpperCase()) == null) { throw new ExceptionInInitializerError("ERROR: Parameter jpagen.mode provided is not supported: MYSQL or ORACLE only!"); } String packageName = Play.configuration.getProperty("jpagen.package.name", "models"); String templatePath = Play.configuration.getProperty("jpagen.template.entity", "jpagen/entity.tmpl"); String templateIdPath = Play.configuration.getProperty("jpagen.template.idClass", "jpagen/idClass.tmpl"); Logger.info("driver: %s url: %s user: %s password: %s", driver, url, user, password); // Open DB Connection SimpleDB db = new SimpleDB(driver, url, user, password); Connection con = db.getConnection(); // Entity template VirtualFile templateFile = VirtualFile.search(Play.templatesPath, templatePath); Logger.info("templateFile: %s", templateFile.getName()); GroovyTemplateCompiler compiler1 = new GroovyTemplateCompiler(); Template entityTemplate = compiler1.compile(templateFile); // Composite Key template VirtualFile templateIdFile = VirtualFile.search(Play.templatesPath, templateIdPath); Logger.info("templateIdFile: %s", templateIdFile.getName()); GroovyTemplateCompiler compiler2 = new GroovyTemplateCompiler(); Template idTemplate = compiler2.compile(templateIdFile); // Get table list from conf/table_list.conf or from metadata DatabaseMetaData meta = con.getMetaData(); List<String> tableList = new ArrayList<String>(); if (Play.getVirtualFile("conf/table_list.conf").exists()) { Logger.info("Using table_list.conf"); tableList = IO.readLines(Play.getFile("conf/table_list.conf")); Logger.info("TableList contains %s lines (including comments and empty lines)", tableList.size()); } else { Logger.info("Using metadata"); ResultSet rs = null; if (schemas != null) { for (String schema : schemas) { rs = meta.getTables(null, schema, null, new String[] { "TABLE" }); while (rs.next()) { tableList.add(schema + "." + rs.getString("TABLE_NAME")); } rs.close(); } } else { rs = meta.getTables(null, null, null, new String[] { "TABLE" }); while (rs.next()) { tableList.add(rs.getString("TABLE_NAME")); } rs.close(); } } int count = 0; int idCount = 0; int skipCount = 0; int skipIdCount = 0; // Iterate over table list for (String tableName : tableList) { if (tableName == null || tableName.trim().length() == 0 || tableName.startsWith("#")) { Logger.debug("skipping line..."); continue; } String schema = ""; if (tableName.indexOf(".") > 0) { Logger.info("tableName: %s", tableName); String[] names = tableName.split("\\."); Logger.debug("%s", Arrays.asList(names)); schema = names[0]; tableName = names[1]; }else{ Logger.info("No schema for table %s", tableName); } Logger.debug("Working on table %s", schema + "." + tableName); Table table = new Table(); table.tableName = tableName; table.packageName = packageName; table.className = JavaExtensions.camelCase(table.tableName.replaceAll("_", " ")); List<String> keys = new ArrayList<String>(); ResultSet rsKeys = meta.getPrimaryKeys(null, (schema.length() == 0 ? null : schema), tableName); while (rsKeys.next()) { String key = rsKeys.getString("COLUMN_NAME"); keys.add(key); Logger.info("Table: %s, primaryKey: %s", (schema.length() > 0 ? schema + "." : "") + tableName, key); } rsKeys.close(); if (keys.size() == 0) { table.isIdLess = true; table.extend = "Model"; } PreparedStatement ps = null; if (mode.equalsIgnoreCase(ModeEnum.MYSQL.name())) { ps = con.prepareStatement("select * from " + (schema.length() > 0 ? schema + "." : "") + tableName + " limit 0"); } if (mode.equalsIgnoreCase(ModeEnum.ORACLE.name())) { ps = con.prepareStatement("select * from " + (schema.length() > 0 ? schema + "." : "") + tableName + " where rownum < 2"); } ResultSet rs = ps.executeQuery(); ResultSetMetaData tm = rs.getMetaData(); // Setting Composite Keys class IdClass idClass = new IdClass(); idClass.className = table.className + "Id"; idClass.packageName = table.packageName; // Iterating on columns int cc = tm.getColumnCount(); for (int i = 1; i <= cc; i++) { Column column = new Column(); column.columnName = tm.getColumnName(i); column.columnType = tm.getColumnClassName(i).substring(tm.getColumnClassName(i).lastIndexOf(".") + 1); if (column.columnType.equals("[B")) { Logger.error("BLOB??? %s", tm.getColumnClassName(i)); column.columnType = "Blob"; } if (column.columnType.equals("String")) { column.max = tm.getPrecision(i); } column.columnPropertyName = JavaExtensions.camelCase(column.columnName.toLowerCase().replaceAll("_", " ")); column.columnPropertyName = normalizeColumnName(column.columnPropertyName.substring(0, 1).toLowerCase() + column.columnPropertyName.substring(1)); if (tm.isNullable(i) == tm.columnNoNulls) { column.nullable = false; } if (keys.contains(column.columnName)) { column.primary = true; if (keys.size() > 1) { idClass.keys.add(column); } } if (column.columnPropertyName.equals("id")) { table.extend = "GenericModel"; } table.columns.add(column); } rs.close(); ps.close(); // Composite Key if (keys.size() > 1) { table.idClass = table.className + "Id.class"; Logger.info("Key: %s", idClass.className); String relativePath = "app/" + packageName.replace('.', '/') + "/" + table.className + "Id.java"; if (!VirtualFile.fromRelativePath(relativePath).exists()) { File idFile = VirtualFile.fromRelativePath(relativePath).getRealFile(); Map<String, Object> params = new HashMap<String, Object>(); params.put("idClass", idClass); String output = idTemplate.render(params); IO.writeContent(output, idFile); idCount++; } else { skipIdCount++; Logger.warn("File %s already exists...NOT OVERWRITING", relativePath); } } // Entity String relativePath = "app/" + packageName.replace('.', '/') + "/" + table.className + ".java"; if (!VirtualFile.fromRelativePath(relativePath).exists()) { Map<String, Object> params = new HashMap<String, Object>(); params.put("table", table); String output = entityTemplate.render(params); File entityFile = VirtualFile.fromRelativePath(relativePath).getRealFile(); IO.writeContent(output, entityFile); count++; } else { skipCount++; Logger.warn("File %s already exists...NOT OVERWRITING", relativePath); } Logger.debug("Table done: %s", tableName); } db.close(); Logger.info("Process finished: %s Entities and %s Composite Keys generated", count, idCount); Logger.warn("%s Entities and %s Composite Keys SKIPPED", skipCount, skipIdCount); } catch (Exception e) { Logger.error(e, e.getMessage()); } System.exit(0); }
public static void main(String[] args) throws Exception { // Load all forbidden keywords init(); try { // init Play Framework File root = new File(System.getProperty("application.path")); Play.init(root, System.getProperty("play.id", "")); Thread.currentThread().setContextClassLoader(Play.classloader); // Load properties String driver = Play.configuration.getProperty("db.driver"); String url = Play.configuration.getProperty("db.url"); String user = Play.configuration.getProperty("db.user"); String password = Play.configuration.getProperty("db.pass", ""); String temp = Play.configuration.getProperty("db.default.schema", ""); String[] schemas = null; if (temp.length() > 0) { schemas = temp.split(","); } String mode = Play.configuration.getProperty("jpagen.mode"); if (mode == null || mode.trim().length() == 0) { throw new ExceptionInInitializerError("ERROR: Parameter jpagen.mode is mandatory!"); } if (ModeEnum.valueOf(mode.toUpperCase()) == null) { throw new ExceptionInInitializerError("ERROR: Parameter jpagen.mode provided is not supported: MYSQL or ORACLE only!"); } String packageName = Play.configuration.getProperty("jpagen.package.name", "models"); String templatePath = Play.configuration.getProperty("jpagen.template.entity", "jpagen/entity.tmpl"); String templateIdPath = Play.configuration.getProperty("jpagen.template.idClass", "jpagen/idClass.tmpl"); Logger.info("driver: %s url: %s user: %s password: %s", driver, url, user, password); // Open DB Connection SimpleDB db = new SimpleDB(driver, url, user, password); Connection con = db.getConnection(); // Entity template VirtualFile templateFile = VirtualFile.search(Play.templatesPath, templatePath); Logger.info("templateFile: %s", templateFile.getName()); GroovyTemplateCompiler compiler1 = new GroovyTemplateCompiler(); Template entityTemplate = compiler1.compile(templateFile); // Composite Key template VirtualFile templateIdFile = VirtualFile.search(Play.templatesPath, templateIdPath); Logger.info("templateIdFile: %s", templateIdFile.getName()); GroovyTemplateCompiler compiler2 = new GroovyTemplateCompiler(); Template idTemplate = compiler2.compile(templateIdFile); // Get table list from conf/table_list.conf or from metadata DatabaseMetaData meta = con.getMetaData(); List<String> tableList = new ArrayList<String>(); if (Play.getVirtualFile("conf/table_list.conf").exists()) { Logger.info("Using table_list.conf"); tableList = IO.readLines(Play.getFile("conf/table_list.conf")); Logger.info("TableList contains %s lines (including comments and empty lines)", tableList.size()); } else { Logger.info("Using metadata"); ResultSet rs = null; if (schemas != null) { for (String schema : schemas) { rs = meta.getTables(null, schema, null, new String[] { "TABLE" }); while (rs.next()) { tableList.add(schema + "." + rs.getString("TABLE_NAME")); } rs.close(); } } else { rs = meta.getTables(null, null, null, new String[] { "TABLE" }); while (rs.next()) { tableList.add(rs.getString("TABLE_NAME")); } rs.close(); } } int count = 0; int idCount = 0; int skipCount = 0; int skipIdCount = 0; // Iterate over table list for (String tableName : tableList) { if (tableName == null || tableName.trim().length() == 0 || tableName.startsWith("#")) { Logger.debug("skipping line..."); continue; } String schema = ""; if (tableName.indexOf(".") > 0) { Logger.info("tableName: %s", tableName); String[] names = tableName.split("\\."); Logger.debug("%s", Arrays.asList(names)); schema = names[0]; tableName = names[1]; }else{ Logger.info("No schema for table %s", tableName); } Logger.debug("Working on table %s", schema + "." + tableName); Table table = new Table(); table.tableName = tableName; table.packageName = packageName; table.className = JavaExtensions.camelCase(table.tableName.toLowerCase().replaceAll("_", " ")); List<String> keys = new ArrayList<String>(); ResultSet rsKeys = meta.getPrimaryKeys(null, (schema.length() == 0 ? null : schema), tableName); while (rsKeys.next()) { String key = rsKeys.getString("COLUMN_NAME"); keys.add(key); Logger.info("Table: %s, primaryKey: %s", (schema.length() > 0 ? schema + "." : "") + tableName, key); } rsKeys.close(); if (keys.size() == 0) { table.isIdLess = true; table.extend = "Model"; } PreparedStatement ps = null; if (mode.equalsIgnoreCase(ModeEnum.MYSQL.name())) { ps = con.prepareStatement("select * from " + (schema.length() > 0 ? schema + "." : "") + tableName + " limit 0"); } if (mode.equalsIgnoreCase(ModeEnum.ORACLE.name())) { ps = con.prepareStatement("select * from " + (schema.length() > 0 ? schema + "." : "") + tableName + " where rownum < 2"); } ResultSet rs = ps.executeQuery(); ResultSetMetaData tm = rs.getMetaData(); // Setting Composite Keys class IdClass idClass = new IdClass(); idClass.className = table.className + "Id"; idClass.packageName = table.packageName; // Iterating on columns int cc = tm.getColumnCount(); for (int i = 1; i <= cc; i++) { Column column = new Column(); column.columnName = tm.getColumnName(i); column.columnType = tm.getColumnClassName(i).substring(tm.getColumnClassName(i).lastIndexOf(".") + 1); if (column.columnType.equals("[B")) { Logger.error("BLOB??? %s", tm.getColumnClassName(i)); column.columnType = "Blob"; } if (column.columnType.equals("String")) { column.max = tm.getPrecision(i); } column.columnPropertyName = JavaExtensions.camelCase(column.columnName.toLowerCase().replaceAll("_", " ")); column.columnPropertyName = normalizeColumnName(column.columnPropertyName.substring(0, 1).toLowerCase() + column.columnPropertyName.substring(1)); if (tm.isNullable(i) == tm.columnNoNulls) { column.nullable = false; } if (keys.contains(column.columnName)) { column.primary = true; if (keys.size() > 1) { idClass.keys.add(column); } } if (column.columnPropertyName.equals("id")) { table.extend = "GenericModel"; } table.columns.add(column); } rs.close(); ps.close(); // Composite Key if (keys.size() > 1) { table.idClass = table.className + "Id.class"; Logger.info("Key: %s", idClass.className); String relativePath = "app/" + packageName.replace('.', '/') + "/" + table.className + "Id.java"; if (!VirtualFile.fromRelativePath(relativePath).exists()) { File idFile = VirtualFile.fromRelativePath(relativePath).getRealFile(); Map<String, Object> params = new HashMap<String, Object>(); params.put("idClass", idClass); String output = idTemplate.render(params); IO.writeContent(output, idFile); idCount++; } else { skipIdCount++; Logger.warn("File %s already exists...NOT OVERWRITING", relativePath); } } // Entity String relativePath = "app/" + packageName.replace('.', '/') + "/" + table.className + ".java"; if (!VirtualFile.fromRelativePath(relativePath).exists()) { Map<String, Object> params = new HashMap<String, Object>(); params.put("table", table); String output = entityTemplate.render(params); File entityFile = VirtualFile.fromRelativePath(relativePath).getRealFile(); IO.writeContent(output, entityFile); count++; } else { skipCount++; Logger.warn("File %s already exists...NOT OVERWRITING", relativePath); } Logger.debug("Table done: %s", tableName); } db.close(); Logger.info("Process finished: %s Entities and %s Composite Keys generated", count, idCount); Logger.warn("%s Entities and %s Composite Keys SKIPPED", skipCount, skipIdCount); } catch (Exception e) { Logger.error(e, e.getMessage()); } System.exit(0); }
diff --git a/liquibase-core/src/main/java/liquibase/sqlgenerator/core/SetTableRemarksGenerator.java b/liquibase-core/src/main/java/liquibase/sqlgenerator/core/SetTableRemarksGenerator.java index 7f70fcce..53586795 100644 --- a/liquibase-core/src/main/java/liquibase/sqlgenerator/core/SetTableRemarksGenerator.java +++ b/liquibase-core/src/main/java/liquibase/sqlgenerator/core/SetTableRemarksGenerator.java @@ -1,41 +1,42 @@ package liquibase.sqlgenerator.core; import liquibase.database.Database; import liquibase.database.core.MySQLDatabase; import liquibase.database.core.OracleDatabase; import liquibase.exception.ValidationErrors; import liquibase.sql.Sql; import liquibase.sql.UnparsedSql; import liquibase.sqlgenerator.SqlGenerator; import liquibase.sqlgenerator.SqlGeneratorChain; import liquibase.statement.core.SetTableRemarksStatement; public class SetTableRemarksGenerator implements SqlGenerator<SetTableRemarksStatement> { public int getPriority() { return PRIORITY_DEFAULT; } public boolean supports(SetTableRemarksStatement statement, Database database) { return database instanceof MySQLDatabase || database instanceof OracleDatabase; } public ValidationErrors validate(SetTableRemarksStatement setTableRemarksStatement, Database database, SqlGeneratorChain sqlGeneratorChain) { ValidationErrors validationErrors = new ValidationErrors(); validationErrors.checkRequiredField("tableName", setTableRemarksStatement.getTableName()); validationErrors.checkRequiredField("remarks", setTableRemarksStatement.getRemarks()); return validationErrors; } public Sql[] generateSql(SetTableRemarksStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { String sql; + String remarks = database.escapeStringForDatabase(statement.getRemarks()); if (database instanceof OracleDatabase) { - sql = "COMMENT ON TABLE "+database.escapeTableName(statement.getSchemaName(), statement.getTableName())+" IS '"+statement.getRemarks()+"'"; + sql = "COMMENT ON TABLE "+database.escapeTableName(statement.getSchemaName(), statement.getTableName())+" IS '"+remarks+"'"; } else { - sql = "ALTER TABLE "+database.escapeTableName(statement.getSchemaName(), statement.getTableName())+" COMMENT = '"+statement.getRemarks()+"'"; + sql = "ALTER TABLE "+database.escapeTableName(statement.getSchemaName(), statement.getTableName())+" COMMENT = '"+remarks+"'"; } return new Sql[] { new UnparsedSql(sql) }; } }
false
true
public Sql[] generateSql(SetTableRemarksStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { String sql; if (database instanceof OracleDatabase) { sql = "COMMENT ON TABLE "+database.escapeTableName(statement.getSchemaName(), statement.getTableName())+" IS '"+statement.getRemarks()+"'"; } else { sql = "ALTER TABLE "+database.escapeTableName(statement.getSchemaName(), statement.getTableName())+" COMMENT = '"+statement.getRemarks()+"'"; } return new Sql[] { new UnparsedSql(sql) }; }
public Sql[] generateSql(SetTableRemarksStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { String sql; String remarks = database.escapeStringForDatabase(statement.getRemarks()); if (database instanceof OracleDatabase) { sql = "COMMENT ON TABLE "+database.escapeTableName(statement.getSchemaName(), statement.getTableName())+" IS '"+remarks+"'"; } else { sql = "ALTER TABLE "+database.escapeTableName(statement.getSchemaName(), statement.getTableName())+" COMMENT = '"+remarks+"'"; } return new Sql[] { new UnparsedSql(sql) }; }
diff --git a/src/java/davmail/imap/ImapConnection.java b/src/java/davmail/imap/ImapConnection.java index 5c62a50..e677c31 100644 --- a/src/java/davmail/imap/ImapConnection.java +++ b/src/java/davmail/imap/ImapConnection.java @@ -1,1711 +1,1711 @@ /* * DavMail POP/IMAP/SMTP/CalDav/LDAP Exchange Gateway * Copyright (C) 2009 Mickael Guessant * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package davmail.imap; import com.sun.mail.imap.protocol.BASE64MailboxDecoder; import com.sun.mail.imap.protocol.BASE64MailboxEncoder; import davmail.AbstractConnection; import davmail.BundleMessage; import davmail.DavGateway; import davmail.Settings; import davmail.exception.DavMailException; import davmail.exception.HttpForbiddenException; import davmail.exception.HttpNotFoundException; import davmail.exception.InsufficientStorageException; import davmail.exchange.ExchangeSession; import davmail.exchange.ExchangeSessionFactory; import davmail.ui.tray.DavGatewayTray; import davmail.util.IOUtil; import davmail.util.StringUtil; import org.apache.commons.httpclient.HttpException; import org.apache.log4j.Logger; import javax.mail.MessagingException; import javax.mail.internet.*; import javax.mail.util.SharedByteArrayInputStream; import java.io.*; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * Dav Gateway smtp connection implementation. * Still alpha code : need to find a way to handle message ids */ public class ImapConnection extends AbstractConnection { private static final Logger LOGGER = Logger.getLogger(ImapConnection.class); protected String baseMailboxPath; ExchangeSession.Folder currentFolder; /** * Initialize the streams and start the thread. * * @param clientSocket IMAP client socket */ public ImapConnection(Socket clientSocket) { super(ImapConnection.class.getSimpleName(), clientSocket, null); } @Override public void run() { final String capabilities; int imapIdleDelay = Settings.getIntProperty("davmail.imapIdleDelay") * 60; if (imapIdleDelay > 0) { capabilities = "CAPABILITY IMAP4REV1 AUTH=LOGIN IDLE"; } else { capabilities = "CAPABILITY IMAP4REV1 AUTH=LOGIN"; } String line; String commandId = null; IMAPTokenizer tokens; try { ExchangeSessionFactory.checkConfig(); - sendClient("* OK [" + capabilities + "] IMAP4rev1 DavMail " + DavGateway.getCurrentVersion() + "server ready"); + sendClient("* OK [" + capabilities + "] IMAP4rev1 DavMail " + DavGateway.getCurrentVersion() + " server ready"); for (; ;) { line = readClient(); // unable to read line, connection closed ? if (line == null) { break; } tokens = new IMAPTokenizer(line); if (tokens.hasMoreTokens()) { commandId = tokens.nextToken(); if (tokens.hasMoreTokens()) { String command = tokens.nextToken(); if ("LOGOUT".equalsIgnoreCase(command)) { sendClient("* BYE Closing connection"); break; } if ("capability".equalsIgnoreCase(command)) { sendClient("* " + capabilities); sendClient(commandId + " OK CAPABILITY completed"); } else if ("login".equalsIgnoreCase(command)) { parseCredentials(tokens); // detect shared mailbox access splitUserName(); try { session = ExchangeSessionFactory.getInstance(userName, password); sendClient(commandId + " OK Authenticated"); state = State.AUTHENTICATED; } catch (Exception e) { DavGatewayTray.error(e); sendClient(commandId + " NO LOGIN failed"); state = State.INITIAL; } } else if ("AUTHENTICATE".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String authenticationMethod = tokens.nextToken(); if ("LOGIN".equalsIgnoreCase(authenticationMethod)) { try { sendClient("+ " + base64Encode("Username:")); state = State.LOGIN; userName = base64Decode(readClient()); // detect shared mailbox access splitUserName(); sendClient("+ " + base64Encode("Password:")); state = State.PASSWORD; password = base64Decode(readClient()); session = ExchangeSessionFactory.getInstance(userName, password); sendClient(commandId + " OK Authenticated"); state = State.AUTHENTICATED; } catch (Exception e) { DavGatewayTray.error(e); sendClient(commandId + " NO LOGIN failed"); state = State.INITIAL; } } else { sendClient(commandId + " NO unsupported authentication method"); } } else { sendClient(commandId + " BAD authentication method required"); } } else { if (state != State.AUTHENTICATED) { sendClient(commandId + " BAD command authentication required"); } else { // check for expired session session = ExchangeSessionFactory.getInstance(session, userName, password); if ("lsub".equalsIgnoreCase(command) || "list".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String folderContext; if (baseMailboxPath == null) { folderContext = BASE64MailboxDecoder.decode(tokens.nextToken()); } else { folderContext = baseMailboxPath + BASE64MailboxDecoder.decode(tokens.nextToken()); } if (tokens.hasMoreTokens()) { String folderQuery = folderContext + BASE64MailboxDecoder.decode(tokens.nextToken()); if (folderQuery.endsWith("%/%") && !"/%/%".equals(folderQuery)) { List<ExchangeSession.Folder> folders = session.getSubFolders(folderQuery.substring(0, folderQuery.length() - 3), false); for (ExchangeSession.Folder folder : folders) { sendClient("* " + command + " (" + folder.getFlags() + ") \"/\" \"" + BASE64MailboxEncoder.encode(folder.folderPath) + '\"'); sendSubFolders(command, folder.folderPath, false); } sendClient(commandId + " OK " + command + " completed"); } else if (folderQuery.endsWith("%") || folderQuery.endsWith("*")) { if ("/*".equals(folderQuery) || "/%".equals(folderQuery) || "/%/%".equals(folderQuery)) { folderQuery = folderQuery.substring(1); if ("%/%".equals(folderQuery)) { folderQuery = folderQuery.substring(0, folderQuery.length() - 2); } sendClient("* " + command + " (\\HasChildren) \"/\" \"/public\""); } if ("*%".equals(folderQuery)) { folderQuery = "*"; } boolean recursive = folderQuery.endsWith("*") && !folderQuery.startsWith("/public"); sendSubFolders(command, folderQuery.substring(0, folderQuery.length() - 1), recursive); sendClient(commandId + " OK " + command + " completed"); } else { ExchangeSession.Folder folder = null; try { folder = session.getFolder(folderQuery); } catch (HttpForbiddenException e) { // access forbidden, ignore DavGatewayTray.debug(new BundleMessage("LOG_FOLDER_ACCESS_FORBIDDEN", folderQuery)); } catch (HttpNotFoundException e) { // not found, ignore DavGatewayTray.debug(new BundleMessage("LOG_FOLDER_NOT_FOUND", folderQuery)); } catch (HttpException e) { // other errors, ignore DavGatewayTray.debug(new BundleMessage("LOG_FOLDER_ACCESS_ERROR", folderQuery, e.getMessage())); } if (folder != null) { sendClient("* " + command + " (" + folder.getFlags() + ") \"/\" \"" + BASE64MailboxEncoder.encode(folder.folderPath) + '\"'); sendClient(commandId + " OK " + command + " completed"); } else { sendClient(commandId + " NO Folder not found"); } } } else { sendClient(commandId + " BAD missing folder argument"); } } else { sendClient(commandId + " BAD missing folder argument"); } } else if ("select".equalsIgnoreCase(command) || "examine".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); if (baseMailboxPath != null && !folderName.startsWith("/")) { folderName = baseMailboxPath + folderName; } try { currentFolder = session.getFolder(folderName); currentFolder.loadMessages(); sendClient("* " + currentFolder.count() + " EXISTS"); sendClient("* " + currentFolder.count() + " RECENT"); sendClient("* OK [UIDVALIDITY 1]"); if (currentFolder.count() == 0) { sendClient("* OK [UIDNEXT 1]"); } else { sendClient("* OK [UIDNEXT " + currentFolder.getUidNext() + ']'); } sendClient("* FLAGS (\\Answered \\Deleted \\Draft \\Flagged \\Seen $Forwarded Junk)"); sendClient("* OK [PERMANENTFLAGS (\\Answered \\Deleted \\Draft \\Flagged \\Seen $Forwarded Junk)]"); if ("select".equalsIgnoreCase(command)) { sendClient(commandId + " OK [READ-WRITE] " + command + " completed"); } else { sendClient(commandId + " OK [READ-ONLY] " + command + " completed"); } } catch (HttpNotFoundException e) { sendClient(commandId + " NO Not found"); } catch (HttpForbiddenException e) { sendClient(commandId + " NO Forbidden"); } } else { sendClient(commandId + " BAD command unrecognized"); } } else if ("expunge".equalsIgnoreCase(command)) { if (expunge(false)) { // need to refresh folder to avoid 404 errors session.refreshFolder(currentFolder); } sendClient(commandId + " OK " + command + " completed"); } else if ("close".equalsIgnoreCase(command)) { expunge(true); // deselect folder currentFolder = null; sendClient(commandId + " OK " + command + " completed"); } else if ("create".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); session.createMessageFolder(folderName); sendClient(commandId + " OK folder created"); } else { sendClient(commandId + " BAD missing create argument"); } } else if ("rename".equalsIgnoreCase(command)) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); String targetName = BASE64MailboxDecoder.decode(tokens.nextToken()); try { session.moveFolder(folderName, targetName); sendClient(commandId + " OK rename completed"); } catch (HttpException e) { sendClient(commandId + " NO " + e.getMessage()); } } else if ("delete".equalsIgnoreCase(command)) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); try { session.deleteFolder(folderName); sendClient(commandId + " OK folder deleted"); } catch (HttpException e) { sendClient(commandId + " NO " + e.getMessage()); } } else if ("uid".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String subcommand = tokens.nextToken(); if ("fetch".equalsIgnoreCase(subcommand)) { if (currentFolder == null) { sendClient(commandId + " NO no folder selected"); } else { String ranges = tokens.nextToken(); if (ranges == null) { sendClient(commandId + " BAD missing range parameter"); } else { String parameters = null; if (tokens.hasMoreTokens()) { parameters = tokens.nextToken(); } UIDRangeIterator uidRangeIterator = new UIDRangeIterator(currentFolder.messages, ranges); while (uidRangeIterator.hasNext()) { DavGatewayTray.switchIcon(); ExchangeSession.Message message = uidRangeIterator.next(); try { handleFetch(message, uidRangeIterator.currentIndex, parameters); } catch (SocketException e) { // client closed connection throw e; } catch (IOException e) { DavGatewayTray.log(e); sendClient(commandId + " NO Unable to retrieve message: " + e.getMessage()); } } sendClient(commandId + " OK UID FETCH completed"); } } } else if ("search".equalsIgnoreCase(subcommand)) { List<Long> uidList = handleSearch(tokens); if (uidList.isEmpty()) { sendClient("* SEARCH"); } else { for (long uid : uidList) { sendClient("* SEARCH " + uid); } } sendClient(commandId + " OK SEARCH completed"); } else if ("store".equalsIgnoreCase(subcommand)) { UIDRangeIterator uidRangeIterator = new UIDRangeIterator(currentFolder.messages, tokens.nextToken()); String action = tokens.nextToken(); String flags = tokens.nextToken(); handleStore(commandId, uidRangeIterator, action, flags); } else if ("copy".equalsIgnoreCase(subcommand)) { try { UIDRangeIterator uidRangeIterator = new UIDRangeIterator(currentFolder.messages, tokens.nextToken()); String targetName = BASE64MailboxDecoder.decode(tokens.nextToken()); while (uidRangeIterator.hasNext()) { DavGatewayTray.switchIcon(); ExchangeSession.Message message = uidRangeIterator.next(); session.copyMessage(message, targetName); } sendClient(commandId + " OK copy completed"); } catch (HttpException e) { sendClient(commandId + " NO " + e.getMessage()); } } } else { sendClient(commandId + " BAD command unrecognized"); } } else if ("search".equalsIgnoreCase(command)) { if (currentFolder == null) { sendClient(commandId + " NO no folder selected"); } else { List<Long> uidList = handleSearch(tokens); if (uidList.isEmpty()) { sendClient("* SEARCH"); } else { int currentIndex = 0; for (ExchangeSession.Message message : currentFolder.messages) { currentIndex++; if (uidList.contains(message.getImapUid())) { sendClient("* SEARCH " + currentIndex); } } } sendClient(commandId + " OK SEARCH completed"); } } else if ("fetch".equalsIgnoreCase(command)) { if (currentFolder == null) { sendClient(commandId + " NO no folder selected"); } else { RangeIterator rangeIterator = new RangeIterator(currentFolder.messages, tokens.nextToken()); String parameters = null; if (tokens.hasMoreTokens()) { parameters = tokens.nextToken(); } while (rangeIterator.hasNext()) { DavGatewayTray.switchIcon(); ExchangeSession.Message message = rangeIterator.next(); try { handleFetch(message, rangeIterator.currentIndex, parameters); } catch (SocketException e) { // client closed connection, rethrow exception throw e; } catch (IOException e) { DavGatewayTray.log(e); sendClient(commandId + " NO Unable to retrieve message: " + e.getMessage()); } } sendClient(commandId + " OK FETCH completed"); } } else if ("store".equalsIgnoreCase(command)) { RangeIterator rangeIterator = new RangeIterator(currentFolder.messages, tokens.nextToken()); String action = tokens.nextToken(); String flags = tokens.nextToken(); handleStore(commandId, rangeIterator, action, flags); } else if ("copy".equalsIgnoreCase(command)) { try { RangeIterator rangeIterator = new RangeIterator(currentFolder.messages, tokens.nextToken()); String targetName = BASE64MailboxDecoder.decode(tokens.nextToken()); while (rangeIterator.hasNext()) { DavGatewayTray.switchIcon(); ExchangeSession.Message message = rangeIterator.next(); session.copyMessage(message, targetName); } sendClient(commandId + " OK copy completed"); } catch (HttpException e) { sendClient(commandId + " NO " + e.getMessage()); } } else if ("append".equalsIgnoreCase(command)) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); HashMap<String, String> properties = new HashMap<String, String>(); String flags = null; String date = null; // handle optional flags String nextToken = tokens.nextQuotedToken(); if (nextToken.startsWith("(")) { flags = removeQuotes(nextToken); if (tokens.hasMoreTokens()) { nextToken = tokens.nextToken(); if (tokens.hasMoreTokens()) { date = nextToken; nextToken = tokens.nextToken(); } } } else if (tokens.hasMoreTokens()) { date = removeQuotes(nextToken); nextToken = tokens.nextToken(); } if (flags != null) { // parse flags, on create read and draft flags are on the // same messageFlags property, 8 means draft and 1 means read StringTokenizer flagtokenizer = new StringTokenizer(flags); while (flagtokenizer.hasMoreTokens()) { String flag = flagtokenizer.nextToken(); if ("\\Seen".equals(flag)) { if (properties.containsKey("draft")) { // draft message, add read flag properties.put("draft", "9"); } else { // not (yet) draft, set read flag properties.put("draft", "1"); } } else if ("\\Flagged".equals(flag)) { properties.put("flagged", "2"); } else if ("\\Answered".equals(flag)) { properties.put("answered", "102"); } else if ("$Forwarded".equals(flag)) { properties.put("forwarded", "104"); } else if ("\\Draft".equals(flag)) { if (properties.containsKey("draft")) { // read message, add draft flag properties.put("draft", "9"); } else { // not (yet) read, set draft flag properties.put("draft", "8"); } } else if ("Junk".equals(flag)) { properties.put("junk", "1"); } } } // handle optional date if (date != null) { SimpleDateFormat dateParser = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss Z", Locale.ENGLISH); Date dateReceived = dateParser.parse(date); SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); dateFormatter.setTimeZone(ExchangeSession.GMT_TIMEZONE); properties.put("datereceived", dateFormatter.format(dateReceived)); } - int size = Integer.parseInt(nextToken); + int size = Integer.parseInt(removeQuotes(nextToken)); sendClient("+ send literal data"); byte[] buffer = in.readContent(size); // empty line readClient(); MimeMessage mimeMessage = new MimeMessage(null, new SharedByteArrayInputStream(buffer)); String messageName = UUID.randomUUID().toString() + ".EML"; try { session.createMessage(folderName, messageName, properties, mimeMessage); sendClient(commandId + " OK APPEND completed"); } catch (InsufficientStorageException e) { sendClient(commandId + " NO " + e.getMessage()); } } else if ("idle".equalsIgnoreCase(command) && imapIdleDelay > 0) { if (currentFolder != null) { sendClient("+ idling "); // clear cache before going to idle mode currentFolder.clearCache(); DavGatewayTray.resetIcon(); try { int count = 0; while (in.available() == 0) { if (++count >= imapIdleDelay) { count = 0; List<Long> previousImapUidList = currentFolder.getImapUidList(); if (session.refreshFolder(currentFolder)) { handleRefresh(previousImapUidList, currentFolder.getImapUidList()); } } // sleep 1 second Thread.sleep(1000); } // read DONE line line = readClient(); if ("DONE".equals(line)) { sendClient(commandId + " OK " + command + " terminated"); } else { sendClient(commandId + " BAD command unrecognized"); } } catch (IOException e) { // client connection closed throw new SocketException(e.getMessage()); } } else { sendClient(commandId + " NO no folder selected"); } } else if ("noop".equalsIgnoreCase(command) || "check".equalsIgnoreCase(command)) { if (currentFolder != null) { DavGatewayTray.debug(new BundleMessage("LOG_IMAP_COMMAND", command, currentFolder.folderPath)); List<Long> previousImapUidList = currentFolder.getImapUidList(); if (session.refreshFolder(currentFolder)) { handleRefresh(previousImapUidList, currentFolder.getImapUidList()); } } sendClient(commandId + " OK " + command + " completed"); } else if ("subscribe".equalsIgnoreCase(command) || "unsubscribe".equalsIgnoreCase(command)) { sendClient(commandId + " OK " + command + " completed"); } else if ("status".equalsIgnoreCase(command)) { try { String encodedFolderName = tokens.nextToken(); String folderName = BASE64MailboxDecoder.decode(encodedFolderName); ExchangeSession.Folder folder = session.getFolder(folderName); // must retrieve messages folder.loadMessages(); String parameters = tokens.nextToken(); StringBuilder answer = new StringBuilder(); StringTokenizer parametersTokens = new StringTokenizer(parameters); while (parametersTokens.hasMoreTokens()) { String token = parametersTokens.nextToken(); if ("MESSAGES".equalsIgnoreCase(token)) { answer.append("MESSAGES ").append(folder.count()).append(' '); } if ("RECENT".equalsIgnoreCase(token)) { answer.append("RECENT ").append(folder.count()).append(' '); } if ("UIDNEXT".equalsIgnoreCase(token)) { if (folder.count() == 0) { answer.append("UIDNEXT 1 "); } else { if (folder.count() == 0) { answer.append("UIDNEXT 1 "); } else { answer.append("UIDNEXT ").append(folder.getUidNext()).append(' '); } } } if ("UIDVALIDITY".equalsIgnoreCase(token)) { answer.append("UIDVALIDITY 1 "); } if ("UNSEEN".equalsIgnoreCase(token)) { answer.append("UNSEEN ").append(folder.unreadCount).append(' '); } } sendClient("* STATUS \"" + encodedFolderName + "\" (" + answer.toString().trim() + ')'); sendClient(commandId + " OK " + command + " completed"); } catch (HttpException e) { sendClient(commandId + " NO folder not found"); } } else { sendClient(commandId + " BAD command unrecognized"); } } } } else { sendClient(commandId + " BAD missing command"); } } else { sendClient("BAD Null command"); } DavGatewayTray.resetIcon(); } os.flush(); } catch (SocketTimeoutException e) { DavGatewayTray.debug(new BundleMessage("LOG_CLOSE_CONNECTION_ON_TIMEOUT")); try { sendClient("* BYE Closing connection"); } catch (IOException e1) { DavGatewayTray.debug(new BundleMessage("LOG_EXCEPTION_CLOSING_CONNECTION_ON_TIMEOUT")); } } catch (SocketException e) { LOGGER.warn(BundleMessage.formatLog("LOG_CLIENT_CLOSED_CONNECTION")); } catch (Exception e) { DavGatewayTray.log(e); try { String message = ((e.getMessage() == null) ? e.toString() : e.getMessage()).replaceAll("\\n", " "); if (commandId != null) { sendClient(commandId + " BAD unable to handle request: " + message); } else { sendClient("* BAD unable to handle request: " + message); } } catch (IOException e2) { DavGatewayTray.warn(new BundleMessage("LOG_EXCEPTION_SENDING_ERROR_TO_CLIENT"), e2); } } finally { close(); } DavGatewayTray.resetIcon(); } /** * Detect shared mailbox access. * see http://msexchangeteam.com/archive/2004/03/31/105275.aspx */ protected void splitUserName() { String[] tokens = null; if (userName.indexOf('/') >= 0) { tokens = userName.split("/"); } else if (userName.indexOf('\\') >= 0) { tokens = userName.split("\\\\"); } if (tokens != null && tokens.length == 3) { userName = tokens[0] + '\\' + tokens[1]; baseMailboxPath = "/users/" + tokens[2] + '/'; } } /** * Send expunge untagged response for removed IMAP message uids. * * @param previousImapUidList uid list before refresh * @param imapUidList uid list after refresh * @throws IOException on error */ private void handleRefresh(List<Long> previousImapUidList, List<Long> imapUidList) throws IOException { // int index = 1; for (long previousImapUid : previousImapUidList) { if (!imapUidList.contains(previousImapUid)) { sendClient("* " + index + " EXPUNGE"); } else { index++; } } sendClient("* " + currentFolder.count() + " EXISTS"); sendClient("* " + currentFolder.count() + " RECENT"); } private void handleFetch(ExchangeSession.Message message, int currentIndex, String parameters) throws IOException, MessagingException { StringBuilder buffer = new StringBuilder(); buffer.append("* ").append(currentIndex).append(" FETCH (UID ").append(message.getImapUid()); if (parameters != null) { StringTokenizer paramTokens = new StringTokenizer(parameters); while (paramTokens.hasMoreTokens()) { @SuppressWarnings({"NonConstantStringShouldBeStringBuffer"}) String param = paramTokens.nextToken(); if ("FLAGS".equals(param)) { buffer.append(" FLAGS (").append(message.getImapFlags()).append(')'); } else if ("RFC822.SIZE".equals(param)) { buffer.append(" RFC822.SIZE ").append(message.getMimeMessageSize()); } else if ("ENVELOPE".equals(param)) { appendEnvelope(buffer, message); } else if ("BODYSTRUCTURE".equals(param)) { appendBodyStructure(buffer, message); } else if ("INTERNALDATE".equals(param) && message.date != null && message.date.length() > 0) { try { SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); dateParser.setTimeZone(ExchangeSession.GMT_TIMEZONE); Date date = ExchangeSession.getZuluDateFormat().parse(message.date); SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss Z", Locale.ENGLISH); buffer.append(" INTERNALDATE \"").append(dateFormatter.format(date)).append('\"'); } catch (ParseException e) { throw new DavMailException("EXCEPTION_INVALID_DATE", message.date); } } else if (param.startsWith("BODY[") || param.startsWith("BODY.PEEK[") || "RFC822.HEADER".equals(param)) { // get full param if (param.indexOf('[') >= 0) { StringBuilder paramBuffer = new StringBuilder(param); while (paramTokens.hasMoreTokens() && param.indexOf(']') < 0) { paramBuffer.append(' ').append(paramTokens.nextToken()); } param = paramBuffer.toString(); } // parse buffer size int startIndex = 0; int maxSize = Integer.MAX_VALUE; int ltIndex = param.indexOf('<'); if (ltIndex >= 0) { int dotIndex = param.indexOf('.', ltIndex); if (dotIndex >= 0) { startIndex = Integer.parseInt(param.substring(ltIndex + 1, dotIndex)); maxSize = Integer.parseInt(param.substring(dotIndex + 1, param.indexOf('>'))); } } ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream partInputStream = null; OutputStream partOutputStream = null; // load message MimeMessage mimeMessage = message.getMimeMessage(); // try to parse message part index String partIndexString = StringUtil.getToken(param, "[", "]"); if ("".equals(partIndexString)) { // write message with headers partOutputStream = new PartialOutputStream(baos, startIndex, maxSize); partInputStream = message.getRawInputStream(); } else if ("TEXT".equals(partIndexString)) { // write message without headers partOutputStream = new PartialOutputStream(baos, startIndex, maxSize); partInputStream = mimeMessage.getRawInputStream(); } else if ("RFC822.HEADER".equals(param) || partIndexString.startsWith("HEADER")) { // Header requested fetch headers String[] requestedHeaders = getRequestedHeaders(partIndexString); if (requestedHeaders != null) { Enumeration headerEnumeration = message.getMimeMessage().getMatchingHeaderLines(requestedHeaders); while (headerEnumeration.hasMoreElements()) { baos.write(((String) headerEnumeration.nextElement()).getBytes("UTF-8")); baos.write(13); baos.write(10); } } else { // write headers only partOutputStream = new PartOutputStream(baos, true, false, startIndex, maxSize); partInputStream = message.getRawInputStream(); } } else { MimePart bodyPart = mimeMessage; String[] partIndexStrings = partIndexString.split("\\."); for (String subPartIndexString : partIndexStrings) { // ignore MIME subpart index, will return full part if ("MIME".equals(subPartIndexString)) { break; } int subPartIndex; // try to parse part index try { subPartIndex = Integer.parseInt(subPartIndexString); } catch (NumberFormatException e) { throw new DavMailException("EXCEPTION_INVALID_PARAMETER", param); } Object mimeBody = bodyPart.getContent(); if (mimeBody instanceof MimeMultipart) { MimeMultipart multiPart = (MimeMultipart) mimeBody; if (subPartIndex - 1 < multiPart.getCount()) { bodyPart = (MimePart) multiPart.getBodyPart(subPartIndex - 1); } else { throw new DavMailException("EXCEPTION_INVALID_PARAMETER", param); } } else if (subPartIndex != 1) { throw new DavMailException("EXCEPTION_INVALID_PARAMETER", param); } } // write selected part, without headers partOutputStream = new PartialOutputStream(baos, startIndex, maxSize); if (bodyPart instanceof MimeMessage) { partInputStream = ((MimeMessage) bodyPart).getRawInputStream(); } else { partInputStream = ((MimeBodyPart) bodyPart).getRawInputStream(); } } // copy selected content to baos if (partInputStream != null && partOutputStream != null) { IOUtil.write(partInputStream, partOutputStream); partInputStream.close(); partOutputStream.close(); } baos.close(); if ("RFC822.HEADER".equals(param)) { buffer.append(" RFC822.HEADER "); } else { buffer.append(" BODY[").append(partIndexString).append(']'); } // partial if (startIndex > 0 || maxSize != Integer.MAX_VALUE) { buffer.append('<').append(startIndex).append('>'); } buffer.append(" {").append(baos.size()).append('}'); sendClient(buffer.toString()); os.write(baos.toByteArray()); os.flush(); buffer.setLength(0); } } } buffer.append(')'); sendClient(buffer.toString()); // do not keep message content in memory message.dropMimeMessage(); } protected String[] getRequestedHeaders(String partIndexString) { int startIndex = partIndexString.indexOf('('); int endIndex = partIndexString.indexOf(')'); if (startIndex >= 0 && endIndex >= 0) { return partIndexString.substring(startIndex + 1, endIndex - 1).split(" "); } else { return null; } } protected void handleStore(String commandId, AbstractRangeIterator rangeIterator, String action, String flags) throws IOException { while (rangeIterator.hasNext()) { DavGatewayTray.switchIcon(); ExchangeSession.Message message = rangeIterator.next(); updateFlags(message, action, flags); sendClient("* " + (rangeIterator.getCurrentIndex()) + " FETCH (UID " + message.getImapUid() + " FLAGS (" + (message.getImapFlags()) + "))"); } // auto expunge if (Settings.getBooleanProperty("davmail.imapAutoExpunge")) { if (expunge(false)) { session.refreshFolder(currentFolder); } } sendClient(commandId + " OK STORE completed"); } protected ExchangeSession.Condition buildConditions(SearchConditions conditions, IMAPTokenizer tokens) throws IOException { ExchangeSession.MultiCondition condition = null; while (tokens.hasMoreTokens()) { String token = tokens.nextQuotedToken().toUpperCase(); if (token.startsWith("(") && token.endsWith(")")) { // quoted search param if (condition == null) { condition = session.and(); } condition.add(buildConditions(conditions, new IMAPTokenizer(token.substring(1, token.length() - 1)))); } else if ("OR".equals(token)) { condition = session.or(); } else if (token.startsWith("OR ")) { condition = appendOrSearchParams(token, conditions); } else { if (condition == null) { condition = session.and(); } condition.add(appendSearchParam(tokens, token, conditions)); } } return condition; } protected List<Long> handleSearch(IMAPTokenizer tokens) throws IOException { List<Long> uidList = new ArrayList<Long>(); SearchConditions conditions = new SearchConditions(); ExchangeSession.Condition condition = buildConditions(conditions, tokens); ExchangeSession.MessageList localMessages = currentFolder.searchMessages(condition); Iterator<ExchangeSession.Message> iterator; if (conditions.uidRange != null) { iterator = new UIDRangeIterator(localMessages, conditions.uidRange); } else if (conditions.indexRange != null) { iterator = new RangeIterator(localMessages, conditions.indexRange); } else { iterator = localMessages.iterator(); } while (iterator.hasNext()) { ExchangeSession.Message message = iterator.next(); if ((conditions.flagged == null || message.flagged == conditions.flagged) && (conditions.answered == null || message.answered == conditions.answered)) { uidList.add(message.getImapUid()); } } return uidList; } protected void appendEnvelope(StringBuilder buffer, ExchangeSession.Message message) throws IOException { buffer.append(" ENVELOPE ("); try { MimeMessage mimeMessage = message.getMimeMessage(); // Envelope for date, subject, from, sender, reply-to, to, cc, bcc,in-reply-to, message-id appendEnvelopeHeader(buffer, mimeMessage.getHeader("Date")); appendEnvelopeHeader(buffer, mimeMessage.getHeader("Subject")); appendMailEnvelopeHeader(buffer, mimeMessage.getHeader("From")); appendMailEnvelopeHeader(buffer, mimeMessage.getHeader("Sender")); appendMailEnvelopeHeader(buffer, mimeMessage.getHeader("Reply-To")); appendMailEnvelopeHeader(buffer, mimeMessage.getHeader("To")); appendMailEnvelopeHeader(buffer, mimeMessage.getHeader("CC")); appendMailEnvelopeHeader(buffer, mimeMessage.getHeader("BCC")); appendEnvelopeHeader(buffer, mimeMessage.getHeader("In-Reply-To")); appendEnvelopeHeader(buffer, mimeMessage.getHeader("Message-Id")); } catch (MessagingException me) { DavGatewayTray.warn(me); // send fake envelope buffer.append(" NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL"); } buffer.append(')'); } protected void appendEnvelopeHeader(StringBuilder buffer, String[] value) { buffer.append(' '); if (value != null && value.length > 0) { String unfoldedValue = MimeUtility.unfold(value[0]); if (unfoldedValue.indexOf('"') >= 0) { buffer.append('{'); buffer.append(unfoldedValue.length()); buffer.append("}\r\n"); buffer.append(unfoldedValue); } else { buffer.append('"'); buffer.append(unfoldedValue); buffer.append('"'); } } else { buffer.append("NIL"); } } protected void appendMailEnvelopeHeader(StringBuilder buffer, String[] value) { buffer.append(' '); if (value != null && value.length > 0) { try { String unfoldedValue = MimeUtility.unfold(value[0]); InternetAddress[] addresses = InternetAddress.parseHeader(unfoldedValue, false); buffer.append('('); for (InternetAddress address : addresses) { buffer.append('('); String personal = address.getPersonal(); if (personal != null) { buffer.append('"').append(MimeUtility.encodeText(personal)).append('"'); } else { buffer.append("NIL"); } buffer.append(" NIL "); String mail = address.getAddress(); int atIndex = mail.indexOf('@'); if (atIndex >= 0) { buffer.append('"').append(mail.substring(0, atIndex)).append('"'); buffer.append(' '); buffer.append('"').append(mail.substring(atIndex + 1)).append('"'); } else { buffer.append("NIL NIL"); } buffer.append(')'); } buffer.append(')'); } catch (AddressException e) { DavGatewayTray.warn(e); buffer.append("NIL"); } catch (UnsupportedEncodingException e) { DavGatewayTray.warn(e); buffer.append("NIL"); } } else { buffer.append("NIL"); } } protected void appendBodyStructure(StringBuilder buffer, ExchangeSession.Message message) throws IOException { buffer.append(" BODYSTRUCTURE "); try { MimeMessage mimeMessage = message.getMimeMessage(); Object mimeBody = mimeMessage.getContent(); if (mimeBody instanceof MimeMultipart) { appendBodyStructure(buffer, (MimeMultipart) mimeBody); } else { // no multipart, single body appendBodyStructure(buffer, mimeMessage); } } catch (UnsupportedEncodingException e) { DavGatewayTray.warn(e); // failover: send default bodystructure buffer.append("(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\") NIL NIL NIL NIL NIL)"); } catch (MessagingException me) { DavGatewayTray.warn(me); // failover: send default bodystructure buffer.append("(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\") NIL NIL NIL NIL NIL)"); } } protected void appendBodyStructure(StringBuilder buffer, MimeMultipart multiPart) throws IOException, MessagingException { buffer.append('('); for (int i = 0; i < multiPart.getCount(); i++) { MimeBodyPart bodyPart = (MimeBodyPart) multiPart.getBodyPart(i); Object mimeBody = bodyPart.getContent(); if (mimeBody instanceof MimeMultipart) { appendBodyStructure(buffer, (MimeMultipart) mimeBody); } else { // no multipart, single body appendBodyStructure(buffer, bodyPart); } } int slashIndex = multiPart.getContentType().indexOf('/'); if (slashIndex < 0) { throw new DavMailException("EXCEPTION_INVALID_CONTENT_TYPE", multiPart.getContentType()); } int semiColonIndex = multiPart.getContentType().indexOf(';'); if (semiColonIndex < 0) { buffer.append(" \"").append(multiPart.getContentType().substring(slashIndex + 1).toUpperCase()).append("\")"); } else { buffer.append(" \"").append(multiPart.getContentType().substring(slashIndex + 1, semiColonIndex).trim().toUpperCase()).append("\")"); } } protected void appendBodyStructure(StringBuilder buffer, MimePart bodyPart) throws IOException, MessagingException { String contentType = bodyPart.getContentType(); int slashIndex = contentType.indexOf('/'); if (slashIndex < 0) { throw new DavMailException("EXCEPTION_INVALID_CONTENT_TYPE", contentType); } buffer.append("(\"").append(contentType.substring(0, slashIndex).toUpperCase()).append("\" \""); int semiColonIndex = contentType.indexOf(';'); if (semiColonIndex < 0) { buffer.append(contentType.substring(slashIndex + 1).toUpperCase()).append("\" NIL"); } else { // extended content type buffer.append(contentType.substring(slashIndex + 1, semiColonIndex).trim().toUpperCase()).append('\"'); int charsetindex = contentType.indexOf("charset="); int nameindex = contentType.indexOf("name="); if (charsetindex >= 0 || nameindex >= 0) { buffer.append(" ("); if (charsetindex >= 0) { buffer.append("\"CHARSET\" "); int charsetSemiColonIndex = contentType.indexOf(';', charsetindex); int charsetEndIndex; if (charsetSemiColonIndex > 0) { charsetEndIndex = charsetSemiColonIndex; } else { charsetEndIndex = contentType.length(); } String charSet = contentType.substring(charsetindex + "charset=".length(), charsetEndIndex); if (!charSet.startsWith("\"")) { buffer.append('"'); } buffer.append(charSet.trim().toUpperCase()); if (!charSet.endsWith("\"")) { buffer.append('"'); } } if (nameindex >= 0) { if (charsetindex >= 0) { buffer.append(' '); } buffer.append("\"NAME\" "); int nameSemiColonIndex = contentType.indexOf(';', nameindex); int nameEndIndex; if (nameSemiColonIndex > 0) { nameEndIndex = nameSemiColonIndex; } else { nameEndIndex = contentType.length(); } String name = contentType.substring(nameindex + "name=".length(), nameEndIndex); if (!name.startsWith("\"")) { buffer.append('"'); } buffer.append(name.trim()); if (!name.endsWith("\"")) { buffer.append('"'); } } buffer.append(')'); } else { buffer.append(" NIL"); } } appendBodyStructureValue(buffer, bodyPart.getContentID()); appendBodyStructureValue(buffer, bodyPart.getDescription()); appendBodyStructureValue(buffer, bodyPart.getEncoding()); appendBodyStructureValue(buffer, bodyPart.getSize()); // line count not implemented in JavaMail, return fake line count appendBodyStructureValue(buffer, bodyPart.getSize() / 80); buffer.append(')'); } protected void appendBodyStructureValue(StringBuilder buffer, String value) { if (value == null) { buffer.append(" NIL"); } else { buffer.append(" \"").append(value.toUpperCase()).append('\"'); } } protected void appendBodyStructureValue(StringBuilder buffer, int value) { if (value < 0) { buffer.append(" NIL"); } else { buffer.append(' ').append(value); } } protected void sendSubFolders(String command, String folderPath, boolean recursive) throws IOException { try { List<ExchangeSession.Folder> folders = session.getSubFolders(folderPath, recursive); for (ExchangeSession.Folder folder : folders) { sendClient("* " + command + " (" + folder.getFlags() + ") \"/\" \"" + BASE64MailboxEncoder.encode(folder.folderPath) + '\"'); } } catch (HttpForbiddenException e) { // access forbidden, ignore DavGatewayTray.debug(new BundleMessage("LOG_SUBFOLDER_ACCESS_FORBIDDEN", folderPath)); } catch (HttpNotFoundException e) { // not found, ignore DavGatewayTray.debug(new BundleMessage("LOG_FOLDER_NOT_FOUND", folderPath)); } catch (HttpException e) { // other errors, ignore DavGatewayTray.debug(new BundleMessage("LOG_FOLDER_ACCESS_ERROR", folderPath, e.getMessage())); } } /** * client side search conditions */ static final class SearchConditions { Boolean flagged; Boolean answered; String indexRange; String uidRange; } protected ExchangeSession.MultiCondition appendOrSearchParams(String token, SearchConditions conditions) throws IOException { ExchangeSession.MultiCondition orCondition = session.or(); IMAPTokenizer innerTokens = new IMAPTokenizer(token); innerTokens.nextToken(); while (innerTokens.hasMoreTokens()) { String innerToken = innerTokens.nextToken(); orCondition.add(appendSearchParam(innerTokens, innerToken, conditions)); } return orCondition; } protected ExchangeSession.Condition appendSearchParam(StringTokenizer tokens, String token, SearchConditions conditions) throws IOException { if ("NOT".equals(token)) { String nextToken = tokens.nextToken(); if ("DELETED".equals(nextToken)) { // conditions.deleted = Boolean.FALSE; return session.isNull("deleted"); } else { return session.not(appendSearchParam(tokens, nextToken, conditions)); } } else if (token.startsWith("OR ")) { return appendOrSearchParams(token, conditions); } else if ("SUBJECT".equals(token)) { return session.contains("subject", tokens.nextToken()); } else if ("BODY".equals(token)) { return session.contains("body", tokens.nextToken()); } else if ("FROM".equals(token)) { return session.contains("from", tokens.nextToken()); } else if ("TO".equals(token)) { return session.contains("to", tokens.nextToken()); } else if ("CC".equals(token)) { return session.contains("cc", tokens.nextToken()); } else if ("LARGER".equals(token)) { return session.gte("messageSize", tokens.nextToken()); } else if ("SMALLER".equals(token)) { return session.lt("messageSize", tokens.nextToken()); } else if (token.startsWith("SENT") || "SINCE".equals(token) || "BEFORE".equals(token)) { return appendDateSearchParam(tokens, token); } else if ("SEEN".equals(token)) { return session.isTrue("read"); } else if ("UNSEEN".equals(token) || "NEW".equals(token)) { return session.isFalse("read"); } else if ("DELETED".equals(token)) { // conditions.deleted = Boolean.TRUE; return session.isEqualTo("deleted", "1"); } else if ("UNDELETED".equals(token) || "NOT DELETED".equals(token)) { // conditions.deleted = Boolean.FALSE; return session.isNull("deleted"); } else if ("FLAGGED".equals(token)) { conditions.flagged = Boolean.TRUE; } else if ("UNFLAGGED".equals(token) || "NEW".equals(token)) { conditions.flagged = Boolean.FALSE; } else if ("ANSWERED".equals(token)) { conditions.answered = Boolean.TRUE; } else if ("UNANSWERED".equals(token)) { conditions.answered = Boolean.FALSE; } else if ("HEADER".equals(token)) { String headerName = tokens.nextToken().toLowerCase(); String value = tokens.nextToken(); if ("message-id".equals(headerName) && !value.startsWith("<")) { value = '<' + value + '>'; } return session.headerIsEqualTo(headerName, value); } else if ("UID".equals(token)) { String range = tokens.nextToken(); if ("1:*".equals(range)) { // ignore: this is a noop filter } else { conditions.uidRange = range; } } else if ("OLD".equals(token) || "RECENT".equals(token) || "ALL".equals(token)) { // ignore } else if (token.indexOf(':') >= 0 || token.matches("\\d+")) { // range search conditions.indexRange = token; } else { throw new DavMailException("EXCEPTION_INVALID_SEARCH_PARAMETERS", token); } // client side search token return null; } protected ExchangeSession.Condition appendDateSearchParam(StringTokenizer tokens, String token) throws IOException { Date startDate; Date endDate; SimpleDateFormat parser = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH); parser.setTimeZone(ExchangeSession.GMT_TIMEZONE); SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); dateFormatter.setTimeZone(ExchangeSession.GMT_TIMEZONE); String dateToken = tokens.nextToken(); try { startDate = parser.parse(dateToken); Calendar calendar = Calendar.getInstance(); calendar.setTime(startDate); calendar.add(Calendar.DAY_OF_MONTH, 1); endDate = calendar.getTime(); } catch (ParseException e) { throw new DavMailException("EXCEPTION_INVALID_SEARCH_PARAMETERS", dateToken); } String searchAttribute; if (token.startsWith("SENT")) { searchAttribute = "date"; } else { searchAttribute = "lastmodified"; } if (token.endsWith("ON")) { return session.and(session.gt(searchAttribute, dateFormatter.format(startDate)), session.lt(searchAttribute, dateFormatter.format(endDate))); } else if (token.endsWith("BEFORE")) { return session.lt(searchAttribute, dateFormatter.format(startDate)); } else if (token.endsWith("SINCE")) { return session.gte(searchAttribute, dateFormatter.format(startDate)); } else { throw new DavMailException("EXCEPTION_INVALID_SEARCH_PARAMETERS", dateToken); } } protected boolean expunge(boolean silent) throws IOException { boolean hasDeleted = false; if (currentFolder.messages != null) { int index = 1; for (ExchangeSession.Message message : currentFolder.messages) { if (message.deleted) { message.delete(); hasDeleted = true; if (!silent) { sendClient("* " + index + " EXPUNGE"); } } else { index++; } } } return hasDeleted; } protected void updateFlags(ExchangeSession.Message message, String action, String flags) throws IOException { HashMap<String, String> properties = new HashMap<String, String>(); if ("-Flags".equalsIgnoreCase(action) || "-FLAGS.SILENT".equalsIgnoreCase(action)) { StringTokenizer flagtokenizer = new StringTokenizer(flags); while (flagtokenizer.hasMoreTokens()) { String flag = flagtokenizer.nextToken(); if ("\\Seen".equalsIgnoreCase(flag) && message.read) { properties.put("read", "0"); message.read = false; } else if ("\\Flagged".equalsIgnoreCase(flag) && message.flagged) { properties.put("flagged", "0"); message.flagged = false; } else if ("\\Deleted".equalsIgnoreCase(flag) && message.deleted) { properties.put("deleted", null); message.deleted = false; } else if ("Junk".equalsIgnoreCase(flag) && message.junk) { properties.put("junk", "0"); message.junk = false; } else if ("$Forwarded".equalsIgnoreCase(flag) && message.forwarded) { properties.put("forwarded", null); message.forwarded = false; } else if ("\\Answered".equalsIgnoreCase(flag) && message.answered) { properties.put("answered", null); message.answered = false; } } } else if ("+Flags".equalsIgnoreCase(action) || "+FLAGS.SILENT".equalsIgnoreCase(action)) { StringTokenizer flagtokenizer = new StringTokenizer(flags); while (flagtokenizer.hasMoreTokens()) { String flag = flagtokenizer.nextToken(); if ("\\Seen".equalsIgnoreCase(flag) && !message.read) { properties.put("read", "1"); message.read = true; } else if ("\\Deleted".equalsIgnoreCase(flag) && !message.deleted) { message.deleted = true; properties.put("deleted", "1"); } else if ("\\Flagged".equalsIgnoreCase(flag) && !message.flagged) { properties.put("flagged", "2"); message.flagged = true; } else if ("\\Answered".equalsIgnoreCase(flag) && !message.answered) { properties.put("answered", "102"); message.answered = true; } else if ("$Forwarded".equalsIgnoreCase(flag) && !message.forwarded) { properties.put("forwarded", "104"); message.forwarded = true; } else if ("Junk".equalsIgnoreCase(flag) && !message.junk) { properties.put("junk", "1"); message.junk = true; } } } else if ("FLAGS".equalsIgnoreCase(action) || "FLAGS.SILENT".equalsIgnoreCase(action)) { // flag list with default values boolean read = false; boolean deleted = false; boolean junk = false; boolean flagged = false; boolean answered = false; boolean forwarded = false; // set flags from new flag list StringTokenizer flagtokenizer = new StringTokenizer(flags); while (flagtokenizer.hasMoreTokens()) { String flag = flagtokenizer.nextToken(); if ("\\Seen".equalsIgnoreCase(flag)) { read = true; } else if ("\\Deleted".equalsIgnoreCase(flag)) { deleted = true; } else if ("\\Flagged".equalsIgnoreCase(flag)) { flagged = true; } else if ("\\Answered".equalsIgnoreCase(flag)) { answered = true; } else if ("$Forwarded".equalsIgnoreCase(flag)) { forwarded = true; } else if ("Junk".equalsIgnoreCase(flag)) { junk = true; } } if (read != message.read) { message.read = read; if (message.read) { properties.put("read", "1"); } else { properties.put("read", "0"); } } if (deleted != message.deleted) { message.deleted = deleted; if (message.deleted) { properties.put("deleted", "1"); } else { properties.put("deleted", null); } } if (flagged != message.flagged) { message.flagged = flagged; if (message.flagged) { properties.put("flagged", "2"); } else { properties.put("flagged", "0"); } } if (answered != message.answered) { message.answered = answered; if (message.answered) { properties.put("answered", "102"); } else if (!forwarded) { // remove property only if not forwarded properties.put("answered", null); } } if (forwarded != message.forwarded) { message.forwarded = forwarded; if (message.forwarded) { properties.put("forwarded", "104"); } else if (!answered) { // remove property only if not answered properties.put("forwarded", null); } } if (junk != message.junk) { message.junk = junk; if (message.junk) { properties.put("junk", "1"); } else { properties.put("junk", "0"); } } } if (!properties.isEmpty()) { session.updateMessage(message, properties); } } /** * Decode IMAP credentials * * @param tokens tokens * @throws IOException on error */ protected void parseCredentials(StringTokenizer tokens) throws IOException { if (tokens.hasMoreTokens()) { userName = tokens.nextToken(); } else { throw new DavMailException("EXCEPTION_INVALID_CREDENTIALS"); } if (tokens.hasMoreTokens()) { password = tokens.nextToken(); } else { throw new DavMailException("EXCEPTION_INVALID_CREDENTIALS"); } int backslashindex = userName.indexOf('\\'); if (backslashindex > 0) { userName = userName.substring(0, backslashindex) + userName.substring(backslashindex + 1); } } protected String removeQuotes(String value) { String result = value; if (result.startsWith("\"") || result.startsWith("{") || result.startsWith("(")) { result = result.substring(1); } if (result.endsWith("\"") || result.endsWith("}") || result.endsWith(")")) { result = result.substring(0, result.length() - 1); } return result; } /** * Filter to output only headers, also count full size */ private static final class PartOutputStream extends FilterOutputStream { private static final int START = 0; private static final int CR = 1; private static final int CRLF = 2; private static final int CRLFCR = 3; private static final int BODY = 4; private int state = START; private int size; private int bufferSize; private final boolean writeHeaders; private final boolean writeBody; private final int startIndex; private final int maxSize; private PartOutputStream(OutputStream os, boolean writeHeaders, boolean writeBody, int startIndex, int maxSize) { super(os); this.writeHeaders = writeHeaders; this.writeBody = writeBody; this.startIndex = startIndex; this.maxSize = maxSize; } @Override public void write(int b) throws IOException { size++; if (((state != BODY && writeHeaders) || (state == BODY && writeBody)) && (size > startIndex) && (bufferSize < maxSize) ) { super.write(b); bufferSize++; } if (state == START) { if (b == '\r') { state = CR; } } else if (state == CR) { if (b == '\n') { state = CRLF; } else { state = START; } } else if (state == CRLF) { if (b == '\r') { state = CRLFCR; } else { state = START; } } else if (state == CRLFCR) { if (b == '\n') { state = BODY; } else { state = START; } } } } /** * Partial output stream, start at startIndex and write maxSize bytes. */ private static final class PartialOutputStream extends FilterOutputStream { private int size; private int bufferSize; private final int startIndex; private final int maxSize; private PartialOutputStream(OutputStream os, int startIndex, int maxSize) { super(os); this.startIndex = startIndex; this.maxSize = maxSize; } @Override public void write(int b) throws IOException { size++; if ((size > startIndex) && (bufferSize < maxSize)) { super.write(b); bufferSize++; } } } protected abstract static class AbstractRangeIterator implements Iterator<ExchangeSession.Message> { ExchangeSession.MessageList messages; int currentIndex; protected int getCurrentIndex() { return currentIndex; } } protected static class UIDRangeIterator extends AbstractRangeIterator { final String[] ranges; int currentRangeIndex; long startUid; long endUid; protected UIDRangeIterator(ExchangeSession.MessageList messages, String value) { this.messages = messages; ranges = value.split(","); } protected long convertToLong(String value) { if ("*".equals(value)) { return Long.MAX_VALUE; } else { return Long.parseLong(value); } } protected void skipToNextRangeStartUid() { if (currentRangeIndex < ranges.length) { String currentRange = ranges[currentRangeIndex++]; int colonIndex = currentRange.indexOf(':'); if (colonIndex > 0) { startUid = convertToLong(currentRange.substring(0, colonIndex)); endUid = convertToLong(currentRange.substring(colonIndex + 1)); if (endUid < startUid) { long swap = endUid; endUid = startUid; startUid = swap; } } else if ("*".equals(currentRange)) { startUid = endUid = messages.get(messages.size() - 1).getImapUid(); } else { startUid = endUid = convertToLong(currentRange); } while (currentIndex < messages.size() && messages.get(currentIndex).getImapUid() < startUid) { currentIndex++; } } else { currentIndex = messages.size(); } } protected boolean hasNextInRange() { return hasNextIndex() && messages.get(currentIndex).getImapUid() <= endUid; } protected boolean hasNextIndex() { return currentIndex < messages.size(); } protected boolean hasNextRange() { return currentRangeIndex < ranges.length; } public boolean hasNext() { boolean hasNextInRange = hasNextInRange(); // if has next range and current index after current range end, reset index if (hasNextRange() && !hasNextInRange) { currentIndex = 0; } while (hasNextIndex() && !hasNextInRange) { skipToNextRangeStartUid(); hasNextInRange = hasNextInRange(); } return hasNextIndex(); } public ExchangeSession.Message next() { ExchangeSession.Message message = messages.get(currentIndex++); long uid = message.getImapUid(); if (uid < startUid || uid > endUid) { throw new RuntimeException("Message uid " + uid + " not in range " + startUid + ':' + endUid); } return message; } public void remove() { throw new UnsupportedOperationException(); } } protected static class RangeIterator extends AbstractRangeIterator { final String[] ranges; int currentRangeIndex; long startUid; long endUid; protected RangeIterator(ExchangeSession.MessageList messages, String value) { this.messages = messages; ranges = value.split(","); } protected long convertToLong(String value) { if ("*".equals(value)) { return Long.MAX_VALUE; } else { return Long.parseLong(value); } } protected void skipToNextRangeStart() { if (currentRangeIndex < ranges.length) { String currentRange = ranges[currentRangeIndex++]; int colonIndex = currentRange.indexOf(':'); if (colonIndex > 0) { startUid = convertToLong(currentRange.substring(0, colonIndex)); endUid = convertToLong(currentRange.substring(colonIndex + 1)); if (endUid < startUid) { long swap = endUid; endUid = startUid; startUid = swap; } } else if ("*".equals(currentRange)) { startUid = endUid = messages.size(); } else { startUid = endUid = convertToLong(currentRange); } while (currentIndex < messages.size() && (currentIndex + 1) < startUid) { currentIndex++; } } else { currentIndex = messages.size(); } } protected boolean hasNextInRange() { return hasNextIndex() && currentIndex < endUid; } protected boolean hasNextIndex() { return currentIndex < messages.size(); } protected boolean hasNextRange() { return currentRangeIndex < ranges.length; } public boolean hasNext() { boolean hasNextInRange = hasNextInRange(); // if has next range and current index after current range end, reset index if (hasNextRange() && !hasNextInRange) { currentIndex = 0; } while (hasNextIndex() && !hasNextInRange) { skipToNextRangeStart(); hasNextInRange = hasNextInRange(); } return hasNextIndex(); } public ExchangeSession.Message next() { return messages.get(currentIndex++); } public void remove() { throw new UnsupportedOperationException(); } } class IMAPTokenizer extends StringTokenizer { IMAPTokenizer(String value) { super(value); } @Override public String nextToken() { return removeQuotes(nextQuotedToken()); } public String nextQuotedToken() { StringBuilder nextToken = new StringBuilder(); nextToken.append(super.nextToken()); while (hasMoreTokens() && nextToken.length() > 0 && nextToken.charAt(0) == '"' && (nextToken.charAt(nextToken.length() - 1) != '"' || nextToken.length() == 1)) { nextToken.append(' ').append(super.nextToken()); } while (hasMoreTokens() && nextToken.length() > 0 && nextToken.charAt(0) == '(' && nextToken.charAt(nextToken.length() - 1) != ')') { nextToken.append(' ').append(super.nextToken()); } while (hasMoreTokens() && nextToken.length() > 0 && nextToken.indexOf("[") != -1 && nextToken.charAt(nextToken.length() - 1) != ']') { nextToken.append(' ').append(super.nextToken()); } return nextToken.toString(); } } }
false
true
public void run() { final String capabilities; int imapIdleDelay = Settings.getIntProperty("davmail.imapIdleDelay") * 60; if (imapIdleDelay > 0) { capabilities = "CAPABILITY IMAP4REV1 AUTH=LOGIN IDLE"; } else { capabilities = "CAPABILITY IMAP4REV1 AUTH=LOGIN"; } String line; String commandId = null; IMAPTokenizer tokens; try { ExchangeSessionFactory.checkConfig(); sendClient("* OK [" + capabilities + "] IMAP4rev1 DavMail " + DavGateway.getCurrentVersion() + "server ready"); for (; ;) { line = readClient(); // unable to read line, connection closed ? if (line == null) { break; } tokens = new IMAPTokenizer(line); if (tokens.hasMoreTokens()) { commandId = tokens.nextToken(); if (tokens.hasMoreTokens()) { String command = tokens.nextToken(); if ("LOGOUT".equalsIgnoreCase(command)) { sendClient("* BYE Closing connection"); break; } if ("capability".equalsIgnoreCase(command)) { sendClient("* " + capabilities); sendClient(commandId + " OK CAPABILITY completed"); } else if ("login".equalsIgnoreCase(command)) { parseCredentials(tokens); // detect shared mailbox access splitUserName(); try { session = ExchangeSessionFactory.getInstance(userName, password); sendClient(commandId + " OK Authenticated"); state = State.AUTHENTICATED; } catch (Exception e) { DavGatewayTray.error(e); sendClient(commandId + " NO LOGIN failed"); state = State.INITIAL; } } else if ("AUTHENTICATE".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String authenticationMethod = tokens.nextToken(); if ("LOGIN".equalsIgnoreCase(authenticationMethod)) { try { sendClient("+ " + base64Encode("Username:")); state = State.LOGIN; userName = base64Decode(readClient()); // detect shared mailbox access splitUserName(); sendClient("+ " + base64Encode("Password:")); state = State.PASSWORD; password = base64Decode(readClient()); session = ExchangeSessionFactory.getInstance(userName, password); sendClient(commandId + " OK Authenticated"); state = State.AUTHENTICATED; } catch (Exception e) { DavGatewayTray.error(e); sendClient(commandId + " NO LOGIN failed"); state = State.INITIAL; } } else { sendClient(commandId + " NO unsupported authentication method"); } } else { sendClient(commandId + " BAD authentication method required"); } } else { if (state != State.AUTHENTICATED) { sendClient(commandId + " BAD command authentication required"); } else { // check for expired session session = ExchangeSessionFactory.getInstance(session, userName, password); if ("lsub".equalsIgnoreCase(command) || "list".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String folderContext; if (baseMailboxPath == null) { folderContext = BASE64MailboxDecoder.decode(tokens.nextToken()); } else { folderContext = baseMailboxPath + BASE64MailboxDecoder.decode(tokens.nextToken()); } if (tokens.hasMoreTokens()) { String folderQuery = folderContext + BASE64MailboxDecoder.decode(tokens.nextToken()); if (folderQuery.endsWith("%/%") && !"/%/%".equals(folderQuery)) { List<ExchangeSession.Folder> folders = session.getSubFolders(folderQuery.substring(0, folderQuery.length() - 3), false); for (ExchangeSession.Folder folder : folders) { sendClient("* " + command + " (" + folder.getFlags() + ") \"/\" \"" + BASE64MailboxEncoder.encode(folder.folderPath) + '\"'); sendSubFolders(command, folder.folderPath, false); } sendClient(commandId + " OK " + command + " completed"); } else if (folderQuery.endsWith("%") || folderQuery.endsWith("*")) { if ("/*".equals(folderQuery) || "/%".equals(folderQuery) || "/%/%".equals(folderQuery)) { folderQuery = folderQuery.substring(1); if ("%/%".equals(folderQuery)) { folderQuery = folderQuery.substring(0, folderQuery.length() - 2); } sendClient("* " + command + " (\\HasChildren) \"/\" \"/public\""); } if ("*%".equals(folderQuery)) { folderQuery = "*"; } boolean recursive = folderQuery.endsWith("*") && !folderQuery.startsWith("/public"); sendSubFolders(command, folderQuery.substring(0, folderQuery.length() - 1), recursive); sendClient(commandId + " OK " + command + " completed"); } else { ExchangeSession.Folder folder = null; try { folder = session.getFolder(folderQuery); } catch (HttpForbiddenException e) { // access forbidden, ignore DavGatewayTray.debug(new BundleMessage("LOG_FOLDER_ACCESS_FORBIDDEN", folderQuery)); } catch (HttpNotFoundException e) { // not found, ignore DavGatewayTray.debug(new BundleMessage("LOG_FOLDER_NOT_FOUND", folderQuery)); } catch (HttpException e) { // other errors, ignore DavGatewayTray.debug(new BundleMessage("LOG_FOLDER_ACCESS_ERROR", folderQuery, e.getMessage())); } if (folder != null) { sendClient("* " + command + " (" + folder.getFlags() + ") \"/\" \"" + BASE64MailboxEncoder.encode(folder.folderPath) + '\"'); sendClient(commandId + " OK " + command + " completed"); } else { sendClient(commandId + " NO Folder not found"); } } } else { sendClient(commandId + " BAD missing folder argument"); } } else { sendClient(commandId + " BAD missing folder argument"); } } else if ("select".equalsIgnoreCase(command) || "examine".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); if (baseMailboxPath != null && !folderName.startsWith("/")) { folderName = baseMailboxPath + folderName; } try { currentFolder = session.getFolder(folderName); currentFolder.loadMessages(); sendClient("* " + currentFolder.count() + " EXISTS"); sendClient("* " + currentFolder.count() + " RECENT"); sendClient("* OK [UIDVALIDITY 1]"); if (currentFolder.count() == 0) { sendClient("* OK [UIDNEXT 1]"); } else { sendClient("* OK [UIDNEXT " + currentFolder.getUidNext() + ']'); } sendClient("* FLAGS (\\Answered \\Deleted \\Draft \\Flagged \\Seen $Forwarded Junk)"); sendClient("* OK [PERMANENTFLAGS (\\Answered \\Deleted \\Draft \\Flagged \\Seen $Forwarded Junk)]"); if ("select".equalsIgnoreCase(command)) { sendClient(commandId + " OK [READ-WRITE] " + command + " completed"); } else { sendClient(commandId + " OK [READ-ONLY] " + command + " completed"); } } catch (HttpNotFoundException e) { sendClient(commandId + " NO Not found"); } catch (HttpForbiddenException e) { sendClient(commandId + " NO Forbidden"); } } else { sendClient(commandId + " BAD command unrecognized"); } } else if ("expunge".equalsIgnoreCase(command)) { if (expunge(false)) { // need to refresh folder to avoid 404 errors session.refreshFolder(currentFolder); } sendClient(commandId + " OK " + command + " completed"); } else if ("close".equalsIgnoreCase(command)) { expunge(true); // deselect folder currentFolder = null; sendClient(commandId + " OK " + command + " completed"); } else if ("create".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); session.createMessageFolder(folderName); sendClient(commandId + " OK folder created"); } else { sendClient(commandId + " BAD missing create argument"); } } else if ("rename".equalsIgnoreCase(command)) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); String targetName = BASE64MailboxDecoder.decode(tokens.nextToken()); try { session.moveFolder(folderName, targetName); sendClient(commandId + " OK rename completed"); } catch (HttpException e) { sendClient(commandId + " NO " + e.getMessage()); } } else if ("delete".equalsIgnoreCase(command)) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); try { session.deleteFolder(folderName); sendClient(commandId + " OK folder deleted"); } catch (HttpException e) { sendClient(commandId + " NO " + e.getMessage()); } } else if ("uid".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String subcommand = tokens.nextToken(); if ("fetch".equalsIgnoreCase(subcommand)) { if (currentFolder == null) { sendClient(commandId + " NO no folder selected"); } else { String ranges = tokens.nextToken(); if (ranges == null) { sendClient(commandId + " BAD missing range parameter"); } else { String parameters = null; if (tokens.hasMoreTokens()) { parameters = tokens.nextToken(); } UIDRangeIterator uidRangeIterator = new UIDRangeIterator(currentFolder.messages, ranges); while (uidRangeIterator.hasNext()) { DavGatewayTray.switchIcon(); ExchangeSession.Message message = uidRangeIterator.next(); try { handleFetch(message, uidRangeIterator.currentIndex, parameters); } catch (SocketException e) { // client closed connection throw e; } catch (IOException e) { DavGatewayTray.log(e); sendClient(commandId + " NO Unable to retrieve message: " + e.getMessage()); } } sendClient(commandId + " OK UID FETCH completed"); } } } else if ("search".equalsIgnoreCase(subcommand)) { List<Long> uidList = handleSearch(tokens); if (uidList.isEmpty()) { sendClient("* SEARCH"); } else { for (long uid : uidList) { sendClient("* SEARCH " + uid); } } sendClient(commandId + " OK SEARCH completed"); } else if ("store".equalsIgnoreCase(subcommand)) { UIDRangeIterator uidRangeIterator = new UIDRangeIterator(currentFolder.messages, tokens.nextToken()); String action = tokens.nextToken(); String flags = tokens.nextToken(); handleStore(commandId, uidRangeIterator, action, flags); } else if ("copy".equalsIgnoreCase(subcommand)) { try { UIDRangeIterator uidRangeIterator = new UIDRangeIterator(currentFolder.messages, tokens.nextToken()); String targetName = BASE64MailboxDecoder.decode(tokens.nextToken()); while (uidRangeIterator.hasNext()) { DavGatewayTray.switchIcon(); ExchangeSession.Message message = uidRangeIterator.next(); session.copyMessage(message, targetName); } sendClient(commandId + " OK copy completed"); } catch (HttpException e) { sendClient(commandId + " NO " + e.getMessage()); } } } else { sendClient(commandId + " BAD command unrecognized"); } } else if ("search".equalsIgnoreCase(command)) { if (currentFolder == null) { sendClient(commandId + " NO no folder selected"); } else { List<Long> uidList = handleSearch(tokens); if (uidList.isEmpty()) { sendClient("* SEARCH"); } else { int currentIndex = 0; for (ExchangeSession.Message message : currentFolder.messages) { currentIndex++; if (uidList.contains(message.getImapUid())) { sendClient("* SEARCH " + currentIndex); } } } sendClient(commandId + " OK SEARCH completed"); } } else if ("fetch".equalsIgnoreCase(command)) { if (currentFolder == null) { sendClient(commandId + " NO no folder selected"); } else { RangeIterator rangeIterator = new RangeIterator(currentFolder.messages, tokens.nextToken()); String parameters = null; if (tokens.hasMoreTokens()) { parameters = tokens.nextToken(); } while (rangeIterator.hasNext()) { DavGatewayTray.switchIcon(); ExchangeSession.Message message = rangeIterator.next(); try { handleFetch(message, rangeIterator.currentIndex, parameters); } catch (SocketException e) { // client closed connection, rethrow exception throw e; } catch (IOException e) { DavGatewayTray.log(e); sendClient(commandId + " NO Unable to retrieve message: " + e.getMessage()); } } sendClient(commandId + " OK FETCH completed"); } } else if ("store".equalsIgnoreCase(command)) { RangeIterator rangeIterator = new RangeIterator(currentFolder.messages, tokens.nextToken()); String action = tokens.nextToken(); String flags = tokens.nextToken(); handleStore(commandId, rangeIterator, action, flags); } else if ("copy".equalsIgnoreCase(command)) { try { RangeIterator rangeIterator = new RangeIterator(currentFolder.messages, tokens.nextToken()); String targetName = BASE64MailboxDecoder.decode(tokens.nextToken()); while (rangeIterator.hasNext()) { DavGatewayTray.switchIcon(); ExchangeSession.Message message = rangeIterator.next(); session.copyMessage(message, targetName); } sendClient(commandId + " OK copy completed"); } catch (HttpException e) { sendClient(commandId + " NO " + e.getMessage()); } } else if ("append".equalsIgnoreCase(command)) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); HashMap<String, String> properties = new HashMap<String, String>(); String flags = null; String date = null; // handle optional flags String nextToken = tokens.nextQuotedToken(); if (nextToken.startsWith("(")) { flags = removeQuotes(nextToken); if (tokens.hasMoreTokens()) { nextToken = tokens.nextToken(); if (tokens.hasMoreTokens()) { date = nextToken; nextToken = tokens.nextToken(); } } } else if (tokens.hasMoreTokens()) { date = removeQuotes(nextToken); nextToken = tokens.nextToken(); } if (flags != null) { // parse flags, on create read and draft flags are on the // same messageFlags property, 8 means draft and 1 means read StringTokenizer flagtokenizer = new StringTokenizer(flags); while (flagtokenizer.hasMoreTokens()) { String flag = flagtokenizer.nextToken(); if ("\\Seen".equals(flag)) { if (properties.containsKey("draft")) { // draft message, add read flag properties.put("draft", "9"); } else { // not (yet) draft, set read flag properties.put("draft", "1"); } } else if ("\\Flagged".equals(flag)) { properties.put("flagged", "2"); } else if ("\\Answered".equals(flag)) { properties.put("answered", "102"); } else if ("$Forwarded".equals(flag)) { properties.put("forwarded", "104"); } else if ("\\Draft".equals(flag)) { if (properties.containsKey("draft")) { // read message, add draft flag properties.put("draft", "9"); } else { // not (yet) read, set draft flag properties.put("draft", "8"); } } else if ("Junk".equals(flag)) { properties.put("junk", "1"); } } } // handle optional date if (date != null) { SimpleDateFormat dateParser = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss Z", Locale.ENGLISH); Date dateReceived = dateParser.parse(date); SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); dateFormatter.setTimeZone(ExchangeSession.GMT_TIMEZONE); properties.put("datereceived", dateFormatter.format(dateReceived)); } int size = Integer.parseInt(nextToken); sendClient("+ send literal data"); byte[] buffer = in.readContent(size); // empty line readClient(); MimeMessage mimeMessage = new MimeMessage(null, new SharedByteArrayInputStream(buffer)); String messageName = UUID.randomUUID().toString() + ".EML"; try { session.createMessage(folderName, messageName, properties, mimeMessage); sendClient(commandId + " OK APPEND completed"); } catch (InsufficientStorageException e) { sendClient(commandId + " NO " + e.getMessage()); } } else if ("idle".equalsIgnoreCase(command) && imapIdleDelay > 0) { if (currentFolder != null) { sendClient("+ idling "); // clear cache before going to idle mode currentFolder.clearCache(); DavGatewayTray.resetIcon(); try { int count = 0; while (in.available() == 0) { if (++count >= imapIdleDelay) { count = 0; List<Long> previousImapUidList = currentFolder.getImapUidList(); if (session.refreshFolder(currentFolder)) { handleRefresh(previousImapUidList, currentFolder.getImapUidList()); } } // sleep 1 second Thread.sleep(1000); } // read DONE line line = readClient(); if ("DONE".equals(line)) { sendClient(commandId + " OK " + command + " terminated"); } else { sendClient(commandId + " BAD command unrecognized"); } } catch (IOException e) { // client connection closed throw new SocketException(e.getMessage()); } } else { sendClient(commandId + " NO no folder selected"); } } else if ("noop".equalsIgnoreCase(command) || "check".equalsIgnoreCase(command)) { if (currentFolder != null) { DavGatewayTray.debug(new BundleMessage("LOG_IMAP_COMMAND", command, currentFolder.folderPath)); List<Long> previousImapUidList = currentFolder.getImapUidList(); if (session.refreshFolder(currentFolder)) { handleRefresh(previousImapUidList, currentFolder.getImapUidList()); } } sendClient(commandId + " OK " + command + " completed"); } else if ("subscribe".equalsIgnoreCase(command) || "unsubscribe".equalsIgnoreCase(command)) { sendClient(commandId + " OK " + command + " completed"); } else if ("status".equalsIgnoreCase(command)) { try { String encodedFolderName = tokens.nextToken(); String folderName = BASE64MailboxDecoder.decode(encodedFolderName); ExchangeSession.Folder folder = session.getFolder(folderName); // must retrieve messages folder.loadMessages(); String parameters = tokens.nextToken(); StringBuilder answer = new StringBuilder(); StringTokenizer parametersTokens = new StringTokenizer(parameters); while (parametersTokens.hasMoreTokens()) { String token = parametersTokens.nextToken(); if ("MESSAGES".equalsIgnoreCase(token)) { answer.append("MESSAGES ").append(folder.count()).append(' '); } if ("RECENT".equalsIgnoreCase(token)) { answer.append("RECENT ").append(folder.count()).append(' '); } if ("UIDNEXT".equalsIgnoreCase(token)) { if (folder.count() == 0) { answer.append("UIDNEXT 1 "); } else { if (folder.count() == 0) { answer.append("UIDNEXT 1 "); } else { answer.append("UIDNEXT ").append(folder.getUidNext()).append(' '); } } } if ("UIDVALIDITY".equalsIgnoreCase(token)) { answer.append("UIDVALIDITY 1 "); } if ("UNSEEN".equalsIgnoreCase(token)) { answer.append("UNSEEN ").append(folder.unreadCount).append(' '); } } sendClient("* STATUS \"" + encodedFolderName + "\" (" + answer.toString().trim() + ')'); sendClient(commandId + " OK " + command + " completed"); } catch (HttpException e) { sendClient(commandId + " NO folder not found"); } } else { sendClient(commandId + " BAD command unrecognized"); } } } } else { sendClient(commandId + " BAD missing command"); } } else { sendClient("BAD Null command"); } DavGatewayTray.resetIcon(); } os.flush(); } catch (SocketTimeoutException e) { DavGatewayTray.debug(new BundleMessage("LOG_CLOSE_CONNECTION_ON_TIMEOUT")); try { sendClient("* BYE Closing connection"); } catch (IOException e1) { DavGatewayTray.debug(new BundleMessage("LOG_EXCEPTION_CLOSING_CONNECTION_ON_TIMEOUT")); } } catch (SocketException e) { LOGGER.warn(BundleMessage.formatLog("LOG_CLIENT_CLOSED_CONNECTION")); } catch (Exception e) { DavGatewayTray.log(e); try { String message = ((e.getMessage() == null) ? e.toString() : e.getMessage()).replaceAll("\\n", " "); if (commandId != null) { sendClient(commandId + " BAD unable to handle request: " + message); } else { sendClient("* BAD unable to handle request: " + message); } } catch (IOException e2) { DavGatewayTray.warn(new BundleMessage("LOG_EXCEPTION_SENDING_ERROR_TO_CLIENT"), e2); } } finally { close(); } DavGatewayTray.resetIcon(); }
public void run() { final String capabilities; int imapIdleDelay = Settings.getIntProperty("davmail.imapIdleDelay") * 60; if (imapIdleDelay > 0) { capabilities = "CAPABILITY IMAP4REV1 AUTH=LOGIN IDLE"; } else { capabilities = "CAPABILITY IMAP4REV1 AUTH=LOGIN"; } String line; String commandId = null; IMAPTokenizer tokens; try { ExchangeSessionFactory.checkConfig(); sendClient("* OK [" + capabilities + "] IMAP4rev1 DavMail " + DavGateway.getCurrentVersion() + " server ready"); for (; ;) { line = readClient(); // unable to read line, connection closed ? if (line == null) { break; } tokens = new IMAPTokenizer(line); if (tokens.hasMoreTokens()) { commandId = tokens.nextToken(); if (tokens.hasMoreTokens()) { String command = tokens.nextToken(); if ("LOGOUT".equalsIgnoreCase(command)) { sendClient("* BYE Closing connection"); break; } if ("capability".equalsIgnoreCase(command)) { sendClient("* " + capabilities); sendClient(commandId + " OK CAPABILITY completed"); } else if ("login".equalsIgnoreCase(command)) { parseCredentials(tokens); // detect shared mailbox access splitUserName(); try { session = ExchangeSessionFactory.getInstance(userName, password); sendClient(commandId + " OK Authenticated"); state = State.AUTHENTICATED; } catch (Exception e) { DavGatewayTray.error(e); sendClient(commandId + " NO LOGIN failed"); state = State.INITIAL; } } else if ("AUTHENTICATE".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String authenticationMethod = tokens.nextToken(); if ("LOGIN".equalsIgnoreCase(authenticationMethod)) { try { sendClient("+ " + base64Encode("Username:")); state = State.LOGIN; userName = base64Decode(readClient()); // detect shared mailbox access splitUserName(); sendClient("+ " + base64Encode("Password:")); state = State.PASSWORD; password = base64Decode(readClient()); session = ExchangeSessionFactory.getInstance(userName, password); sendClient(commandId + " OK Authenticated"); state = State.AUTHENTICATED; } catch (Exception e) { DavGatewayTray.error(e); sendClient(commandId + " NO LOGIN failed"); state = State.INITIAL; } } else { sendClient(commandId + " NO unsupported authentication method"); } } else { sendClient(commandId + " BAD authentication method required"); } } else { if (state != State.AUTHENTICATED) { sendClient(commandId + " BAD command authentication required"); } else { // check for expired session session = ExchangeSessionFactory.getInstance(session, userName, password); if ("lsub".equalsIgnoreCase(command) || "list".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String folderContext; if (baseMailboxPath == null) { folderContext = BASE64MailboxDecoder.decode(tokens.nextToken()); } else { folderContext = baseMailboxPath + BASE64MailboxDecoder.decode(tokens.nextToken()); } if (tokens.hasMoreTokens()) { String folderQuery = folderContext + BASE64MailboxDecoder.decode(tokens.nextToken()); if (folderQuery.endsWith("%/%") && !"/%/%".equals(folderQuery)) { List<ExchangeSession.Folder> folders = session.getSubFolders(folderQuery.substring(0, folderQuery.length() - 3), false); for (ExchangeSession.Folder folder : folders) { sendClient("* " + command + " (" + folder.getFlags() + ") \"/\" \"" + BASE64MailboxEncoder.encode(folder.folderPath) + '\"'); sendSubFolders(command, folder.folderPath, false); } sendClient(commandId + " OK " + command + " completed"); } else if (folderQuery.endsWith("%") || folderQuery.endsWith("*")) { if ("/*".equals(folderQuery) || "/%".equals(folderQuery) || "/%/%".equals(folderQuery)) { folderQuery = folderQuery.substring(1); if ("%/%".equals(folderQuery)) { folderQuery = folderQuery.substring(0, folderQuery.length() - 2); } sendClient("* " + command + " (\\HasChildren) \"/\" \"/public\""); } if ("*%".equals(folderQuery)) { folderQuery = "*"; } boolean recursive = folderQuery.endsWith("*") && !folderQuery.startsWith("/public"); sendSubFolders(command, folderQuery.substring(0, folderQuery.length() - 1), recursive); sendClient(commandId + " OK " + command + " completed"); } else { ExchangeSession.Folder folder = null; try { folder = session.getFolder(folderQuery); } catch (HttpForbiddenException e) { // access forbidden, ignore DavGatewayTray.debug(new BundleMessage("LOG_FOLDER_ACCESS_FORBIDDEN", folderQuery)); } catch (HttpNotFoundException e) { // not found, ignore DavGatewayTray.debug(new BundleMessage("LOG_FOLDER_NOT_FOUND", folderQuery)); } catch (HttpException e) { // other errors, ignore DavGatewayTray.debug(new BundleMessage("LOG_FOLDER_ACCESS_ERROR", folderQuery, e.getMessage())); } if (folder != null) { sendClient("* " + command + " (" + folder.getFlags() + ") \"/\" \"" + BASE64MailboxEncoder.encode(folder.folderPath) + '\"'); sendClient(commandId + " OK " + command + " completed"); } else { sendClient(commandId + " NO Folder not found"); } } } else { sendClient(commandId + " BAD missing folder argument"); } } else { sendClient(commandId + " BAD missing folder argument"); } } else if ("select".equalsIgnoreCase(command) || "examine".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); if (baseMailboxPath != null && !folderName.startsWith("/")) { folderName = baseMailboxPath + folderName; } try { currentFolder = session.getFolder(folderName); currentFolder.loadMessages(); sendClient("* " + currentFolder.count() + " EXISTS"); sendClient("* " + currentFolder.count() + " RECENT"); sendClient("* OK [UIDVALIDITY 1]"); if (currentFolder.count() == 0) { sendClient("* OK [UIDNEXT 1]"); } else { sendClient("* OK [UIDNEXT " + currentFolder.getUidNext() + ']'); } sendClient("* FLAGS (\\Answered \\Deleted \\Draft \\Flagged \\Seen $Forwarded Junk)"); sendClient("* OK [PERMANENTFLAGS (\\Answered \\Deleted \\Draft \\Flagged \\Seen $Forwarded Junk)]"); if ("select".equalsIgnoreCase(command)) { sendClient(commandId + " OK [READ-WRITE] " + command + " completed"); } else { sendClient(commandId + " OK [READ-ONLY] " + command + " completed"); } } catch (HttpNotFoundException e) { sendClient(commandId + " NO Not found"); } catch (HttpForbiddenException e) { sendClient(commandId + " NO Forbidden"); } } else { sendClient(commandId + " BAD command unrecognized"); } } else if ("expunge".equalsIgnoreCase(command)) { if (expunge(false)) { // need to refresh folder to avoid 404 errors session.refreshFolder(currentFolder); } sendClient(commandId + " OK " + command + " completed"); } else if ("close".equalsIgnoreCase(command)) { expunge(true); // deselect folder currentFolder = null; sendClient(commandId + " OK " + command + " completed"); } else if ("create".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); session.createMessageFolder(folderName); sendClient(commandId + " OK folder created"); } else { sendClient(commandId + " BAD missing create argument"); } } else if ("rename".equalsIgnoreCase(command)) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); String targetName = BASE64MailboxDecoder.decode(tokens.nextToken()); try { session.moveFolder(folderName, targetName); sendClient(commandId + " OK rename completed"); } catch (HttpException e) { sendClient(commandId + " NO " + e.getMessage()); } } else if ("delete".equalsIgnoreCase(command)) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); try { session.deleteFolder(folderName); sendClient(commandId + " OK folder deleted"); } catch (HttpException e) { sendClient(commandId + " NO " + e.getMessage()); } } else if ("uid".equalsIgnoreCase(command)) { if (tokens.hasMoreTokens()) { String subcommand = tokens.nextToken(); if ("fetch".equalsIgnoreCase(subcommand)) { if (currentFolder == null) { sendClient(commandId + " NO no folder selected"); } else { String ranges = tokens.nextToken(); if (ranges == null) { sendClient(commandId + " BAD missing range parameter"); } else { String parameters = null; if (tokens.hasMoreTokens()) { parameters = tokens.nextToken(); } UIDRangeIterator uidRangeIterator = new UIDRangeIterator(currentFolder.messages, ranges); while (uidRangeIterator.hasNext()) { DavGatewayTray.switchIcon(); ExchangeSession.Message message = uidRangeIterator.next(); try { handleFetch(message, uidRangeIterator.currentIndex, parameters); } catch (SocketException e) { // client closed connection throw e; } catch (IOException e) { DavGatewayTray.log(e); sendClient(commandId + " NO Unable to retrieve message: " + e.getMessage()); } } sendClient(commandId + " OK UID FETCH completed"); } } } else if ("search".equalsIgnoreCase(subcommand)) { List<Long> uidList = handleSearch(tokens); if (uidList.isEmpty()) { sendClient("* SEARCH"); } else { for (long uid : uidList) { sendClient("* SEARCH " + uid); } } sendClient(commandId + " OK SEARCH completed"); } else if ("store".equalsIgnoreCase(subcommand)) { UIDRangeIterator uidRangeIterator = new UIDRangeIterator(currentFolder.messages, tokens.nextToken()); String action = tokens.nextToken(); String flags = tokens.nextToken(); handleStore(commandId, uidRangeIterator, action, flags); } else if ("copy".equalsIgnoreCase(subcommand)) { try { UIDRangeIterator uidRangeIterator = new UIDRangeIterator(currentFolder.messages, tokens.nextToken()); String targetName = BASE64MailboxDecoder.decode(tokens.nextToken()); while (uidRangeIterator.hasNext()) { DavGatewayTray.switchIcon(); ExchangeSession.Message message = uidRangeIterator.next(); session.copyMessage(message, targetName); } sendClient(commandId + " OK copy completed"); } catch (HttpException e) { sendClient(commandId + " NO " + e.getMessage()); } } } else { sendClient(commandId + " BAD command unrecognized"); } } else if ("search".equalsIgnoreCase(command)) { if (currentFolder == null) { sendClient(commandId + " NO no folder selected"); } else { List<Long> uidList = handleSearch(tokens); if (uidList.isEmpty()) { sendClient("* SEARCH"); } else { int currentIndex = 0; for (ExchangeSession.Message message : currentFolder.messages) { currentIndex++; if (uidList.contains(message.getImapUid())) { sendClient("* SEARCH " + currentIndex); } } } sendClient(commandId + " OK SEARCH completed"); } } else if ("fetch".equalsIgnoreCase(command)) { if (currentFolder == null) { sendClient(commandId + " NO no folder selected"); } else { RangeIterator rangeIterator = new RangeIterator(currentFolder.messages, tokens.nextToken()); String parameters = null; if (tokens.hasMoreTokens()) { parameters = tokens.nextToken(); } while (rangeIterator.hasNext()) { DavGatewayTray.switchIcon(); ExchangeSession.Message message = rangeIterator.next(); try { handleFetch(message, rangeIterator.currentIndex, parameters); } catch (SocketException e) { // client closed connection, rethrow exception throw e; } catch (IOException e) { DavGatewayTray.log(e); sendClient(commandId + " NO Unable to retrieve message: " + e.getMessage()); } } sendClient(commandId + " OK FETCH completed"); } } else if ("store".equalsIgnoreCase(command)) { RangeIterator rangeIterator = new RangeIterator(currentFolder.messages, tokens.nextToken()); String action = tokens.nextToken(); String flags = tokens.nextToken(); handleStore(commandId, rangeIterator, action, flags); } else if ("copy".equalsIgnoreCase(command)) { try { RangeIterator rangeIterator = new RangeIterator(currentFolder.messages, tokens.nextToken()); String targetName = BASE64MailboxDecoder.decode(tokens.nextToken()); while (rangeIterator.hasNext()) { DavGatewayTray.switchIcon(); ExchangeSession.Message message = rangeIterator.next(); session.copyMessage(message, targetName); } sendClient(commandId + " OK copy completed"); } catch (HttpException e) { sendClient(commandId + " NO " + e.getMessage()); } } else if ("append".equalsIgnoreCase(command)) { String folderName = BASE64MailboxDecoder.decode(tokens.nextToken()); HashMap<String, String> properties = new HashMap<String, String>(); String flags = null; String date = null; // handle optional flags String nextToken = tokens.nextQuotedToken(); if (nextToken.startsWith("(")) { flags = removeQuotes(nextToken); if (tokens.hasMoreTokens()) { nextToken = tokens.nextToken(); if (tokens.hasMoreTokens()) { date = nextToken; nextToken = tokens.nextToken(); } } } else if (tokens.hasMoreTokens()) { date = removeQuotes(nextToken); nextToken = tokens.nextToken(); } if (flags != null) { // parse flags, on create read and draft flags are on the // same messageFlags property, 8 means draft and 1 means read StringTokenizer flagtokenizer = new StringTokenizer(flags); while (flagtokenizer.hasMoreTokens()) { String flag = flagtokenizer.nextToken(); if ("\\Seen".equals(flag)) { if (properties.containsKey("draft")) { // draft message, add read flag properties.put("draft", "9"); } else { // not (yet) draft, set read flag properties.put("draft", "1"); } } else if ("\\Flagged".equals(flag)) { properties.put("flagged", "2"); } else if ("\\Answered".equals(flag)) { properties.put("answered", "102"); } else if ("$Forwarded".equals(flag)) { properties.put("forwarded", "104"); } else if ("\\Draft".equals(flag)) { if (properties.containsKey("draft")) { // read message, add draft flag properties.put("draft", "9"); } else { // not (yet) read, set draft flag properties.put("draft", "8"); } } else if ("Junk".equals(flag)) { properties.put("junk", "1"); } } } // handle optional date if (date != null) { SimpleDateFormat dateParser = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss Z", Locale.ENGLISH); Date dateReceived = dateParser.parse(date); SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); dateFormatter.setTimeZone(ExchangeSession.GMT_TIMEZONE); properties.put("datereceived", dateFormatter.format(dateReceived)); } int size = Integer.parseInt(removeQuotes(nextToken)); sendClient("+ send literal data"); byte[] buffer = in.readContent(size); // empty line readClient(); MimeMessage mimeMessage = new MimeMessage(null, new SharedByteArrayInputStream(buffer)); String messageName = UUID.randomUUID().toString() + ".EML"; try { session.createMessage(folderName, messageName, properties, mimeMessage); sendClient(commandId + " OK APPEND completed"); } catch (InsufficientStorageException e) { sendClient(commandId + " NO " + e.getMessage()); } } else if ("idle".equalsIgnoreCase(command) && imapIdleDelay > 0) { if (currentFolder != null) { sendClient("+ idling "); // clear cache before going to idle mode currentFolder.clearCache(); DavGatewayTray.resetIcon(); try { int count = 0; while (in.available() == 0) { if (++count >= imapIdleDelay) { count = 0; List<Long> previousImapUidList = currentFolder.getImapUidList(); if (session.refreshFolder(currentFolder)) { handleRefresh(previousImapUidList, currentFolder.getImapUidList()); } } // sleep 1 second Thread.sleep(1000); } // read DONE line line = readClient(); if ("DONE".equals(line)) { sendClient(commandId + " OK " + command + " terminated"); } else { sendClient(commandId + " BAD command unrecognized"); } } catch (IOException e) { // client connection closed throw new SocketException(e.getMessage()); } } else { sendClient(commandId + " NO no folder selected"); } } else if ("noop".equalsIgnoreCase(command) || "check".equalsIgnoreCase(command)) { if (currentFolder != null) { DavGatewayTray.debug(new BundleMessage("LOG_IMAP_COMMAND", command, currentFolder.folderPath)); List<Long> previousImapUidList = currentFolder.getImapUidList(); if (session.refreshFolder(currentFolder)) { handleRefresh(previousImapUidList, currentFolder.getImapUidList()); } } sendClient(commandId + " OK " + command + " completed"); } else if ("subscribe".equalsIgnoreCase(command) || "unsubscribe".equalsIgnoreCase(command)) { sendClient(commandId + " OK " + command + " completed"); } else if ("status".equalsIgnoreCase(command)) { try { String encodedFolderName = tokens.nextToken(); String folderName = BASE64MailboxDecoder.decode(encodedFolderName); ExchangeSession.Folder folder = session.getFolder(folderName); // must retrieve messages folder.loadMessages(); String parameters = tokens.nextToken(); StringBuilder answer = new StringBuilder(); StringTokenizer parametersTokens = new StringTokenizer(parameters); while (parametersTokens.hasMoreTokens()) { String token = parametersTokens.nextToken(); if ("MESSAGES".equalsIgnoreCase(token)) { answer.append("MESSAGES ").append(folder.count()).append(' '); } if ("RECENT".equalsIgnoreCase(token)) { answer.append("RECENT ").append(folder.count()).append(' '); } if ("UIDNEXT".equalsIgnoreCase(token)) { if (folder.count() == 0) { answer.append("UIDNEXT 1 "); } else { if (folder.count() == 0) { answer.append("UIDNEXT 1 "); } else { answer.append("UIDNEXT ").append(folder.getUidNext()).append(' '); } } } if ("UIDVALIDITY".equalsIgnoreCase(token)) { answer.append("UIDVALIDITY 1 "); } if ("UNSEEN".equalsIgnoreCase(token)) { answer.append("UNSEEN ").append(folder.unreadCount).append(' '); } } sendClient("* STATUS \"" + encodedFolderName + "\" (" + answer.toString().trim() + ')'); sendClient(commandId + " OK " + command + " completed"); } catch (HttpException e) { sendClient(commandId + " NO folder not found"); } } else { sendClient(commandId + " BAD command unrecognized"); } } } } else { sendClient(commandId + " BAD missing command"); } } else { sendClient("BAD Null command"); } DavGatewayTray.resetIcon(); } os.flush(); } catch (SocketTimeoutException e) { DavGatewayTray.debug(new BundleMessage("LOG_CLOSE_CONNECTION_ON_TIMEOUT")); try { sendClient("* BYE Closing connection"); } catch (IOException e1) { DavGatewayTray.debug(new BundleMessage("LOG_EXCEPTION_CLOSING_CONNECTION_ON_TIMEOUT")); } } catch (SocketException e) { LOGGER.warn(BundleMessage.formatLog("LOG_CLIENT_CLOSED_CONNECTION")); } catch (Exception e) { DavGatewayTray.log(e); try { String message = ((e.getMessage() == null) ? e.toString() : e.getMessage()).replaceAll("\\n", " "); if (commandId != null) { sendClient(commandId + " BAD unable to handle request: " + message); } else { sendClient("* BAD unable to handle request: " + message); } } catch (IOException e2) { DavGatewayTray.warn(new BundleMessage("LOG_EXCEPTION_SENDING_ERROR_TO_CLIENT"), e2); } } finally { close(); } DavGatewayTray.resetIcon(); }
diff --git a/finance/swing/src/main/java/com/lavida/swing/service/ArticlesTableModel.java b/finance/swing/src/main/java/com/lavida/swing/service/ArticlesTableModel.java index 97b9c77..42c3ee4 100644 --- a/finance/swing/src/main/java/com/lavida/swing/service/ArticlesTableModel.java +++ b/finance/swing/src/main/java/com/lavida/swing/service/ArticlesTableModel.java @@ -1,685 +1,685 @@ package com.lavida.swing.service; import com.google.gdata.util.ServiceException; import com.lavida.service.FiltersPurpose; import com.lavida.service.UserService; import com.lavida.service.ViewColumn; import com.lavida.service.dao.ArticleDao; import com.lavida.service.entity.ArticleJdo; import com.lavida.service.utils.DateConverter; import com.lavida.swing.LocaleHolder; import com.lavida.swing.event.ArticleUpdateEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationListener; import org.springframework.context.MessageSource; import javax.annotation.PostConstruct; import javax.annotation.Resource; import javax.swing.table.AbstractTableModel; import java.io.IOException; import java.lang.reflect.Field; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * Created: 15:33 06.08.13 * <p/> * The <code>ArticlesTableModel</code> class specifies the methods the * <code>JTable</code> will use to interrogate a tabular data model of ArticlesJdo. * * @author Ruslan */ public class ArticlesTableModel extends AbstractTableModel implements ApplicationListener<ArticleUpdateEvent> { private static final Logger logger = LoggerFactory.getLogger(ArticlesTableModel.class); private List<String> headerTitles = new ArrayList<String>(); private List<String> articleFieldsSequence; private Map<Integer, SimpleDateFormat> columnIndexToDateFormat; private ArticleJdo selectedArticle; private int totalCountArticles; private double totalPurchaseCostEUR, totalCostEUR, totalPriceUAH, totalCostUAH, minimalMultiplier, normalMultiplier; private String sellerName; @Resource private ArticleDao articleDao; @Resource private ArticleServiceSwingWrapper articleServiceSwingWrapper; @Resource private UserService userService; @Resource private MessageSource messageSource; @Resource private LocaleHolder localeHolder; private String queryName; private List<ArticleJdo> tableData; private static final List<String> FORBIDDEN_ROLES = new ArrayList<String>(); static { FORBIDDEN_ROLES.add("ROLE_SELLER_LA_VIDA"); FORBIDDEN_ROLES.add("ROLE_SELLER_SLAVYANKA"); FORBIDDEN_ROLES.add("ROLE_SELLER_NOVOMOSKOVSK"); } @Override public void onApplicationEvent(ArticleUpdateEvent event) { updateTableData(); } private void updateTableData () { if (queryName != null) { tableData = articleDao.get(queryName); } } public List<ArticleJdo> getTableData() { if (tableData == null && queryName != null) { tableData = articleDao.get(queryName); } return tableData; } public FiltersPurpose getFiltersPurpose() { if (ArticleJdo.FIND_SOLD.equals(queryName) || ArticleJdo.FIND_SOLD_LA_VIDA.equals(queryName) || ArticleJdo.FIND_SOLD_SLAVYANKA.equals(queryName) || ArticleJdo.FIND_SOLD_NOVOMOSKOVSK.equals(queryName)) { return FiltersPurpose.SOLD_PRODUCTS; } else if (ArticleJdo.FIND_NOT_SOLD.equals(queryName) || ArticleJdo.FIND_NOT_SOLD_LA_VIDA.equals(queryName) || ArticleJdo.FIND_NOT_SOLD_SLAVYANKA.equals(queryName) || ArticleJdo.FIND_NOT_SOLD_NOVOMOSKOVSK.equals(queryName)) { return FiltersPurpose.SELL_PRODUCTS; } else { return FiltersPurpose.ADD_NEW_PRODUCTS; } } @Override public int getRowCount() { return getTableData().size(); } @Override public int getColumnCount() { return headerTitles.size(); } @Override public String getColumnName(int columnIndex) { return headerTitles.get(columnIndex); } @Override public Object getValueAt(int rowIndex, int columnIndex) { Object value = getRawValueAt(rowIndex, columnIndex); if (value instanceof Calendar) { return columnIndexToDateFormat.get(columnIndex).format(((Calendar) value).getTime()); } else if (value instanceof Date) { return columnIndexToDateFormat.get(columnIndex).format(value); } else { return value; } } public ArticleJdo getArticleJdoByRowIndex(int rowIndex) { return getTableData().get(rowIndex); } public Object getRawValueAt(int rowIndex, int columnIndex) { ArticleJdo articleJdo = getArticleJdoByRowIndex(rowIndex); try { Field field = ArticleJdo.class.getDeclaredField(articleFieldsSequence.get(columnIndex)); field.setAccessible(true); return field.get(articleJdo); } catch (Exception e) { logger.warn(e.getMessage(), e); throw new RuntimeException(e); } } @PostConstruct public void initHeaderFieldAndTitles() { this.articleFieldsSequence = new ArrayList<String>(); this.headerTitles = new ArrayList<String>(); this.columnIndexToDateFormat = new HashMap<Integer, SimpleDateFormat>(); if (queryName != null) { this.tableData = articleDao.get(queryName); } else { this.tableData = new ArrayList<ArticleJdo>(); } for (Field field : ArticleJdo.class.getDeclaredFields()) { ViewColumn viewColumn = field.getAnnotation(ViewColumn.class); if (viewColumn != null && viewColumn.show()) { field.setAccessible(true); if (ArticleJdo.FIND_NOT_SOLD.equals(queryName) && !(viewColumn.titleKey().equals("mainForm.table.articles.column.sell.marker.title") || viewColumn.titleKey().equals("mainForm.table.articles.column.sell.date.title") || viewColumn.titleKey().equals("mainForm.table.articles.column.seller.title") || viewColumn.titleKey().equals("mainForm.table.articles.column.tags.title") || viewColumn.titleKey().equals("mainForm.table.articles.column.refund.title"))) { this.articleFieldsSequence.add(field.getName()); if (viewColumn.titleKey().isEmpty()) { this.headerTitles.add(field.getName()); } else { this.headerTitles.add(messageSource.getMessage(viewColumn.titleKey(), null, localeHolder.getLocale())); } } else if (ArticleJdo.FIND_SOLD.equals(queryName)) { this.articleFieldsSequence.add(field.getName()); if (viewColumn.titleKey().isEmpty()) { this.headerTitles.add(field.getName()); } else { this.headerTitles.add(messageSource.getMessage(viewColumn.titleKey(), null, localeHolder.getLocale())); } } else if (queryName == null && !(viewColumn.titleKey().equals("mainForm.table.articles.column.sell.marker.title") || viewColumn.titleKey().equals("mainForm.table.articles.column.sell.date.title") || viewColumn.titleKey().equals("mainForm.table.articles.column.seller.title") || viewColumn.titleKey().equals("mainForm.table.articles.column.tags.title") || viewColumn.titleKey().equals("mainForm.table.articles.column.raised.price.uah.title") || viewColumn.titleKey().equals("mainForm.table.articles.column.old.price.uah.title") || viewColumn.titleKey().equals("mainForm.table.articles.column.refund.title"))) { this.articleFieldsSequence.add(field.getName()); if (viewColumn.titleKey().isEmpty()) { this.headerTitles.add(field.getName()); } else { this.headerTitles.add(messageSource.getMessage(viewColumn.titleKey(), null, localeHolder.getLocale())); } } if (field.getType() == Calendar.class) { this.columnIndexToDateFormat.put(headerTitles.size() - 1, new SimpleDateFormat(viewColumn.datePattern())); } else if (field.getType() == Date.class) { this.columnIndexToDateFormat.put(headerTitles.size() - 1, new SimpleDateFormat(viewColumn.datePattern())); } } } } public List<String> getForbiddenHeadersToShow(MessageSource messageSource, Locale locale, List<String> userRoles) { List<String> forbiddenHeaders = new ArrayList<String>(); for (Field field : ArticleJdo.class.getDeclaredFields()) { ViewColumn viewColumn = field.getAnnotation(ViewColumn.class); if (viewColumn != null && viewColumn.show()) { if (ArticleJdo.FIND_NOT_SOLD.equals(queryName) && !(viewColumn.titleKey().equals("mainForm.table.articles.column.sell.marker.title") || viewColumn.titleKey().equals("mainForm.table.articles.column.sell.date.title") || viewColumn.titleKey().equals("mainForm.table.articles.column.seller.title") || viewColumn.titleKey().equals("mainForm.table.articles.column.tags.title") || viewColumn.titleKey().equals("mainForm.table.articles.column.refund.title"))) { if (isForbidden(userRoles, viewColumn.forbiddenRoles())) { forbiddenHeaders.add(viewColumn.titleKey().isEmpty() ? field.getName() : messageSource.getMessage(viewColumn.titleKey(), null, locale)); } } else if (ArticleJdo.FIND_SOLD.equals(queryName)) { if (isForbidden(userRoles, viewColumn.forbiddenRoles())) { forbiddenHeaders.add(viewColumn.titleKey().isEmpty() ? field.getName() : messageSource.getMessage(viewColumn.titleKey(), null, locale)); } } else if (queryName == null && !(viewColumn.titleKey().equals("mainForm.table.articles.column.sell.marker.title") || viewColumn.titleKey().equals("mainForm.table.articles.column.sell.date.title") || viewColumn.titleKey().equals("mainForm.table.articles.column.seller.title") || viewColumn.titleKey().equals("mainForm.table.articles.column.tags.title") || viewColumn.titleKey().equals("mainForm.table.articles.column.raised.price.uah.title") || viewColumn.titleKey().equals("mainForm.table.articles.column.old.price.uah.title") || viewColumn.titleKey().equals("mainForm.table.articles.column.refund.title"))) { if (isForbidden(userRoles, viewColumn.forbiddenRoles())) { forbiddenHeaders.add(viewColumn.titleKey().isEmpty() ? field.getName() : messageSource.getMessage(viewColumn.titleKey(), null, locale)); } } } } return forbiddenHeaders; } private boolean isForbidden(List<String> userRoles, String forbiddenRoles) { if (!forbiddenRoles.isEmpty()) { String[] forbiddenRolesArray = forbiddenRoles.split(","); for (String forbiddenRole : forbiddenRolesArray) { if (userRoles.contains(forbiddenRole.trim())) { return true; } } } return false; } private boolean isForbidden(List<String> userRoles, List<String> forbiddenRoles) { for (String forbiddenRole : forbiddenRoles) { if (userRoles.contains(forbiddenRole)) { return true; } } return false; } /** * Initializes fields of the analyze component. */ public void initAnalyzeFields() { int totalCount = 0; double totalCostEUR = 0; double totalPrice = 0; double totalPurchaseCostEUR = 0; double totalCostUAH = 0; double normalMultiplierSum = 0; double normalMultiplier = 0; double minimalMultiplier = 0; List<ArticleJdo> articleJdoList = getTableData(); if (articleJdoList.size() > 0) { minimalMultiplier = articleJdoList.get(0).getMultiplier(); for (ArticleJdo articleJdo : articleJdoList) { ++totalCount; totalPurchaseCostEUR += articleJdo.getPurchasePriceEUR(); totalCostEUR += articleJdo.getTotalCostEUR(); totalCostUAH += articleJdo.getTotalCostUAH(); totalPrice += (articleJdo.getSalePrice()); if (minimalMultiplier > articleJdo.getMultiplier()) { minimalMultiplier = articleJdo.getMultiplier(); } normalMultiplierSum += articleJdo.getMultiplier(); } normalMultiplier = normalMultiplierSum / totalCount; } this.totalCountArticles = totalCount; this.totalCostEUR = totalCostEUR; this.totalPriceUAH = totalPrice; this.totalPurchaseCostEUR = totalPurchaseCostEUR; this.totalCostUAH = totalCostUAH; this.minimalMultiplier = minimalMultiplier; this.normalMultiplier = normalMultiplier; } public Map<String, Integer> getColumnHeaderToWidth() { Map<String, Integer> columnHeaderToWidth = new HashMap<String, Integer>(headerTitles.size()); label: for (String columnHeader : headerTitles) { Integer width; for (Field field : ArticleJdo.class.getDeclaredFields()) { ViewColumn viewColumn = field.getAnnotation(ViewColumn.class); if (viewColumn != null) { if (viewColumn.titleKey().isEmpty() && columnHeader.equals(field.getName())) { width = viewColumn.columnWidth(); columnHeaderToWidth.put(columnHeader, width); continue label; } else if (!viewColumn.titleKey().isEmpty() && columnHeader.equals(messageSource.getMessage(viewColumn.titleKey(), null, localeHolder.getLocale()))) { width = viewColumn.columnWidth(); columnHeaderToWidth.put(columnHeader, width); continue label; } } } } return columnHeaderToWidth; } /** * Returns true if the user has permissions. * * @param rowIndex the row being queried * @param columnIndex the column being queried * @return true the user has permissions. */ @Override public boolean isCellEditable(int rowIndex, int columnIndex) { if (articleFieldsSequence.get(columnIndex).equals("totalCostEUR") || articleFieldsSequence.get(columnIndex).equals("calculatedSalePrice")) { return false; } else return !isForbidden(userService.getCurrentUserRoles(), FORBIDDEN_ROLES); } /** * This empty implementation is provided so users don't have to implement * this method if their data model is not editable. * * @param aValue value to assign to cell * @param rowIndex row of cell * @param columnIndex column of cell */ @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { ArticleJdo articleJdo = getArticleJdoByRowIndex(rowIndex); String value = (String) aValue; SimpleDateFormat calendarFormatter = new SimpleDateFormat("dd.MM.yyyy"); calendarFormatter.setLenient(false); try { Field field = ArticleJdo.class.getDeclaredField(articleFieldsSequence.get(columnIndex)); field.setAccessible(true); if (int.class == field.getType()) { int typeValue; if (value.isEmpty()) { typeValue = 1; } else { typeValue = Integer.parseInt(value); } if (typeValue != field.getInt(articleJdo)) { field.setInt(articleJdo, typeValue); if (field.getName().equals("quantity") && typeValue > 1) { field.set(articleJdo, 1); int quantity = typeValue; for (int i = 1; i < quantity; ++i) { ArticleJdo newArticle = (ArticleJdo) articleJdo.clone(); newArticle.setSpreadsheetRow(0); newArticle.setId(0); tableData.add(newArticle); updateTable(newArticle); } } } else return; } else if (boolean.class == field.getType()) { boolean typeValue = Boolean.parseBoolean(value); if (typeValue != field.getBoolean(articleJdo)) { field.setBoolean(articleJdo, typeValue); } else return; } else if (double.class == field.getType()) { double typeValue; if (value.isEmpty()) { typeValue = 0.0; } else { typeValue = fixIfNeedAndParseDouble(value); typeValue = BigDecimal.valueOf(typeValue).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); } if (typeValue != field.getDouble(articleJdo)) { field.setDouble(articleJdo, typeValue); if (field.getName().equals("transportCostEUR") || field.getName().equals("purchasePriceEUR")) { double totalCostEUR = articleJdo.getPurchasePriceEUR() + articleJdo.getTransportCostEUR() + 0.065*(articleJdo.getPurchasePriceEUR() + articleJdo.getTransportCostEUR()); totalCostEUR = BigDecimal.valueOf(totalCostEUR).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); articleJdo.setTotalCostEUR(totalCostEUR); double totalCostUAH = totalCostEUR * 11.0; totalCostUAH = BigDecimal.valueOf(totalCostUAH).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); articleJdo.setTotalCostUAH(totalCostUAH); double calculatedSalePrice = totalCostUAH * articleJdo.getMultiplier() * 1.1; calculatedSalePrice = BigDecimal.valueOf(calculatedSalePrice).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); articleJdo.setCalculatedSalePrice(calculatedSalePrice); } if (field.getName().equals("multiplier") || field.getName().equals("totalCostUAH")) { - double calculatedSalePrice = articleJdo.getTotalCostUAH() * articleJdo.getMultiplier(); + double calculatedSalePrice = articleJdo.getTotalCostUAH() * articleJdo.getMultiplier() * 1.1; calculatedSalePrice = BigDecimal.valueOf(calculatedSalePrice).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); articleJdo.setCalculatedSalePrice(calculatedSalePrice); } } else return; } else if (char.class == field.getType()) { char typeValue = value.charAt(0); if (typeValue != field.getChar(articleJdo)) { field.setChar(articleJdo, typeValue); } else return; } else if (long.class == field.getType()) { long typeValue = Long.parseLong(value); if (typeValue != field.getLong(articleJdo)) { field.setLong(articleJdo, typeValue); } else return; } else if (Integer.class == field.getType()) { Integer typeValue; if (value.isEmpty()) { typeValue = 0; } else { typeValue = Integer.parseInt(value); } if (!typeValue.equals(field.get(articleJdo))) { field.set(articleJdo, typeValue); if (field.getName().equals("quantity") && typeValue > 1) { field.set(articleJdo, 1); int quantity = typeValue; for (int i = 1; i < quantity; ++i) { ArticleJdo newArticle = (ArticleJdo) articleJdo.clone(); newArticle.setSpreadsheetRow(0); newArticle.setId(0); tableData.add(newArticle); updateTable(newArticle); } } } else return; } else if (Boolean.class == field.getType()) { Boolean typeValue = Boolean.parseBoolean(value); if (!typeValue.equals(field.get(articleJdo))) { field.set(articleJdo, typeValue); } else return; } else if (Double.class == field.getType()) { Double typeValue; if (value.isEmpty()) { typeValue = 0.0; } else { typeValue = fixIfNeedAndParseDouble(value); typeValue = BigDecimal.valueOf(typeValue).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); } if (!typeValue.equals(field.get(articleJdo))) { field.set(articleJdo, typeValue); if (field.getName().equals("transportCostEUR") || field.getName().equals("purchasePriceEUR")) { double totalCostEUR = articleJdo.getPurchasePriceEUR() + articleJdo.getTransportCostEUR(); totalCostEUR = BigDecimal.valueOf(totalCostEUR).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); articleJdo.setTotalCostEUR(totalCostEUR); double totalCostUAH = totalCostEUR * 11.0; totalCostUAH = BigDecimal.valueOf(totalCostUAH).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); articleJdo.setTotalCostUAH(totalCostUAH); double calculatedSalePrice = totalCostUAH * articleJdo.getMultiplier(); calculatedSalePrice = BigDecimal.valueOf(calculatedSalePrice).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); articleJdo.setCalculatedSalePrice(calculatedSalePrice); } if (field.getName().equals("multiplier") || field.getName().equals("totalCostUAH")) { double calculatedSalePrice = articleJdo.getTotalCostUAH() * articleJdo.getMultiplier(); calculatedSalePrice = BigDecimal.valueOf(calculatedSalePrice).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); articleJdo.setCalculatedSalePrice(calculatedSalePrice); } } else return; } else if (Character.class == field.getType()) { Character typeValue = value.charAt(0); if (!typeValue.equals(field.get(articleJdo))) { field.set(articleJdo, typeValue); } else return; } else if (Long.class == field.getType()) { Long typeValue = Long.parseLong(value); if (!typeValue.equals(field.get(articleJdo))) { field.set(articleJdo, typeValue); } else return; } else if (Calendar.class == field.getType()) { Calendar typeValue = Calendar.getInstance(); if (!value.isEmpty()) { String formattedValue = value.replace(",", ".").trim(); if (formattedValue.matches("\\d{2}.\\d{2}.\\d{4}")) { Date time; try { time = calendarFormatter.parse(formattedValue); } catch (ParseException e) { logger.warn(e.getMessage(), e); return; } typeValue.setTime(time); if (!typeValue.equals(field.get(articleJdo))) { field.set(articleJdo, typeValue); } else return; } } else { if (field.get(articleJdo) != null) { field.set(articleJdo, null); } else return; } } else if (Date.class == field.getType()) { if (!value.isEmpty()) { String formattedValue = value.replace(",", ".").trim(); if (formattedValue.matches("\\d{2}.\\d{2}.\\d{4} \\d{2}:\\d{2}:\\d{2}")) { Date typeValue; try { typeValue = DateConverter.convertStringToDate(formattedValue); } catch (ParseException e) { logger.warn(e.getMessage(), e); return; } if (!typeValue.equals(field.get(articleJdo))) { field.set(articleJdo, typeValue); } else return; } } else { if (field.get(articleJdo) != null) { field.set(articleJdo, null); } else return; } } else { if (!value.equals(field.get(articleJdo))) { field.set(articleJdo, value); } else return; } } catch (Exception e) { logger.warn(e.getMessage(), e); throw new RuntimeException(e); } updateTable(articleJdo); } private double fixIfNeedAndParseDouble(String doubleString) { // todo make reusable with GoogleCellsTransformer if (doubleString == null || doubleString.trim().isEmpty()) { return 0; } return Double.parseDouble(doubleString.replace(" ", "").replace(",", ".")); } /** * Returns <code>Object.class</code> regardless of <code>columnIndex</code>. * * @param columnIndex the column being queried * @return the {@code Class} object representing the class or interface * that declares the field represented by this {@code Field} object. */ @Override public Class<?> getColumnClass(int columnIndex) { return Object.class; } /** * Updates table and remote spreadsheet with the changed article * * @param changedArticle the articleJdo to be updated. */ private void updateTable(ArticleJdo changedArticle) { if (queryName != null) { try { articleServiceSwingWrapper.updateToSpreadsheet(changedArticle, null); articleServiceSwingWrapper.update(changedArticle); } catch (IOException e) { logger.warn(e.getMessage(), e); changedArticle.setPostponedOperationDate(new Date()); articleServiceSwingWrapper.update(changedArticle); } catch (ServiceException e) { logger.warn(e.getMessage(), e); changedArticle.setPostponedOperationDate(new Date()); articleServiceSwingWrapper.update(changedArticle); } } fireTableDataChanged(); } /** * Changes the ArticlesTableModel queryName according to the user's first role. * @param userRoles the list of user's roles. */ public void filterTableDataByRole (List<String> userRoles) { if (ArticleJdo.FIND_NOT_SOLD.equals(queryName)) { for (String role : userRoles) { if ("ROLE_SELLER_LA_VIDA".equals(role)) { this.setQueryName(ArticleJdo.FIND_NOT_SOLD_LA_VIDA); updateTableData(); fireTableDataChanged(); return; } else if ("ROLE_SELLER_SLAVYANKA".equals(role)) { this.setQueryName(ArticleJdo.FIND_NOT_SOLD_SLAVYANKA); updateTableData(); fireTableDataChanged(); return; } else if ("ROLE_SELLER_NOVOMOSKOVSK".equals(role)) { this.setQueryName(ArticleJdo.FIND_NOT_SOLD_NOVOMOSKOVSK); updateTableData(); fireTableDataChanged(); return; } } } else if (ArticleJdo.FIND_SOLD.equals(queryName)) { for (String role : userRoles) { if ("ROLE_SELLER_LA_VIDA".equals(role)) { this.setQueryName(ArticleJdo.FIND_SOLD_LA_VIDA); updateTableData(); fireTableDataChanged(); return; } else if ("ROLE_SELLER_SLAVYANKA".equals(role)) { this.setQueryName(ArticleJdo.FIND_SOLD_SLAVYANKA); updateTableData(); fireTableDataChanged(); return; } else if ("ROLE_SELLER_NOVOMOSKOVSK".equals(role)) { this.setQueryName(ArticleJdo.FIND_SOLD_NOVOMOSKOVSK); updateTableData(); fireTableDataChanged(); return; } } } } public void setSelectedArticle(ArticleJdo selectedArticle) { this.selectedArticle = selectedArticle; } public ArticleJdo getSelectedArticle() { return selectedArticle; } public void setQueryName(String queryName) { this.queryName = queryName; } public int getTotalCountArticles() { return totalCountArticles; } public double getTotalCostEUR() { return totalCostEUR; } public double getTotalPriceUAH() { return totalPriceUAH; } public String getSellerName() { return sellerName; } public void setSellerName(String sellerName) { this.sellerName = sellerName; } public void setTableData(List<ArticleJdo> tableData) { this.tableData = tableData; } public List<String> getHeaderTitles() { return headerTitles; } public double getTotalPurchaseCostEUR() { return totalPurchaseCostEUR; } public double getTotalCostUAH() { return totalCostUAH; } public double getMinimalMultiplier() { return minimalMultiplier; } public double getNormalMultiplier() { return normalMultiplier; } }
true
true
public void setValueAt(Object aValue, int rowIndex, int columnIndex) { ArticleJdo articleJdo = getArticleJdoByRowIndex(rowIndex); String value = (String) aValue; SimpleDateFormat calendarFormatter = new SimpleDateFormat("dd.MM.yyyy"); calendarFormatter.setLenient(false); try { Field field = ArticleJdo.class.getDeclaredField(articleFieldsSequence.get(columnIndex)); field.setAccessible(true); if (int.class == field.getType()) { int typeValue; if (value.isEmpty()) { typeValue = 1; } else { typeValue = Integer.parseInt(value); } if (typeValue != field.getInt(articleJdo)) { field.setInt(articleJdo, typeValue); if (field.getName().equals("quantity") && typeValue > 1) { field.set(articleJdo, 1); int quantity = typeValue; for (int i = 1; i < quantity; ++i) { ArticleJdo newArticle = (ArticleJdo) articleJdo.clone(); newArticle.setSpreadsheetRow(0); newArticle.setId(0); tableData.add(newArticle); updateTable(newArticle); } } } else return; } else if (boolean.class == field.getType()) { boolean typeValue = Boolean.parseBoolean(value); if (typeValue != field.getBoolean(articleJdo)) { field.setBoolean(articleJdo, typeValue); } else return; } else if (double.class == field.getType()) { double typeValue; if (value.isEmpty()) { typeValue = 0.0; } else { typeValue = fixIfNeedAndParseDouble(value); typeValue = BigDecimal.valueOf(typeValue).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); } if (typeValue != field.getDouble(articleJdo)) { field.setDouble(articleJdo, typeValue); if (field.getName().equals("transportCostEUR") || field.getName().equals("purchasePriceEUR")) { double totalCostEUR = articleJdo.getPurchasePriceEUR() + articleJdo.getTransportCostEUR() + 0.065*(articleJdo.getPurchasePriceEUR() + articleJdo.getTransportCostEUR()); totalCostEUR = BigDecimal.valueOf(totalCostEUR).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); articleJdo.setTotalCostEUR(totalCostEUR); double totalCostUAH = totalCostEUR * 11.0; totalCostUAH = BigDecimal.valueOf(totalCostUAH).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); articleJdo.setTotalCostUAH(totalCostUAH); double calculatedSalePrice = totalCostUAH * articleJdo.getMultiplier() * 1.1; calculatedSalePrice = BigDecimal.valueOf(calculatedSalePrice).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); articleJdo.setCalculatedSalePrice(calculatedSalePrice); } if (field.getName().equals("multiplier") || field.getName().equals("totalCostUAH")) { double calculatedSalePrice = articleJdo.getTotalCostUAH() * articleJdo.getMultiplier(); calculatedSalePrice = BigDecimal.valueOf(calculatedSalePrice).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); articleJdo.setCalculatedSalePrice(calculatedSalePrice); } } else return; } else if (char.class == field.getType()) { char typeValue = value.charAt(0); if (typeValue != field.getChar(articleJdo)) { field.setChar(articleJdo, typeValue); } else return; } else if (long.class == field.getType()) { long typeValue = Long.parseLong(value); if (typeValue != field.getLong(articleJdo)) { field.setLong(articleJdo, typeValue); } else return; } else if (Integer.class == field.getType()) { Integer typeValue; if (value.isEmpty()) { typeValue = 0; } else { typeValue = Integer.parseInt(value); } if (!typeValue.equals(field.get(articleJdo))) { field.set(articleJdo, typeValue); if (field.getName().equals("quantity") && typeValue > 1) { field.set(articleJdo, 1); int quantity = typeValue; for (int i = 1; i < quantity; ++i) { ArticleJdo newArticle = (ArticleJdo) articleJdo.clone(); newArticle.setSpreadsheetRow(0); newArticle.setId(0); tableData.add(newArticle); updateTable(newArticle); } } } else return; } else if (Boolean.class == field.getType()) { Boolean typeValue = Boolean.parseBoolean(value); if (!typeValue.equals(field.get(articleJdo))) { field.set(articleJdo, typeValue); } else return; } else if (Double.class == field.getType()) { Double typeValue; if (value.isEmpty()) { typeValue = 0.0; } else { typeValue = fixIfNeedAndParseDouble(value); typeValue = BigDecimal.valueOf(typeValue).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); } if (!typeValue.equals(field.get(articleJdo))) { field.set(articleJdo, typeValue); if (field.getName().equals("transportCostEUR") || field.getName().equals("purchasePriceEUR")) { double totalCostEUR = articleJdo.getPurchasePriceEUR() + articleJdo.getTransportCostEUR(); totalCostEUR = BigDecimal.valueOf(totalCostEUR).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); articleJdo.setTotalCostEUR(totalCostEUR); double totalCostUAH = totalCostEUR * 11.0; totalCostUAH = BigDecimal.valueOf(totalCostUAH).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); articleJdo.setTotalCostUAH(totalCostUAH); double calculatedSalePrice = totalCostUAH * articleJdo.getMultiplier(); calculatedSalePrice = BigDecimal.valueOf(calculatedSalePrice).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); articleJdo.setCalculatedSalePrice(calculatedSalePrice); } if (field.getName().equals("multiplier") || field.getName().equals("totalCostUAH")) { double calculatedSalePrice = articleJdo.getTotalCostUAH() * articleJdo.getMultiplier(); calculatedSalePrice = BigDecimal.valueOf(calculatedSalePrice).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); articleJdo.setCalculatedSalePrice(calculatedSalePrice); } } else return; } else if (Character.class == field.getType()) { Character typeValue = value.charAt(0); if (!typeValue.equals(field.get(articleJdo))) { field.set(articleJdo, typeValue); } else return; } else if (Long.class == field.getType()) { Long typeValue = Long.parseLong(value); if (!typeValue.equals(field.get(articleJdo))) { field.set(articleJdo, typeValue); } else return; } else if (Calendar.class == field.getType()) { Calendar typeValue = Calendar.getInstance(); if (!value.isEmpty()) { String formattedValue = value.replace(",", ".").trim(); if (formattedValue.matches("\\d{2}.\\d{2}.\\d{4}")) { Date time; try { time = calendarFormatter.parse(formattedValue); } catch (ParseException e) { logger.warn(e.getMessage(), e); return; } typeValue.setTime(time); if (!typeValue.equals(field.get(articleJdo))) { field.set(articleJdo, typeValue); } else return; } } else { if (field.get(articleJdo) != null) { field.set(articleJdo, null); } else return; } } else if (Date.class == field.getType()) { if (!value.isEmpty()) { String formattedValue = value.replace(",", ".").trim(); if (formattedValue.matches("\\d{2}.\\d{2}.\\d{4} \\d{2}:\\d{2}:\\d{2}")) { Date typeValue; try { typeValue = DateConverter.convertStringToDate(formattedValue); } catch (ParseException e) { logger.warn(e.getMessage(), e); return; } if (!typeValue.equals(field.get(articleJdo))) { field.set(articleJdo, typeValue); } else return; } } else { if (field.get(articleJdo) != null) { field.set(articleJdo, null); } else return; } } else { if (!value.equals(field.get(articleJdo))) { field.set(articleJdo, value); } else return; } } catch (Exception e) { logger.warn(e.getMessage(), e); throw new RuntimeException(e); } updateTable(articleJdo); }
public void setValueAt(Object aValue, int rowIndex, int columnIndex) { ArticleJdo articleJdo = getArticleJdoByRowIndex(rowIndex); String value = (String) aValue; SimpleDateFormat calendarFormatter = new SimpleDateFormat("dd.MM.yyyy"); calendarFormatter.setLenient(false); try { Field field = ArticleJdo.class.getDeclaredField(articleFieldsSequence.get(columnIndex)); field.setAccessible(true); if (int.class == field.getType()) { int typeValue; if (value.isEmpty()) { typeValue = 1; } else { typeValue = Integer.parseInt(value); } if (typeValue != field.getInt(articleJdo)) { field.setInt(articleJdo, typeValue); if (field.getName().equals("quantity") && typeValue > 1) { field.set(articleJdo, 1); int quantity = typeValue; for (int i = 1; i < quantity; ++i) { ArticleJdo newArticle = (ArticleJdo) articleJdo.clone(); newArticle.setSpreadsheetRow(0); newArticle.setId(0); tableData.add(newArticle); updateTable(newArticle); } } } else return; } else if (boolean.class == field.getType()) { boolean typeValue = Boolean.parseBoolean(value); if (typeValue != field.getBoolean(articleJdo)) { field.setBoolean(articleJdo, typeValue); } else return; } else if (double.class == field.getType()) { double typeValue; if (value.isEmpty()) { typeValue = 0.0; } else { typeValue = fixIfNeedAndParseDouble(value); typeValue = BigDecimal.valueOf(typeValue).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); } if (typeValue != field.getDouble(articleJdo)) { field.setDouble(articleJdo, typeValue); if (field.getName().equals("transportCostEUR") || field.getName().equals("purchasePriceEUR")) { double totalCostEUR = articleJdo.getPurchasePriceEUR() + articleJdo.getTransportCostEUR() + 0.065*(articleJdo.getPurchasePriceEUR() + articleJdo.getTransportCostEUR()); totalCostEUR = BigDecimal.valueOf(totalCostEUR).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); articleJdo.setTotalCostEUR(totalCostEUR); double totalCostUAH = totalCostEUR * 11.0; totalCostUAH = BigDecimal.valueOf(totalCostUAH).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); articleJdo.setTotalCostUAH(totalCostUAH); double calculatedSalePrice = totalCostUAH * articleJdo.getMultiplier() * 1.1; calculatedSalePrice = BigDecimal.valueOf(calculatedSalePrice).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); articleJdo.setCalculatedSalePrice(calculatedSalePrice); } if (field.getName().equals("multiplier") || field.getName().equals("totalCostUAH")) { double calculatedSalePrice = articleJdo.getTotalCostUAH() * articleJdo.getMultiplier() * 1.1; calculatedSalePrice = BigDecimal.valueOf(calculatedSalePrice).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); articleJdo.setCalculatedSalePrice(calculatedSalePrice); } } else return; } else if (char.class == field.getType()) { char typeValue = value.charAt(0); if (typeValue != field.getChar(articleJdo)) { field.setChar(articleJdo, typeValue); } else return; } else if (long.class == field.getType()) { long typeValue = Long.parseLong(value); if (typeValue != field.getLong(articleJdo)) { field.setLong(articleJdo, typeValue); } else return; } else if (Integer.class == field.getType()) { Integer typeValue; if (value.isEmpty()) { typeValue = 0; } else { typeValue = Integer.parseInt(value); } if (!typeValue.equals(field.get(articleJdo))) { field.set(articleJdo, typeValue); if (field.getName().equals("quantity") && typeValue > 1) { field.set(articleJdo, 1); int quantity = typeValue; for (int i = 1; i < quantity; ++i) { ArticleJdo newArticle = (ArticleJdo) articleJdo.clone(); newArticle.setSpreadsheetRow(0); newArticle.setId(0); tableData.add(newArticle); updateTable(newArticle); } } } else return; } else if (Boolean.class == field.getType()) { Boolean typeValue = Boolean.parseBoolean(value); if (!typeValue.equals(field.get(articleJdo))) { field.set(articleJdo, typeValue); } else return; } else if (Double.class == field.getType()) { Double typeValue; if (value.isEmpty()) { typeValue = 0.0; } else { typeValue = fixIfNeedAndParseDouble(value); typeValue = BigDecimal.valueOf(typeValue).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); } if (!typeValue.equals(field.get(articleJdo))) { field.set(articleJdo, typeValue); if (field.getName().equals("transportCostEUR") || field.getName().equals("purchasePriceEUR")) { double totalCostEUR = articleJdo.getPurchasePriceEUR() + articleJdo.getTransportCostEUR(); totalCostEUR = BigDecimal.valueOf(totalCostEUR).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); articleJdo.setTotalCostEUR(totalCostEUR); double totalCostUAH = totalCostEUR * 11.0; totalCostUAH = BigDecimal.valueOf(totalCostUAH).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); articleJdo.setTotalCostUAH(totalCostUAH); double calculatedSalePrice = totalCostUAH * articleJdo.getMultiplier(); calculatedSalePrice = BigDecimal.valueOf(calculatedSalePrice).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); articleJdo.setCalculatedSalePrice(calculatedSalePrice); } if (field.getName().equals("multiplier") || field.getName().equals("totalCostUAH")) { double calculatedSalePrice = articleJdo.getTotalCostUAH() * articleJdo.getMultiplier(); calculatedSalePrice = BigDecimal.valueOf(calculatedSalePrice).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue(); articleJdo.setCalculatedSalePrice(calculatedSalePrice); } } else return; } else if (Character.class == field.getType()) { Character typeValue = value.charAt(0); if (!typeValue.equals(field.get(articleJdo))) { field.set(articleJdo, typeValue); } else return; } else if (Long.class == field.getType()) { Long typeValue = Long.parseLong(value); if (!typeValue.equals(field.get(articleJdo))) { field.set(articleJdo, typeValue); } else return; } else if (Calendar.class == field.getType()) { Calendar typeValue = Calendar.getInstance(); if (!value.isEmpty()) { String formattedValue = value.replace(",", ".").trim(); if (formattedValue.matches("\\d{2}.\\d{2}.\\d{4}")) { Date time; try { time = calendarFormatter.parse(formattedValue); } catch (ParseException e) { logger.warn(e.getMessage(), e); return; } typeValue.setTime(time); if (!typeValue.equals(field.get(articleJdo))) { field.set(articleJdo, typeValue); } else return; } } else { if (field.get(articleJdo) != null) { field.set(articleJdo, null); } else return; } } else if (Date.class == field.getType()) { if (!value.isEmpty()) { String formattedValue = value.replace(",", ".").trim(); if (formattedValue.matches("\\d{2}.\\d{2}.\\d{4} \\d{2}:\\d{2}:\\d{2}")) { Date typeValue; try { typeValue = DateConverter.convertStringToDate(formattedValue); } catch (ParseException e) { logger.warn(e.getMessage(), e); return; } if (!typeValue.equals(field.get(articleJdo))) { field.set(articleJdo, typeValue); } else return; } } else { if (field.get(articleJdo) != null) { field.set(articleJdo, null); } else return; } } else { if (!value.equals(field.get(articleJdo))) { field.set(articleJdo, value); } else return; } } catch (Exception e) { logger.warn(e.getMessage(), e); throw new RuntimeException(e); } updateTable(articleJdo); }
diff --git a/as/plugins/org.jboss.ide.eclipse.as.core/jbosscore/org/jboss/ide/eclipse/as/core/extensions/descriptors/XPathQuery.java b/as/plugins/org.jboss.ide.eclipse.as.core/jbosscore/org/jboss/ide/eclipse/as/core/extensions/descriptors/XPathQuery.java index 748987799..dc58b21f0 100644 --- a/as/plugins/org.jboss.ide.eclipse.as.core/jbosscore/org/jboss/ide/eclipse/as/core/extensions/descriptors/XPathQuery.java +++ b/as/plugins/org.jboss.ide.eclipse.as.core/jbosscore/org/jboss/ide/eclipse/as/core/extensions/descriptors/XPathQuery.java @@ -1,175 +1,180 @@ /** * JBoss, a Division of Red Hat * Copyright 2006, Red Hat Middleware, LLC, and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.ide.eclipse.as.core.extensions.descriptors; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.dom4j.Document; import org.dom4j.Node; import org.eclipse.core.runtime.Path; import org.jboss.ide.eclipse.as.core.extensions.descriptors.XPathFileResult.XPathResultNode; /** * A simple value object to hold the XPath query data * @author [email protected] * */ public class XPathQuery implements Serializable { private static final long serialVersionUID = 1L; /* * XPath-important fields */ protected String name; protected String baseDir; protected String filePattern; protected String xpathPattern; protected String attribute; /* * The filter, need not be saved on serialize */ protected transient AntFileFilter filter; /* * The file results, need not be saved on serialize */ protected transient XPathFileResult[] results; protected transient XPathCategory category; protected transient XMLDocumentRepository repository = null; public XPathQuery(String name, List list) { this.name = name; this.baseDir = list.get(0).equals(XPathModel.EMPTY_STRING) ? null : (String)list.get(0); this.filePattern = list.get(1).equals(XPathModel.EMPTY_STRING) ? null : (String)list.get(1); this.xpathPattern = list.get(2).equals(XPathModel.EMPTY_STRING) ? null : (String)list.get(2); this.attribute = list.size() < 3 || list.get(3).equals(XPathModel.EMPTY_STRING) ? null : (String)list.get(3); } public XPathQuery(String name, String baseDir, String filePattern, String xpathPattern, String attribute) { this.name = name; this.baseDir = baseDir; this.filePattern = filePattern; this.xpathPattern = xpathPattern; this.attribute = attribute; this.results = null; } protected AntFileFilter getFilter() { if( filter == null ) filter = new AntFileFilter(baseDir, filePattern); return filter; } public void refresh() { String[] files = getFilter().getIncludedFiles(); boolean changed = false; for( int i = 0; i < files.length; i++ ) { changed = changed || getRepository().refresh(new Path(baseDir).append(files[i]).toOSString()); } if( changed ) { results = null; } } public XPathFileResult[] getResults() { if( results == null ) loadResults(); return results; } public boolean resultsLoaded() { return results == null ? false : true; } protected void loadResults() { - String[] files = getFilter().getIncludedFiles(); - String fileLoc; - ArrayList<XPathFileResult> resultList = new ArrayList<XPathFileResult>(); - List<Node> nodeList = null; - for( int i = 0; i < files.length; i++ ) { - fileLoc = new Path(baseDir).append(files[i]).toOSString(); - Document d = getRepository().getDocument(fileLoc); - if( d != null ) - nodeList = d.selectNodes(xpathPattern); - if( nodeList != null && nodeList.size() > 0 ) - resultList.add(new XPathFileResult(this, fileLoc, nodeList)); + try { + String[] files = getFilter().getIncludedFiles(); + String fileLoc; + ArrayList<XPathFileResult> resultList = new ArrayList<XPathFileResult>(); + List<Node> nodeList = null; + for( int i = 0; i < files.length; i++ ) { + fileLoc = new Path(baseDir).append(files[i]).toOSString(); + Document d = getRepository().getDocument(fileLoc); + if( d != null ) + nodeList = d.selectNodes(xpathPattern); + if( nodeList != null && nodeList.size() > 0 ) + resultList.add(new XPathFileResult(this, fileLoc, nodeList)); + } + results = resultList.toArray(new XPathFileResult[resultList.size()]); + } catch( IllegalStateException ise ) { + // cannot load TODO log? + results = new XPathFileResult[0]; } - results = resultList.toArray(new XPathFileResult[resultList.size()]); } public String getFirstResult() { XPathFileResult[] fileResults = getResults(); if( fileResults.length > 0 ) { XPathResultNode[] nodes = fileResults[0].getChildren(); if( nodes.length > 0 ) { return nodes[0].getText(); } } return null; } /* * Field Getters and setters */ public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFilePattern() { return filePattern; } public void setFilePattern(String filePattern) { this.filePattern = filePattern; } public String getXpathPattern() { return xpathPattern; } public void setXpathPattern(String xpathPattern) { this.xpathPattern = xpathPattern; } public String getAttribute() { return attribute; } public void setAttribute(String attribute) { this.attribute = attribute; } public String getBaseDir() { return baseDir; } public void setBaseDir(String baseDir) { this.baseDir = baseDir; } public XPathCategory getCategory() { return category; } public void setCategory(XPathCategory category) { this.category = category; } public void setRepository(XMLDocumentRepository repo) { this.repository = repo; } protected XMLDocumentRepository getRepository() { return repository == null ? XMLDocumentRepository.getDefault() : repository; } }
false
true
protected void loadResults() { String[] files = getFilter().getIncludedFiles(); String fileLoc; ArrayList<XPathFileResult> resultList = new ArrayList<XPathFileResult>(); List<Node> nodeList = null; for( int i = 0; i < files.length; i++ ) { fileLoc = new Path(baseDir).append(files[i]).toOSString(); Document d = getRepository().getDocument(fileLoc); if( d != null ) nodeList = d.selectNodes(xpathPattern); if( nodeList != null && nodeList.size() > 0 ) resultList.add(new XPathFileResult(this, fileLoc, nodeList)); } results = resultList.toArray(new XPathFileResult[resultList.size()]); }
protected void loadResults() { try { String[] files = getFilter().getIncludedFiles(); String fileLoc; ArrayList<XPathFileResult> resultList = new ArrayList<XPathFileResult>(); List<Node> nodeList = null; for( int i = 0; i < files.length; i++ ) { fileLoc = new Path(baseDir).append(files[i]).toOSString(); Document d = getRepository().getDocument(fileLoc); if( d != null ) nodeList = d.selectNodes(xpathPattern); if( nodeList != null && nodeList.size() > 0 ) resultList.add(new XPathFileResult(this, fileLoc, nodeList)); } results = resultList.toArray(new XPathFileResult[resultList.size()]); } catch( IllegalStateException ise ) { // cannot load TODO log? results = new XPathFileResult[0]; } }
diff --git a/server/src/test/java/com/barchart/netty/server/http/TestHttpServer.java b/server/src/test/java/com/barchart/netty/server/http/TestHttpServer.java index decc226..75c3643 100644 --- a/server/src/test/java/com/barchart/netty/server/http/TestHttpServer.java +++ b/server/src/test/java/com/barchart/netty/server/http/TestHttpServer.java @@ -1,407 +1,408 @@ /** * Copyright (C) 2011-2013 Barchart, Inc. <http://www.barchart.com/> * * All rights reserved. Licensed under the OSI BSD License. * * http://www.opensource.org/licenses/bsd-license.php */ package com.barchart.netty.server.http; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import io.netty.channel.nio.NioEventLoopGroup; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.util.Queue; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.HttpHostConnectException; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.PoolingClientConnectionManager; import org.apache.http.util.EntityUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.barchart.netty.server.Servers; import com.barchart.netty.server.http.request.HttpServerRequest; import com.barchart.netty.server.http.request.RequestHandlerBase; public class TestHttpServer { private HttpServer server; private HttpClient client; private int port; private TestRequestHandler basic; private TestRequestHandler async; private TestRequestHandler asyncDelayed; private TestRequestHandler clientDisconnect; private TestRequestHandler error; private TestRequestHandler channelError; private TestRequestHandler serviceHandler; private TestRequestHandler infoHandler; private ChunkedRequestHandler chunkedHandler; @Before public void setUp() throws Exception { basic = new TestRequestHandler("basic", false, 0, 0, false, false); async = new TestRequestHandler("async", true, 0, 0, false, false); asyncDelayed = new TestRequestHandler("async-delayed", true, 50, 0, false, false); clientDisconnect = new TestRequestHandler("", true, 500, 500, false, false); error = new TestRequestHandler("error", false, 0, 0, true, false); channelError = new TestRequestHandler("channel-error", false, 0, 0, false, true); infoHandler = new TestRequestHandler("info", false, 0, 0, false, false); serviceHandler = new TestRequestHandler("service", false, 0, 0, false, false); chunkedHandler = new ChunkedRequestHandler("chunked"); final ServerSocket s = new ServerSocket(0); port = s.getLocalPort(); s.close(); + Thread.sleep(100); server = Servers.createHttpServer().requestHandler("/basic", basic) .group(new NioEventLoopGroup(1)) .requestHandler("/async", async) .requestHandler("/async-delayed", asyncDelayed) .requestHandler("/client-disconnect", clientDisconnect) .requestHandler("/channel-error", channelError) .requestHandler("/error", error) .requestHandler("/service/info", infoHandler) .requestHandler("/service", serviceHandler) .requestHandler("/chunked", chunkedHandler) .maxConnections(1); server.listen(port, "localhost"); client = new DefaultHttpClient(new PoolingClientConnectionManager()); } @After public void tearDown() throws Exception { if (server.running()) { server.shutdown().sync(); } } @Test public void testBasicRequest() throws Exception { for (int i = 0; i < 100; i++) { final HttpGet get = new HttpGet("http://localhost:" + port + "/basic"); final HttpResponse response = client.execute(get); final String content = new BufferedReader(new InputStreamReader(response .getEntity().getContent())).readLine().trim(); assertEquals("basic", content); } } @Test public void testChunkedRequest() throws Exception { for (int i = 0; i < 100; i++) { final HttpGet get = new HttpGet("http://localhost:" + port + "/chunked"); final HttpResponse response = client.execute(get); final String content = new BufferedReader(new InputStreamReader(response .getEntity().getContent())).readLine().trim(); assertEquals("chunked", content); } } @Test public void testPostRequest() throws Exception { for (int i = 0; i < 100; i++) { final HttpPost post = new HttpPost("http://localhost:" + port + "/basic"); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); post.setEntity(new StringEntity("id=1&id=2")); final HttpResponse response = client.execute(post); final String content = new BufferedReader(new InputStreamReader(response .getEntity().getContent())).readLine().trim(); assertEquals("basic", content); assertEquals(1, basic.parameters.size()); assertEquals(2, basic.parameters.get("id").size()); assertEquals("1", basic.parameters.get("id").get(0)); assertEquals("2", basic.parameters.get("id").get(1)); } } @Test public void testAsyncRequest() throws Exception { final HttpGet get = new HttpGet("http://localhost:" + port + "/async"); final HttpResponse response = client.execute(get); final String content = new BufferedReader(new InputStreamReader(response.getEntity() .getContent())).readLine().trim(); assertNotNull(async.lastFuture); assertFalse(async.lastFuture.isCancelled()); assertEquals("async", content); } @Test public void testAsyncDelayedRequest() throws Exception { final HttpGet get = new HttpGet("http://localhost:" + port + "/async-delayed"); final HttpResponse response = client.execute(get); final String content = new BufferedReader(new InputStreamReader(response.getEntity() .getContent())).readLine().trim(); assertNotNull(asyncDelayed.lastFuture); assertFalse(asyncDelayed.lastFuture.isCancelled()); assertEquals("async-delayed", content); } @Test public void testUnknownHandler() throws Exception { final HttpGet get = new HttpGet("http://localhost:" + port + "/unknown"); final HttpResponse response = client.execute(get); EntityUtils.consume(response.getEntity()); assertEquals(404, response.getStatusLine().getStatusCode()); } @Test public void testServerError() throws Exception { final HttpGet get = new HttpGet("http://localhost:" + port + "/error"); final HttpResponse response = client.execute(get); EntityUtils.consume(response.getEntity()); assertEquals(500, response.getStatusLine().getStatusCode()); } @Test public void testReuseRequest() throws Exception { // Parameters were being remembered between requests in pooled objects HttpGet get = new HttpGet("http://localhost:" + port + "/basic?field=value"); HttpResponse response = client.execute(get); assertEquals(200, response.getStatusLine().getStatusCode()); EntityUtils.consume(response.getEntity()); assertEquals(1, basic.parameters.get("field").size()); assertEquals("value", basic.parameters.get("field").get(0)); get = new HttpGet("http://localhost:" + port + "/basic?field=value2"); response = client.execute(get); assertEquals(200, response.getStatusLine().getStatusCode()); EntityUtils.consume(response.getEntity()); assertEquals(1, basic.parameters.get("field").size()); assertEquals("value2", basic.parameters.get("field").get(0)); } @Test public void testMultipleRequests() throws Exception { // New Beta3 was failing on second request due to shared buffer use for (int i = 0; i < 100; i++) { final HttpGet get = new HttpGet("http://localhost:" + port + "/basic"); final HttpResponse response = client.execute(get); assertEquals(200, response.getStatusLine().getStatusCode()); EntityUtils.consume(response.getEntity()); } } @Test public void testPatternRequests() throws Exception { { final HttpGet get = new HttpGet("http://localhost:" + port + "/service/info/10"); final HttpResponse response = client.execute(get); final String content = new BufferedReader(new InputStreamReader(response .getEntity().getContent())).readLine().trim(); assertEquals("info", content); } { final HttpGet get = new HttpGet("http://localhost:" + port + "/service/something/else"); final HttpResponse response = client.execute(get); final String content = new BufferedReader(new InputStreamReader(response .getEntity().getContent())).readLine().trim(); assertEquals("service", content); } } @Test public void testTooManyConnections() throws Exception { final Queue<Integer> status = new LinkedBlockingQueue<Integer>(); final Runnable r = new Runnable() { @Override public void run() { try { final HttpResponse response = client.execute(new HttpGet("http://localhost:" + port + "/client-disconnect")); status.add(response.getStatusLine().getStatusCode()); EntityUtils.consume(response.getEntity()); } catch (final Exception e) { e.printStackTrace(); } } }; final Thread t1 = new Thread(r); t1.start(); final Thread t2 = new Thread(r); t2.start(); t1.join(); t2.join(); assertEquals(2, status.size()); assertTrue(status.contains(200)); assertTrue(status.contains(503)); } @Test public void testShutdown() throws Exception { final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); final AtomicBoolean pass = new AtomicBoolean(false); executor.schedule(new Runnable() { @Override public void run() { try { server.shutdown().sync(); } catch (final InterruptedException e1) { e1.printStackTrace(); } try { client.execute(new HttpGet("http://localhost:" + port + "/basic")); } catch (final HttpHostConnectException hhce) { pass.set(true); } catch (final Exception e) { e.printStackTrace(); } } }, 1000, TimeUnit.MILLISECONDS); final HttpGet get = new HttpGet("http://localhost:" + port + "/client-disconnect"); final HttpResponse response = client.execute(get); EntityUtils.consume(response.getEntity()); assertEquals(200, response.getStatusLine().getStatusCode()); // assertTrue(pass.get()); } @Test(expected = HttpHostConnectException.class) public void testKill() throws Exception { final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); executor.schedule(new Runnable() { @Override public void run() { server.kill(); } }, 500, TimeUnit.MILLISECONDS); final HttpGet get = new HttpGet("http://localhost:" + port + "/client-disconnect"); // Should throw exception client.execute(get).getEntity(); } // @Test // Exposed old server handler issue, "Response has already been started" public void testRepeated() throws Exception { for (int i = 0; i < 10000; i++) { testAsyncRequest(); } } private static class ChunkedRequestHandler extends RequestHandlerBase { String data; public ChunkedRequestHandler(final String data_) { data = data_; } @Override public void handle(final HttpServerRequest request) throws IOException { request.response().setChunkSize(1); request.response().write(data); request.response().finish(); } } }
true
true
public void setUp() throws Exception { basic = new TestRequestHandler("basic", false, 0, 0, false, false); async = new TestRequestHandler("async", true, 0, 0, false, false); asyncDelayed = new TestRequestHandler("async-delayed", true, 50, 0, false, false); clientDisconnect = new TestRequestHandler("", true, 500, 500, false, false); error = new TestRequestHandler("error", false, 0, 0, true, false); channelError = new TestRequestHandler("channel-error", false, 0, 0, false, true); infoHandler = new TestRequestHandler("info", false, 0, 0, false, false); serviceHandler = new TestRequestHandler("service", false, 0, 0, false, false); chunkedHandler = new ChunkedRequestHandler("chunked"); final ServerSocket s = new ServerSocket(0); port = s.getLocalPort(); s.close(); server = Servers.createHttpServer().requestHandler("/basic", basic) .group(new NioEventLoopGroup(1)) .requestHandler("/async", async) .requestHandler("/async-delayed", asyncDelayed) .requestHandler("/client-disconnect", clientDisconnect) .requestHandler("/channel-error", channelError) .requestHandler("/error", error) .requestHandler("/service/info", infoHandler) .requestHandler("/service", serviceHandler) .requestHandler("/chunked", chunkedHandler) .maxConnections(1); server.listen(port, "localhost"); client = new DefaultHttpClient(new PoolingClientConnectionManager()); }
public void setUp() throws Exception { basic = new TestRequestHandler("basic", false, 0, 0, false, false); async = new TestRequestHandler("async", true, 0, 0, false, false); asyncDelayed = new TestRequestHandler("async-delayed", true, 50, 0, false, false); clientDisconnect = new TestRequestHandler("", true, 500, 500, false, false); error = new TestRequestHandler("error", false, 0, 0, true, false); channelError = new TestRequestHandler("channel-error", false, 0, 0, false, true); infoHandler = new TestRequestHandler("info", false, 0, 0, false, false); serviceHandler = new TestRequestHandler("service", false, 0, 0, false, false); chunkedHandler = new ChunkedRequestHandler("chunked"); final ServerSocket s = new ServerSocket(0); port = s.getLocalPort(); s.close(); Thread.sleep(100); server = Servers.createHttpServer().requestHandler("/basic", basic) .group(new NioEventLoopGroup(1)) .requestHandler("/async", async) .requestHandler("/async-delayed", asyncDelayed) .requestHandler("/client-disconnect", clientDisconnect) .requestHandler("/channel-error", channelError) .requestHandler("/error", error) .requestHandler("/service/info", infoHandler) .requestHandler("/service", serviceHandler) .requestHandler("/chunked", chunkedHandler) .maxConnections(1); server.listen(port, "localhost"); client = new DefaultHttpClient(new PoolingClientConnectionManager()); }
diff --git a/src/main/java/hudson/plugins/jira/Updater.java b/src/main/java/hudson/plugins/jira/Updater.java index 079a5c0..406cef3 100644 --- a/src/main/java/hudson/plugins/jira/Updater.java +++ b/src/main/java/hudson/plugins/jira/Updater.java @@ -1,133 +1,134 @@ package hudson.plugins.jira; import hudson.Util; import hudson.model.AbstractBuild; import hudson.model.AbstractBuild.DependencyChange; import hudson.model.BuildListener; import hudson.model.Hudson; import hudson.model.Result; import hudson.scm.ChangeLogSet.Entry; import javax.xml.rpc.ServiceException; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Actual JIRA update logic. * * * @author Kohsuke Kawaguchi */ class Updater { static boolean perform(AbstractBuild build, BuildListener listener) throws InterruptedException, IOException { PrintStream logger = listener.getLogger(); JiraSite site = JiraSite.get(build.getProject()); if(site==null) { logger.println(Messages.Updater_NoJiraSite()); build.setResult(Result.FAILURE); return true; } String rootUrl = Hudson.getInstance().getRootUrl(); if(rootUrl==null) { logger.println(Messages.Updater_NoHudsonUrl()); build.setResult(Result.FAILURE); return true; } Set<String> ids = findIssueIdsRecursive(build); if(ids.isEmpty()) { if(debug) logger.println("No JIRA issues found."); return true; // nothing found here. } List<JiraIssue> issues = new ArrayList<JiraIssue>(); try { JiraSession session = site.createSession(); if(session==null) { logger.println(Messages.Updater_NoRemoteAccess()); build.setResult(Result.FAILURE); return true; } for (String id : ids) { if(!session.existsIssue(id)) { if(debug) logger.println(id+" looked like a JIRA issue but it wans't"); continue; // token looked like a JIRA issue but it's actually not. } logger.println(Messages.Updater_Updating(id)); session.addComment(id, String.format( site.supportsWikiStyleComment? "Integrated in !%1$snocacheImages/16x16/%3$s! [%2$s|%4$s]": "Integrated in %2$s (See [%4$s])", rootUrl, build, build.getResult().color.getImage(), Util.encode(rootUrl+build.getUrl()))); issues.add(new JiraIssue(session.getIssue(id))); } } catch (ServiceException e) { - e.printStackTrace(listener.error(Messages.Updater_FailedToConnect())); + listener.getLogger().println(Messages.Updater_FailedToConnect()); + e.printStackTrace(listener.getLogger()); } build.getActions().add(new JiraBuildAction(build,issues)); return true; } /** * Finds the strings that match JIRA issue ID patterns. * * This method returns all likely candidates and doesn't check * if such ID actually exists or not. We don't want to use * {@link JiraSite#existsIssue(String)} here so that new projects * in JIRA can be detected. */ private static Set<String> findIssueIdsRecursive(AbstractBuild<?,?> build) { Set<String> ids = new HashSet<String>(); findIssues(build,ids); // check for issues fixed in dependencies for( DependencyChange depc : build.getDependencyChanges(build.getPreviousBuild()).values()) for(AbstractBuild b : depc.getBuilds()) findIssues(b,ids); return ids; } private static void findIssues(AbstractBuild<?,?> build, Set<String> ids) { for (Entry change : build.getChangeSet()) { LOGGER.fine("Looking for JIRA ID in "+change.getMsg()); Matcher m = ISSUE_PATTERN.matcher(change.getMsg()); while (m.find()) ids.add(m.group()); } } /** * Regexp pattern that identifies JIRA issue token. * * <p> * At least two upper alphabetic. * Numbers are also allowed as project keys (see issue #729) */ public static final Pattern ISSUE_PATTERN = Pattern.compile("\\b[A-Z]([A-Z0-9]+)-[1-9][0-9]*\\b"); private static final Logger LOGGER = Logger.getLogger(Updater.class.getName()); /** * Debug flag. */ public static boolean debug = false; }
true
true
static boolean perform(AbstractBuild build, BuildListener listener) throws InterruptedException, IOException { PrintStream logger = listener.getLogger(); JiraSite site = JiraSite.get(build.getProject()); if(site==null) { logger.println(Messages.Updater_NoJiraSite()); build.setResult(Result.FAILURE); return true; } String rootUrl = Hudson.getInstance().getRootUrl(); if(rootUrl==null) { logger.println(Messages.Updater_NoHudsonUrl()); build.setResult(Result.FAILURE); return true; } Set<String> ids = findIssueIdsRecursive(build); if(ids.isEmpty()) { if(debug) logger.println("No JIRA issues found."); return true; // nothing found here. } List<JiraIssue> issues = new ArrayList<JiraIssue>(); try { JiraSession session = site.createSession(); if(session==null) { logger.println(Messages.Updater_NoRemoteAccess()); build.setResult(Result.FAILURE); return true; } for (String id : ids) { if(!session.existsIssue(id)) { if(debug) logger.println(id+" looked like a JIRA issue but it wans't"); continue; // token looked like a JIRA issue but it's actually not. } logger.println(Messages.Updater_Updating(id)); session.addComment(id, String.format( site.supportsWikiStyleComment? "Integrated in !%1$snocacheImages/16x16/%3$s! [%2$s|%4$s]": "Integrated in %2$s (See [%4$s])", rootUrl, build, build.getResult().color.getImage(), Util.encode(rootUrl+build.getUrl()))); issues.add(new JiraIssue(session.getIssue(id))); } } catch (ServiceException e) { e.printStackTrace(listener.error(Messages.Updater_FailedToConnect())); } build.getActions().add(new JiraBuildAction(build,issues)); return true; }
static boolean perform(AbstractBuild build, BuildListener listener) throws InterruptedException, IOException { PrintStream logger = listener.getLogger(); JiraSite site = JiraSite.get(build.getProject()); if(site==null) { logger.println(Messages.Updater_NoJiraSite()); build.setResult(Result.FAILURE); return true; } String rootUrl = Hudson.getInstance().getRootUrl(); if(rootUrl==null) { logger.println(Messages.Updater_NoHudsonUrl()); build.setResult(Result.FAILURE); return true; } Set<String> ids = findIssueIdsRecursive(build); if(ids.isEmpty()) { if(debug) logger.println("No JIRA issues found."); return true; // nothing found here. } List<JiraIssue> issues = new ArrayList<JiraIssue>(); try { JiraSession session = site.createSession(); if(session==null) { logger.println(Messages.Updater_NoRemoteAccess()); build.setResult(Result.FAILURE); return true; } for (String id : ids) { if(!session.existsIssue(id)) { if(debug) logger.println(id+" looked like a JIRA issue but it wans't"); continue; // token looked like a JIRA issue but it's actually not. } logger.println(Messages.Updater_Updating(id)); session.addComment(id, String.format( site.supportsWikiStyleComment? "Integrated in !%1$snocacheImages/16x16/%3$s! [%2$s|%4$s]": "Integrated in %2$s (See [%4$s])", rootUrl, build, build.getResult().color.getImage(), Util.encode(rootUrl+build.getUrl()))); issues.add(new JiraIssue(session.getIssue(id))); } } catch (ServiceException e) { listener.getLogger().println(Messages.Updater_FailedToConnect()); e.printStackTrace(listener.getLogger()); } build.getActions().add(new JiraBuildAction(build,issues)); return true; }
diff --git a/src/org/muckebox/android/net/DownloadServer.java b/src/org/muckebox/android/net/DownloadServer.java index 3daf05a..8abc398 100644 --- a/src/org/muckebox/android/net/DownloadServer.java +++ b/src/org/muckebox/android/net/DownloadServer.java @@ -1,230 +1,230 @@ /* * Copyright 2013 Karsten Patzwaldt * * 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.muckebox.android.net; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.nio.ByteBuffer; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.entity.ContentProducer; import org.apache.http.entity.EntityTemplate; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.impl.DefaultHttpServerConnection; import org.apache.http.params.BasicHttpParams; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.BasicHttpProcessor; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.protocol.HttpRequestHandlerRegistry; import org.apache.http.protocol.HttpService; import org.apache.http.protocol.ResponseConnControl; import org.apache.http.protocol.ResponseContent; import android.util.Log; public class DownloadServer extends Thread { private static final String LOG_TAG = "DownloadServer"; private static final int PORT_MIN = 10000; private static final int PORT_MAX = 20000; private String mMimeType; private boolean mReady = false; private boolean mStopped = false; private ServerSocket mServerSocket; private int mPort; private static int mLastPort = 0; private BlockingQueue<ByteBuffer> mQueue; private BasicHttpProcessor mHttpProcessor; private BasicHttpContext mHttpContext; private HttpService mHttpService; private HttpRequestHandlerRegistry mRegistry; private class FileHandler implements HttpRequestHandler { @Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { EntityTemplate entity = new EntityTemplate(new ContentProducer() { public void writeTo(final OutputStream os) throws IOException { while (true) { try { ByteBuffer buf = mQueue.take(); os.write(buf.array(), 0, buf.position()); if (buf.position() == 0 || mStopped) break; } catch (InterruptedException e) { throw new IOException(e.toString()); } } } }); entity.setContentType(mMimeType); entity.setChunked(true); response.setEntity(entity); } } private static void d(String text) { Log.d(LOG_TAG, Thread.currentThread().getId() + ": " + text); } public String getUrl() { return "http://localhost:" + mPort + "/"; } public DownloadServer(String mimeType) { super(LOG_TAG); mMimeType = mimeType; mQueue = new LinkedBlockingQueue<ByteBuffer>(); mPort = getRandomPort(); initHttpServer(); } private int getRandomPort() { int ret; do { ret = PORT_MIN + (int) (Math.random() * ((PORT_MAX - PORT_MIN) + 1)); } while (ret == mLastPort); mLastPort = ret; return ret; } @Override public void run() { super.run(); try { d("Starting server on " + mPort); mServerSocket = new ServerSocket(mPort, 0, InetAddress.getByName("localhost")); mServerSocket.setReuseAddress(true); try { mReady = true; while (! mStopped) { Socket socket = null; DefaultHttpServerConnection connection = new DefaultHttpServerConnection(); try { d("Waiting for new connection"); socket = mServerSocket.accept(); d("Got connection"); connection.bind(socket, new BasicHttpParams()); mHttpService.handleRequest(connection, mHttpContext); d("Request handling finished"); } catch (HttpException e) { Log.e(LOG_TAG, "Got HTTP error: " + e); } finally { connection.shutdown(); if (socket != null) socket.close(); socket = null; } } } finally { if (mServerSocket != null) mServerSocket.close(); } d("Server stopped"); } catch (IOException e) { - Log.e(LOG_TAG, "IOException, maybe ok"); + Log.i(LOG_TAG, "IOException, probably ok"); e.printStackTrace(); } } private void initHttpServer() { mHttpProcessor = new BasicHttpProcessor(); mHttpContext = new BasicHttpContext(); mHttpService = new HttpService(mHttpProcessor, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory()); mHttpProcessor.addInterceptor(new ResponseContent()); mHttpProcessor.addInterceptor(new ResponseConnControl()); mRegistry = new HttpRequestHandlerRegistry(); mRegistry.register("*", new FileHandler()); mHttpService.setHandlerResolver(mRegistry); } public void feed(ByteBuffer buf) { try { mQueue.put(buf); } catch (InterruptedException e) { Log.e(LOG_TAG, "Interrupted while putting, should not happen"); } } public void finish() { d("Finishing input data stream"); feed(ByteBuffer.allocate(0)); } public void quit() { d("Stopping server"); mStopped = true; mQueue.clear(); finish(); try { mServerSocket.close(); } catch (IOException e) { Log.e(LOG_TAG, "Could not close server socket!"); } } public boolean isReady() { return mReady; } }
true
true
public void run() { super.run(); try { d("Starting server on " + mPort); mServerSocket = new ServerSocket(mPort, 0, InetAddress.getByName("localhost")); mServerSocket.setReuseAddress(true); try { mReady = true; while (! mStopped) { Socket socket = null; DefaultHttpServerConnection connection = new DefaultHttpServerConnection(); try { d("Waiting for new connection"); socket = mServerSocket.accept(); d("Got connection"); connection.bind(socket, new BasicHttpParams()); mHttpService.handleRequest(connection, mHttpContext); d("Request handling finished"); } catch (HttpException e) { Log.e(LOG_TAG, "Got HTTP error: " + e); } finally { connection.shutdown(); if (socket != null) socket.close(); socket = null; } } } finally { if (mServerSocket != null) mServerSocket.close(); } d("Server stopped"); } catch (IOException e) { Log.e(LOG_TAG, "IOException, maybe ok"); e.printStackTrace(); } }
public void run() { super.run(); try { d("Starting server on " + mPort); mServerSocket = new ServerSocket(mPort, 0, InetAddress.getByName("localhost")); mServerSocket.setReuseAddress(true); try { mReady = true; while (! mStopped) { Socket socket = null; DefaultHttpServerConnection connection = new DefaultHttpServerConnection(); try { d("Waiting for new connection"); socket = mServerSocket.accept(); d("Got connection"); connection.bind(socket, new BasicHttpParams()); mHttpService.handleRequest(connection, mHttpContext); d("Request handling finished"); } catch (HttpException e) { Log.e(LOG_TAG, "Got HTTP error: " + e); } finally { connection.shutdown(); if (socket != null) socket.close(); socket = null; } } } finally { if (mServerSocket != null) mServerSocket.close(); } d("Server stopped"); } catch (IOException e) { Log.i(LOG_TAG, "IOException, probably ok"); e.printStackTrace(); } }
diff --git a/src/org/apache/xerces/xinclude/XIncludeHandler.java b/src/org/apache/xerces/xinclude/XIncludeHandler.java index 7e33af55..6ac885dd 100644 --- a/src/org/apache/xerces/xinclude/XIncludeHandler.java +++ b/src/org/apache/xerces/xinclude/XIncludeHandler.java @@ -1,2585 +1,2587 @@ /* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xerces.xinclude; import java.io.CharConversionException; import java.io.IOException; import java.util.Enumeration; import java.util.Stack; import java.util.StringTokenizer; import java.util.Vector; import org.apache.xerces.impl.Constants; import org.apache.xerces.impl.XMLEntityManager; import org.apache.xerces.impl.XMLErrorReporter; import org.apache.xerces.impl.io.MalformedByteSequenceException; import org.apache.xerces.impl.msg.XMLMessageFormatter; import org.apache.xerces.util.AugmentationsImpl; import org.apache.xerces.util.HTTPInputSource; import org.apache.xerces.util.IntStack; import org.apache.xerces.util.ParserConfigurationSettings; import org.apache.xerces.util.SecurityManager; import org.apache.xerces.util.SymbolTable; import org.apache.xerces.util.URI; import org.apache.xerces.util.XMLAttributesImpl; import org.apache.xerces.util.XMLResourceIdentifierImpl; import org.apache.xerces.util.XMLChar; import org.apache.xerces.util.XMLSymbols; import org.apache.xerces.util.URI.MalformedURIException; import org.apache.xerces.xni.Augmentations; import org.apache.xerces.xni.NamespaceContext; import org.apache.xerces.xni.QName; import org.apache.xerces.xni.XMLAttributes; import org.apache.xerces.xni.XMLDTDHandler; import org.apache.xerces.xni.XMLDocumentHandler; import org.apache.xerces.xni.XMLLocator; import org.apache.xerces.xni.XMLResourceIdentifier; import org.apache.xerces.xni.XMLString; import org.apache.xerces.xni.XNIException; import org.apache.xerces.xni.parser.XMLComponent; import org.apache.xerces.xni.parser.XMLComponentManager; import org.apache.xerces.xni.parser.XMLConfigurationException; import org.apache.xerces.xni.parser.XMLDTDFilter; import org.apache.xerces.xni.parser.XMLDTDSource; import org.apache.xerces.xni.parser.XMLDocumentFilter; import org.apache.xerces.xni.parser.XMLDocumentSource; import org.apache.xerces.xni.parser.XMLEntityResolver; import org.apache.xerces.xni.parser.XMLInputSource; import org.apache.xerces.xni.parser.XMLParserConfiguration; /** * <p> * This is a pipeline component which performs XInclude handling, according to the * W3C specification for XML Inclusions. * </p> * <p> * This component analyzes each event in the pipeline, looking for &lt;include&gt; * elements. An &lt;include&gt; element is one which has a namespace of * <code>http://www.w3.org/2001/XInclude</code> and a localname of <code>include</code>. * When it finds an &lt;include&gt; element, it attempts to include the file specified * in the <code>href</code> attribute of the element. If inclusion succeeds, all * children of the &lt;include&gt; element are ignored (with the exception of * checking for invalid children as outlined in the specification). If the inclusion * fails, the &lt;fallback&gt; child of the &lt;include&gt; element is processed. * </p> * <p> * See the <a href="http://www.w3.org/TR/xinclude/">XInclude specification</a> for * more information on how XInclude is to be used. * </p> * <p> * This component requires the following features and properties from the * component manager that uses it: * <ul> * <li>http://xml.org/sax/features/allow-dtd-events-after-endDTD</li> * <li>http://apache.org/xml/properties/internal/error-reporter</li> * <li>http://apache.org/xml/properties/internal/entity-resolver</li> * </ul> * Optional property: * <ul> * <li>http://apache.org/xml/properties/input-buffer-size</li> * </ul> * * Furthermore, the <code>NamespaceContext</code> used in the pipeline is required * to be an instance of <code>XIncludeNamespaceSupport</code>. * </p> * <p> * Currently, this implementation has only partial support for the XInclude specification. * Specifically, it is missing support for XPointer document fragments. Thus, only whole * documents can be included using this component in the pipeline. * </p> * * @author Peter McCracken, IBM * @author Michael Glavassevich, IBM * * @version $Id$ * * @see XIncludeNamespaceSupport */ public class XIncludeHandler implements XMLComponent, XMLDocumentFilter, XMLDTDFilter { public final static String XINCLUDE_DEFAULT_CONFIGURATION = "org.apache.xerces.parsers.XIncludeParserConfiguration"; public final static String HTTP_ACCEPT = "Accept"; public final static String HTTP_ACCEPT_LANGUAGE = "Accept-Language"; public final static String XPOINTER = "xpointer"; public final static String XINCLUDE_NS_URI = "http://www.w3.org/2001/XInclude".intern(); public final static String XINCLUDE_INCLUDE = "include".intern(); public final static String XINCLUDE_FALLBACK = "fallback".intern(); public final static String XINCLUDE_PARSE_XML = "xml".intern(); public final static String XINCLUDE_PARSE_TEXT = "text".intern(); public final static String XINCLUDE_ATTR_HREF = "href".intern(); public final static String XINCLUDE_ATTR_PARSE = "parse".intern(); public final static String XINCLUDE_ATTR_ENCODING = "encoding".intern(); public final static String XINCLUDE_ATTR_ACCEPT = "accept".intern(); public final static String XINCLUDE_ATTR_ACCEPT_LANGUAGE = "accept-language".intern(); // Top Level Information Items have [included] property in infoset public final static String XINCLUDE_INCLUDED = "[included]".intern(); /** The identifier for the Augmentation that contains the current base URI */ public final static String CURRENT_BASE_URI = "currentBaseURI"; // used for adding [base URI] attributes public final static String XINCLUDE_BASE = "base".intern(); public final static QName XML_BASE_QNAME = new QName( XMLSymbols.PREFIX_XML, XINCLUDE_BASE, (XMLSymbols.PREFIX_XML + ":" + XINCLUDE_BASE).intern(), NamespaceContext.XML_URI); // used for adding [language] attributes public final static String XINCLUDE_LANG = "lang".intern(); public final static QName XML_LANG_QNAME = new QName( XMLSymbols.PREFIX_XML, XINCLUDE_LANG, (XMLSymbols.PREFIX_XML + ":" + XINCLUDE_LANG).intern(), NamespaceContext.XML_URI); public final static QName NEW_NS_ATTR_QNAME = new QName( XMLSymbols.PREFIX_XMLNS, "", XMLSymbols.PREFIX_XMLNS + ":", NamespaceContext.XMLNS_URI); // Processing States private final static int STATE_NORMAL_PROCESSING = 1; // we go into this state after a successful include (thus we ignore the children // of the include) or after a fallback private final static int STATE_IGNORE = 2; // we go into this state after a failed include. If we don't encounter a fallback // before we reach the end include tag, it's a fatal error private final static int STATE_EXPECT_FALLBACK = 3; // recognized features and properties /** Feature identifier: validation. */ protected static final String VALIDATION = Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE; /** Feature identifier: schema validation. */ protected static final String SCHEMA_VALIDATION = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_VALIDATION_FEATURE; /** Feature identifier: dynamic validation. */ protected static final String DYNAMIC_VALIDATION = Constants.XERCES_FEATURE_PREFIX + Constants.DYNAMIC_VALIDATION_FEATURE; /** Feature identifier: allow notation and unparsed entity events to be sent out of order. */ protected static final String ALLOW_UE_AND_NOTATION_EVENTS = Constants.SAX_FEATURE_PREFIX + Constants.ALLOW_DTD_EVENTS_AFTER_ENDDTD_FEATURE; /** Property identifier: symbol table. */ protected static final String SYMBOL_TABLE = Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY; /** Property identifier: error reporter. */ protected static final String ERROR_REPORTER = Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY; /** Property identifier: entity resolver. */ protected static final String ENTITY_RESOLVER = Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY; /** property identifier: security manager. */ protected static final String SECURITY_MANAGER = Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY; /** property identifier: buffer size. */ public static final String BUFFER_SIZE = Constants.XERCES_PROPERTY_PREFIX + Constants.BUFFER_SIZE_PROPERTY; /** Recognized features. */ private static final String[] RECOGNIZED_FEATURES = { ALLOW_UE_AND_NOTATION_EVENTS }; /** Feature defaults. */ private static final Boolean[] FEATURE_DEFAULTS = { Boolean.TRUE }; /** Recognized properties. */ private static final String[] RECOGNIZED_PROPERTIES = { ERROR_REPORTER, ENTITY_RESOLVER, SECURITY_MANAGER, BUFFER_SIZE }; /** Property defaults. */ private static final Object[] PROPERTY_DEFAULTS = { null, null, null, new Integer(XMLEntityManager.DEFAULT_BUFFER_SIZE) }; // instance variables // for XMLDocumentFilter protected XMLDocumentHandler fDocumentHandler; protected XMLDocumentSource fDocumentSource; // for XMLDTDFilter protected XMLDTDHandler fDTDHandler; protected XMLDTDSource fDTDSource; // for XIncludeHandler protected XIncludeHandler fParentXIncludeHandler; // for buffer size in XIncludeTextReader protected int fBufferSize = XMLEntityManager.DEFAULT_BUFFER_SIZE; // It "feels wrong" to store this value here. However, // calculating it can be time consuming, so we cache it. // It's never going to change in the lifetime of this XIncludeHandler protected String fParentRelativeURI; // we cache the child parser configuration, so we don't have to re-create // the objects when the parser is re-used protected XMLParserConfiguration fChildConfig; protected XMLLocator fDocLocation; protected XIncludeNamespaceSupport fNamespaceContext; protected SymbolTable fSymbolTable; protected XMLErrorReporter fErrorReporter; protected XMLEntityResolver fEntityResolver; protected SecurityManager fSecurityManager; // these are needed for text include processing protected XIncludeTextReader fXInclude10TextReader; protected XIncludeTextReader fXInclude11TextReader; // these are needed for XML Base processing protected XMLResourceIdentifier fCurrentBaseURI; protected IntStack fBaseURIScope; protected Stack fBaseURI; protected Stack fLiteralSystemID; protected Stack fExpandedSystemID; // these are needed for Language Fixup protected IntStack fLanguageScope; protected Stack fLanguageStack; protected String fCurrentLanguage; // used for passing features on to child XIncludeHandler objects protected ParserConfigurationSettings fSettings; // The current element depth. We start at depth 0 (before we've reached any elements). // The first element is at depth 1. private int fDepth; // The current element depth of the result infoset. private int fResultDepth; // this value must be at least 1 private static final int INITIAL_SIZE = 8; // Used to ensure that fallbacks are always children of include elements, // and that include elements are never children of other include elements. // An index contains true if the ancestor of the current element which resides // at that depth was an include element. private boolean[] fSawInclude = new boolean[INITIAL_SIZE]; // Ensures that only one fallback element can be at a single depth. // An index contains true if we have seen any fallback elements at that depth, // and it is only reset to false when the end tag of the parent is encountered. private boolean[] fSawFallback = new boolean[INITIAL_SIZE]; // The state of the processor at each given depth. private int[] fState = new int[INITIAL_SIZE]; // buffering the necessary DTD events private Vector fNotations; private Vector fUnparsedEntities; // for SAX compatibility. // Has the value of the ALLOW_UE_AND_NOTATION_EVENTS feature private boolean fSendUEAndNotationEvents; // track the version of the document being parsed private boolean fIsXML11; // track whether a DTD is being parsed private boolean fInDTD; // track whether the root element of the result infoset has been processed private boolean fSeenRootElement; // Constructors public XIncludeHandler() { fDepth = 0; fSawFallback[fDepth] = false; fSawInclude[fDepth] = false; fState[fDepth] = STATE_NORMAL_PROCESSING; fNotations = new Vector(); fUnparsedEntities = new Vector(); fBaseURIScope = new IntStack(); fBaseURI = new Stack(); fLiteralSystemID = new Stack(); fExpandedSystemID = new Stack(); fCurrentBaseURI = new XMLResourceIdentifierImpl(); fLanguageScope = new IntStack(); fLanguageStack = new Stack(); fCurrentLanguage = null; } // XMLComponent methods public void reset(XMLComponentManager componentManager) throws XNIException { fNamespaceContext = null; fDepth = 0; fResultDepth = 0; fNotations = new Vector(); fUnparsedEntities = new Vector(); fParentRelativeURI = null; fIsXML11 = false; fInDTD = false; fSeenRootElement = false; fBaseURIScope.clear(); fBaseURI.clear(); fLiteralSystemID.clear(); fExpandedSystemID.clear(); // REVISIT: Find a better method for maintaining // the state of the XInclude processor. These arrays // can potentially grow quite large. Cleaning them // out on reset may be very time consuming. -- mrglavas // // clear the previous settings from the arrays for (int i = 0; i < fState.length; ++i) { fState[i] = STATE_NORMAL_PROCESSING; } for (int i = 0; i < fSawFallback.length; ++i) { fSawFallback[i] = false; } for (int i = 0; i < fSawInclude.length; ++i) { fSawInclude[i] = false; } try { fSendUEAndNotationEvents = componentManager.getFeature(ALLOW_UE_AND_NOTATION_EVENTS); if (fChildConfig != null) { fChildConfig.setFeature( ALLOW_UE_AND_NOTATION_EVENTS, fSendUEAndNotationEvents); } } catch (XMLConfigurationException e) { } // Get symbol table. try { SymbolTable value = (SymbolTable)componentManager.getProperty(SYMBOL_TABLE); if (value != null) { fSymbolTable = value; if (fChildConfig != null) { fChildConfig.setProperty(SYMBOL_TABLE, value); } } } catch (XMLConfigurationException e) { fSymbolTable = null; } // Get error reporter. try { XMLErrorReporter value = (XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER); if (value != null) { setErrorReporter(value); if (fChildConfig != null) { fChildConfig.setProperty(ERROR_REPORTER, value); } } } catch (XMLConfigurationException e) { fErrorReporter = null; } // Get entity resolver. try { XMLEntityResolver value = (XMLEntityResolver)componentManager.getProperty( ENTITY_RESOLVER); if (value != null) { fEntityResolver = value; if (fChildConfig != null) { fChildConfig.setProperty(ENTITY_RESOLVER, value); } } } catch (XMLConfigurationException e) { fEntityResolver = null; } // Get security manager. try { SecurityManager value = (SecurityManager)componentManager.getProperty( SECURITY_MANAGER); if (value != null) { fSecurityManager = value; if (fChildConfig != null) { fChildConfig.setProperty(SECURITY_MANAGER, value); } } } catch (XMLConfigurationException e) { fSecurityManager = null; } // Get buffer size. try { Integer value = (Integer)componentManager.getProperty( BUFFER_SIZE); if (value != null && value.intValue() > 0) { fBufferSize = value.intValue(); if (fChildConfig != null) { fChildConfig.setProperty(BUFFER_SIZE, value); } } else { fBufferSize = ((Integer)getPropertyDefault(BUFFER_SIZE)).intValue(); } } catch (XMLConfigurationException e) { fBufferSize = ((Integer)getPropertyDefault(BUFFER_SIZE)).intValue(); } // Reset XML 1.0 text reader. if (fXInclude10TextReader != null) { fXInclude10TextReader.setBufferSize(fBufferSize); } // Reset XML 1.1 text reader. if (fXInclude11TextReader != null) { fXInclude11TextReader.setBufferSize(fBufferSize); } fSettings = new ParserConfigurationSettings(); copyFeatures(componentManager, fSettings); // we don't want a schema validator on the new pipeline, // so if it was enabled, we set the feature to false as // well as other validation features. try { if (componentManager.getFeature(SCHEMA_VALIDATION)) { fSettings.setFeature(SCHEMA_VALIDATION, false); fSettings.setFeature(DYNAMIC_VALIDATION, false); fSettings.setFeature(VALIDATION, false); } } catch (XMLConfigurationException e) {} // Don't reset fChildConfig -- we don't want it to share the same components. // It will be reset when it is actually used to parse something. } // reset(XMLComponentManager) /** * Returns a list of feature identifiers that are recognized by * this component. This method may return null if no features * are recognized by this component. */ public String[] getRecognizedFeatures() { return RECOGNIZED_FEATURES; } // getRecognizedFeatures():String[] /** * Sets the state of a feature. This method is called by the component * manager any time after reset when a feature changes state. * <p> * <strong>Note:</strong> Components should silently ignore features * that do not affect the operation of the component. * * @param featureId The feature identifier. * @param state The state of the feature. * * @throws SAXNotRecognizedException The component should not throw * this exception. * @throws SAXNotSupportedException The component should not throw * this exception. */ public void setFeature(String featureId, boolean state) throws XMLConfigurationException { if (featureId.equals(ALLOW_UE_AND_NOTATION_EVENTS)) { fSendUEAndNotationEvents = state; } if (fSettings != null) { fSettings.setFeature(featureId, state); } } // setFeature(String,boolean) /** * Returns a list of property identifiers that are recognized by * this component. This method may return null if no properties * are recognized by this component. */ public String[] getRecognizedProperties() { return RECOGNIZED_PROPERTIES; } // getRecognizedProperties():String[] /** * Sets the value of a property. This method is called by the component * manager any time after reset when a property changes value. * <p> * <strong>Note:</strong> Components should silently ignore properties * that do not affect the operation of the component. * * @param propertyId The property identifier. * @param value The value of the property. * * @throws SAXNotRecognizedException The component should not throw * this exception. * @throws SAXNotSupportedException The component should not throw * this exception. */ public void setProperty(String propertyId, Object value) throws XMLConfigurationException { if (propertyId.equals(SYMBOL_TABLE)) { fSymbolTable = (SymbolTable)value; if (fChildConfig != null) { fChildConfig.setProperty(propertyId, value); } return; } if (propertyId.equals(ERROR_REPORTER)) { setErrorReporter((XMLErrorReporter)value); if (fChildConfig != null) { fChildConfig.setProperty(propertyId, value); } return; } if (propertyId.equals(ENTITY_RESOLVER)) { fEntityResolver = (XMLEntityResolver)value; if (fChildConfig != null) { fChildConfig.setProperty(propertyId, value); } return; } if (propertyId.equals(SECURITY_MANAGER)) { fSecurityManager = (SecurityManager)value; if (fChildConfig != null) { fChildConfig.setProperty(propertyId, value); } return; } if (propertyId.equals(BUFFER_SIZE)) { Integer bufferSize = (Integer) value; if (fChildConfig != null) { fChildConfig.setProperty(propertyId, value); } if (bufferSize != null && bufferSize.intValue() > 0) { fBufferSize = bufferSize.intValue(); // Reset XML 1.0 text reader. if (fXInclude10TextReader != null) { fXInclude10TextReader.setBufferSize(fBufferSize); } // Reset XML 1.1 text reader. if (fXInclude11TextReader != null) { fXInclude11TextReader.setBufferSize(fBufferSize); } } return; } } // setProperty(String,Object) /** * Returns the default state for a feature, or null if this * component does not want to report a default value for this * feature. * * @param featureId The feature identifier. * * @since Xerces 2.2.0 */ public Boolean getFeatureDefault(String featureId) { for (int i = 0; i < RECOGNIZED_FEATURES.length; i++) { if (RECOGNIZED_FEATURES[i].equals(featureId)) { return FEATURE_DEFAULTS[i]; } } return null; } // getFeatureDefault(String):Boolean /** * Returns the default state for a property, or null if this * component does not want to report a default value for this * property. * * @param propertyId The property identifier. * * @since Xerces 2.2.0 */ public Object getPropertyDefault(String propertyId) { for (int i = 0; i < RECOGNIZED_PROPERTIES.length; i++) { if (RECOGNIZED_PROPERTIES[i].equals(propertyId)) { return PROPERTY_DEFAULTS[i]; } } return null; } // getPropertyDefault(String):Object public void setDocumentHandler(XMLDocumentHandler handler) { fDocumentHandler = handler; } public XMLDocumentHandler getDocumentHandler() { return fDocumentHandler; } // XMLDocumentHandler methods /** * Event sent at the start of the document. * * A fatal error will occur here, if it is detected that this document has been processed * before. * * This event is only passed on to the document handler if this is the root document. */ public void startDocument( XMLLocator locator, String encoding, NamespaceContext namespaceContext, Augmentations augs) throws XNIException { // we do this to ensure that the proper location is reported in errors // otherwise, the locator from the root document would always be used fErrorReporter.setDocumentLocator(locator); if (!isRootDocument() && fParentXIncludeHandler.searchForRecursiveIncludes(locator)) { reportFatalError( "RecursiveInclude", new Object[] { locator.getExpandedSystemId()}); } if (!(namespaceContext instanceof XIncludeNamespaceSupport)) { reportFatalError("IncompatibleNamespaceContext"); } fNamespaceContext = (XIncludeNamespaceSupport)namespaceContext; fDocLocation = locator; // initialize the current base URI fCurrentBaseURI.setBaseSystemId(locator.getBaseSystemId()); fCurrentBaseURI.setExpandedSystemId(locator.getExpandedSystemId()); fCurrentBaseURI.setLiteralSystemId(locator.getLiteralSystemId()); saveBaseURI(); if (augs == null) { augs = new AugmentationsImpl(); } augs.putItem(CURRENT_BASE_URI, fCurrentBaseURI); // initialize the current language fCurrentLanguage = XMLSymbols.EMPTY_STRING; saveLanguage(fCurrentLanguage); if (isRootDocument() && fDocumentHandler != null) { fDocumentHandler.startDocument( locator, encoding, namespaceContext, augs); } } public void xmlDecl( String version, String encoding, String standalone, Augmentations augs) throws XNIException { fIsXML11 = "1.1".equals(version); if (isRootDocument() && fDocumentHandler != null) { fDocumentHandler.xmlDecl(version, encoding, standalone, augs); } } public void doctypeDecl( String rootElement, String publicId, String systemId, Augmentations augs) throws XNIException { if (isRootDocument() && fDocumentHandler != null) { fDocumentHandler.doctypeDecl(rootElement, publicId, systemId, augs); } } public void comment(XMLString text, Augmentations augs) throws XNIException { if (!fInDTD) { if (fDocumentHandler != null && getState() == STATE_NORMAL_PROCESSING) { fDepth++; augs = modifyAugmentations(augs); fDocumentHandler.comment(text, augs); fDepth--; } } else if (fDTDHandler != null) { fDTDHandler.comment(text, augs); } } public void processingInstruction( String target, XMLString data, Augmentations augs) throws XNIException { if (!fInDTD) { if (fDocumentHandler != null && getState() == STATE_NORMAL_PROCESSING) { // we need to change the depth like this so that modifyAugmentations() works fDepth++; augs = modifyAugmentations(augs); fDocumentHandler.processingInstruction(target, data, augs); fDepth--; } } else if (fDTDHandler != null) { fDTDHandler.processingInstruction(target, data, augs); } } public void startElement( QName element, XMLAttributes attributes, Augmentations augs) throws XNIException { fDepth++; setState(getState(fDepth - 1)); // we process the xml:base and xml:lang attributes regardless // of what type of element it is. processXMLBaseAttributes(attributes); processXMLLangAttributes(attributes); if (isIncludeElement(element)) { boolean success = this.handleIncludeElement(attributes); if (success) { setState(STATE_IGNORE); } else { setState(STATE_EXPECT_FALLBACK); } } else if (isFallbackElement(element)) { this.handleFallbackElement(); } else if (hasXIncludeNamespace(element)) { if (getSawInclude(fDepth - 1)) { reportFatalError( "IncludeChild", new Object[] { element.rawname }); } if (getSawFallback(fDepth - 1)) { reportFatalError( "FallbackChild", new Object[] { element.rawname }); } if (getState() == STATE_NORMAL_PROCESSING) { if (fResultDepth++ == 0 && isRootDocument()) { checkMultipleRootElements(); } if (fDocumentHandler != null) { augs = modifyAugmentations(augs); attributes = processAttributes(attributes); fDocumentHandler.startElement(element, attributes, augs); } } } else if (getState() == STATE_NORMAL_PROCESSING) { if (fResultDepth++ == 0 && isRootDocument()) { checkMultipleRootElements(); } if (fDocumentHandler != null) { augs = modifyAugmentations(augs); attributes = processAttributes(attributes); fDocumentHandler.startElement(element, attributes, augs); } } } public void emptyElement( QName element, XMLAttributes attributes, Augmentations augs) throws XNIException { fDepth++; setState(getState(fDepth - 1)); // we process the xml:base and xml:lang attributes regardless // of what type of element it is. processXMLBaseAttributes(attributes); processXMLLangAttributes(attributes); if (isIncludeElement(element)) { boolean success = this.handleIncludeElement(attributes); if (success) { setState(STATE_IGNORE); } else { reportFatalError("NoFallback"); } } else if (isFallbackElement(element)) { this.handleFallbackElement(); } else if (hasXIncludeNamespace(element)) { if (getSawInclude(fDepth - 1)) { reportFatalError( "IncludeChild", new Object[] { element.rawname }); } if (getSawFallback(fDepth - 1)) { reportFatalError( "FallbackChild", new Object[] { element.rawname }); } if (getState() == STATE_NORMAL_PROCESSING) { if (fResultDepth == 0 && isRootDocument()) { checkMultipleRootElements(); } if (fDocumentHandler != null) { augs = modifyAugmentations(augs); attributes = processAttributes(attributes); fDocumentHandler.emptyElement(element, attributes, augs); } } } else if (getState() == STATE_NORMAL_PROCESSING) { if (fResultDepth == 0 && isRootDocument()) { checkMultipleRootElements(); } if (fDocumentHandler != null) { augs = modifyAugmentations(augs); attributes = processAttributes(attributes); fDocumentHandler.emptyElement(element, attributes, augs); } } // reset the out of scope stack elements setSawFallback(fDepth + 1, false); setSawInclude(fDepth + 1, false); // check if an xml:base has gone out of scope if (fBaseURIScope.size() > 0 && fDepth == fBaseURIScope.peek()) { // pop the values from the stack restoreBaseURI(); } fDepth--; } public void endElement(QName element, Augmentations augs) throws XNIException { if (isIncludeElement(element)) { // if we're ending an include element, and we were expecting a fallback // we check to see if the children of this include element contained a fallback if (getState() == STATE_EXPECT_FALLBACK && !getSawFallback(fDepth + 1)) { reportFatalError("NoFallback"); } } if (isFallbackElement(element)) { // the state would have been set to normal processing if we were expecting the fallback element // now that we're done processing it, we should ignore all the other children of the include element if (getState() == STATE_NORMAL_PROCESSING) { setState(STATE_IGNORE); } } else if ( fDocumentHandler != null && getState() == STATE_NORMAL_PROCESSING) { --fResultDepth; fDocumentHandler.endElement(element, augs); } // reset the out of scope stack elements setSawFallback(fDepth + 1, false); setSawInclude(fDepth + 1, false); // check if an xml:base has gone out of scope if (fBaseURIScope.size() > 0 && fDepth == fBaseURIScope.peek()) { // pop the values from the stack restoreBaseURI(); } // check if an xml:lang has gone out of scope if (fLanguageScope.size() > 0 && fDepth == fLanguageScope.peek()) { // pop the language from the stack fCurrentLanguage = restoreLanguage(); } fDepth--; } public void startGeneralEntity( String name, XMLResourceIdentifier resId, String encoding, Augmentations augs) throws XNIException { if (getState() == STATE_NORMAL_PROCESSING) { if (fResultDepth == 0 && isRootDocument()) { if (augs != null && Boolean.TRUE.equals(augs.getItem(Constants.ENTITY_SKIPPED))) { reportFatalError("UnexpandedEntityReferenceIllegal"); } } else if (fDocumentHandler != null) { fDocumentHandler.startGeneralEntity(name, resId, encoding, augs); } } } public void textDecl(String version, String encoding, Augmentations augs) throws XNIException { if (fDocumentHandler != null && getState() == STATE_NORMAL_PROCESSING) { fDocumentHandler.textDecl(version, encoding, augs); } } public void endGeneralEntity(String name, Augmentations augs) throws XNIException { if (fDocumentHandler != null && getState() == STATE_NORMAL_PROCESSING && (fResultDepth != 0 || !isRootDocument())) { fDocumentHandler.endGeneralEntity(name, augs); } } public void characters(XMLString text, Augmentations augs) throws XNIException { if (getState() == STATE_NORMAL_PROCESSING) { if (fResultDepth == 0 && isRootDocument()) { checkWhitespace(text); } else if (fDocumentHandler != null) { // we need to change the depth like this so that modifyAugmentations() works fDepth++; augs = modifyAugmentations(augs); fDocumentHandler.characters(text, augs); fDepth--; } } } public void ignorableWhitespace(XMLString text, Augmentations augs) throws XNIException { if (fDocumentHandler != null && getState() == STATE_NORMAL_PROCESSING && (fResultDepth != 0 || !isRootDocument())) { fDocumentHandler.ignorableWhitespace(text, augs); } } public void startCDATA(Augmentations augs) throws XNIException { if (fDocumentHandler != null && getState() == STATE_NORMAL_PROCESSING && (fResultDepth != 0 || !isRootDocument())) { fDocumentHandler.startCDATA(augs); } } public void endCDATA(Augmentations augs) throws XNIException { if (fDocumentHandler != null && getState() == STATE_NORMAL_PROCESSING && (fResultDepth != 0 || !isRootDocument())) { fDocumentHandler.endCDATA(augs); } } public void endDocument(Augmentations augs) throws XNIException { if (isRootDocument()) { if (!fSeenRootElement) { reportFatalError("RootElementRequired"); } if (fDocumentHandler != null) { fDocumentHandler.endDocument(augs); } } } public void setDocumentSource(XMLDocumentSource source) { fDocumentSource = source; } public XMLDocumentSource getDocumentSource() { return fDocumentSource; } // DTDHandler methods // We are only interested in the notation and unparsed entity declarations, // the rest we just pass on /* (non-Javadoc) * @see org.apache.xerces.xni.XMLDTDHandler#attributeDecl(java.lang.String, java.lang.String, java.lang.String, java.lang.String[], java.lang.String, org.apache.xerces.xni.XMLString, org.apache.xerces.xni.XMLString, org.apache.xerces.xni.Augmentations) */ public void attributeDecl( String elementName, String attributeName, String type, String[] enumeration, String defaultType, XMLString defaultValue, XMLString nonNormalizedDefaultValue, Augmentations augmentations) throws XNIException { if (fDTDHandler != null) { fDTDHandler.attributeDecl( elementName, attributeName, type, enumeration, defaultType, defaultValue, nonNormalizedDefaultValue, augmentations); } } /* (non-Javadoc) * @see org.apache.xerces.xni.XMLDTDHandler#elementDecl(java.lang.String, java.lang.String, org.apache.xerces.xni.Augmentations) */ public void elementDecl( String name, String contentModel, Augmentations augmentations) throws XNIException { if (fDTDHandler != null) { fDTDHandler.elementDecl(name, contentModel, augmentations); } } /* (non-Javadoc) * @see org.apache.xerces.xni.XMLDTDHandler#endAttlist(org.apache.xerces.xni.Augmentations) */ public void endAttlist(Augmentations augmentations) throws XNIException { if (fDTDHandler != null) { fDTDHandler.endAttlist(augmentations); } } /* (non-Javadoc) * @see org.apache.xerces.xni.XMLDTDHandler#endConditional(org.apache.xerces.xni.Augmentations) */ public void endConditional(Augmentations augmentations) throws XNIException { if (fDTDHandler != null) { fDTDHandler.endConditional(augmentations); } } /* (non-Javadoc) * @see org.apache.xerces.xni.XMLDTDHandler#endDTD(org.apache.xerces.xni.Augmentations) */ public void endDTD(Augmentations augmentations) throws XNIException { if (fDTDHandler != null) { fDTDHandler.endDTD(augmentations); } fInDTD = false; } /* (non-Javadoc) * @see org.apache.xerces.xni.XMLDTDHandler#endExternalSubset(org.apache.xerces.xni.Augmentations) */ public void endExternalSubset(Augmentations augmentations) throws XNIException { if (fDTDHandler != null) { fDTDHandler.endExternalSubset(augmentations); } } /* (non-Javadoc) * @see org.apache.xerces.xni.XMLDTDHandler#endParameterEntity(java.lang.String, org.apache.xerces.xni.Augmentations) */ public void endParameterEntity(String name, Augmentations augmentations) throws XNIException { if (fDTDHandler != null) { fDTDHandler.endParameterEntity(name, augmentations); } } /* (non-Javadoc) * @see org.apache.xerces.xni.XMLDTDHandler#externalEntityDecl(java.lang.String, org.apache.xerces.xni.XMLResourceIdentifier, org.apache.xerces.xni.Augmentations) */ public void externalEntityDecl( String name, XMLResourceIdentifier identifier, Augmentations augmentations) throws XNIException { if (fDTDHandler != null) { fDTDHandler.externalEntityDecl(name, identifier, augmentations); } } /* (non-Javadoc) * @see org.apache.xerces.xni.XMLDTDHandler#getDTDSource() */ public XMLDTDSource getDTDSource() { return fDTDSource; } /* (non-Javadoc) * @see org.apache.xerces.xni.XMLDTDHandler#ignoredCharacters(org.apache.xerces.xni.XMLString, org.apache.xerces.xni.Augmentations) */ public void ignoredCharacters(XMLString text, Augmentations augmentations) throws XNIException { if (fDTDHandler != null) { fDTDHandler.ignoredCharacters(text, augmentations); } } /* (non-Javadoc) * @see org.apache.xerces.xni.XMLDTDHandler#internalEntityDecl(java.lang.String, org.apache.xerces.xni.XMLString, org.apache.xerces.xni.XMLString, org.apache.xerces.xni.Augmentations) */ public void internalEntityDecl( String name, XMLString text, XMLString nonNormalizedText, Augmentations augmentations) throws XNIException { if (fDTDHandler != null) { fDTDHandler.internalEntityDecl( name, text, nonNormalizedText, augmentations); } } /* (non-Javadoc) * @see org.apache.xerces.xni.XMLDTDHandler#notationDecl(java.lang.String, org.apache.xerces.xni.XMLResourceIdentifier, org.apache.xerces.xni.Augmentations) */ public void notationDecl( String name, XMLResourceIdentifier identifier, Augmentations augmentations) throws XNIException { this.addNotation(name, identifier, augmentations); if (fDTDHandler != null) { fDTDHandler.notationDecl(name, identifier, augmentations); } } /* (non-Javadoc) * @see org.apache.xerces.xni.XMLDTDHandler#setDTDSource(org.apache.xerces.xni.parser.XMLDTDSource) */ public void setDTDSource(XMLDTDSource source) { fDTDSource = source; } /* (non-Javadoc) * @see org.apache.xerces.xni.XMLDTDHandler#startAttlist(java.lang.String, org.apache.xerces.xni.Augmentations) */ public void startAttlist(String elementName, Augmentations augmentations) throws XNIException { if (fDTDHandler != null) { fDTDHandler.startAttlist(elementName, augmentations); } } /* (non-Javadoc) * @see org.apache.xerces.xni.XMLDTDHandler#startConditional(short, org.apache.xerces.xni.Augmentations) */ public void startConditional(short type, Augmentations augmentations) throws XNIException { if (fDTDHandler != null) { fDTDHandler.startConditional(type, augmentations); } } /* (non-Javadoc) * @see org.apache.xerces.xni.XMLDTDHandler#startDTD(org.apache.xerces.xni.XMLLocator, org.apache.xerces.xni.Augmentations) */ public void startDTD(XMLLocator locator, Augmentations augmentations) throws XNIException { fInDTD = true; if (fDTDHandler != null) { fDTDHandler.startDTD(locator, augmentations); } } /* (non-Javadoc) * @see org.apache.xerces.xni.XMLDTDHandler#startExternalSubset(org.apache.xerces.xni.XMLResourceIdentifier, org.apache.xerces.xni.Augmentations) */ public void startExternalSubset( XMLResourceIdentifier identifier, Augmentations augmentations) throws XNIException { if (fDTDHandler != null) { fDTDHandler.startExternalSubset(identifier, augmentations); } } /* (non-Javadoc) * @see org.apache.xerces.xni.XMLDTDHandler#startParameterEntity(java.lang.String, org.apache.xerces.xni.XMLResourceIdentifier, java.lang.String, org.apache.xerces.xni.Augmentations) */ public void startParameterEntity( String name, XMLResourceIdentifier identifier, String encoding, Augmentations augmentations) throws XNIException { if (fDTDHandler != null) { fDTDHandler.startParameterEntity( name, identifier, encoding, augmentations); } } /* (non-Javadoc) * @see org.apache.xerces.xni.XMLDTDHandler#unparsedEntityDecl(java.lang.String, org.apache.xerces.xni.XMLResourceIdentifier, java.lang.String, org.apache.xerces.xni.Augmentations) */ public void unparsedEntityDecl( String name, XMLResourceIdentifier identifier, String notation, Augmentations augmentations) throws XNIException { this.addUnparsedEntity(name, identifier, notation, augmentations); if (fDTDHandler != null) { fDTDHandler.unparsedEntityDecl( name, identifier, notation, augmentations); } } /* (non-Javadoc) * @see org.apache.xerces.xni.parser.XMLDTDSource#getDTDHandler() */ public XMLDTDHandler getDTDHandler() { return fDTDHandler; } /* (non-Javadoc) * @see org.apache.xerces.xni.parser.XMLDTDSource#setDTDHandler(org.apache.xerces.xni.XMLDTDHandler) */ public void setDTDHandler(XMLDTDHandler handler) { fDTDHandler = handler; } // XIncludeHandler methods private void setErrorReporter(XMLErrorReporter reporter) { fErrorReporter = reporter; if (fErrorReporter != null) { fErrorReporter.putMessageFormatter( XIncludeMessageFormatter.XINCLUDE_DOMAIN, new XIncludeMessageFormatter()); // this ensures the proper location is displayed in error messages if (fDocLocation != null) { fErrorReporter.setDocumentLocator(fDocLocation); } } } protected void handleFallbackElement() { setSawInclude(fDepth, false); fNamespaceContext.setContextInvalid(); if (!getSawInclude(fDepth - 1)) { reportFatalError("FallbackParent"); } if (getSawFallback(fDepth)) { reportFatalError("MultipleFallbacks"); } else { setSawFallback(fDepth, true); } // Either the state is STATE_EXPECT_FALLBACK or it's STATE_IGNORE. // If we're ignoring, we want to stay ignoring. But if we're expecting this fallback element, // we want to signal that we should process the children. if (getState() == STATE_EXPECT_FALLBACK) { setState(STATE_NORMAL_PROCESSING); } } protected boolean handleIncludeElement(XMLAttributes attributes) throws XNIException { setSawInclude(fDepth, true); fNamespaceContext.setContextInvalid(); if (getSawInclude(fDepth - 1)) { reportFatalError("IncludeChild", new Object[] { XINCLUDE_INCLUDE }); } if (getState() == STATE_IGNORE) return true; // TODO: does Java use IURIs by default? // [Definition: An internationalized URI reference, or IURI, is a URI reference that directly uses [Unicode] characters.] // TODO: figure out what section 4.1.1 of the XInclude spec is talking about // has to do with disallowed ASCII character escaping // this ties in with the above IURI section, but I suspect Java already does it String href = attributes.getValue(XINCLUDE_ATTR_HREF); String parse = attributes.getValue(XINCLUDE_ATTR_PARSE); String xpointer = attributes.getValue(XPOINTER); String accept = attributes.getValue(XINCLUDE_ATTR_ACCEPT); String acceptLanguage = attributes.getValue(XINCLUDE_ATTR_ACCEPT_LANGUAGE); if (href == null && xpointer == null) { reportFatalError("XpointerMissing"); } if (parse == null) { parse = XINCLUDE_PARSE_XML; } // Verify that if an accept and/or an accept-language attribute exist // that the value(s) don't contain disallowed characters. if (accept != null && !isValidInHTTPHeader(accept)) { - reportFatalError("AcceptMalformed", null); + reportFatalError("AcceptMalformed", null); + accept = null; } if (acceptLanguage != null && !isValidInHTTPHeader(acceptLanguage)) { reportFatalError("AcceptLanguageMalformed", null); + acceptLanguage = null; } XMLInputSource includedSource = null; if (fEntityResolver != null) { try { XMLResourceIdentifier resourceIdentifier = new XMLResourceIdentifierImpl( null, href, fCurrentBaseURI.getExpandedSystemId(), XMLEntityManager.expandSystemId( href, fCurrentBaseURI.getExpandedSystemId(), false)); includedSource = fEntityResolver.resolveEntity(resourceIdentifier); if (includedSource != null && !(includedSource instanceof HTTPInputSource) && (accept != null || acceptLanguage != null) && includedSource.getCharacterStream() == null && includedSource.getByteStream() == null) { includedSource = createInputSource(includedSource.getPublicId(), includedSource.getSystemId(), includedSource.getBaseSystemId(), accept, acceptLanguage); } } catch (IOException e) { reportResourceError( "XMLResourceError", new Object[] { href, e.getMessage()}); return false; } } if (includedSource == null) { // setup an HTTPInputSource if either of the content negotation attributes were specified. if (accept != null || acceptLanguage != null) { includedSource = createInputSource(null, href, fCurrentBaseURI.getExpandedSystemId(), accept, acceptLanguage); } else { includedSource = new XMLInputSource(null, href, fCurrentBaseURI.getExpandedSystemId()); } } if (parse.equals(XINCLUDE_PARSE_XML)) { // Instead of always creating a new configuration, the first one can be reused if (fChildConfig == null) { String parserName = XINCLUDE_DEFAULT_CONFIGURATION; fChildConfig = (XMLParserConfiguration)ObjectFactory.newInstance( parserName, ObjectFactory.findClassLoader(), true); // use the same symbol table, error reporter, entity resolver, security manager and buffer size. if (fSymbolTable != null) fChildConfig.setProperty(SYMBOL_TABLE, fSymbolTable); if (fErrorReporter != null) fChildConfig.setProperty(ERROR_REPORTER, fErrorReporter); if (fEntityResolver != null) fChildConfig.setProperty(ENTITY_RESOLVER, fEntityResolver); if (fSecurityManager != null) fChildConfig.setProperty(SECURITY_MANAGER, fSecurityManager); fChildConfig.setProperty(BUFFER_SIZE, new Integer(fBufferSize)); // use the same namespace context fChildConfig.setProperty( Constants.XERCES_PROPERTY_PREFIX + Constants.NAMESPACE_CONTEXT_PROPERTY, fNamespaceContext); XIncludeHandler newHandler = (XIncludeHandler)fChildConfig.getProperty( Constants.XERCES_PROPERTY_PREFIX + Constants.XINCLUDE_HANDLER_PROPERTY); newHandler.setParent(this); newHandler.setDocumentHandler(this.getDocumentHandler()); } // set all features on parserConfig to match this parser configuration copyFeatures(fSettings, fChildConfig); try { fNamespaceContext.pushScope(); fChildConfig.parse(includedSource); // necessary to make sure proper location is reported in errors if (fErrorReporter != null) { fErrorReporter.setDocumentLocator(fDocLocation); } } catch (XNIException e) { // necessary to make sure proper location is reported in errors if (fErrorReporter != null) { fErrorReporter.setDocumentLocator(fDocLocation); } reportFatalError("XMLParseError", new Object[] { href }); } catch (IOException e) { // necessary to make sure proper location is reported in errors if (fErrorReporter != null) { fErrorReporter.setDocumentLocator(fDocLocation); } // An IOException indicates that we had trouble reading the file, not // that it was an invalid XML file. So we send a resource error, not a // fatal error. reportResourceError( "XMLResourceError", new Object[] { href, e.getMessage()}); return false; } finally { fNamespaceContext.popScope(); } } else if (parse.equals(XINCLUDE_PARSE_TEXT)) { // we only care about encoding for parse="text" String encoding = attributes.getValue(XINCLUDE_ATTR_ENCODING); includedSource.setEncoding(encoding); XIncludeTextReader textReader = null; try { // Setup the appropriate text reader. if (!fIsXML11) { if (fXInclude10TextReader == null) { fXInclude10TextReader = new XIncludeTextReader(includedSource, this, fBufferSize); } else { fXInclude10TextReader.setInputSource(includedSource); } textReader = fXInclude10TextReader; } else { if (fXInclude11TextReader == null) { fXInclude11TextReader = new XInclude11TextReader(includedSource, this, fBufferSize); } else { fXInclude11TextReader.setInputSource(includedSource); } textReader = fXInclude11TextReader; } textReader.setErrorReporter(fErrorReporter); textReader.parse(); } // encoding errors catch (MalformedByteSequenceException ex) { fErrorReporter.reportError(ex.getDomain(), ex.getKey(), ex.getArguments(), XMLErrorReporter.SEVERITY_FATAL_ERROR); } catch (CharConversionException e) { fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN, "CharConversionFailure", null, XMLErrorReporter.SEVERITY_FATAL_ERROR); } catch (IOException e) { reportResourceError( "TextResourceError", new Object[] { href, e.getMessage()}); return false; } finally { if (textReader != null) { try { textReader.close(); } catch (IOException e) { reportResourceError( "TextResourceError", new Object[] { href, e.getMessage()}); return false; } } } } else { reportFatalError("InvalidParseValue", new Object[] { parse }); } return true; } /** * Returns true if the element has the namespace "http://www.w3.org/2001/XInclude" * @param element the element to check * @return true if the element has the namespace "http://www.w3.org/2001/XInclude" */ protected boolean hasXIncludeNamespace(QName element) { // REVISIT: The namespace of this element should be bound // already. Why are we looking it up from the namespace // context? -- mrglavas return element.uri == XINCLUDE_NS_URI || fNamespaceContext.getURI(element.prefix) == XINCLUDE_NS_URI; } /** * Checks if the element is an &lt;include&gt; element. The element must have * the XInclude namespace, and a local name of "include". * * @param element the element to check * @return true if the element is an &lt;include&gt; element * @see #hasXIncludeNamespace(QName) */ protected boolean isIncludeElement(QName element) { return element.localpart.equals(XINCLUDE_INCLUDE) && hasXIncludeNamespace(element); } /** * Checks if the element is an &lt;fallback&gt; element. The element must have * the XInclude namespace, and a local name of "fallback". * * @param element the element to check * @return true if the element is an &lt;fallback; element * @see #hasXIncludeNamespace(QName) */ protected boolean isFallbackElement(QName element) { return element.localpart.equals(XINCLUDE_FALLBACK) && hasXIncludeNamespace(element); } /** * Returns true if the current [base URI] is the same as the [base URI] that * was in effect on the include parent. This method should <em>only</em> be called * when the current element is a top level included element, i.e. the direct child * of a fallback element, or the root elements in an included document. * The "include parent" is the element which, in the result infoset, will be the * direct parent of the current element. * @return true if the [base URIs] are the same string */ protected boolean sameBaseURIAsIncludeParent() { String parentBaseURI = getIncludeParentBaseURI(); String baseURI = fCurrentBaseURI.getExpandedSystemId(); // REVISIT: should we use File#sameFile() ? // I think the benefit of using it is that it resolves host names // instead of just doing a string comparison. // TODO: [base URI] is still an open issue with the working group. // They're deciding if xml:base should be added if the [base URI] is different in terms // of resolving relative references, or if it should be added if they are different at all. // Revisit this after a final decision has been made. // The decision also affects whether we output the file name of the URI, or just the path. return parentBaseURI != null && parentBaseURI.equals(baseURI); } /** * Returns true if the current [language] is equivalent to the [language] that * was in effect on the include parent, taking case-insensitivity into account * as per [RFC 3066]. This method should <em>only</em> be called when the * current element is a top level included element, i.e. the direct child * of a fallback element, or the root elements in an included document. * The "include parent" is the element which, in the result infoset, will be the * direct parent of the current element. * * @return true if the [language] properties have the same value * taking case-insensitivity into account as per [RFC 3066]. */ protected boolean sameLanguageAsIncludeParent() { String parentLanguage = getIncludeParentLanguage(); return parentLanguage != null && parentLanguage.equalsIgnoreCase(fCurrentLanguage); } /** * Checks if the file indicated by the given XMLLocator has already been included * in the current stack. * @param includedSource the source to check for inclusion * @return true if the source has already been included */ protected boolean searchForRecursiveIncludes(XMLLocator includedSource) { String includedSystemId = includedSource.getExpandedSystemId(); if (includedSystemId == null) { try { includedSystemId = XMLEntityManager.expandSystemId( includedSource.getLiteralSystemId(), includedSource.getBaseSystemId(), false); } catch (MalformedURIException e) { reportFatalError("ExpandedSystemId"); } } if (includedSystemId.equals(fCurrentBaseURI.getExpandedSystemId())) { return true; } if (fParentXIncludeHandler == null) { return false; } return fParentXIncludeHandler.searchForRecursiveIncludes( includedSource); } /** * Returns true if the current element is a top level included item. This means * it's either the child of a fallback element, or the top level item in an * included document * @return true if the current element is a top level included item */ protected boolean isTopLevelIncludedItem() { return isTopLevelIncludedItemViaInclude() || isTopLevelIncludedItemViaFallback(); } protected boolean isTopLevelIncludedItemViaInclude() { return fDepth == 1 && !isRootDocument(); } protected boolean isTopLevelIncludedItemViaFallback() { // Technically, this doesn't check if the parent was a fallback, it also // would return true if any of the parent's sibling elements were fallbacks. // However, this doesn't matter, since we will always be ignoring elements // whose parent's siblings were fallbacks. return getSawFallback(fDepth - 1); } /** * Processes the XMLAttributes object of startElement() calls. Performs the following tasks: * <ul> * <li> If the element is a top level included item whose [base URI] is different from the * [base URI] of the include parent, then an xml:base attribute is added to specify the * true [base URI] * <li> For all namespace prefixes which are in-scope in an included item, but not in scope * in the include parent, a xmlns:prefix attribute is added * <li> For all attributes with a type of ENTITY, ENTITIES or NOTATIONS, the notations and * unparsed entities are processed as described in the spec, sections 4.5.1 and 4.5.2 * </ul> * @param attributes * @return */ protected XMLAttributes processAttributes(XMLAttributes attributes) { if (isTopLevelIncludedItem()) { // Modify attributes to fix the base URI (spec 4.5.5). // We only do it to top level included elements, which have a different // base URI than their include parent. if (!sameBaseURIAsIncludeParent()) { if (attributes == null) { attributes = new XMLAttributesImpl(); } // This causes errors with schema validation, if the schema doesn't // specify that these elements can have an xml:base attribute // TODO: add a user option to turn this off? String uri = null; try { uri = this.getRelativeBaseURI(); } catch (MalformedURIException e) { // this shouldn't ever happen, since by definition, we had to traverse // the same URIs to even get to this place uri = fCurrentBaseURI.getExpandedSystemId(); } int index = attributes.addAttribute( XML_BASE_QNAME, XMLSymbols.fCDATASymbol, uri); attributes.setSpecified(index, true); } // Modify attributes to perform language-fixup (spec 4.5.6). // We only do it to top level included elements, which have a different // [language] than their include parent. if (!sameLanguageAsIncludeParent()) { if (attributes == null) { attributes = new XMLAttributesImpl(); } int index = attributes.addAttribute( XML_LANG_QNAME, XMLSymbols.fCDATASymbol, fCurrentLanguage); attributes.setSpecified(index, true); } // Modify attributes of included items to do namespace-fixup. (spec 4.5.4) Enumeration inscopeNS = fNamespaceContext.getAllPrefixes(); while (inscopeNS.hasMoreElements()) { String prefix = (String)inscopeNS.nextElement(); String parentURI = fNamespaceContext.getURIFromIncludeParent(prefix); String uri = fNamespaceContext.getURI(prefix); if (parentURI != uri && attributes != null) { if (prefix == XMLSymbols.EMPTY_STRING) { if (attributes .getValue( NamespaceContext.XMLNS_URI, XMLSymbols.PREFIX_XMLNS) == null) { if (attributes == null) { attributes = new XMLAttributesImpl(); } QName ns = (QName)NEW_NS_ATTR_QNAME.clone(); ns.prefix = null; ns.localpart = XMLSymbols.PREFIX_XMLNS; ns.rawname = XMLSymbols.PREFIX_XMLNS; int index = attributes.addAttribute( ns, XMLSymbols.fCDATASymbol, uri != null ? uri : XMLSymbols.EMPTY_STRING); attributes.setSpecified(index, true); // Need to re-declare this prefix in the current context // in order for the SAX parser to report the appropriate // start and end prefix mapping events. -- mrglavas fNamespaceContext.declarePrefix(prefix, uri); } } else if ( attributes.getValue(NamespaceContext.XMLNS_URI, prefix) == null) { if (attributes == null) { attributes = new XMLAttributesImpl(); } QName ns = (QName)NEW_NS_ATTR_QNAME.clone(); ns.localpart = prefix; ns.rawname += prefix; ns.rawname = (fSymbolTable != null) ? fSymbolTable.addSymbol(ns.rawname) : ns.rawname.intern(); int index = attributes.addAttribute( ns, XMLSymbols.fCDATASymbol, uri != null ? uri : XMLSymbols.EMPTY_STRING); attributes.setSpecified(index, true); // Need to re-declare this prefix in the current context // in order for the SAX parser to report the appropriate // start and end prefix mapping events. -- mrglavas fNamespaceContext.declarePrefix(prefix, uri); } } } } if (attributes != null) { int length = attributes.getLength(); for (int i = 0; i < length; i++) { String type = attributes.getType(i); String value = attributes.getValue(i); if (type == XMLSymbols.fENTITYSymbol) { this.checkUnparsedEntity(value); } if (type == XMLSymbols.fENTITIESSymbol) { // 4.5.1 - Unparsed Entities StringTokenizer st = new StringTokenizer(value); while (st.hasMoreTokens()) { String entName = st.nextToken(); this.checkUnparsedEntity(entName); } } else if (type == XMLSymbols.fNOTATIONSymbol) { // 4.5.2 - Notations this.checkNotation(value); } /* We actually don't need to do anything for 4.5.3, because at this stage the * value of the attribute is just a string. It will be taken care of later * in the pipeline, when the IDREFs are actually resolved against IDs. * * if (type == XMLSymbols.fIDREFSymbol || type == XMLSymbols.fIDREFSSymbol) { } */ } } return attributes; } /** * Returns a URI, relative to the include parent's base URI, of the current * [base URI]. For instance, if the current [base URI] was "dir1/dir2/file.xml" * and the include parent's [base URI] was "dir/", this would return "dir2/file.xml". * @return the relative URI */ protected String getRelativeBaseURI() throws MalformedURIException { int includeParentDepth = getIncludeParentDepth(); String relativeURI = this.getRelativeURI(includeParentDepth); if (isRootDocument()) { return relativeURI; } else { if (relativeURI.equals("")) { relativeURI = fCurrentBaseURI.getLiteralSystemId(); } if (includeParentDepth == 0) { if (fParentRelativeURI == null) { fParentRelativeURI = fParentXIncludeHandler.getRelativeBaseURI(); } if (fParentRelativeURI.equals("")) { return relativeURI; } URI uri = new URI("file", fParentRelativeURI); uri = new URI(uri, relativeURI); return uri.getPath(); } else { return relativeURI; } } } /** * Returns the [base URI] of the include parent. * @return the base URI of the include parent. */ private String getIncludeParentBaseURI() { int depth = getIncludeParentDepth(); if (!isRootDocument() && depth == 0) { return fParentXIncludeHandler.getIncludeParentBaseURI(); } else { return this.getBaseURI(depth); } } /** * Returns the [language] of the include parent. * * @return the language property of the include parent. */ private String getIncludeParentLanguage() { int depth = getIncludeParentDepth(); if (!isRootDocument() && depth == 0) { return fParentXIncludeHandler.getIncludeParentLanguage(); } else { return getLanguage(depth); } } /** * Returns the depth of the include parent. Here, the include parent is * calculated as the last non-include or non-fallback element. It is assumed * this method is called when the current element is a top level included item. * Returning 0 indicates that the top level element in this document * was an include element. * @return the depth of the top level include element */ private int getIncludeParentDepth() { // We don't start at fDepth, since it is either the top level included item, // or an include element, when this method is called. for (int i = fDepth - 1; i >= 0; i--) { // This technically might not always return the first non-include/fallback // element that it comes to, since sawFallback() returns true if a fallback // was ever encountered at that depth. However, if a fallback was encountered // at that depth, and it wasn't the direct descendant of the current element // then we can't be in a situation where we're calling this method (because // we'll always be in STATE_IGNORE) if (!getSawInclude(i) && !getSawFallback(i)) { return i; } } // shouldn't get here, since depth 0 should never have an include element or // a fallback element return 0; } /** * Modify the augmentations. Add an [included] infoset item, if the current * element is a top level included item. * @param augs the Augmentations to modify. * @return the modified Augmentations */ protected Augmentations modifyAugmentations(Augmentations augs) { return modifyAugmentations(augs, false); } /** * Modify the augmentations. Add an [included] infoset item, if <code>force</code> * is true, or if the current element is a top level included item. * @param augs the Augmentations to modify. * @param force whether to force modification * @return the modified Augmentations */ protected Augmentations modifyAugmentations( Augmentations augs, boolean force) { if (force || isTopLevelIncludedItem()) { if (augs == null) { augs = new AugmentationsImpl(); } augs.putItem(XINCLUDE_INCLUDED, Boolean.TRUE); } return augs; } protected int getState(int depth) { return fState[depth]; } protected int getState() { return fState[fDepth]; } protected void setState(int state) { if (fDepth >= fState.length) { int[] newarray = new int[fDepth * 2]; System.arraycopy(fState, 0, newarray, 0, fState.length); fState = newarray; } fState[fDepth] = state; } /** * Records that an &lt;fallback&gt; was encountered at the specified depth, * as an ancestor of the current element, or as a sibling of an ancestor of the * current element. * * @param depth * @param val */ protected void setSawFallback(int depth, boolean val) { if (depth >= fSawFallback.length) { boolean[] newarray = new boolean[depth * 2]; System.arraycopy(fSawFallback, 0, newarray, 0, fSawFallback.length); fSawFallback = newarray; } fSawFallback[depth] = val; } /** * Returns whether an &lt;fallback&gt; was encountered at the specified depth, * as an ancestor of the current element, or as a sibling of an ancestor of the * current element. * * @param depth */ protected boolean getSawFallback(int depth) { if (depth >= fSawFallback.length) { return false; } return fSawFallback[depth]; } /** * Records that an &lt;include&gt; was encountered at the specified depth, * as an ancestor of the current item. * * @param depth * @param val */ protected void setSawInclude(int depth, boolean val) { if (depth >= fSawInclude.length) { boolean[] newarray = new boolean[depth * 2]; System.arraycopy(fSawInclude, 0, newarray, 0, fSawInclude.length); fSawInclude = newarray; } fSawInclude[depth] = val; } /** * Return whether an &lt;include&gt; was encountered at the specified depth, * as an ancestor of the current item. * * @param depth * @return */ protected boolean getSawInclude(int depth) { if (depth >= fSawInclude.length) { return false; } return fSawInclude[depth]; } protected void reportResourceError(String key) { this.reportFatalError(key, null); } protected void reportResourceError(String key, Object[] args) { this.reportError(key, args, XMLErrorReporter.SEVERITY_WARNING); } protected void reportFatalError(String key) { this.reportFatalError(key, null); } protected void reportFatalError(String key, Object[] args) { this.reportError(key, args, XMLErrorReporter.SEVERITY_FATAL_ERROR); } private void reportError(String key, Object[] args, short severity) { if (fErrorReporter != null) { fErrorReporter.reportError( XIncludeMessageFormatter.XINCLUDE_DOMAIN, key, args, severity); } // we won't worry about when error reporter is null, since there should always be // at least the default error reporter } /** * Set the parent of this XIncludeHandler in the tree * @param parent */ protected void setParent(XIncludeHandler parent) { fParentXIncludeHandler = parent; } // used to know whether to pass declarations to the document handler protected boolean isRootDocument() { return fParentXIncludeHandler == null; } /** * Caches an unparsed entity. * @param name the name of the unparsed entity * @param identifier the location of the unparsed entity * @param augmentations any Augmentations that were on the original unparsed entity declaration */ protected void addUnparsedEntity( String name, XMLResourceIdentifier identifier, String notation, Augmentations augmentations) { UnparsedEntity ent = new UnparsedEntity(); ent.name = name; ent.systemId = identifier.getLiteralSystemId(); ent.publicId = identifier.getPublicId(); ent.baseURI = identifier.getBaseSystemId(); ent.notation = notation; ent.augmentations = augmentations; fUnparsedEntities.add(ent); } /** * Caches a notation. * @param name the name of the notation * @param identifier the location of the notation * @param augmentations any Augmentations that were on the original notation declaration */ protected void addNotation( String name, XMLResourceIdentifier identifier, Augmentations augmentations) { Notation not = new Notation(); not.name = name; not.systemId = identifier.getLiteralSystemId(); not.publicId = identifier.getPublicId(); not.baseURI = identifier.getBaseSystemId(); not.augmentations = augmentations; fNotations.add(not); } /** * Checks if an UnparsedEntity with the given name was declared in the DTD of the document * for the current pipeline. If so, then the notation for the UnparsedEntity is checked. * If that turns out okay, then the UnparsedEntity is passed to the root pipeline to * be checked for conflicts, and sent to the root DTDHandler. * * @param entName the name of the UnparsedEntity to check */ protected void checkUnparsedEntity(String entName) { UnparsedEntity ent = new UnparsedEntity(); ent.name = entName; int index = fUnparsedEntities.indexOf(ent); if (index != -1) { ent = (UnparsedEntity)fUnparsedEntities.get(index); // first check the notation of the unparsed entity checkNotation(ent.notation); checkAndSendUnparsedEntity(ent); } } /** * Checks if a Notation with the given name was declared in the DTD of the document * for the current pipeline. If so, that Notation is passed to the root pipeline to * be checked for conflicts, and sent to the root DTDHandler * * @param notName the name of the Notation to check */ protected void checkNotation(String notName) { Notation not = new Notation(); not.name = notName; int index = fNotations.indexOf(not); if (index != -1) { not = (Notation)fNotations.get(index); checkAndSendNotation(not); } } /** * The purpose of this method is to check if an UnparsedEntity conflicts with a previously * declared entity in the current pipeline stack. If there is no conflict, the * UnparsedEntity is sent by the root pipeline. * * @param ent the UnparsedEntity to check for conflicts */ protected void checkAndSendUnparsedEntity(UnparsedEntity ent) { if (isRootDocument()) { int index = fUnparsedEntities.indexOf(ent); if (index == -1) { // There is no unparsed entity with the same name that we have sent. // Calling unparsedEntityDecl() will add the entity to our local store, // and also send the unparsed entity to the DTDHandler XMLResourceIdentifier id = new XMLResourceIdentifierImpl( ent.publicId, ent.systemId, ent.baseURI, null); this.addUnparsedEntity( ent.name, id, ent.notation, ent.augmentations); if (fSendUEAndNotationEvents && fDTDHandler != null) { fDTDHandler.unparsedEntityDecl( ent.name, id, ent.notation, ent.augmentations); } } else { UnparsedEntity localEntity = (UnparsedEntity)fUnparsedEntities.get(index); if (!ent.isDuplicate(localEntity)) { reportFatalError( "NonDuplicateUnparsedEntity", new Object[] { ent.name }); } } } else { fParentXIncludeHandler.checkAndSendUnparsedEntity(ent); } } /** * The purpose of this method is to check if a Notation conflicts with a previously * declared notation in the current pipeline stack. If there is no conflict, the * Notation is sent by the root pipeline. * * @param not the Notation to check for conflicts */ protected void checkAndSendNotation(Notation not) { if (isRootDocument()) { int index = fNotations.indexOf(not); if (index == -1) { // There is no notation with the same name that we have sent. XMLResourceIdentifier id = new XMLResourceIdentifierImpl( not.publicId, not.systemId, not.baseURI, null); this.addNotation(not.name, id, not.augmentations); if (fSendUEAndNotationEvents && fDTDHandler != null) { fDTDHandler.notationDecl(not.name, id, not.augmentations); } } else { Notation localNotation = (Notation)fNotations.get(index); if (!not.isDuplicate(localNotation)) { reportFatalError( "NonDuplicateNotation", new Object[] { not.name }); } } } else { fParentXIncludeHandler.checkAndSendNotation(not); } } /** * Checks whether the string only contains white space characters. * * @param value the text to check */ private void checkWhitespace(XMLString value) { int end = value.offset + value.length; for (int i = value.offset; i < end; ++i) { if (!XMLChar.isSpace(value.ch[i])) { reportFatalError("ContentIllegalAtTopLevel"); return; } } } /** * Checks whether the root element has already been processed. */ private void checkMultipleRootElements() { if (fSeenRootElement) { reportFatalError("MultipleRootElements"); } fSeenRootElement = true; } // It would be nice if we didn't have to repeat code like this, but there's no interface that has // setFeature() and addRecognizedFeatures() that the objects have in common. protected void copyFeatures( XMLComponentManager from, ParserConfigurationSettings to) { Enumeration features = Constants.getXercesFeatures(); copyFeatures1(features, Constants.XERCES_FEATURE_PREFIX, from, to); features = Constants.getSAXFeatures(); copyFeatures1(features, Constants.SAX_FEATURE_PREFIX, from, to); } protected void copyFeatures( XMLComponentManager from, XMLParserConfiguration to) { Enumeration features = Constants.getXercesFeatures(); copyFeatures1(features, Constants.XERCES_FEATURE_PREFIX, from, to); features = Constants.getSAXFeatures(); copyFeatures1(features, Constants.SAX_FEATURE_PREFIX, from, to); } private void copyFeatures1( Enumeration features, String featurePrefix, XMLComponentManager from, ParserConfigurationSettings to) { while (features.hasMoreElements()) { String featureId = featurePrefix + (String)features.nextElement(); to.addRecognizedFeatures(new String[] { featureId }); try { to.setFeature(featureId, from.getFeature(featureId)); } catch (XMLConfigurationException e) { // componentManager doesn't support this feature, // so we won't worry about it } } } private void copyFeatures1( Enumeration features, String featurePrefix, XMLComponentManager from, XMLParserConfiguration to) { while (features.hasMoreElements()) { String featureId = featurePrefix + (String)features.nextElement(); boolean value = from.getFeature(featureId); try { to.setFeature(featureId, value); } catch (XMLConfigurationException e) { // componentManager doesn't support this feature, // so we won't worry about it } } } // This is a storage class to hold information about the notations. // We're not using XMLNotationDecl because we don't want to lose the augmentations. protected class Notation { public String name; public String systemId; public String baseURI; public String publicId; public Augmentations augmentations; // equals() returns true if two Notations have the same name. // Useful for searching Vectors for notations with the same name public boolean equals(Object obj) { if (obj == null) { return false; } if (obj instanceof Notation) { Notation other = (Notation)obj; return name.equals(other.name); } return false; } // from 4.5.2 // Notation items with the same [name], [system identifier], // [public identifier], and [declaration base URI] are considered // to be duplicate public boolean isDuplicate(Object obj) { if (obj != null && obj instanceof Notation) { Notation other = (Notation)obj; return name.equals(other.name) && (systemId == other.systemId || (systemId != null && systemId.equals(other.systemId))) && (publicId == other.publicId || (publicId != null && publicId.equals(other.publicId))) && (baseURI == other.baseURI || (baseURI != null && baseURI.equals(other.baseURI))); } return false; } } // This is a storage class to hold information about the unparsed entities. // We're not using XMLEntityDecl because we don't want to lose the augmentations. protected class UnparsedEntity { public String name; public String systemId; public String baseURI; public String publicId; public String notation; public Augmentations augmentations; // equals() returns true if two UnparsedEntities have the same name. // Useful for searching Vectors for entities with the same name public boolean equals(Object obj) { if (obj == null) { return false; } if (obj instanceof UnparsedEntity) { UnparsedEntity other = (UnparsedEntity)obj; return name.equals(other.name); } return false; } // from 4.5.1: // Unparsed entity items with the same [name], [system identifier], // [public identifier], [declaration base URI], [notation name], and // [notation] are considered to be duplicate public boolean isDuplicate(Object obj) { if (obj != null && obj instanceof UnparsedEntity) { UnparsedEntity other = (UnparsedEntity)obj; return name.equals(other.name) && (systemId == other.systemId || (systemId != null && systemId.equals(other.systemId))) && (publicId == other.publicId || (publicId != null && publicId.equals(other.publicId))) && (baseURI == other.baseURI || (baseURI != null && baseURI.equals(other.baseURI))) && (notation == other.notation || (notation != null && notation.equals(other.notation))); } return false; } } // The following methods are used for XML Base processing /** * Saves the current base URI to the top of the stack. */ protected void saveBaseURI() { fBaseURIScope.push(fDepth); fBaseURI.push(fCurrentBaseURI.getBaseSystemId()); fLiteralSystemID.push(fCurrentBaseURI.getLiteralSystemId()); fExpandedSystemID.push(fCurrentBaseURI.getExpandedSystemId()); } /** * Discards the URIs at the top of the stack, and restores the ones beneath it. */ protected void restoreBaseURI() { fBaseURI.pop(); fLiteralSystemID.pop(); fExpandedSystemID.pop(); fBaseURIScope.pop(); fCurrentBaseURI.setBaseSystemId((String)fBaseURI.peek()); fCurrentBaseURI.setLiteralSystemId((String)fLiteralSystemID.peek()); fCurrentBaseURI.setExpandedSystemId((String)fExpandedSystemID.peek()); } // The following methods are used for language processing /** * Saves the given language on the top of the stack. * * @param lanaguage the language to push onto the stack. */ protected void saveLanguage(String language) { fLanguageScope.push(fDepth); fLanguageStack.push(language); } /** * Discards the language at the top of the stack, and returns the one beneath it. */ public String restoreLanguage() { fLanguageStack.pop(); fLanguageScope.pop(); return (String) fLanguageStack.peek(); } /** * Gets the base URI that was in use at that depth * @param depth * @return the base URI */ public String getBaseURI(int depth) { int scope = scopeOfBaseURI(depth); return (String)fExpandedSystemID.elementAt(scope); } /** * Gets the language that was in use at that depth. * @param depth * @return the language */ public String getLanguage(int depth) { int scope = scopeOfLanguage(depth); return (String)fLanguageStack.elementAt(scope); } /** * Returns a relative URI, which when resolved against the base URI at the * specified depth, will create the current base URI. * This is accomplished by merged the literal system IDs. * @param depth the depth at which to start creating the relative URI * @return a relative URI to convert the base URI at the given depth to the current * base URI */ public String getRelativeURI(int depth) throws MalformedURIException { // The literal system id at the location given by "start" is *in focus* at // the given depth. So we need to adjust it to the next scope, so that we // only process out of focus literal system ids int start = scopeOfBaseURI(depth) + 1; if (start == fBaseURIScope.size()) { // If that is the last system id, then we don't need a relative URI return ""; } URI uri = new URI("file", (String)fLiteralSystemID.elementAt(start)); for (int i = start + 1; i < fBaseURIScope.size(); i++) { uri = new URI(uri, (String)fLiteralSystemID.elementAt(i)); } return uri.getPath(); } // We need to find two consecutive elements in the scope stack, // such that the first is lower than 'depth' (or equal), and the // second is higher. private int scopeOfBaseURI(int depth) { for (int i = fBaseURIScope.size() - 1; i >= 0; i--) { if (fBaseURIScope.elementAt(i) <= depth) return i; } // we should never get here, because 0 was put on the stack in startDocument() return -1; } private int scopeOfLanguage(int depth) { for (int i = fLanguageScope.size() - 1; i >= 0; i--) { if (fLanguageScope.elementAt(i) <= depth) return i; } // we should never get here, because 0 was put on the stack in startDocument() return -1; } /** * Search for a xml:base attribute, and if one is found, put the new base URI into * effect. */ protected void processXMLBaseAttributes(XMLAttributes attributes) { String baseURIValue = attributes.getValue(NamespaceContext.XML_URI, "base"); if (baseURIValue != null) { try { String expandedValue = XMLEntityManager.expandSystemId( baseURIValue, fCurrentBaseURI.getExpandedSystemId(), false); fCurrentBaseURI.setLiteralSystemId(baseURIValue); fCurrentBaseURI.setBaseSystemId( fCurrentBaseURI.getExpandedSystemId()); fCurrentBaseURI.setExpandedSystemId(expandedValue); // push the new values on the stack saveBaseURI(); } catch (MalformedURIException e) { // REVISIT: throw error here } } } /** * Search for a xml:lang attribute, and if one is found, put the new * [language] into effect. */ protected void processXMLLangAttributes(XMLAttributes attributes) { String language = attributes.getValue(NamespaceContext.XML_URI, "lang"); if (language != null) { fCurrentLanguage = language; saveLanguage(fCurrentLanguage); } } /** * Returns <code>true</code> if the given string * would be valid in an HTTP header. * * @param value string to check * @return <code>true</code> if the given string * would be valid in an HTTP header */ private boolean isValidInHTTPHeader (String value) { char ch; for (int i = value.length() - 1; i >= 0; --i) { ch = value.charAt(i); if (ch < 0x20 || ch > 0x7E) { return false; } } return true; } /** * Returns a new <code>XMLInputSource</code> from the given parameters. */ private XMLInputSource createInputSource(String publicId, String systemId, String baseSystemId, String accept, String acceptLanguage) { HTTPInputSource httpSource = new HTTPInputSource(publicId, systemId, baseSystemId); if (accept != null && accept.length() > 0) { httpSource.setHTTPRequestProperty(XIncludeHandler.HTTP_ACCEPT, accept); } if (acceptLanguage != null && acceptLanguage.length() > 0) { httpSource.setHTTPRequestProperty(XIncludeHandler.HTTP_ACCEPT_LANGUAGE, acceptLanguage); } return httpSource; } }
false
true
protected boolean handleIncludeElement(XMLAttributes attributes) throws XNIException { setSawInclude(fDepth, true); fNamespaceContext.setContextInvalid(); if (getSawInclude(fDepth - 1)) { reportFatalError("IncludeChild", new Object[] { XINCLUDE_INCLUDE }); } if (getState() == STATE_IGNORE) return true; // TODO: does Java use IURIs by default? // [Definition: An internationalized URI reference, or IURI, is a URI reference that directly uses [Unicode] characters.] // TODO: figure out what section 4.1.1 of the XInclude spec is talking about // has to do with disallowed ASCII character escaping // this ties in with the above IURI section, but I suspect Java already does it String href = attributes.getValue(XINCLUDE_ATTR_HREF); String parse = attributes.getValue(XINCLUDE_ATTR_PARSE); String xpointer = attributes.getValue(XPOINTER); String accept = attributes.getValue(XINCLUDE_ATTR_ACCEPT); String acceptLanguage = attributes.getValue(XINCLUDE_ATTR_ACCEPT_LANGUAGE); if (href == null && xpointer == null) { reportFatalError("XpointerMissing"); } if (parse == null) { parse = XINCLUDE_PARSE_XML; } // Verify that if an accept and/or an accept-language attribute exist // that the value(s) don't contain disallowed characters. if (accept != null && !isValidInHTTPHeader(accept)) { reportFatalError("AcceptMalformed", null); } if (acceptLanguage != null && !isValidInHTTPHeader(acceptLanguage)) { reportFatalError("AcceptLanguageMalformed", null); } XMLInputSource includedSource = null; if (fEntityResolver != null) { try { XMLResourceIdentifier resourceIdentifier = new XMLResourceIdentifierImpl( null, href, fCurrentBaseURI.getExpandedSystemId(), XMLEntityManager.expandSystemId( href, fCurrentBaseURI.getExpandedSystemId(), false)); includedSource = fEntityResolver.resolveEntity(resourceIdentifier); if (includedSource != null && !(includedSource instanceof HTTPInputSource) && (accept != null || acceptLanguage != null) && includedSource.getCharacterStream() == null && includedSource.getByteStream() == null) { includedSource = createInputSource(includedSource.getPublicId(), includedSource.getSystemId(), includedSource.getBaseSystemId(), accept, acceptLanguage); } } catch (IOException e) { reportResourceError( "XMLResourceError", new Object[] { href, e.getMessage()}); return false; } } if (includedSource == null) { // setup an HTTPInputSource if either of the content negotation attributes were specified. if (accept != null || acceptLanguage != null) { includedSource = createInputSource(null, href, fCurrentBaseURI.getExpandedSystemId(), accept, acceptLanguage); } else { includedSource = new XMLInputSource(null, href, fCurrentBaseURI.getExpandedSystemId()); } } if (parse.equals(XINCLUDE_PARSE_XML)) { // Instead of always creating a new configuration, the first one can be reused if (fChildConfig == null) { String parserName = XINCLUDE_DEFAULT_CONFIGURATION; fChildConfig = (XMLParserConfiguration)ObjectFactory.newInstance( parserName, ObjectFactory.findClassLoader(), true); // use the same symbol table, error reporter, entity resolver, security manager and buffer size. if (fSymbolTable != null) fChildConfig.setProperty(SYMBOL_TABLE, fSymbolTable); if (fErrorReporter != null) fChildConfig.setProperty(ERROR_REPORTER, fErrorReporter); if (fEntityResolver != null) fChildConfig.setProperty(ENTITY_RESOLVER, fEntityResolver); if (fSecurityManager != null) fChildConfig.setProperty(SECURITY_MANAGER, fSecurityManager); fChildConfig.setProperty(BUFFER_SIZE, new Integer(fBufferSize)); // use the same namespace context fChildConfig.setProperty( Constants.XERCES_PROPERTY_PREFIX + Constants.NAMESPACE_CONTEXT_PROPERTY, fNamespaceContext); XIncludeHandler newHandler = (XIncludeHandler)fChildConfig.getProperty( Constants.XERCES_PROPERTY_PREFIX + Constants.XINCLUDE_HANDLER_PROPERTY); newHandler.setParent(this); newHandler.setDocumentHandler(this.getDocumentHandler()); } // set all features on parserConfig to match this parser configuration copyFeatures(fSettings, fChildConfig); try { fNamespaceContext.pushScope(); fChildConfig.parse(includedSource); // necessary to make sure proper location is reported in errors if (fErrorReporter != null) { fErrorReporter.setDocumentLocator(fDocLocation); } } catch (XNIException e) { // necessary to make sure proper location is reported in errors if (fErrorReporter != null) { fErrorReporter.setDocumentLocator(fDocLocation); } reportFatalError("XMLParseError", new Object[] { href }); } catch (IOException e) { // necessary to make sure proper location is reported in errors if (fErrorReporter != null) { fErrorReporter.setDocumentLocator(fDocLocation); } // An IOException indicates that we had trouble reading the file, not // that it was an invalid XML file. So we send a resource error, not a // fatal error. reportResourceError( "XMLResourceError", new Object[] { href, e.getMessage()}); return false; } finally { fNamespaceContext.popScope(); } } else if (parse.equals(XINCLUDE_PARSE_TEXT)) { // we only care about encoding for parse="text" String encoding = attributes.getValue(XINCLUDE_ATTR_ENCODING); includedSource.setEncoding(encoding); XIncludeTextReader textReader = null; try { // Setup the appropriate text reader. if (!fIsXML11) { if (fXInclude10TextReader == null) { fXInclude10TextReader = new XIncludeTextReader(includedSource, this, fBufferSize); } else { fXInclude10TextReader.setInputSource(includedSource); } textReader = fXInclude10TextReader; } else { if (fXInclude11TextReader == null) { fXInclude11TextReader = new XInclude11TextReader(includedSource, this, fBufferSize); } else { fXInclude11TextReader.setInputSource(includedSource); } textReader = fXInclude11TextReader; } textReader.setErrorReporter(fErrorReporter); textReader.parse(); } // encoding errors catch (MalformedByteSequenceException ex) { fErrorReporter.reportError(ex.getDomain(), ex.getKey(), ex.getArguments(), XMLErrorReporter.SEVERITY_FATAL_ERROR); } catch (CharConversionException e) { fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN, "CharConversionFailure", null, XMLErrorReporter.SEVERITY_FATAL_ERROR); } catch (IOException e) { reportResourceError( "TextResourceError", new Object[] { href, e.getMessage()}); return false; } finally { if (textReader != null) { try { textReader.close(); } catch (IOException e) { reportResourceError( "TextResourceError", new Object[] { href, e.getMessage()}); return false; } } } } else { reportFatalError("InvalidParseValue", new Object[] { parse }); } return true; }
protected boolean handleIncludeElement(XMLAttributes attributes) throws XNIException { setSawInclude(fDepth, true); fNamespaceContext.setContextInvalid(); if (getSawInclude(fDepth - 1)) { reportFatalError("IncludeChild", new Object[] { XINCLUDE_INCLUDE }); } if (getState() == STATE_IGNORE) return true; // TODO: does Java use IURIs by default? // [Definition: An internationalized URI reference, or IURI, is a URI reference that directly uses [Unicode] characters.] // TODO: figure out what section 4.1.1 of the XInclude spec is talking about // has to do with disallowed ASCII character escaping // this ties in with the above IURI section, but I suspect Java already does it String href = attributes.getValue(XINCLUDE_ATTR_HREF); String parse = attributes.getValue(XINCLUDE_ATTR_PARSE); String xpointer = attributes.getValue(XPOINTER); String accept = attributes.getValue(XINCLUDE_ATTR_ACCEPT); String acceptLanguage = attributes.getValue(XINCLUDE_ATTR_ACCEPT_LANGUAGE); if (href == null && xpointer == null) { reportFatalError("XpointerMissing"); } if (parse == null) { parse = XINCLUDE_PARSE_XML; } // Verify that if an accept and/or an accept-language attribute exist // that the value(s) don't contain disallowed characters. if (accept != null && !isValidInHTTPHeader(accept)) { reportFatalError("AcceptMalformed", null); accept = null; } if (acceptLanguage != null && !isValidInHTTPHeader(acceptLanguage)) { reportFatalError("AcceptLanguageMalformed", null); acceptLanguage = null; } XMLInputSource includedSource = null; if (fEntityResolver != null) { try { XMLResourceIdentifier resourceIdentifier = new XMLResourceIdentifierImpl( null, href, fCurrentBaseURI.getExpandedSystemId(), XMLEntityManager.expandSystemId( href, fCurrentBaseURI.getExpandedSystemId(), false)); includedSource = fEntityResolver.resolveEntity(resourceIdentifier); if (includedSource != null && !(includedSource instanceof HTTPInputSource) && (accept != null || acceptLanguage != null) && includedSource.getCharacterStream() == null && includedSource.getByteStream() == null) { includedSource = createInputSource(includedSource.getPublicId(), includedSource.getSystemId(), includedSource.getBaseSystemId(), accept, acceptLanguage); } } catch (IOException e) { reportResourceError( "XMLResourceError", new Object[] { href, e.getMessage()}); return false; } } if (includedSource == null) { // setup an HTTPInputSource if either of the content negotation attributes were specified. if (accept != null || acceptLanguage != null) { includedSource = createInputSource(null, href, fCurrentBaseURI.getExpandedSystemId(), accept, acceptLanguage); } else { includedSource = new XMLInputSource(null, href, fCurrentBaseURI.getExpandedSystemId()); } } if (parse.equals(XINCLUDE_PARSE_XML)) { // Instead of always creating a new configuration, the first one can be reused if (fChildConfig == null) { String parserName = XINCLUDE_DEFAULT_CONFIGURATION; fChildConfig = (XMLParserConfiguration)ObjectFactory.newInstance( parserName, ObjectFactory.findClassLoader(), true); // use the same symbol table, error reporter, entity resolver, security manager and buffer size. if (fSymbolTable != null) fChildConfig.setProperty(SYMBOL_TABLE, fSymbolTable); if (fErrorReporter != null) fChildConfig.setProperty(ERROR_REPORTER, fErrorReporter); if (fEntityResolver != null) fChildConfig.setProperty(ENTITY_RESOLVER, fEntityResolver); if (fSecurityManager != null) fChildConfig.setProperty(SECURITY_MANAGER, fSecurityManager); fChildConfig.setProperty(BUFFER_SIZE, new Integer(fBufferSize)); // use the same namespace context fChildConfig.setProperty( Constants.XERCES_PROPERTY_PREFIX + Constants.NAMESPACE_CONTEXT_PROPERTY, fNamespaceContext); XIncludeHandler newHandler = (XIncludeHandler)fChildConfig.getProperty( Constants.XERCES_PROPERTY_PREFIX + Constants.XINCLUDE_HANDLER_PROPERTY); newHandler.setParent(this); newHandler.setDocumentHandler(this.getDocumentHandler()); } // set all features on parserConfig to match this parser configuration copyFeatures(fSettings, fChildConfig); try { fNamespaceContext.pushScope(); fChildConfig.parse(includedSource); // necessary to make sure proper location is reported in errors if (fErrorReporter != null) { fErrorReporter.setDocumentLocator(fDocLocation); } } catch (XNIException e) { // necessary to make sure proper location is reported in errors if (fErrorReporter != null) { fErrorReporter.setDocumentLocator(fDocLocation); } reportFatalError("XMLParseError", new Object[] { href }); } catch (IOException e) { // necessary to make sure proper location is reported in errors if (fErrorReporter != null) { fErrorReporter.setDocumentLocator(fDocLocation); } // An IOException indicates that we had trouble reading the file, not // that it was an invalid XML file. So we send a resource error, not a // fatal error. reportResourceError( "XMLResourceError", new Object[] { href, e.getMessage()}); return false; } finally { fNamespaceContext.popScope(); } } else if (parse.equals(XINCLUDE_PARSE_TEXT)) { // we only care about encoding for parse="text" String encoding = attributes.getValue(XINCLUDE_ATTR_ENCODING); includedSource.setEncoding(encoding); XIncludeTextReader textReader = null; try { // Setup the appropriate text reader. if (!fIsXML11) { if (fXInclude10TextReader == null) { fXInclude10TextReader = new XIncludeTextReader(includedSource, this, fBufferSize); } else { fXInclude10TextReader.setInputSource(includedSource); } textReader = fXInclude10TextReader; } else { if (fXInclude11TextReader == null) { fXInclude11TextReader = new XInclude11TextReader(includedSource, this, fBufferSize); } else { fXInclude11TextReader.setInputSource(includedSource); } textReader = fXInclude11TextReader; } textReader.setErrorReporter(fErrorReporter); textReader.parse(); } // encoding errors catch (MalformedByteSequenceException ex) { fErrorReporter.reportError(ex.getDomain(), ex.getKey(), ex.getArguments(), XMLErrorReporter.SEVERITY_FATAL_ERROR); } catch (CharConversionException e) { fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN, "CharConversionFailure", null, XMLErrorReporter.SEVERITY_FATAL_ERROR); } catch (IOException e) { reportResourceError( "TextResourceError", new Object[] { href, e.getMessage()}); return false; } finally { if (textReader != null) { try { textReader.close(); } catch (IOException e) { reportResourceError( "TextResourceError", new Object[] { href, e.getMessage()}); return false; } } } } else { reportFatalError("InvalidParseValue", new Object[] { parse }); } return true; }
diff --git a/src/main/java/org/pandora/PandoraWorldGenerator.java b/src/main/java/org/pandora/PandoraWorldGenerator.java index 24a342b..6680ab0 100644 --- a/src/main/java/org/pandora/PandoraWorldGenerator.java +++ b/src/main/java/org/pandora/PandoraWorldGenerator.java @@ -1,1280 +1,1280 @@ /* * Copyright (c) 2012-2013 Sean Porter <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.pandora; //* IMPORTS: JDK/JRE import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; //* IMPORTS: BUKKIT import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.plugin.Plugin; import org.bukkit.World; //* IMPORTS: PANDORA import org.pandora.datatypes.BlockValues; import org.pandora.events.PandoraStructureGenerateEvent; //* IMPORTS: OTHER //* NOT NEEDED public abstract class PandoraWorldGenerator { private Map<Location, Map<Block, BlockValues>> modifiedBlocks; private List<BlockValues> replaceBlacklist = new ArrayList<BlockValues>(); private Map<Location, List<Block>> replaceWhitelist = new HashMap<Location, List<Block>>(); private final Plugin plugin; private final boolean notifyOnBlockChanges; private boolean invertBlacklist = false; public PandoraWorldGenerator(Plugin plugin) { this (plugin, false, false); } public PandoraWorldGenerator(Plugin plugin, boolean notifyOnBlockChanges) { this (plugin, notifyOnBlockChanges, false); } public PandoraWorldGenerator(Plugin plugin, boolean notifyOnBlockChanges, boolean invertBlacklist) { this.plugin = plugin; this.notifyOnBlockChanges = notifyOnBlockChanges; this.invertBlacklist = invertBlacklist; } public boolean addBlock(Block start, Block block, BlockValues values) { if (block == null || values == null || start == null) return false; if (modifiedBlocks == null) modifiedBlocks = new HashMap<Location, Map<Block, BlockValues>>(); Location loc = start.getLocation(); if (!modifiedBlocks.containsKey(loc)) modifiedBlocks.put(loc, new HashMap<Block, BlockValues>()); modifiedBlocks.get(loc).put(block, values); if (isInBlacklist(block.getTypeId(), block.getData())) return false; return true; } public boolean addBlock(Block start, Block block, int id) { return addBlock(start, block, id, (byte) 0); } public boolean addBlock(Block start, Block block, Material material) { return addBlock(start, block, material, (byte) 0); } public boolean addBlock(Block start, Block block, String name) { return addBlock(start, block, name, (byte) 0); } public boolean addBlock(Block start, Location location, BlockValues values) { if (location == null) return false; return addBlock(start, location.getBlock(), values); } public boolean addBlock(Block start, Location location, int id) { return addBlock(start, location, id, (byte) 0); } public boolean addBlock(Block start, Location location, Material material) { return addBlock(start, location, material, (byte) 0); } public boolean addBlock(Block start, Location location, String name) { return addBlock(start, location, name, (byte) 0); } public boolean addBlock(Location start, Block block, BlockValues values) { if (start == null) return false; return addBlock(start.getBlock(), block, values); } public boolean addBlock(Location start, Block block, int id) { if (start == null) return false; return addBlock(start.getBlock(), block, id, (byte) 0); } public boolean addBlock(Location start, Block block, Material material) { if (start == null) return false; return addBlock(start.getBlock(), block, material, (byte) 0); } public boolean addBlock(Location start, Block block, String name) { if (start == null) return false; return addBlock(start.getBlock(), block, name, (byte) 0); } public boolean addBlock(Location start, Location location, BlockValues values) { if (start == null || location == null) return false; return addBlock(start.getBlock(), location.getBlock(), values); } public boolean addBlock(Location start, Location location, int id) { if (start == null) return false; return addBlock(start.getBlock(), location, id, (byte) 0); } public boolean addBlock(Location start, Location location, Material material) { if (start == null) return false; return addBlock(start.getBlock(), location, material, (byte) 0); } public boolean addBlock(Location start, Location location, String name) { if (start == null) return false; return addBlock(start.getBlock(), location, name, (byte) 0); } public boolean addBlock(Block start, Block block, int id, byte data) { try { return addBlock(start, block, new BlockValues(id, data)); } catch (Exception e) { return false; } } public boolean addBlock(Block start, Block block, int id, int data) { return addBlock(start, block, id, (byte) data); } public boolean addBlock(Block start, Block block, Material material, byte data) { try { return addBlock(start, block, new BlockValues(material, data)); } catch (Exception e) { return false; } } public boolean addBlock(Block start, Block block, Material material, int data) { return addBlock(start, block, material, (byte) data); } public boolean addBlock(Block start, Block block, String name, byte data) { try { return addBlock(start, block, new BlockValues(name, data)); } catch (Exception e) { return false; } } public boolean addBlock(Block start, Block block, String name, int data) { return addBlock(start, block, name, (byte) data); } public boolean addBlock(Block start, Location location, int id, byte data) { try { return addBlock(start, location.getBlock(), new BlockValues(id, data)); } catch (Exception e) { return false; } } public boolean addBlock(Block start, Location location, int id, int data) { return addBlock(start, location, id, (byte) data); } public boolean addBlock(Block start, Location location, Material material, byte data) { try { return addBlock(start, location.getBlock(), new BlockValues(material, data)); } catch (Exception e) { return false; } } public boolean addBlock(Block start, Location location, Material material, int data) { return addBlock(start, location, material, (byte) data); } public boolean addBlock(Block start, Location location, String name, byte data) { try { return addBlock(start, location.getBlock(), new BlockValues(name, data)); } catch (Exception e) { return false; } } public boolean addBlock(Block start, Location location, String name, int data) { return addBlock(start, location, name, (byte) data); } public boolean addBlock(Location start, Block block, int id, byte data) { try { return addBlock(start.getBlock(), block, new BlockValues(id, data)); } catch (Exception e) { return false; } } public boolean addBlock(Location start, Block block, int id, int data) { return addBlock(start, block, id, (byte) data); } public boolean addBlock(Location start, Block block, Material material, byte data) { try { return addBlock(start.getBlock(), block, new BlockValues(material, data)); } catch (Exception e) { return false; } } public boolean addBlock(Location start, Block block, Material material, int data) { return addBlock(start, block, material, (byte) data); } public boolean addBlock(Location start, Block block, String name, byte data) { try { return addBlock(start.getBlock(), block, new BlockValues(name, data)); } catch (Exception e) { return false; } } public boolean addBlock(Location start, Block block, String name, int data) { return addBlock(start, block, name, (byte) data); } public boolean addBlock(Location start, Location location, int id, byte data) { try { return addBlock(start.getBlock(), location.getBlock(), new BlockValues(id, data)); } catch (Exception e) { return false; } } public boolean addBlock(Location start, Location location, int id, int data) { return addBlock(start, location, id, (byte) data); } public boolean addBlock(Location start, Location location, Material material, byte data) { try { return addBlock(start.getBlock(), location.getBlock(), new BlockValues(material, data)); } catch (Exception e) { return false; } } public boolean addBlock(Location start, Location location, Material material, int data) { return addBlock(start, location, material, (byte) data); } public boolean addBlock(Location start, Location location, String name, byte data) { try { return addBlock(start.getBlock(), location.getBlock(), new BlockValues(name, data)); } catch (Exception e) { return false; } } public boolean addBlock(Location start, Location location, String name, int data) { return addBlock(start, location, name, (byte) data); } public boolean addBlock(Block start, World world, int x, int y, int z, BlockValues values) { if (world == null || start == null || values == null) return false; return addBlock(start, world.getBlockAt(x, y, z), values); } public boolean addBlock(Block start, World world, int x, int y, int z, int id) { return addBlock(start, world, x, y, z, id, (byte) 0); } public boolean addBlock(Block start, World world, int x, int y, int z, Material material) { return addBlock(start, world, x, y, z, material, (byte) 0); } public boolean addBlock(Block start, World world, int x, int y, int z, String name) { return addBlock(start, world, x, y, z, name, (byte) 0); } public boolean addBlock(Location start, World world, int x, int y, int z, BlockValues values) { if (world == null || start == null || values == null) return false; return addBlock(start.getBlock(), world.getBlockAt(x, y, z), values); } public boolean addBlock(Location start, World world, int x, int y, int z, int id) { if (world == null || start == null) return false; return addBlock(start.getBlock(), world, x, y, z, id, (byte) 0); } public boolean addBlock(Location start, World world, int x, int y, int z, Material material) { if (world == null || start == null) return false; return addBlock(start.getBlock(), world, x, y, z, material, (byte) 0); } public boolean addBlock(Location start, World world, int x, int y, int z, String name) { if (world == null || start == null) return false; return addBlock(start.getBlock(), world, x, y, z, name, (byte) 0); } public boolean addBlock(Block start, World world, int x, int y, int z, int id, byte data) { try { return addBlock(start, world.getBlockAt(x, y, z), new BlockValues(id, data)); } catch (Exception e) { return false; } } public boolean addBlock(Block start, World world, int x, int y, int z, int id, int data) { return addBlock(start, world, x, y, z, id, (byte) data); } public boolean addBlock(Block start, World world, int x, int y, int z, Material material, byte data) { try { return addBlock(start, world.getBlockAt(x, y, z), new BlockValues(material, data)); } catch (Exception e) { return false; } } public boolean addBlock(Block start, World world, int x, int y, int z, Material material, int data) { return addBlock(start, world, x, y, z, material, (byte) data); } public boolean addBlock(Block start, World world, int x, int y, int z, String name, byte data) { try { return addBlock(start, world.getBlockAt(x, y, z), new BlockValues(name, data)); } catch (Exception e) { return false; } } public boolean addBlock(Block start, World world, int x, int y, int z, String name, int data) { return addBlock(start, world, x, y, z, name, (byte) data); } public boolean addBlock(Location start, World world, int x, int y, int z, int id, byte data) { try { return addBlock(start.getBlock(), world.getBlockAt(x, y, z), new BlockValues(id, data)); } catch (Exception e) { return false; } } public boolean addBlock(Location start, World world, int x, int y, int z, int id, int data) { return addBlock(start, world, x, y, z, id, (byte) data); } public boolean addBlock(Location start, World world, int x, int y, int z, Material material, byte data) { try { return addBlock(start.getBlock(), world.getBlockAt(x, y, z), new BlockValues(material, data)); } catch (Exception e) { return false; } } public boolean addBlock(Location start, World world, int x, int y, int z, Material material, int data) { return addBlock(start, world, x, y, z, material, (byte) data); } public boolean addBlock(Location start, World world, int x, int y, int z, String name, byte data) { try { return addBlock(start.getBlock(), world.getBlockAt(x, y, z), new BlockValues(name, data)); } catch (Exception e) { return false; } } public boolean addBlock(Location start, World world, int x, int y, int z, String name, int data) { return addBlock(start, world, x, y, z, name, (byte) data); } public boolean addBlock(World world, int x1, int y1, int z1, int x2, int y2, int z2, int id, byte data) { try { return addBlock(world.getBlockAt(x1, y1, z1), world.getBlockAt(x2, y2, z2), new BlockValues(id, data)); } catch (Exception e) { return false; } } public boolean addBlock(World world, int x1, int y1, int z1, int x2, int y2, int z2, int id, int data) { return addBlock(world, x1, y1, z1, x2, y2, z2, id, (byte) data); } public boolean addBlock(World world, int x1, int y1, int z1, int x2, int y2, int z2, Material material, byte data) { try { return addBlock(world.getBlockAt(x1, y1, z1), world.getBlockAt(x2, y2, z2), new BlockValues(material, data)); } catch (Exception e) { return false; } } public boolean addBlock(World world, int x1, int y1, int z1, int x2, int y2, int z2, Material material, int data) { return addBlock(world, x1, y1, z1, x2, y2, z2, material, (byte) data); } public boolean addBlock(World world, int x1, int y1, int z1, int x2, int y2, int z2, String name, byte data) { try { return addBlock(world.getBlockAt(x1, y1, z1), world.getBlockAt(x2, y2, z2), new BlockValues(name, data)); } catch (Exception e) { return false; } } public boolean addBlock(World world, int x1, int y1, int z1, int x2, int y2, int z2, String name, int data) { return addBlock(world, x1, y1, z1, x2, y2, z2, name, (byte) data); } public PandoraWorldGenerator addToBlacklist(Block block) { if (block == null) return this; return addToBlacklist(block.getTypeId(), block.getData()); } public PandoraWorldGenerator addToBlacklist(Block blocks[]) { for (Block block : blocks) { if (block == null) continue; addToBlacklist(block.getTypeId(), block.getData()); } return this; } public PandoraWorldGenerator addToBlacklist(BlockValues values) { for (BlockValues listItem : replaceBlacklist) { if (listItem.getId() != values.getId()) continue; if (listItem.getData() != values.getData()) continue; return this; } replaceBlacklist.add(values); return this; } public PandoraWorldGenerator addToBlacklist(BlockValues blocks[]) { for (BlockValues block : blocks) { if (block == null) continue; addToBlacklist(block); } return this; } public PandoraWorldGenerator addToBlacklist(int id) { return addToBlacklist(id, (byte) 0); } public PandoraWorldGenerator addToBlacklist(int ids[]) { for (int id : ids) { addToBlacklist(id); } return this; } public PandoraWorldGenerator addToBlacklist(List<Object> objects) { for (Object object : objects) { if (object instanceof Block) addToBlacklist((Block) object); else if (object instanceof BlockValues) addToBlacklist((BlockValues) object); else if (object instanceof Integer) addToBlacklist((Integer) object); else if (object instanceof Material) addToBlacklist((Material) object); else if (object instanceof String) addToBlacklist((String) object); } return this; } public PandoraWorldGenerator addToBlacklist(Location location) { if (location == null) return this; return addToBlacklist(location.getBlock()); } public PandoraWorldGenerator addToBlacklist(Location locations[]) { for (Location location : locations) { if (location == null) continue; addToBlacklist(location); } return this; } public PandoraWorldGenerator addToBlacklist(Material material) { return addToBlacklist(material, (byte) 0); } public PandoraWorldGenerator addToBlacklist(Material materials[]) { for (Material material : materials) { if (material == null) continue; addToBlacklist(material); } return this; } public PandoraWorldGenerator addToBlacklist(String name) { return addToBlacklist(name, (byte) 0); } public PandoraWorldGenerator addToBlacklist(String names[]) { for (String name : names) { if (name == null) continue; addToBlacklist(name); } return this; } public PandoraWorldGenerator addToBlacklist(int id, byte data) { try { return addToBlacklist(new BlockValues(id, data)); } catch (Exception e) { return this; } } public PandoraWorldGenerator addToBlacklist(int id, int data) { return addToBlacklist(id, (byte) data); } public PandoraWorldGenerator addToBlacklist(Material material, byte data) { try { return addToBlacklist(new BlockValues(material, data)); } catch (Exception e) { return this; } } public PandoraWorldGenerator addToBlacklist(Material material, int data) { return addToBlacklist(material, (byte) data); } public PandoraWorldGenerator addToBlacklist(String name, byte data) { try { return addToBlacklist(new BlockValues(name, data)); } catch (Exception e) { return this; } } public PandoraWorldGenerator addToBlacklist(String name, int data) { return addToBlacklist(name, (byte) data); } public PandoraWorldGenerator addToWhitelist(Block start, Block block) { if (start == null || block == null) return this; Location loc = start.getLocation(); if (!replaceWhitelist.containsKey(loc)) replaceWhitelist.put(loc, new ArrayList<Block>()); replaceWhitelist.get(loc).add(block); return this; } public PandoraWorldGenerator addToWhitelist(Block start, Block blocks[]) { if (start == null) return this; for (Block block : blocks) { if (block == null) continue; addToWhitelist(start, block); } return this; } public PandoraWorldGenerator addToWhitelist(Block start, List<Object> objects) { if (start == null) return this; for (Object object : objects) { if (object instanceof Block) addToWhitelist(start, (Block) object); else if (object instanceof Location) addToWhitelist(start, (Location) object); } return this; } public PandoraWorldGenerator addToWhitelist(Block start, Location location) { if (location == null) return this; return addToWhitelist(start, location.getBlock()); } public PandoraWorldGenerator addToWhitelist(Block start, Location locations[]) { if (start == null) return this; for (Location location : locations) { if (location == null) continue; addToWhitelist(start, location); } return this; } public PandoraWorldGenerator addToWhitelist(Location start, Block block) { if (start == null || block == null) return this; return addToWhitelist(start.getBlock(), block); } public PandoraWorldGenerator addToWhitelist(Location start, Block blocks[]) { if (start == null) return this; for (Block block : blocks) { if (block == null) continue; addToWhitelist(start, block); } return this; } public PandoraWorldGenerator addToWhitelist(Location start, List<Object> objects) { if (start == null) return this; for (Object object : objects) { if (object instanceof Block) addToWhitelist(start, (Block) object); else if (object instanceof Location) addToWhitelist(start, (Location) object); } return this; } public PandoraWorldGenerator addToWhitelist(Location start, Location location) { if (location == null) return this; return addToWhitelist(start, location.getBlock()); } public PandoraWorldGenerator addToWhitelist(Location start, Location locations[]) { if (start == null) return this; for (Location location : locations) { if (location == null) continue; addToWhitelist(start, location); } return this; } public PandoraWorldGenerator addToWhitelist(Block start, World world, int x, int y, int z) { try { return addToWhitelist(start, world.getBlockAt(x, y, z)); } catch (Exception e) { return this; } } public PandoraWorldGenerator addToWhitelist(Location start, World world, int x, int y, int z) { try { return addToWhitelist(start.getBlock(), world.getBlockAt(x, y, z)); } catch (Exception e) { return this; } } public PandoraWorldGenerator addToWhitelist(World world, int x1, int y1, int z1, int x2, int y2, int z2) { try { return addToWhitelist(world.getBlockAt(x1, y1, z1), world.getBlockAt(x2, y2, z2)); } catch (Exception e) { return this; } } protected abstract boolean generate(World world, Random random, int x, int y, int z); public void invertBlacklist() { invertBlacklist = (invertBlacklist ? false : true); } public boolean isInBlacklist(Block block) { if (block == null) return false; return isInBlacklist(block.getTypeId(), block.getData()); } public boolean isInBlacklist(BlockValues values) { for (BlockValues listItem : replaceBlacklist) { if (listItem.getId() != values.getId()) continue; if (listItem.getData() != values.getData()) continue; return true; } return false; } public boolean isInBlacklist(int id) { return isInBlacklist(id, (byte) 0); } public boolean isInBlacklist(Location location) { if (location == null) return false; return isInBlacklist(location.getBlock()); } public boolean isInBlacklist(Material material) { return isInBlacklist(material, (byte) 0); } public boolean isInBlacklist(String name) { return isInBlacklist(name, (byte) 0); } public boolean isInBlacklist(int id, byte data) { try { return isInBlacklist(new BlockValues(id, data)); } catch (Exception e) { return false; } } public boolean isInBlacklist(int id, int data) { return isInBlacklist(id, (byte) data); } public boolean isInBlacklist(Material material, byte data) { try { return isInBlacklist(new BlockValues(material, data)); } catch (Exception e) { return false; } } public boolean isInBlacklist(Material material, int data) { return isInBlacklist(material, (byte) data); } public boolean isInBlacklist(String name, byte data) { try { return isInBlacklist(new BlockValues(name, data)); } catch (Exception e) { return false; } } public boolean isInBlacklist(String name, int data) { return isInBlacklist(name, (byte) data); } public boolean isInWhitelist(Block start, Block block) { if (start == null || block == null) return false; else if (!replaceWhitelist.containsKey(start.getLocation())) return false; return replaceWhitelist.get(start.getLocation()).contains(block); } public boolean isInWhitelist(Block start, Location location) { if (start == null || location == null) return false; return isInWhitelist(start, location.getBlock()); } public boolean isInWhitelist(Location start, Block block) { if (start == null || block == null) return false; return isInWhitelist(start.getBlock(), block); } public boolean isInWhitelist(Location start, Location location) { if (start == null || location == null) return false; return isInWhitelist(start.getBlock(), location.getBlock()); } public boolean isInWhitelist(Block start, World world, int x, int y, int z) { try { return isInWhitelist(start, world.getBlockAt(x, y, z)); } catch (Exception e) { return false; } } public boolean isInWhitelist(Location start, World world, int x, int y, int z) { try { return isInWhitelist(start.getBlock(), world.getBlockAt(x, y, z)); } catch (Exception e) { return false; } } public boolean isInWhitelist(World world, int x, int y, int z, Block block) { try { return isInWhitelist(world.getBlockAt(x, y, z), block); } catch (Exception e) { return false; } } public boolean isInWhitelist(World world, int x, int y, int z, Location location) { try { return isInWhitelist(world.getBlockAt(x, y, z), location.getBlock()); } catch (Exception e) { return false; } } public boolean isInWhitelist(World world, int x1, int y1, int z1, int x2, int y2, int z2) { try { return isInWhitelist(world.getBlockAt(x1, y1, z1), world.getBlockAt(x2, y2, z2)); } catch (Exception e) { return false; } } public boolean place(World world, Random random, int x, int y, int z) { return generate(world, random, x, y, z); } public boolean placeBlocks(Block start) { if (start == null) return false; return placeBlocks(start.getLocation(), false); } public boolean placeBlocks(Location start) { return placeBlocks(start, false); } public boolean placeBlocks(Block start, boolean fastFail) { if (start == null) return false; return placeBlocks(start.getLocation(), fastFail); } public boolean placeBlocks(Location start, boolean fastFail) { - if (plugin == null || start == null) + if (plugin == null || start == null || modifiedBlocks == null) return false; else if (!modifiedBlocks.containsKey(start)) return false; Map<Block, BlockValues> modified = modifiedBlocks.get(start); if(modified.isEmpty()) return true; List<BlockState> blocks = new ArrayList<BlockState>(); for(Block block : modified.keySet()) { if(block == null) continue; boolean blacklisted = isInBlacklist(block); if (blacklisted) blacklisted = isInWhitelist(start, block) ? invertBlacklist : true; if(fastFail && blacklisted && !invertBlacklist) { return false; } else if(fastFail && !blacklisted && invertBlacklist) { return false; } BlockState state = block.getState(); state.setTypeId(modified.get(block).getId()); state.setRawData(modified.get(block).getData()); blocks.add(state); } PandoraStructureGenerateEvent event; event = new PandoraStructureGenerateEvent(start, blocks, plugin); Bukkit.getPluginManager().callEvent(event); if(event.isCancelled()) return false; for(Block block : modified.keySet()) { if(block == null) continue; setBlock(block, modified.get(block)); } replaceWhitelist.remove(start); modifiedBlocks.remove(start); return true; } public boolean placeBlocks(World world, int x, int y, int z) { return placeBlocks(world, x, y, z, false); } public boolean placeBlocks(World world, int x, int y, int z, boolean fastFail) { if (world == null) return false; return placeBlocks(new Location(world, x, y, z), fastFail); } public PandoraWorldGenerator removeFromBlacklist(Block block) { if(block == null) return this; return removeFromBlacklist(block.getTypeId(), block.getData()); } public PandoraWorldGenerator removeFromBlacklist(Block blocks[]) { for(Block block : blocks) { if(block == null) continue; removeFromBlacklist(block.getTypeId(), block.getData()); } return this; } public PandoraWorldGenerator removeFromBlacklist(BlockValues values) { for(BlockValues listItem : replaceBlacklist) { if(listItem.getId() != values.getId()) continue; if(listItem.getData() != values.getData()) continue; return this; } replaceBlacklist.remove(values); return this; } public PandoraWorldGenerator removeFromBlacklist(BlockValues blocks[]) { for(BlockValues block : blocks) { if(block == null) continue; removeFromBlacklist(block); } return this; } public PandoraWorldGenerator removeFromBlacklist(int id) { return removeFromBlacklist(id, (byte) 0); } public PandoraWorldGenerator removeFromBlacklist(int ids[]) { for(int id : ids) { removeFromBlacklist(id); } return this; } public PandoraWorldGenerator removeFromBlacklist(List<Object> objects) { for(Object object : objects) { if(object instanceof Block) removeFromBlacklist((Block) object); else if(object instanceof BlockValues) removeFromBlacklist((BlockValues) object); else if(object instanceof Integer) removeFromBlacklist((Integer) object); else if(object instanceof Material) removeFromBlacklist((Material) object); else if(object instanceof String) removeFromBlacklist((String) object); } return this; } public PandoraWorldGenerator removeFromBlacklist(Location location) { if(location == null) return this; return removeFromBlacklist(location.getBlock()); } public PandoraWorldGenerator removeFromBlacklist(Location locations[]) { for(Location location : locations) { if(location == null) continue; removeFromBlacklist(location); } return this; } public PandoraWorldGenerator removeFromBlacklist(Material material) { return removeFromBlacklist(material, (byte) 0); } public PandoraWorldGenerator removeFromBlacklist(Material materials[]) { for(Material material : materials) { if(material == null) continue; removeFromBlacklist(material); } return this; } public PandoraWorldGenerator removeFromBlacklist(String name) { return removeFromBlacklist(name, (byte) 0); } public PandoraWorldGenerator removeFromBlacklist(String names[]) { for(String name : names) { if(name == null) continue; removeFromBlacklist(name); } return this; } public PandoraWorldGenerator removeFromBlacklist(int id, byte data) { try { return removeFromBlacklist(new BlockValues(id, data)); } catch(Exception e) { return this; } } public PandoraWorldGenerator removeFromBlacklist(int id, int data) { return removeFromBlacklist(id, (byte) data); } public PandoraWorldGenerator removeFromBlacklist(Material material, byte data) { try { return removeFromBlacklist(new BlockValues(material, data)); } catch(Exception e) { return this; } } public PandoraWorldGenerator removeFromBlacklist(Material material, int data) { return removeFromBlacklist(material, (byte) data); } public PandoraWorldGenerator removeFromBlacklist(String name, byte data) { try { return removeFromBlacklist(new BlockValues(name, data)); } catch(Exception e) { return this; } } public PandoraWorldGenerator removeFromBlacklist(String name, int data) { return removeFromBlacklist(name, (byte) data); } private void setBlock(Block block, BlockValues values) { setBlock(block, values.getId(), values.getData()); } private void setBlock(Block block, int id) { setBlock(block, id, (byte) 0); } private void setBlock(Block block, int id, byte data) { block.setTypeIdAndData(id, data, notifyOnBlockChanges); } private void setBlock(Block block, int id, int data) { setBlock(block, id, (byte) data); } public void setScale(double xScale, double yScale, double zScale) {} }
true
true
public boolean placeBlocks(Location start, boolean fastFail) { if (plugin == null || start == null) return false; else if (!modifiedBlocks.containsKey(start)) return false; Map<Block, BlockValues> modified = modifiedBlocks.get(start); if(modified.isEmpty()) return true; List<BlockState> blocks = new ArrayList<BlockState>(); for(Block block : modified.keySet()) { if(block == null) continue; boolean blacklisted = isInBlacklist(block); if (blacklisted) blacklisted = isInWhitelist(start, block) ? invertBlacklist : true; if(fastFail && blacklisted && !invertBlacklist) { return false; } else if(fastFail && !blacklisted && invertBlacklist) { return false; } BlockState state = block.getState(); state.setTypeId(modified.get(block).getId()); state.setRawData(modified.get(block).getData()); blocks.add(state); } PandoraStructureGenerateEvent event; event = new PandoraStructureGenerateEvent(start, blocks, plugin); Bukkit.getPluginManager().callEvent(event); if(event.isCancelled()) return false; for(Block block : modified.keySet()) { if(block == null) continue; setBlock(block, modified.get(block)); } replaceWhitelist.remove(start); modifiedBlocks.remove(start); return true; }
public boolean placeBlocks(Location start, boolean fastFail) { if (plugin == null || start == null || modifiedBlocks == null) return false; else if (!modifiedBlocks.containsKey(start)) return false; Map<Block, BlockValues> modified = modifiedBlocks.get(start); if(modified.isEmpty()) return true; List<BlockState> blocks = new ArrayList<BlockState>(); for(Block block : modified.keySet()) { if(block == null) continue; boolean blacklisted = isInBlacklist(block); if (blacklisted) blacklisted = isInWhitelist(start, block) ? invertBlacklist : true; if(fastFail && blacklisted && !invertBlacklist) { return false; } else if(fastFail && !blacklisted && invertBlacklist) { return false; } BlockState state = block.getState(); state.setTypeId(modified.get(block).getId()); state.setRawData(modified.get(block).getData()); blocks.add(state); } PandoraStructureGenerateEvent event; event = new PandoraStructureGenerateEvent(start, blocks, plugin); Bukkit.getPluginManager().callEvent(event); if(event.isCancelled()) return false; for(Block block : modified.keySet()) { if(block == null) continue; setBlock(block, modified.get(block)); } replaceWhitelist.remove(start); modifiedBlocks.remove(start); return true; }
diff --git a/src-support/org/seasr/meandre/support/io/JARInstaller.java b/src-support/org/seasr/meandre/support/io/JARInstaller.java index b861d00d..4552929f 100644 --- a/src-support/org/seasr/meandre/support/io/JARInstaller.java +++ b/src-support/org/seasr/meandre/support/io/JARInstaller.java @@ -1,143 +1,145 @@ /** * * University of Illinois/NCSA * Open Source License * * Copyright (c) 2008, NCSA. All rights reserved. * * Developed by: * The Automated Learning Group * University of Illinois at Urbana-Champaign * http://www.seasr.org * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal with 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: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimers. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimers in * the documentation and/or other materials provided with the distribution. * * Neither the names of The Automated Learning Group, University of * Illinois at Urbana-Champaign, nor the names of its contributors may * be used to endorse or promote products derived from this Software * without specific prior written permission. * * 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 CONTRIBUTORS 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 WITH THE SOFTWARE. * */ package org.seasr.meandre.support.io; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; /** * This class provides basic mechanics to install * the contents of a JAR file into a particular location * for access by components * * @author Xavier Llor&agrave; * @author Boris Capitanu * */ public class JARInstaller { public enum InstallStatus { SUCCESS, FAILED, SKIPPED } /** Chunk size */ private static final int READ_WRITE_CHUNK_SIZE = 65536; /** Install the contents of the jar at the given location. If location * exists no installation is performed, unless forced. * * @param sDestDir The location of the root directory where to install the stuff * @param sJarName The name of the jar to expand * @param bForce Force the installation by deleting the folder * @return True is the process finished correctly, false otherwise. */ public static synchronized InstallStatus installFromStream(InputStream jarStream, String sDestDir, boolean bForce ) { File fRootDir = new File(sDestDir); // Basic checking if ( fRootDir.exists() ) { if ( bForce ) { boolean bOK = deleteDir(fRootDir); if ( !bOK ) return InstallStatus.FAILED; } else { return InstallStatus.SKIPPED; } } else fRootDir.mkdirs(); // Unjar the contents try { JarInputStream jar = new JarInputStream(jarStream); JarEntry je = null; while ( (je=jar.getNextJarEntry())!=null ) { - File fileTarget = new File(sDestDir+File.separator+je.getName().replaceAll("/", File.separator)); + String target = sDestDir+File.separator+je.getName(); + File fileTarget = new File(new File(target).toURI()); if ( je.isDirectory() ) { fileTarget.mkdirs(); } else { FileOutputStream fos = new FileOutputStream(fileTarget); byte [] baBuf = new byte[READ_WRITE_CHUNK_SIZE]; int len; while ((len = jar.read(baBuf)) > 0) { fos.write(baBuf, 0, len); } fos.close(); } } } catch (Throwable t) { + t.printStackTrace(); deleteDir(new File(sDestDir)); return InstallStatus.FAILED; } return InstallStatus.SUCCESS; } /** Deletes all files and subdirectories under dir. * Returns true if all deletions were successful. * If a deletion fails, the method stops attempting to delete and returns false. * * @param dir The directory to delete * @return True if it was properly cleaned, false otherwise */ protected static boolean deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for (int i=0; i<children.length; i++) { boolean success = deleteDir(new File(dir, children[i])); if (!success) { return false; } } } // The directory is now empty so delete it if (dir.exists()) return dir.delete(); else return true; } }
false
true
public static synchronized InstallStatus installFromStream(InputStream jarStream, String sDestDir, boolean bForce ) { File fRootDir = new File(sDestDir); // Basic checking if ( fRootDir.exists() ) { if ( bForce ) { boolean bOK = deleteDir(fRootDir); if ( !bOK ) return InstallStatus.FAILED; } else { return InstallStatus.SKIPPED; } } else fRootDir.mkdirs(); // Unjar the contents try { JarInputStream jar = new JarInputStream(jarStream); JarEntry je = null; while ( (je=jar.getNextJarEntry())!=null ) { File fileTarget = new File(sDestDir+File.separator+je.getName().replaceAll("/", File.separator)); if ( je.isDirectory() ) { fileTarget.mkdirs(); } else { FileOutputStream fos = new FileOutputStream(fileTarget); byte [] baBuf = new byte[READ_WRITE_CHUNK_SIZE]; int len; while ((len = jar.read(baBuf)) > 0) { fos.write(baBuf, 0, len); } fos.close(); } } } catch (Throwable t) { deleteDir(new File(sDestDir)); return InstallStatus.FAILED; } return InstallStatus.SUCCESS; }
public static synchronized InstallStatus installFromStream(InputStream jarStream, String sDestDir, boolean bForce ) { File fRootDir = new File(sDestDir); // Basic checking if ( fRootDir.exists() ) { if ( bForce ) { boolean bOK = deleteDir(fRootDir); if ( !bOK ) return InstallStatus.FAILED; } else { return InstallStatus.SKIPPED; } } else fRootDir.mkdirs(); // Unjar the contents try { JarInputStream jar = new JarInputStream(jarStream); JarEntry je = null; while ( (je=jar.getNextJarEntry())!=null ) { String target = sDestDir+File.separator+je.getName(); File fileTarget = new File(new File(target).toURI()); if ( je.isDirectory() ) { fileTarget.mkdirs(); } else { FileOutputStream fos = new FileOutputStream(fileTarget); byte [] baBuf = new byte[READ_WRITE_CHUNK_SIZE]; int len; while ((len = jar.read(baBuf)) > 0) { fos.write(baBuf, 0, len); } fos.close(); } } } catch (Throwable t) { t.printStackTrace(); deleteDir(new File(sDestDir)); return InstallStatus.FAILED; } return InstallStatus.SUCCESS; }
diff --git a/src/org/nutz/lang/util/MultiLineProperties.java b/src/org/nutz/lang/util/MultiLineProperties.java index 7002295c3..cd8160bd4 100644 --- a/src/org/nutz/lang/util/MultiLineProperties.java +++ b/src/org/nutz/lang/util/MultiLineProperties.java @@ -1,143 +1,143 @@ package org.nutz.lang.util; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.nutz.lang.Strings; /** * 可支持直接书写多行文本的 Properties 文件 * * @author zozoh([email protected]) */ public class MultiLineProperties implements Map<String, String> { public MultiLineProperties(Reader reader) throws IOException { this(); load(reader); } public MultiLineProperties() { maps = new HashMap<String, String>(); keys = new LinkedList<String>(); } protected Map<String, String> maps; protected List<String> keys; public synchronized void load(Reader reader) throws IOException { BufferedReader tr = null; if (reader instanceof BufferedReader) tr = (BufferedReader) reader; else tr = new BufferedReader(reader); this.clear(); String s; while (null != (s = tr.readLine())) { if (Strings.isBlank(s)) continue; - if (s.length() > 0 && s.charAt(0) == '#') + if (s.length() > 0 && s.trim().charAt(0) == '#') //只要第一个非空白字符是#,就认为是注释 continue; int pos; char c = '0'; for (pos = 0; pos < s.length(); pos++) { c = s.charAt(pos); if (c == '=' || c == ':') break; } if (c == '=') { String name = s.substring(0, pos); maps.put(name, s.substring(pos + 1)); keys.add(name); } else if (c == ':') { String name = s.substring(0, pos); StringBuffer sb = new StringBuffer(); sb.append(s.substring(pos + 1)); String ss; while (null != (ss = tr.readLine())) { if (ss.length() > 0 && ss.charAt(0) == '#') break; sb.append("\r\n" + ss); } maps.put(name, sb.toString()); keys.add(name); if (null == ss) return; } else { maps.put(s, null); keys.add(s); } } } public synchronized void clear() { maps.clear(); } public boolean containsKey(Object key) { return maps.containsKey(key); } public boolean containsValue(Object value) { return maps.containsValue(value); } public Set<Entry<String, String>> entrySet() { return maps.entrySet(); } @Override public boolean equals(Object o) { return maps.equals(o); } @Override public int hashCode() { return maps.hashCode(); } public boolean isEmpty() { return maps.isEmpty(); } public Set<String> keySet() { return maps.keySet(); } public List<String> keys() { return keys; } public synchronized String put(String key, String value) { return maps.put(key, value); } @SuppressWarnings({"unchecked", "rawtypes"}) public synchronized void putAll(Map t) { maps.putAll(t); } public synchronized String remove(Object key) { return maps.remove(key); } public int size() { return maps.size(); } public Collection<String> values() { return maps.values(); } public String get(Object key) { return maps.get(key); } }
true
true
public synchronized void load(Reader reader) throws IOException { BufferedReader tr = null; if (reader instanceof BufferedReader) tr = (BufferedReader) reader; else tr = new BufferedReader(reader); this.clear(); String s; while (null != (s = tr.readLine())) { if (Strings.isBlank(s)) continue; if (s.length() > 0 && s.charAt(0) == '#') continue; int pos; char c = '0'; for (pos = 0; pos < s.length(); pos++) { c = s.charAt(pos); if (c == '=' || c == ':') break; } if (c == '=') { String name = s.substring(0, pos); maps.put(name, s.substring(pos + 1)); keys.add(name); } else if (c == ':') { String name = s.substring(0, pos); StringBuffer sb = new StringBuffer(); sb.append(s.substring(pos + 1)); String ss; while (null != (ss = tr.readLine())) { if (ss.length() > 0 && ss.charAt(0) == '#') break; sb.append("\r\n" + ss); } maps.put(name, sb.toString()); keys.add(name); if (null == ss) return; } else { maps.put(s, null); keys.add(s); } } }
public synchronized void load(Reader reader) throws IOException { BufferedReader tr = null; if (reader instanceof BufferedReader) tr = (BufferedReader) reader; else tr = new BufferedReader(reader); this.clear(); String s; while (null != (s = tr.readLine())) { if (Strings.isBlank(s)) continue; if (s.length() > 0 && s.trim().charAt(0) == '#') //只要第一个非空白字符是#,就认为是注释 continue; int pos; char c = '0'; for (pos = 0; pos < s.length(); pos++) { c = s.charAt(pos); if (c == '=' || c == ':') break; } if (c == '=') { String name = s.substring(0, pos); maps.put(name, s.substring(pos + 1)); keys.add(name); } else if (c == ':') { String name = s.substring(0, pos); StringBuffer sb = new StringBuffer(); sb.append(s.substring(pos + 1)); String ss; while (null != (ss = tr.readLine())) { if (ss.length() > 0 && ss.charAt(0) == '#') break; sb.append("\r\n" + ss); } maps.put(name, sb.toString()); keys.add(name); if (null == ss) return; } else { maps.put(s, null); keys.add(s); } } }
diff --git a/org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/RevWalkTextBuiltin.java b/org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/RevWalkTextBuiltin.java index 715cb71b..50fe31f8 100644 --- a/org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/RevWalkTextBuiltin.java +++ b/org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/RevWalkTextBuiltin.java @@ -1,233 +1,235 @@ /* * Copyright (C) 2008, Shawn O. Pearce <[email protected]> * and other copyright owners as documented in the project's IP log. * * This program and the accompanying materials are made available * under the terms of the Eclipse Distribution License v1.0 which * accompanies this distribution, is reproduced below, and is * available at http://www.eclipse.org/org/documents/edl-v10.php * * 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 Eclipse Foundation, Inc. nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.eclipse.jgit.pgm; import java.text.MessageFormat; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.Option; import org.eclipse.jgit.errors.IncorrectObjectTypeException; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.pgm.opt.PathTreeFilterHandler; import org.eclipse.jgit.revwalk.FollowFilter; import org.eclipse.jgit.revwalk.ObjectWalk; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevFlag; import org.eclipse.jgit.revwalk.RevObject; import org.eclipse.jgit.revwalk.RevSort; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.revwalk.filter.AndRevFilter; import org.eclipse.jgit.revwalk.filter.AuthorRevFilter; import org.eclipse.jgit.revwalk.filter.CommitterRevFilter; import org.eclipse.jgit.revwalk.filter.MessageRevFilter; import org.eclipse.jgit.revwalk.filter.RevFilter; import org.eclipse.jgit.treewalk.filter.AndTreeFilter; import org.eclipse.jgit.treewalk.filter.TreeFilter; abstract class RevWalkTextBuiltin extends TextBuiltin { RevWalk walk; @Option(name = "--objects") boolean objects = false; @Option(name = "--parents") boolean parents = false; @Option(name = "--total-count") boolean count = false; @Option(name = "--all") boolean all = false; char[] outbuffer = new char[Constants.OBJECT_ID_LENGTH * 2]; private final EnumSet<RevSort> sorting = EnumSet.noneOf(RevSort.class); private void enableRevSort(final RevSort type, final boolean on) { if (on) sorting.add(type); else sorting.remove(type); } @Option(name = "--date-order") void enableDateOrder(final boolean on) { enableRevSort(RevSort.COMMIT_TIME_DESC, on); } @Option(name = "--topo-order") void enableTopoOrder(final boolean on) { enableRevSort(RevSort.TOPO, on); } @Option(name = "--reverse") void enableReverse(final boolean on) { enableRevSort(RevSort.REVERSE, on); } @Option(name = "--boundary") void enableBoundary(final boolean on) { enableRevSort(RevSort.BOUNDARY, on); } @Option(name = "--follow", metaVar = "metaVar_path") void follow(final String path) { pathFilter = FollowFilter.create(path); } @Argument(index = 0, metaVar = "metaVar_commitish") private final List<RevCommit> commits = new ArrayList<RevCommit>(); @Option(name = "--", metaVar = "metaVar_path", multiValued = true, handler = PathTreeFilterHandler.class) protected TreeFilter pathFilter = TreeFilter.ALL; private final List<RevFilter> revLimiter = new ArrayList<RevFilter>(); @Option(name = "--author") void addAuthorRevFilter(final String who) { revLimiter.add(AuthorRevFilter.create(who)); } @Option(name = "--committer") void addCommitterRevFilter(final String who) { revLimiter.add(CommitterRevFilter.create(who)); } @Option(name = "--grep") void addCMessageRevFilter(final String msg) { revLimiter.add(MessageRevFilter.create(msg)); } @Override protected void run() throws Exception { walk = createWalk(); for (final RevSort s : sorting) walk.sort(s, true); if (pathFilter instanceof FollowFilter) walk.setTreeFilter(pathFilter); else if (pathFilter != TreeFilter.ALL) walk.setTreeFilter(AndTreeFilter.create(pathFilter, TreeFilter.ANY_DIFF)); if (revLimiter.size() == 1) walk.setRevFilter(revLimiter.get(0)); else if (revLimiter.size() > 1) walk.setRevFilter(AndRevFilter.create(revLimiter)); if (all) for (Ref a : db.getAllRefs().values()) { ObjectId oid = a.getPeeledObjectId(); if (oid == null) oid = a.getObjectId(); try { commits.add(walk.parseCommit(oid)); } catch (IncorrectObjectTypeException e) { // Ignore all refs which are not commits } } if (commits.isEmpty()) { final ObjectId head = db.resolve(Constants.HEAD); if (head == null) throw die(MessageFormat.format(CLIText.get().cannotResolve, Constants.HEAD)); commits.add(walk.parseCommit(head)); } for (final RevCommit c : commits) { final RevCommit real = argWalk == walk ? c : walk.parseCommit(c); if (c.has(RevFlag.UNINTERESTING)) walk.markUninteresting(real); else walk.markStart(real); } final long start = System.currentTimeMillis(); final int n = walkLoop(); if (count) { final long end = System.currentTimeMillis(); System.err.print(n); System.err.print(' '); - System.err.println(MessageFormat.format( - CLIText.get().timeInMilliSeconds, end - start)); + System.err + .println(MessageFormat.format( + CLIText.get().timeInMilliSeconds, + Long.valueOf(end - start))); } } protected RevWalk createWalk() { if (objects) return new ObjectWalk(db); if (argWalk != null) return argWalk; return new RevWalk(db); } protected int walkLoop() throws Exception { int n = 0; for (final RevCommit c : walk) { n++; show(c); } if (walk instanceof ObjectWalk) { final ObjectWalk ow = (ObjectWalk) walk; for (;;) { final RevObject obj = ow.nextObject(); if (obj == null) break; show(ow, obj); } } return n; } protected abstract void show(final RevCommit c) throws Exception; protected void show(final ObjectWalk objectWalk, final RevObject currentObject) throws Exception { // Do nothing by default. Most applications cannot show an object. } }
true
true
protected void run() throws Exception { walk = createWalk(); for (final RevSort s : sorting) walk.sort(s, true); if (pathFilter instanceof FollowFilter) walk.setTreeFilter(pathFilter); else if (pathFilter != TreeFilter.ALL) walk.setTreeFilter(AndTreeFilter.create(pathFilter, TreeFilter.ANY_DIFF)); if (revLimiter.size() == 1) walk.setRevFilter(revLimiter.get(0)); else if (revLimiter.size() > 1) walk.setRevFilter(AndRevFilter.create(revLimiter)); if (all) for (Ref a : db.getAllRefs().values()) { ObjectId oid = a.getPeeledObjectId(); if (oid == null) oid = a.getObjectId(); try { commits.add(walk.parseCommit(oid)); } catch (IncorrectObjectTypeException e) { // Ignore all refs which are not commits } } if (commits.isEmpty()) { final ObjectId head = db.resolve(Constants.HEAD); if (head == null) throw die(MessageFormat.format(CLIText.get().cannotResolve, Constants.HEAD)); commits.add(walk.parseCommit(head)); } for (final RevCommit c : commits) { final RevCommit real = argWalk == walk ? c : walk.parseCommit(c); if (c.has(RevFlag.UNINTERESTING)) walk.markUninteresting(real); else walk.markStart(real); } final long start = System.currentTimeMillis(); final int n = walkLoop(); if (count) { final long end = System.currentTimeMillis(); System.err.print(n); System.err.print(' '); System.err.println(MessageFormat.format( CLIText.get().timeInMilliSeconds, end - start)); } }
protected void run() throws Exception { walk = createWalk(); for (final RevSort s : sorting) walk.sort(s, true); if (pathFilter instanceof FollowFilter) walk.setTreeFilter(pathFilter); else if (pathFilter != TreeFilter.ALL) walk.setTreeFilter(AndTreeFilter.create(pathFilter, TreeFilter.ANY_DIFF)); if (revLimiter.size() == 1) walk.setRevFilter(revLimiter.get(0)); else if (revLimiter.size() > 1) walk.setRevFilter(AndRevFilter.create(revLimiter)); if (all) for (Ref a : db.getAllRefs().values()) { ObjectId oid = a.getPeeledObjectId(); if (oid == null) oid = a.getObjectId(); try { commits.add(walk.parseCommit(oid)); } catch (IncorrectObjectTypeException e) { // Ignore all refs which are not commits } } if (commits.isEmpty()) { final ObjectId head = db.resolve(Constants.HEAD); if (head == null) throw die(MessageFormat.format(CLIText.get().cannotResolve, Constants.HEAD)); commits.add(walk.parseCommit(head)); } for (final RevCommit c : commits) { final RevCommit real = argWalk == walk ? c : walk.parseCommit(c); if (c.has(RevFlag.UNINTERESTING)) walk.markUninteresting(real); else walk.markStart(real); } final long start = System.currentTimeMillis(); final int n = walkLoop(); if (count) { final long end = System.currentTimeMillis(); System.err.print(n); System.err.print(' '); System.err .println(MessageFormat.format( CLIText.get().timeInMilliSeconds, Long.valueOf(end - start))); } }
diff --git a/ui/plugins/eu.esdihumboldt.hale.ui.common/src/eu/esdihumboldt/hale/ui/common/definition/viewer/InheritedPropertiesFilter.java b/ui/plugins/eu.esdihumboldt.hale.ui.common/src/eu/esdihumboldt/hale/ui/common/definition/viewer/InheritedPropertiesFilter.java index a449336e8..9f398bb66 100644 --- a/ui/plugins/eu.esdihumboldt.hale.ui.common/src/eu/esdihumboldt/hale/ui/common/definition/viewer/InheritedPropertiesFilter.java +++ b/ui/plugins/eu.esdihumboldt.hale.ui.common/src/eu/esdihumboldt/hale/ui/common/definition/viewer/InheritedPropertiesFilter.java @@ -1,59 +1,59 @@ /* * Copyright (c) 2012 Data Harmonisation Panel * * All rights reserved. This program and the accompanying materials are made * available under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution. If not, see <http://www.gnu.org/licenses/>. * * Contributors: * HUMBOLDT EU Integrated Project #030962 * Data Harmonisation Panel <http://www.dhpanel.eu> */ package eu.esdihumboldt.hale.ui.common.definition.viewer; import org.eclipse.jface.viewers.TreePath; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import com.google.common.base.Objects; import eu.esdihumboldt.hale.common.align.model.EntityDefinition; import eu.esdihumboldt.hale.common.schema.model.ChildDefinition; /** * Filter that hides inherited properties (Only works for * {@link EntityDefinition} elements). * * @author Simon Templer */ public class InheritedPropertiesFilter extends ViewerFilter { @Override public boolean select(Viewer viewer, Object parentElement, Object element) { if (element instanceof TreePath) { element = ((TreePath) element).getLastSegment(); } if (element instanceof EntityDefinition) { EntityDefinition entityDef = (EntityDefinition) element; /* * Only filter properties directly associated to a type, all nested * properties must be shown at all times. */ if (entityDef.getPropertyPath().size() == 1) { ChildDefinition<?> child = entityDef.getPropertyPath().get(0).getChild(); // if declaring group and parent type are the same, show it - return Objects.equal(child.getDeclaringGroup(), child.getParentType()); + return Objects.equal(child.getDeclaringGroup(), entityDef.getType()); } } return true; } }
true
true
public boolean select(Viewer viewer, Object parentElement, Object element) { if (element instanceof TreePath) { element = ((TreePath) element).getLastSegment(); } if (element instanceof EntityDefinition) { EntityDefinition entityDef = (EntityDefinition) element; /* * Only filter properties directly associated to a type, all nested * properties must be shown at all times. */ if (entityDef.getPropertyPath().size() == 1) { ChildDefinition<?> child = entityDef.getPropertyPath().get(0).getChild(); // if declaring group and parent type are the same, show it return Objects.equal(child.getDeclaringGroup(), child.getParentType()); } } return true; }
public boolean select(Viewer viewer, Object parentElement, Object element) { if (element instanceof TreePath) { element = ((TreePath) element).getLastSegment(); } if (element instanceof EntityDefinition) { EntityDefinition entityDef = (EntityDefinition) element; /* * Only filter properties directly associated to a type, all nested * properties must be shown at all times. */ if (entityDef.getPropertyPath().size() == 1) { ChildDefinition<?> child = entityDef.getPropertyPath().get(0).getChild(); // if declaring group and parent type are the same, show it return Objects.equal(child.getDeclaringGroup(), entityDef.getType()); } } return true; }
diff --git a/jcr/src/main/java/org/crsh/jcr/command/JCRCommand.java b/jcr/src/main/java/org/crsh/jcr/command/JCRCommand.java index b09d4ee1..b279b1e8 100644 --- a/jcr/src/main/java/org/crsh/jcr/command/JCRCommand.java +++ b/jcr/src/main/java/org/crsh/jcr/command/JCRCommand.java @@ -1,101 +1,101 @@ /* * Copyright (C) 2010 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.crsh.jcr.command; import org.crsh.cmdline.IntrospectionException; import org.crsh.cmdline.ParameterDescriptor; import org.crsh.cmdline.spi.Completer; import org.crsh.command.CRaSHCommand; import javax.jcr.Item; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.Session; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * @author <a href="mailto:[email protected]">Julien Viet</a> * @version $Revision$ */ public abstract class JCRCommand extends CRaSHCommand implements Completer { protected JCRCommand() throws IntrospectionException { } public Map<String, Boolean> complete(ParameterDescriptor<?> parameter, String prefix) throws Exception { - if (parameter.getAnnotation() instanceof Path) { + if (parameter.getJavaValueType() == Path.class) { - String path = (String)getProperty("currentPath"); + Path path = (Path)getProperty("currentPath"); Session session = (Session)getProperty("session"); // if (session != null) { Node relative = null; if (prefix.length() == 0 || prefix.charAt(0) != '/') { if (path != null) { - Item item = session.getItem(path); + Item item = session.getItem(path.getString()); if (item instanceof Node) { relative = (Node)item; } } } else { relative = session.getRootNode(); prefix = prefix.substring(1); } // Now navigate using the prefix if (relative != null) { for (int index = prefix.indexOf('/');index != -1;index = prefix.indexOf('/')) { String name = prefix.substring(0, index); if (relative.hasNode(name)) { relative = relative.getNode(name); prefix = prefix.substring(index + 1); } else { return Collections.emptyMap(); } } } // Compute the next possible completions Map<String, Boolean> completions = new HashMap<String, Boolean>(); for (NodeIterator i = relative.getNodes(prefix + '*');i.hasNext();) { Node child = i.nextNode(); String suffix = child.getName().substring(prefix.length()); if (child.hasNodes()) { completions.put(suffix + '/', false); } else { completions.put(suffix, true); } } // return completions; } } // return Collections.emptyMap(); } }
false
true
public Map<String, Boolean> complete(ParameterDescriptor<?> parameter, String prefix) throws Exception { if (parameter.getAnnotation() instanceof Path) { String path = (String)getProperty("currentPath"); Session session = (Session)getProperty("session"); // if (session != null) { Node relative = null; if (prefix.length() == 0 || prefix.charAt(0) != '/') { if (path != null) { Item item = session.getItem(path); if (item instanceof Node) { relative = (Node)item; } } } else { relative = session.getRootNode(); prefix = prefix.substring(1); } // Now navigate using the prefix if (relative != null) { for (int index = prefix.indexOf('/');index != -1;index = prefix.indexOf('/')) { String name = prefix.substring(0, index); if (relative.hasNode(name)) { relative = relative.getNode(name); prefix = prefix.substring(index + 1); } else { return Collections.emptyMap(); } } } // Compute the next possible completions Map<String, Boolean> completions = new HashMap<String, Boolean>(); for (NodeIterator i = relative.getNodes(prefix + '*');i.hasNext();) { Node child = i.nextNode(); String suffix = child.getName().substring(prefix.length()); if (child.hasNodes()) { completions.put(suffix + '/', false); } else { completions.put(suffix, true); } } // return completions; } } // return Collections.emptyMap(); }
public Map<String, Boolean> complete(ParameterDescriptor<?> parameter, String prefix) throws Exception { if (parameter.getJavaValueType() == Path.class) { Path path = (Path)getProperty("currentPath"); Session session = (Session)getProperty("session"); // if (session != null) { Node relative = null; if (prefix.length() == 0 || prefix.charAt(0) != '/') { if (path != null) { Item item = session.getItem(path.getString()); if (item instanceof Node) { relative = (Node)item; } } } else { relative = session.getRootNode(); prefix = prefix.substring(1); } // Now navigate using the prefix if (relative != null) { for (int index = prefix.indexOf('/');index != -1;index = prefix.indexOf('/')) { String name = prefix.substring(0, index); if (relative.hasNode(name)) { relative = relative.getNode(name); prefix = prefix.substring(index + 1); } else { return Collections.emptyMap(); } } } // Compute the next possible completions Map<String, Boolean> completions = new HashMap<String, Boolean>(); for (NodeIterator i = relative.getNodes(prefix + '*');i.hasNext();) { Node child = i.nextNode(); String suffix = child.getName().substring(prefix.length()); if (child.hasNodes()) { completions.put(suffix + '/', false); } else { completions.put(suffix, true); } } // return completions; } } // return Collections.emptyMap(); }
diff --git a/microsling/microsling-core/src/main/java/org/apache/sling/microsling/slingservlets/MicrojaxPostServlet.java b/microsling/microsling-core/src/main/java/org/apache/sling/microsling/slingservlets/MicrojaxPostServlet.java index b7a3e47280..13f2af11e1 100644 --- a/microsling/microsling-core/src/main/java/org/apache/sling/microsling/slingservlets/MicrojaxPostServlet.java +++ b/microsling/microsling-core/src/main/java/org/apache/sling/microsling/slingservlets/MicrojaxPostServlet.java @@ -1,380 +1,384 @@ /* * 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.sling.microsling.slingservlets; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.jcr.Item; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; import org.apache.sling.api.HttpStatusCodeException; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.request.RequestParameter; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.apache.sling.api.wrappers.SlingRequestPaths; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** Servlet that implements the microjax POST "protocol", see SLING-92 */ public class MicrojaxPostServlet extends SlingAllMethodsServlet { private static final long serialVersionUID = 1837674988291697074L; private static final Logger log = LoggerFactory.getLogger(MicrojaxPostServlet.class); private final MicrojaxPropertyValueSetter propertyValueSetter = new MicrojaxPropertyValueSetter(); private int createNodeCounter; /** Prefix for parameter names which control this POST * (ujax stands for "microjax", RP_ stands for "request param") */ public static final String RP_PREFIX = "ujax_"; /** Optional request parameter: redirect to the specified URL after POST */ public static final String RP_REDIRECT_TO = RP_PREFIX + "redirect"; /** Optional request parameter: delete the specified content paths */ public static final String RP_DELETE_PATH = RP_PREFIX + "delete"; /** Optional request parameter: only request parameters starting with this prefix are * saved as Properties when creating a Node. Active only if at least one parameter * starts with this prefix, and defaults to {@link DEFAULT_SAVE_PARAM_PREFIX}. */ public static final String RP_SAVE_PARAM_PREFIX = RP_PREFIX + "saveParamPrefix"; /** Default value for {@link RP_SAVE_PARAM_PREFIX} */ public static final String DEFAULT_SAVE_PARAM_PREFIX = "./"; /** Optional request parameter: if value is 0, created node is ordered so as * to be the first child of its parent. */ public static final String RP_ORDER = RP_PREFIX + "order"; /** Code value for RP_ORDER */ public static final String ORDER_ZERO = "0"; /** Optional request parameter: if provided, added at the end of the computed * (or supplied) redirect URL */ public static final String RP_DISPLAY_EXTENSION = RP_PREFIX + "displayExtension"; @Override protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { Session s = null; try { // select the Resource to process Resource currentResource = request.getResource(); Node currentNode = currentResource.adaptTo(Node.class); // need a Node, path and Session String currentPath = null; if(currentNode != null) { currentPath = currentNode.getPath(); s = currentNode.getSession(); } else { currentPath = SlingRequestPaths.getPathInfo(request); s = (Session)request.getAttribute(Session.class.getName()); } final String [] pathsToDelete = request.getParameterValues(RP_DELETE_PATH); if(pathsToDelete!=null) { // process deletes if any, and if so don't do anything else deleteNodes(s, pathsToDelete, currentPath, response); } else { // if no deletes, create or update nodes createOrUpdateNodesFromRequest(request, response, s); } } catch(RepositoryException re) { throw new HttpStatusCodeException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,re.toString(),re); } finally { try { if (s != null && s.hasPendingChanges()) { s.refresh(false); } } catch(RepositoryException re) { log.warn("RepositoryException in finally block: "+ re.getMessage(),re); } } } /** Delete specified nodes, and send response */ protected void deleteNodes(Session s, String [] pathsToDelete, String currentPath, SlingHttpServletResponse response) throws RepositoryException, IOException { processDeletes(s, pathsToDelete, currentPath); s.save(); response.setContentType(getServletContext().getMimeType("dummy.txt")); final PrintWriter pw = new PrintWriter(new OutputStreamWriter(response.getOutputStream())); pw.println("Nodes have been deleted(if they existed):"); for(String path : pathsToDelete) { pw.println(path); } pw.flush(); } /** Create or update node(s) according to current request , and send response */ protected void createOrUpdateNodesFromRequest(SlingHttpServletRequest request, SlingHttpServletResponse response, Session s) throws RepositoryException, IOException { // Where to redirect to when done String redirectPath = request.getHeader("Referer"); // find out the actual "save prefix" to use - only parameters starting with // this prefix are saved as Properties, when creating nodes, see setPropertiesFromRequest() final String savePrefix = getSavePrefix(request); // use the request path (disregarding resource resolution) // but remove any extension or selectors String currentPath = SlingRequestPaths.getPathInfo(request); Node currentNode = null; final int dotPos = currentPath.indexOf('.'); if(dotPos >= 0) { currentPath = currentPath.substring(0,dotPos); } final String starSuffix = "/*"; if(currentPath.endsWith(starSuffix)) { // If the path ends with a *, create a node under its parent, with // a generated node name currentPath = currentPath.substring(0, currentPath.length() - starSuffix.length()); currentPath += "/" + (createNodeCounter++) + System.currentTimeMillis(); } else if(s.itemExists(currentPath)) { // update to an existing node final Item item = s.getItem(currentPath); if(item.isNode()) { currentNode = (Node)item; } else { throw new HttpStatusCodeException(HttpServletResponse.SC_CONFLICT,"Item at path " + currentPath + " is not a Node"); } } else { // request to create a new node at a specific path - use the supplied path as is } Set<Node> createdNodes = new HashSet<Node>(); if(currentNode == null) { currentNode = deepCreateNode(s, currentPath, createdNodes); } currentPath = currentNode.getPath(); // process the "order" command if any final String order = request.getParameter(RP_ORDER); if(order!=null) { processNodeOrder(currentNode,order); } // walk the request parameters, create and save nodes and properties setPropertiesFromRequest(currentNode, request, savePrefix, createdNodes); // sava data and find out where to redirect s.save(); final String forcedRedirect = request.getParameter(RP_REDIRECT_TO); final String redirectExtension = request.getParameter(RP_DISPLAY_EXTENSION); if(forcedRedirect != null) { redirectPath = forcedRedirect; } else if(currentNode != null) { redirectPath = currentNode.getPath(); } if(redirectExtension!=null) { - redirectPath += redirectExtension; + if(redirectExtension.startsWith(".")) { + redirectPath += redirectExtension; + } else { + redirectPath += "." + redirectExtension; + } } final String redirectUrl = SlingRequestPaths.getContextPath(request) + SlingRequestPaths.getServletPath(request) + redirectPath; if(log.isDebugEnabled()) { log.debug("Redirecting to " + redirectUrl); } response.sendRedirect(redirectUrl); } /** Set Node properties from current request * TODO should handle file uploads as well */ private void setPropertiesFromRequest(Node n, SlingHttpServletRequest request, String savePrefix, Set<Node> createdNodes) throws RepositoryException { for(Map.Entry<String, RequestParameter[]> e : request.getRequestParameterMap().entrySet()) { String name = e.getKey(); if(savePrefix!=null) { if(!name.startsWith(savePrefix)) { continue; } name = name.substring(savePrefix.length()); } setProperty(n,request,name,e.getValue(),createdNodes); } } /** Set a single Property on node N * @throws RepositoryException */ private void setProperty(Node n, SlingHttpServletRequest request, String name, RequestParameter[] values, Set<Node> createdNodes) throws RepositoryException { // split the relative path identifying the property to be saved String proppath = name; // @ValueFrom can be used to define mappings between form fields and JCR properties // TODO // final int vfIndex = name.indexOf("@ValueFrom"); // if (vfIndex >= 0) { // // Indirect // proppath = name.substring(0, vfIndex); // } else if (name.indexOf("@") >= 0) { // // skip "Hints" // return; // } final String path = n.getPath(); String parentpath = ""; String propname=name; if (propname.indexOf("/")>=0) { parentpath=proppath.substring(0, name.lastIndexOf("/")); propname = proppath.substring(name.lastIndexOf("/") + 1); } // if the whole thing ended in a slash -> skip if (propname.equals("")) { return; } // get or create the parent node final Session s = n.getSession(); Node parent; if(name.startsWith("/")) { parent = deepCreateNode(s, parentpath, createdNodes); } else if (!parentpath.equals("")) { parent = (Node) s.getItem(path + "/" + parentpath); } else { parent = (Node) s.getItem(path); } // TODO String typehint = request.getParameter(proppath + "@TypeHint"); final String typeHint = null; final boolean nodeIsNew = createdNodes.contains(parent); propertyValueSetter.setProperty(parent, propname, values, typeHint, nodeIsNew); } /** * Deep creates a node, parent-padding with nt:unstructured nodes * * @param path absolute path to node that needs to be deep-created */ private Node deepCreateNode(Session s, String path, Set<Node> createdNodes) throws RepositoryException { if(log.isDebugEnabled()) { log.debug("Deep-creating Node '" + path + "'"); } String[] pathelems = path.substring(1).split("/"); int i = 0; String mypath = ""; Node parent = s.getRootNode(); while (i < pathelems.length) { String name = pathelems[i]; mypath += "/" + name; if (!s.itemExists(mypath)) { createdNodes.add(parent.addNode(name)); } parent = (Node) s.getItem(mypath); i++; } return (parent); } /** Delete Items at the provided paths * @param pathsToDelete each path that does not start with / is * prepended with currentPath */ private void processDeletes(Session s, String [] pathsToDelete, String currentPath) throws RepositoryException { for(String path : pathsToDelete) { if(!path.startsWith("/")) { path = currentPath + "/" + path; } if(s.itemExists(path)) { s.getItem(path).remove(); if(log.isDebugEnabled()) { log.debug("Deleted item " + path); } } else { if(log.isDebugEnabled()) { log.debug("Item '" + path + "' not found for deletion, ignored"); } } } } /** Return the "save prefix" to use, null if none */ private String getSavePrefix(SlingHttpServletRequest request) { String prefix = request.getParameter(RP_SAVE_PARAM_PREFIX); if(prefix==null) { prefix = DEFAULT_SAVE_PARAM_PREFIX; } // if no parameters start with this prefix, it is not used String result = null; for(String name : request.getRequestParameterMap().keySet()) { if(name.startsWith(prefix)) { result = prefix; break; } } return result; } /** If orderCode is ORDER_ZERO, move n so that it is the first * child of its parent * @throws RepositoryException */ private void processNodeOrder(Node n, String orderCode) throws RepositoryException { if(ORDER_ZERO.equals(orderCode)) { final String path = n.getPath(); final Node parent=(Node) n.getSession().getItem(path.substring(0,path.lastIndexOf('/'))); final String myname=path.substring(path.lastIndexOf('/')+1); final String beforename=parent.getNodes().nextNode().getName(); parent.orderBefore(myname, beforename); if(log.isDebugEnabled()) { log.debug("Node " + n.getPath() + " moved to be first child of its parent, due to orderCode=" + orderCode); } } else { if(log.isDebugEnabled()) { log.debug("orderCode '" + orderCode + "' invalid, ignored"); } } } }
true
true
protected void createOrUpdateNodesFromRequest(SlingHttpServletRequest request, SlingHttpServletResponse response, Session s) throws RepositoryException, IOException { // Where to redirect to when done String redirectPath = request.getHeader("Referer"); // find out the actual "save prefix" to use - only parameters starting with // this prefix are saved as Properties, when creating nodes, see setPropertiesFromRequest() final String savePrefix = getSavePrefix(request); // use the request path (disregarding resource resolution) // but remove any extension or selectors String currentPath = SlingRequestPaths.getPathInfo(request); Node currentNode = null; final int dotPos = currentPath.indexOf('.'); if(dotPos >= 0) { currentPath = currentPath.substring(0,dotPos); } final String starSuffix = "/*"; if(currentPath.endsWith(starSuffix)) { // If the path ends with a *, create a node under its parent, with // a generated node name currentPath = currentPath.substring(0, currentPath.length() - starSuffix.length()); currentPath += "/" + (createNodeCounter++) + System.currentTimeMillis(); } else if(s.itemExists(currentPath)) { // update to an existing node final Item item = s.getItem(currentPath); if(item.isNode()) { currentNode = (Node)item; } else { throw new HttpStatusCodeException(HttpServletResponse.SC_CONFLICT,"Item at path " + currentPath + " is not a Node"); } } else { // request to create a new node at a specific path - use the supplied path as is } Set<Node> createdNodes = new HashSet<Node>(); if(currentNode == null) { currentNode = deepCreateNode(s, currentPath, createdNodes); } currentPath = currentNode.getPath(); // process the "order" command if any final String order = request.getParameter(RP_ORDER); if(order!=null) { processNodeOrder(currentNode,order); } // walk the request parameters, create and save nodes and properties setPropertiesFromRequest(currentNode, request, savePrefix, createdNodes); // sava data and find out where to redirect s.save(); final String forcedRedirect = request.getParameter(RP_REDIRECT_TO); final String redirectExtension = request.getParameter(RP_DISPLAY_EXTENSION); if(forcedRedirect != null) { redirectPath = forcedRedirect; } else if(currentNode != null) { redirectPath = currentNode.getPath(); } if(redirectExtension!=null) { redirectPath += redirectExtension; } final String redirectUrl = SlingRequestPaths.getContextPath(request) + SlingRequestPaths.getServletPath(request) + redirectPath; if(log.isDebugEnabled()) { log.debug("Redirecting to " + redirectUrl); } response.sendRedirect(redirectUrl); }
protected void createOrUpdateNodesFromRequest(SlingHttpServletRequest request, SlingHttpServletResponse response, Session s) throws RepositoryException, IOException { // Where to redirect to when done String redirectPath = request.getHeader("Referer"); // find out the actual "save prefix" to use - only parameters starting with // this prefix are saved as Properties, when creating nodes, see setPropertiesFromRequest() final String savePrefix = getSavePrefix(request); // use the request path (disregarding resource resolution) // but remove any extension or selectors String currentPath = SlingRequestPaths.getPathInfo(request); Node currentNode = null; final int dotPos = currentPath.indexOf('.'); if(dotPos >= 0) { currentPath = currentPath.substring(0,dotPos); } final String starSuffix = "/*"; if(currentPath.endsWith(starSuffix)) { // If the path ends with a *, create a node under its parent, with // a generated node name currentPath = currentPath.substring(0, currentPath.length() - starSuffix.length()); currentPath += "/" + (createNodeCounter++) + System.currentTimeMillis(); } else if(s.itemExists(currentPath)) { // update to an existing node final Item item = s.getItem(currentPath); if(item.isNode()) { currentNode = (Node)item; } else { throw new HttpStatusCodeException(HttpServletResponse.SC_CONFLICT,"Item at path " + currentPath + " is not a Node"); } } else { // request to create a new node at a specific path - use the supplied path as is } Set<Node> createdNodes = new HashSet<Node>(); if(currentNode == null) { currentNode = deepCreateNode(s, currentPath, createdNodes); } currentPath = currentNode.getPath(); // process the "order" command if any final String order = request.getParameter(RP_ORDER); if(order!=null) { processNodeOrder(currentNode,order); } // walk the request parameters, create and save nodes and properties setPropertiesFromRequest(currentNode, request, savePrefix, createdNodes); // sava data and find out where to redirect s.save(); final String forcedRedirect = request.getParameter(RP_REDIRECT_TO); final String redirectExtension = request.getParameter(RP_DISPLAY_EXTENSION); if(forcedRedirect != null) { redirectPath = forcedRedirect; } else if(currentNode != null) { redirectPath = currentNode.getPath(); } if(redirectExtension!=null) { if(redirectExtension.startsWith(".")) { redirectPath += redirectExtension; } else { redirectPath += "." + redirectExtension; } } final String redirectUrl = SlingRequestPaths.getContextPath(request) + SlingRequestPaths.getServletPath(request) + redirectPath; if(log.isDebugEnabled()) { log.debug("Redirecting to " + redirectUrl); } response.sendRedirect(redirectUrl); }
diff --git a/objectmodel/MasterPresenter.java b/objectmodel/MasterPresenter.java index df7fb3d..1022db1 100644 --- a/objectmodel/MasterPresenter.java +++ b/objectmodel/MasterPresenter.java @@ -1,1010 +1,1010 @@ /* * Copyright 2012 Anthony Cassidy * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.github.a2g.core.objectmodel; //import java.util.Iterator; import java.util.TreeMap; import java.util.logging.Logger; import com.google.gwt.event.dom.client.LoadHandler; import com.github.a2g.core.action.ActionRunner; import com.github.a2g.core.action.BaseAction; import com.github.a2g.core.action.DoNothingAction; import com.github.a2g.core.action.ChainRootAction; import com.github.a2g.core.action.ChainedAction; import com.github.a2g.core.action.SayAction; import com.github.a2g.core.primitive.ColorEnum; import com.github.a2g.core.primitive.Point; import com.github.a2g.core.action.BaseDialogTreeAction; import com.github.a2g.core.event.PropertyChangeEvent; import com.github.a2g.core.event.PropertyChangeEventHandlerAPI; import com.github.a2g.core.event.SaySpeechCallDialogTreeEvent; import com.github.a2g.core.event.SaySpeechCallDialogTreeEventHandlerAPI; import com.github.a2g.core.event.SetRolloverEvent; import com.github.a2g.core.interfaces.ActionRunnerCallbackAPI; import com.github.a2g.core.interfaces.CommandLineCallbackAPI; import com.github.a2g.core.interfaces.FactoryAPI; import com.github.a2g.core.interfaces.HostingPanelAPI; import com.github.a2g.core.interfaces.ImageAddAPI; import com.github.a2g.core.interfaces.InventoryPresenterCallbackAPI; import com.github.a2g.core.interfaces.LoadAPI; import com.github.a2g.core.interfaces.InternalAPI; import com.github.a2g.core.interfaces.MasterPanelAPI; import com.github.a2g.core.interfaces.MasterPanelAPI.GuiStateEnum; import com.github.a2g.core.interfaces.MasterPresenterHostAPI; import com.github.a2g.core.interfaces.MergeSceneAndStartAPI; import com.github.a2g.core.interfaces.OnDialogTreeAPI; import com.github.a2g.core.interfaces.OnDoCommandAPI; import com.github.a2g.core.interfaces.OnEntryAPI; import com.github.a2g.core.interfaces.OnEveryFrameAPI; import com.github.a2g.core.interfaces.OnFillLoadListAPI; import com.github.a2g.core.interfaces.OnFillLoadListAPIImpl; import com.github.a2g.core.interfaces.OnPreEntryAPI; import com.github.a2g.core.interfaces.PackagedImageAPI; import com.github.a2g.core.interfaces.PopupPanelAPI; import com.github.a2g.core.interfaces.SceneAPI; import com.github.a2g.core.interfaces.TimerAPI; import com.github.a2g.core.interfaces.TimerCallbackAPI; import com.github.a2g.core.interfaces.VerbsPresenterCallbackAPI; import com.google.gwt.event.shared.EventBus; @SuppressWarnings("unused") public class MasterPresenter implements InternalAPI , SaySpeechCallDialogTreeEventHandlerAPI , PropertyChangeEventHandlerAPI , TimerCallbackAPI , ImageAddAPI , MergeSceneAndStartAPI , OnFillLoadListAPI , OnEntryAPI , OnPreEntryAPI , OnEveryFrameAPI , OnDoCommandAPI , OnDialogTreeAPI , CommandLineCallbackAPI , ActionRunnerCallbackAPI , InventoryPresenterCallbackAPI , VerbsPresenterCallbackAPI { private CommandLinePresenter commandLinePresenter; private InventoryPresenter inventoryPresenter; private VerbsPresenter verbsPresenter; private ScenePresenter scenePresenter; private DialogTreePresenter dialogTreePresenter; private LoaderPresenter loadingPresenter; private TitleCardPresenter titleCardPresenter; private SceneAPI callbacks; private TreeMap<Short, SceneObject> theObjectMap; private TreeMap<String, Animation> theAnimationMap; private EventBus bus; private MasterPresenterHostAPI parent; private PopupPanelAPI speechPopup; private TimerAPI timer; private TimerAPI switchTimer; private MasterPanelAPI masterPanel; private ActionRunner dialogActionRunner; private ActionRunner doCommandActionRunner; private int textSpeedDelay; private Integer[] theListOfIndexesToInsertAt; private Logger logger = Logger.getLogger("com.mycompany.level"); private String lastSceneAsString; private String defaultSayAnimation; private short defaultWalker; private String switchDestination; public MasterPresenter(final HostingPanelAPI panel, EventBus bus, MasterPresenterHostAPI parent) { this.bus = bus; this.timer = null; this.switchTimer = null; this.parent = parent; this.textSpeedDelay = 20; this.theObjectMap = new TreeMap<Short, SceneObject>(); this.theAnimationMap = new TreeMap<String, Animation>(); this.doCommandActionRunner = new ActionRunner(this,1); this.dialogActionRunner = new ActionRunner(this,2); this.theListOfIndexesToInsertAt= new Integer[100]; for(int i=0;i<100;i++) theListOfIndexesToInsertAt[i] = new Integer(0); bus.addHandler( SaySpeechCallDialogTreeEvent.TYPE, this); bus.addHandler( PropertyChangeEvent.TYPE, this); this.masterPanel = getFactory().createMasterPanel(320,240, ColorEnum.Black); panel.setThing(this.masterPanel); this.dialogTreePresenter = new DialogTreePresenter( masterPanel.getHostForDialogTree(), bus, this); this.commandLinePresenter = new CommandLinePresenter( masterPanel.getHostForCommandLine(), bus, this); this.inventoryPresenter = new InventoryPresenter( masterPanel.getHostForInventory(), bus, this); this.scenePresenter = new ScenePresenter( masterPanel.getHostForScene(), this); this.verbsPresenter = new VerbsPresenter( masterPanel.getHostForVerbs(), bus, this); this.loadingPresenter = new LoaderPresenter( masterPanel.getHostForLoading(), bus, this, this, parent); this.titleCardPresenter = new TitleCardPresenter( masterPanel.getHostForTitleCard(), bus, this, parent); this.speechPopup = getFactory().createPopupPanel(this,scenePresenter.getWidth(), scenePresenter.getHeight()); this.masterPanel.setActiveState(MasterPanelAPI.GuiStateEnum.Loading); } public void setCallbacks(SceneAPI callbacks) { if(this.callbacks!=null) { lastSceneAsString = this.callbacks.toString(); } this.loadingPresenter.setName(callbacks.toString()); this.callbacks = callbacks; } public MasterPresenter getHeaderPanel() { return this; } @Override public boolean addImageForAnInventoryItem(LoadHandler lh, String objectTextualId, int objectCode, PackagedImageAPI imageResource) { if (this.callbacks == null) { return true; } InventoryItem item = this.inventoryPresenter.getInventory().items().at( objectTextualId); boolean result = true; if (item == null) { Image imageAndPos = inventoryPresenter.getView().createNewImageAndAdddHandlers( imageResource,lh, bus, objectTextualId, objectCode, 0,0); imageAndPos.addImageToPanel( 0 ); boolean initiallyVisible = false; result = inventoryPresenter.addInventory( objectTextualId , objectCode , initiallyVisible , imageAndPos ); } return result; } @Override public boolean addImageForASceneObject(LoadHandler lh, int numberPrefix, int x, int y, int w, int h, String objectTextualId, String animationTextualId, short objectCode, String objPlusAnimCode, PackagedImageAPI imageResource) { if (this.callbacks == null) { return true; } Image imageAndPos = this.scenePresenter.getView().createNewImageAndAddHandlers(lh, imageResource, this, bus, x,y, objectTextualId, objectCode); loadingPresenter.getLoaders().addToAppropriateAnimation(numberPrefix, imageAndPos, objectTextualId, animationTextualId, objectCode, objPlusAnimCode, scenePresenter.getWidth(), scenePresenter.getHeight()); int before = getIndexToInsertAt(numberPrefix); updateTheListOfIndexesToInsertAt(numberPrefix); // this triggers the loading imageAndPos.addImageToPanel( before ); return true; } @Override public SceneObject getObject(short code) { theObjectMap.size(); SceneObject ob = this.theObjectMap.get( code); if (ob == null) { ob = null; } return ob; } @Override public Animation getAnimation(String code) { Animation anim = this.theAnimationMap.get( code); if (anim == null) { // first param is name, second is parent; anim = new Animation("", null); this.theAnimationMap.put(code, anim); } return anim; } @Override public InventoryItem getInventoryItem(int i) { InventoryItem inv = inventoryPresenter.getInventoryItem( i); return inv; } public int getIndexToInsertAt(int numberPrefix) { int i = theListOfIndexesToInsertAt[numberPrefix]; return i; } void updateTheListOfIndexesToInsertAt(int numberPrefix) { for(int i=numberPrefix;i<=99;i++) { theListOfIndexesToInsertAt[i]++; } } @Override public void executeActionWithDialogActionRunner(BaseAction a) { if(a==null) { a = new DoNothingAction(createChainRootAction()); } dialogActionRunner.runAction(a); } @Override public void executeActionWithDoCommandActionRunner(BaseAction a) { if(a==null) { a = new DoNothingAction(createChainRootAction()); } doCommandActionRunner.runAction(a); } public void skip() { dialogActionRunner.skip(); } public void decrementTextSpeed() { textSpeedDelay++; } public void incrementTextSpeed() { textSpeedDelay--; } public void setInitialAnimationsAsCurrent() { int count = this.scenePresenter.getModel().objectCollection().count(); for (int i = 0; i<count; i++) { SceneObject sceneObject = this.scenePresenter.getModel().objectCollection().at(i); if (sceneObject != null) { String initial = sceneObject.getInitialAnimation(); if (sceneObject.getAnimations().at(initial)!=null) { sceneObject.getAnimations().at(initial).setAsCurrentAnimation(); // set x & y to zero sets the base middles // to the positions they were in when all objects were rendered out. sceneObject.setX(0); sceneObject.setY(0); } else { boolean b = true; b = (b) ? true : false; } } } } public void callOnPreEntry() { this.callbacks.onPreEntry(this); } @Override public void onTimer() { int size = this.theObjectMap.size(); if(size==0) { System.out.println("sIZE WAS ZERO"); } if(timer!=null) { this.callbacks.onEveryFrame(this); } if(switchTimer!=null) { switchTimer.cancel(); switchTimer = null; setCameraToZero();// no scene is meant to keep camera position this.parent.instantiateSceneAndCallSetSceneBackOnTheMasterPresenter(switchDestination); switchDestination = ""; } } public void loadInventoryFromAPI() { inventoryPresenter.updateInventory(); } public void saveInventoryToAPI() { InventoryItemCollection items = this.inventoryPresenter.getInventory().items(); for (int i = 0; i < items.getCount(); i++) { String name = items.at(i).getTextualId(); int isCarrying = items.at(i).isVisible() ? 1 : 0; setValue( "CARRYING_" + name.toUpperCase(), isCarrying); } } @Override public void setValue(Object key, int value) { String keyAsString = key.toString(); parent.setValue(keyAsString, value); } @Override public int getValue(Object key) { String keyAsString = key.toString(); int i = parent.getValue(keyAsString); return i; } @Override public boolean isTrue(Object key) { String keyAsString = key.toString(); int property = getValue(keyAsString); return property != 0; } @Override public void switchToSceneFromAction(String scene) { cancelOnEveryFrameTimer(); this.dialogActionRunner.cancel(); //now wait for last on every frame to execute //.. which is about 40 milliseconds //(an on every frame can go more than // this, but usually not). switchTimer = getFactory().createSystemTimer(this); switchDestination = scene; switchTimer.scheduleRepeating(40); } @Override public void switchToScene(String scene) { // since instantiateScene..ToIt does some asynchronous stuff, // I thought maybe I could do it, then cancel the timers. // but I've put it off til I need the microseconds. cancelOnEveryFrameTimer(); this.dialogActionRunner.cancel(); setCameraToZero();// no scene is meant to keep camera position this.parent.instantiateSceneAndCallSetSceneBackOnTheMasterPresenter(scene); } @Override public String getLastScene() { return lastSceneAsString; } @Override public boolean isInDebugMode() { return true; } public void startCallingOnEveryFrame() { timer = getFactory().createSystemTimer(this); timer.scheduleRepeating(40); } public void cancelOnEveryFrameTimer() { if(this.timer!=null) { this.timer.cancel(); timer = null; } } @Override public void setLastCommand(double x, double y, int v, String a, String b) { parent.setLastCommand(x, y, v, a, b); } public void setCommandLineGui(CommandLinePresenter commandLinePanel) { this.commandLinePresenter = commandLinePanel; } @Override public CommandLinePresenter getCommandLineGui() { return commandLinePresenter; } @Override public InventoryPresenter getInventoryGui() { return inventoryPresenter; } public Inventory getInventory() { return inventoryPresenter.getInventory(); } @Override public SceneAPI getCurrentScene() { return this.callbacks; } @Override public void executeBranchOnCurrentScene(int branchId) { this.dialogActionRunner.cancel(); // clear it so any old branches don't show up this.dialogTreePresenter.clear(); // make dialogtreepanel active if not already this.setDialogTreeActive(true); // get the chain from the client code BaseDialogTreeAction actionChain = this.callbacks.onDialogTree(this, createChainRootAction(), branchId); // execute it executeActionWithDialogActionRunner( actionChain ); } public void saySpeechAndThenExecuteBranchWithBranchId(String speech, int branchId) { this.dialogTreePresenter.clear(); String animId = getDialogTreeGui().getDialogTreeTalkAnimation(); // This is a bit sneaky: // 1. we construct a BaseAction that sas the speech // 2. we pass this to onDialogTree // 3. where the user appends other actions to it // 4. Then we execute it // Thus it will say the text, and do what the user prescribes. SayAction say = new SayAction(createChainRootAction(), animId, speech); BaseDialogTreeAction actionChain = callbacks.onDialogTree(this, say, branchId); executeActionWithDialogActionRunner(actionChain); } public void callOnEnterScene() { BaseAction a = this.callbacks.onEntry(this,createChainRootAction()); //.. then executeBaseAction->actionRunner::runAction will add an TitleCardAction // the title card executeActionWithDoCommandActionRunner(a); } @Override public VerbsPresenter getVerbsGui() { return this.verbsPresenter; } @Override public DialogTreePresenter getDialogTreeGui() { return this.dialogTreePresenter; } @Override public ScenePresenter getSceneGui() { return this.scenePresenter; } @Override public void onSaySpeechCallBranch(String speech, int branchId) { saySpeechAndThenExecuteBranchWithBranchId(speech, branchId); } public MasterPanelAPI getMasterPanel() { return masterPanel; } void setCameraToZero() { scenePresenter.setCameraX(0); scenePresenter.setCameraY(0); } @Override public void startScene() { masterPanel.setActiveState(MasterPanelAPI.GuiStateEnum.Loading); loadInventoryFromAPI(); setInitialAnimationsAsCurrent(); //setAllObjectsToVisible(); // it is reasonable for a person to set current animations in pre-entry // and expect them to stay current, so we set cuurentAnimations before pre-entry. callOnPreEntry(); startCallingOnEveryFrame(); this.masterPanel.setActiveState(MasterPanelAPI.GuiStateEnum.TitleCardOverOnEnterScene); callOnEnterScene(); } @Override public void addEssential(LoadAPI blah) { loadingPresenter.getLoaders().addEssential(blah, this); } @Override public void kickStartLoading() { loadingPresenter.getLoaders().calculateImagesToLoadAndOmitInventoryIfSame(); int total = loadingPresenter.getLoaders().imagesToLoad(); boolean isSameInventory = loadingPresenter.getLoaders().isSameInventoryAsLastTime(); // hide all visible images. // (using scene's data is quicker than using scenePanel data) for(int i=0;i<scenePresenter.getModel().objectCollection().count();i++) { scenePresenter.getModel().objectCollection().at(i).setVisible(false); } theObjectMap.clear(); theAnimationMap.clear(); this.theObjectMap.clear(); this.theAnimationMap.clear(); scenePresenter.reset(); // set gui to blank masterPanel.setActiveState(MasterPanelAPI.GuiStateEnum.Loading); //scenePresenter.clear(); don't clear, all its images are switched off anyhow. loadingPresenter.clear(); //commandLinePresenter.clear(); verbsPresenter.clear(); if(!isSameInventory) { inventoryPresenter.clear(); } loadingPresenter.setTotal(total); loadingPresenter.getLoaders().loadNext(); } @Override public void setScenePixelSize(int width, int height) { this.scenePresenter.setPixelSize(width, height); this.titleCardPresenter.setPixelSize(width, height); this.loadingPresenter.setPixelSize(width, height); this.dialogTreePresenter.setPixelSize(width, height>>1); this.verbsPresenter.setWidthOfScene(width); } @Override public int getPopupDelay() { return textSpeedDelay; } public void setScene(SceneAPI scene) { setCallbacks(scene); this.callbacks.onFillLoadList(new OnFillLoadListAPIImpl(this)); } @Override public void restartReloading() { loadingPresenter.getLoaders().clearLoaders(); this.callbacks.onFillLoadList(new OnFillLoadListAPIImpl(this)); } @Override public void mergeWithScene(LoadedLoad s) { String name = s.getName(); logger.fine(name); System.out.println("dumping " + name); SceneObjectCollection theirs = s.getSceneObjectCollection(); SceneObjectCollection ours = this.scenePresenter.getModel().objectCollection(); for(int i=0;i<theirs.count();i++) { SceneObject srcObject = theirs.at(i); String objTextualId = srcObject.getTextualId(); int prefix = srcObject.getNumberPrefix(); short objectCode = srcObject.getCode(); SceneObject destObject = ours.at(objTextualId); if(destObject==null) { destObject = new SceneObject(objTextualId, scenePresenter.getWidth(), scenePresenter.getHeight()); destObject.setNumberPrefix(prefix); destObject.setCode(objectCode); if (objectCode == -1) { parent.alert( "Missing initial image for " + objTextualId - + " "); + + "\n At the least it will need an image in a placeholder folder, so it shows up in list of objects."); return; } ours.add(destObject); this.theObjectMap.put(objectCode,destObject); System.out.println("object " + objTextualId + " " + objectCode); } for(int j=0;j<srcObject.getAnimations().getCount();j++) { Animation srcAnimation = srcObject.getAnimations().at(j); String animTextualId = srcAnimation.getTextualId(); Animation destAnimation = destObject.getAnimations().at(animTextualId); if(destAnimation==null) { destAnimation = new Animation(animTextualId, destObject); destObject.getAnimations().add(destAnimation); this.theAnimationMap.put(animTextualId, destAnimation); } //System.out.println("new anim " + objTextualId + " " + animTextualId+" = "+animationCode); for(int k=0;k<srcAnimation.getFrames().getCount();k++) { Image srcImage = srcAnimation.getFrames().at(k); destAnimation.getFrames().add(srcImage); } } } } MasterPanelAPI.GuiStateEnum getStateIfEntering(MasterPanelAPI.GuiStateEnum state) { switch(state) { case OnEnterScene: return MasterPanelAPI.GuiStateEnum.TitleCardOverOnEnterScene; case DialogTree:return MasterPanelAPI.GuiStateEnum.TitleCardOverDialogTree; case CutScene:return MasterPanelAPI.GuiStateEnum.TitleCardOverCutScene; case ActiveScene:return MasterPanelAPI.GuiStateEnum.TitleCardOverActiveScene; case Loading:return MasterPanelAPI.GuiStateEnum.TitleCardOverLoading; default: return state; } } MasterPanelAPI.GuiStateEnum getStateIfExiting(MasterPanelAPI.GuiStateEnum state) { switch(state) { case TitleCardOverOnEnterScene:return MasterPanelAPI.GuiStateEnum.OnEnterScene; case TitleCardOverDialogTree: return MasterPanelAPI.GuiStateEnum.DialogTree; case TitleCardOverCutScene: return MasterPanelAPI.GuiStateEnum.CutScene; case TitleCardOverActiveScene: return MasterPanelAPI.GuiStateEnum.ActiveScene; case TitleCardOverLoading: return MasterPanelAPI.GuiStateEnum.Loading; default: return state; } } @Override public void displayTitleCard(String text) { boolean isEntering = text.length()>0; if(isEntering) { titleCardPresenter.setText(text); } MasterPanelAPI.GuiStateEnum state = masterPanel.getActiveState(); state = isEntering? getStateIfEntering(state) : getStateIfExiting(state); masterPanel.setActiveState(state); } @Override public void incrementProgress() { loadingPresenter.incrementProgress(); } @Override public MasterPresenterHostAPI getMasterHostAPI() { return parent; } @Override public FactoryAPI getFactory() { return parent.getFactory(bus, this); } @Override public void doCommand(int verbAsCode, int verbAsVerbEnumeration, SentenceItem sentenceA, SentenceItem sentenceB, double x, double y) { BaseAction a = this.callbacks.onDoCommand( this, createChainRootAction(), verbAsCode, sentenceA, sentenceB, x+scenePresenter.getCameraX(), y+scenePresenter.getCameraY()); this.commandLinePresenter.setMouseable(false); executeActionWithDoCommandActionRunner(a); setLastCommand(x, y, verbAsVerbEnumeration, sentenceA.getTextualId(), sentenceB.getTextualId()); } @Override public void actionFinished(int id) { this.commandLinePresenter.clear(); this.commandLinePresenter.setMouseable(true); if(masterPanel.getActiveState() == MasterPanelAPI.GuiStateEnum.OnEnterScene) { this.masterPanel.setActiveState(MasterPanelAPI.GuiStateEnum.ActiveScene); } } @Override public void setInventoryPixelSize(int width, int height) { this.inventoryPresenter.setSizeOfSingleInventoryImage(width,height); this.verbsPresenter.setWidthOfInventory(inventoryPresenter.getWidth()); } @Override public void onClickVerbsOrInventory() { // a click on the inventory results in negative coords. commandLinePresenter.onClick(-1, -1); } @Override public void onMouseOverVerbsOrInventory (String displayName, String textualId, int code) { getCommandLineGui().onSetMouseOver(displayName, textualId, code); bus.fireEvent( new SetRolloverEvent( displayName, textualId, code)); } @Override public void onPropertyChange(PropertyChangeEvent inventoryEvent) { this.inventoryPresenter.updateInventory(); } @Override public SceneAPI getSceneByName(String string) { return this.parent.getSceneViaCache(string); } @Override public void setDialogTreeActive(boolean isInDialogTreeMode) { if(isInDialogTreeMode) { this.masterPanel.setActiveState(MasterPanelAPI.GuiStateEnum.DialogTree); } else { this.masterPanel.setActiveState(MasterPanelAPI.GuiStateEnum.ActiveScene); } } @Override public boolean isCommandLineActive() { boolean isCommandLineActive = masterPanel.getActiveState()==MasterPanelAPI.GuiStateEnum.ActiveScene; return isCommandLineActive; } @Override public void clearAllLoadedLoads() { this.loadingPresenter.clearAllLoadedLoads(); } @Override public void setActiveState(GuiStateEnum state) { this.masterPanel.setActiveState(state); } @Override public ChainRootAction createChainRootAction() { ChainRootAction npa = new ChainRootAction(this); return npa; } @Override public void executeChainedAction(ChainedAction ba) { executeActionWithDoCommandActionRunner(ba); } @Override public void setDefaultSayAnimation(String sayAnimation) { this.defaultSayAnimation = sayAnimation; } @Override public void setDefaultWalker(short object) { this.defaultWalker = object; } @Override public String getDefaultSayAnimation() { return this.defaultSayAnimation; } @Override public short getDefaultWalker() { return this.defaultWalker; } @Override public void setStateOfPopup(boolean visible, double x, double y, ColorEnum talkingColor, String speech,BaseAction ba) { if(talkingColor==null) { talkingColor = ColorEnum.Red; } if(!visible) { if(this.speechPopup!=null) { this.speechPopup.setVisible(false); this.speechPopup = null; } return; } if(speechPopup==null) { this.speechPopup = getFactory().createPopupPanel(this, scenePresenter.getWidth(), scenePresenter.getHeight()); } speechPopup.setColor(talkingColor); speechPopup.setText(speech); if(ba!=null) speechPopup.setCancelCallback(ba); speechPopup.setPopupPosition(x, y); speechPopup.setVisible(true); } @Override public void clickToContinue() { // TODO Auto-generated method stub } @Override public void enableClickToContinue() { this.loadingPresenter.enableClickToContinue(); } }
true
true
public void mergeWithScene(LoadedLoad s) { String name = s.getName(); logger.fine(name); System.out.println("dumping " + name); SceneObjectCollection theirs = s.getSceneObjectCollection(); SceneObjectCollection ours = this.scenePresenter.getModel().objectCollection(); for(int i=0;i<theirs.count();i++) { SceneObject srcObject = theirs.at(i); String objTextualId = srcObject.getTextualId(); int prefix = srcObject.getNumberPrefix(); short objectCode = srcObject.getCode(); SceneObject destObject = ours.at(objTextualId); if(destObject==null) { destObject = new SceneObject(objTextualId, scenePresenter.getWidth(), scenePresenter.getHeight()); destObject.setNumberPrefix(prefix); destObject.setCode(objectCode); if (objectCode == -1) { parent.alert( "Missing initial image for " + objTextualId + " "); return; } ours.add(destObject); this.theObjectMap.put(objectCode,destObject); System.out.println("object " + objTextualId + " " + objectCode); } for(int j=0;j<srcObject.getAnimations().getCount();j++) { Animation srcAnimation = srcObject.getAnimations().at(j); String animTextualId = srcAnimation.getTextualId(); Animation destAnimation = destObject.getAnimations().at(animTextualId); if(destAnimation==null) { destAnimation = new Animation(animTextualId, destObject); destObject.getAnimations().add(destAnimation); this.theAnimationMap.put(animTextualId, destAnimation); } //System.out.println("new anim " + objTextualId + " " + animTextualId+" = "+animationCode); for(int k=0;k<srcAnimation.getFrames().getCount();k++) { Image srcImage = srcAnimation.getFrames().at(k); destAnimation.getFrames().add(srcImage); } } } }
public void mergeWithScene(LoadedLoad s) { String name = s.getName(); logger.fine(name); System.out.println("dumping " + name); SceneObjectCollection theirs = s.getSceneObjectCollection(); SceneObjectCollection ours = this.scenePresenter.getModel().objectCollection(); for(int i=0;i<theirs.count();i++) { SceneObject srcObject = theirs.at(i); String objTextualId = srcObject.getTextualId(); int prefix = srcObject.getNumberPrefix(); short objectCode = srcObject.getCode(); SceneObject destObject = ours.at(objTextualId); if(destObject==null) { destObject = new SceneObject(objTextualId, scenePresenter.getWidth(), scenePresenter.getHeight()); destObject.setNumberPrefix(prefix); destObject.setCode(objectCode); if (objectCode == -1) { parent.alert( "Missing initial image for " + objTextualId + "\n At the least it will need an image in a placeholder folder, so it shows up in list of objects."); return; } ours.add(destObject); this.theObjectMap.put(objectCode,destObject); System.out.println("object " + objTextualId + " " + objectCode); } for(int j=0;j<srcObject.getAnimations().getCount();j++) { Animation srcAnimation = srcObject.getAnimations().at(j); String animTextualId = srcAnimation.getTextualId(); Animation destAnimation = destObject.getAnimations().at(animTextualId); if(destAnimation==null) { destAnimation = new Animation(animTextualId, destObject); destObject.getAnimations().add(destAnimation); this.theAnimationMap.put(animTextualId, destAnimation); } //System.out.println("new anim " + objTextualId + " " + animTextualId+" = "+animationCode); for(int k=0;k<srcAnimation.getFrames().getCount();k++) { Image srcImage = srcAnimation.getFrames().at(k); destAnimation.getFrames().add(srcImage); } } } }
diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/RepositoryManipulationPage.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/RepositoryManipulationPage.java index 8fc6a67c8..28f3d879f 100644 --- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/RepositoryManipulationPage.java +++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/dialogs/RepositoryManipulationPage.java @@ -1,912 +1,912 @@ /******************************************************************************* * Copyright (c) 2007, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.equinox.internal.provisional.p2.ui.dialogs; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.util.ArrayList; import java.util.Hashtable; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.ui.*; import org.eclipse.equinox.internal.p2.ui.dialogs.*; import org.eclipse.equinox.internal.p2.ui.model.ElementUtils; import org.eclipse.equinox.internal.p2.ui.model.MetadataRepositoryElement; import org.eclipse.equinox.internal.p2.ui.viewers.MetadataRepositoryElementComparator; import org.eclipse.equinox.internal.p2.ui.viewers.RepositoryDetailsLabelProvider; import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent; import org.eclipse.equinox.internal.provisional.p2.ui.*; import org.eclipse.equinox.internal.provisional.p2.ui.model.MetadataRepositories; import org.eclipse.equinox.internal.provisional.p2.ui.operations.*; import org.eclipse.equinox.internal.provisional.p2.ui.policy.*; import org.eclipse.equinox.internal.provisional.p2.ui.viewers.*; import org.eclipse.jface.dialogs.*; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.jface.viewers.*; import org.eclipse.jface.window.Window; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.accessibility.AccessibleAdapter; import org.eclipse.swt.accessibility.AccessibleEvent; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.dnd.*; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.*; import org.eclipse.ui.*; import org.eclipse.ui.dialogs.PatternFilter; import org.eclipse.ui.progress.IElementCollector; import org.eclipse.ui.progress.WorkbenchJob; import org.eclipse.ui.statushandlers.StatusManager; /** * Page that allows users to update, add, remove, import, and * export repositories. This page can be hosted inside a preference * dialog or inside its own dialog. When hosting this page inside * a non-preference dialog, some of the dialog methods will likely * have to call page methods. The following snippet shows how to host * this page inside a TitleAreaDialog. * <pre> * TitleAreaDialog dialog = new TitleAreaDialog(shell) { * * RepositoryManipulationPage page; * * protected Control createDialogArea(Composite parent) { * page = new RepositoryManipulationPage(policy); * page.createControl(parent); * this.setTitle("Software Sites"); * this.setMessage("The enabled sites will be searched for software. Disabled sites are ignored.); * return page.getControl(); * } * * protected void okPressed() { * if (page.performOk()) * super.okPressed(); * } * * protected void cancelPressed() { * if (page.performCancel()) * super.cancelPressed(); * } * }; * dialog.open(); * </pre> * * @since 3.5 */ public class RepositoryManipulationPage extends PreferencePage implements IWorkbenchPreferencePage, ICopyable { final static String DEFAULT_FILTER_TEXT = ProvUIMessages.RepositoryManipulationPage_DefaultFilterString; private final static int FILTER_DELAY = 200; StructuredViewerProvisioningListener listener; TableViewer repositoryViewer; Table table; Policy policy; Display display; boolean changed = false; MetadataRepositoryElementComparator comparator; RepositoryDetailsLabelProvider labelProvider; RepositoryManipulator manipulator; RepositoryManipulator localCacheRepoManipulator; CachedMetadataRepositories input; Text pattern, details; PatternFilter filter; WorkbenchJob filterJob; Button addButton, removeButton, editButton, refreshButton, disableButton, exportButton; class CachedMetadataRepositories extends MetadataRepositories { Hashtable cachedElements; CachedMetadataRepositories() { super(policy); setIncludeDisabledRepositories(manipulator != null); } public int getQueryType() { return QueryProvider.METADATA_REPOS; } public void fetchDeferredChildren(Object o, IElementCollector collector, IProgressMonitor monitor) { if (cachedElements == null) { super.fetchDeferredChildren(o, collector, monitor); // now we know we have children Object[] children = getChildren(o); cachedElements = new Hashtable(children.length); for (int i = 0; i < children.length; i++) { if (children[i] instanceof MetadataRepositoryElement) cachedElements.put(URIUtil.toUnencodedString(((MetadataRepositoryElement) children[i]).getLocation()), children[i]); } return; } // Use the cache rather than fetching children collector.add(cachedElements.values().toArray(), monitor); } } class MetadataRepositoryPatternFilter extends PatternFilter { MetadataRepositoryPatternFilter() { setIncludeLeadingWildcard(true); } public boolean isElementVisible(Viewer viewer, Object element) { if (element instanceof MetadataRepositoryElement) { return wordMatches(labelProvider.getColumnText(element, RepositoryDetailsLabelProvider.COL_NAME) + " " + labelProvider.getColumnText(element, RepositoryDetailsLabelProvider.COL_LOCATION)); //$NON-NLS-1$ } return false; } } /** * This method must be called before the contents are created. * @param policy */ public void setPolicy(Policy policy) { this.policy = policy; manipulator = policy.getRepositoryManipulator(); } protected Control createContents(Composite parent) { display = parent.getDisplay(); // The help refers to the full-blown dialog. No help if it's read only. if (manipulator != null) PlatformUI.getWorkbench().getHelpSystem().setHelp(parent.getShell(), IProvHelpContextIds.REPOSITORY_MANIPULATION_DIALOG); Composite composite = new Composite(parent, SWT.NONE); GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); composite.setLayoutData(gd); GridLayout layout = new GridLayout(); layout.numColumns = manipulator == null ? 1 : 2; layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); composite.setLayout(layout); // Filter box pattern = new Text(composite, SWT.SINGLE | SWT.BORDER | SWT.SEARCH | SWT.CANCEL); pattern.getAccessible().addAccessibleListener(new AccessibleAdapter() { public void getName(AccessibleEvent e) { e.result = DEFAULT_FILTER_TEXT; } }); pattern.setText(DEFAULT_FILTER_TEXT); pattern.selectAll(); pattern.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { applyFilter(); } }); pattern.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.keyCode == SWT.ARROW_DOWN) { if (table.getItemCount() > 0) { table.setFocus(); } else if (e.character == SWT.CR) { return; } } } }); pattern.addFocusListener(new FocusAdapter() { public void focusGained(FocusEvent e) { display.asyncExec(new Runnable() { public void run() { if (!pattern.isDisposed()) { if (DEFAULT_FILTER_TEXT.equals(pattern.getText().trim())) { pattern.selectAll(); } } } }); } }); gd = new GridData(SWT.FILL, SWT.FILL, true, false); pattern.setLayoutData(gd); // spacer to fill other column if (manipulator != null) new Label(composite, SWT.NONE); // Table of available repositories repositoryViewer = new TableViewer(composite, SWT.MULTI | SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); table = repositoryViewer.getTable(); // Key listener for delete table.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.keyCode == SWT.DEL) { removeRepositories(); } } }); setTableColumns(); CopyUtils.activateCopy(this, table); repositoryViewer.setComparer(new ProvElementComparer()); comparator = new MetadataRepositoryElementComparator(RepositoryDetailsLabelProvider.COL_NAME); repositoryViewer.setComparator(comparator); filter = new MetadataRepositoryPatternFilter(); repositoryViewer.setFilters(new ViewerFilter[] {filter}); // We don't need a deferred content provider because we are caching local results before // actually querying repositoryViewer.setContentProvider(new ProvElementContentProvider()); labelProvider = new RepositoryDetailsLabelProvider(); repositoryViewer.setLabelProvider(labelProvider); // Edit the nickname repositoryViewer.setCellModifier(new ICellModifier() { public boolean canModify(Object element, String property) { - return true; + return element instanceof MetadataRepositoryElement; } public Object getValue(Object element, String property) { return ((MetadataRepositoryElement) element).getName(); } public void modify(Object element, String property, Object value) { if (value != null && value.toString().length() >= 0) { MetadataRepositoryElement repo; if (element instanceof Item) { repo = (MetadataRepositoryElement) ((Item) element).getData(); } else if (element instanceof MetadataRepositoryElement) { repo = (MetadataRepositoryElement) element; } else { return; } changed = true; repo.setNickname(value.toString()); if (comparator.getSortKey() == RepositoryDetailsLabelProvider.COL_NAME) repositoryViewer.refresh(true); else repositoryViewer.update(repo, null); } } }); repositoryViewer.setColumnProperties(new String[] {"nickname"}); //$NON-NLS-1$ repositoryViewer.setCellEditors(new CellEditor[] {new TextCellEditor(repositoryViewer.getTable())}); repositoryViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { if (manipulator != null) validateButtons(); setDetails(); } }); // Input last repositoryViewer.setInput(getInput()); GridData data = new GridData(SWT.FILL, SWT.FILL, true, true); data.widthHint = convertWidthInCharsToPixels(ILayoutConstants.DEFAULT_TABLE_WIDTH); data.heightHint = convertHeightInCharsToPixels(ILayoutConstants.DEFAULT_TABLE_HEIGHT); table.setLayoutData(data); // Drop targets and vertical buttons only if repository manipulation is provided. if (manipulator != null) { DropTarget target = new DropTarget(table, DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK); target.setTransfer(new Transfer[] {URLTransfer.getInstance(), FileTransfer.getInstance()}); target.addDropListener(new RepositoryManipulatorDropTarget(getRepositoryManipulator(), table)); // Vertical buttons Composite verticalButtonBar = createVerticalButtonBar(composite); data = new GridData(SWT.FILL, SWT.FILL, false, false); data.verticalAlignment = SWT.TOP; data.verticalIndent = 0; verticalButtonBar.setLayoutData(data); listener = getViewerProvisioningListener(); ProvUI.addProvisioningListener(listener); composite.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent event) { ProvUI.removeProvisioningListener(listener); } }); validateButtons(); } // Details area details = new Text(composite, SWT.READ_ONLY | SWT.WRAP); data = new GridData(SWT.FILL, SWT.FILL, true, false); data.heightHint = convertHeightInCharsToPixels(ILayoutConstants.DEFAULT_SITEDETAILS_HEIGHT); details.setLayoutData(data); Dialog.applyDialogFont(composite); return composite; } private Button createVerticalButton(Composite parent, String label, boolean defaultButton) { Button button = new Button(parent, SWT.PUSH); button.setText(label); GridData data = setVerticalButtonLayoutData(button); data.horizontalAlignment = GridData.FILL; button.setToolTipText(label); if (defaultButton) { Shell shell = parent.getShell(); if (shell != null) { shell.setDefaultButton(button); } } return button; } private GridData setVerticalButtonLayoutData(Button button) { GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); int widthHint = convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH); Point minSize = button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true); data.widthHint = Math.max(widthHint, minSize.x); button.setLayoutData(data); return data; } private void setTableColumns() { table.setHeaderVisible(true); String[] columnHeaders; if (manipulator != null) columnHeaders = new String[] {ProvUIMessages.RepositoryManipulationPage_NameColumnTitle, ProvUIMessages.RepositoryManipulationPage_LocationColumnTitle, ProvUIMessages.RepositoryManipulationPage_EnabledColumnTitle}; else columnHeaders = new String[] {ProvUIMessages.RepositoryManipulationPage_NameColumnTitle, ProvUIMessages.RepositoryManipulationPage_LocationColumnTitle}; for (int i = 0; i < columnHeaders.length; i++) { TableColumn tc = new TableColumn(table, SWT.NONE, i); tc.setResizable(true); tc.setText(columnHeaders[i]); if (i == RepositoryDetailsLabelProvider.COL_ENABLEMENT) { tc.setWidth(convertWidthInCharsToPixels(ILayoutConstants.DEFAULT_SMALL_COLUMN_WIDTH)); tc.setAlignment(SWT.CENTER); } else if (i == RepositoryDetailsLabelProvider.COL_NAME) { tc.setWidth(convertWidthInCharsToPixels(ILayoutConstants.DEFAULT_COLUMN_WIDTH)); } else { tc.setWidth(convertWidthInCharsToPixels(ILayoutConstants.DEFAULT_PRIMARY_COLUMN_WIDTH)); } tc.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { columnSelected((TableColumn) e.widget); } public void widgetSelected(SelectionEvent e) { columnSelected((TableColumn) e.widget); } }); // First column only if (i == 0) { table.setSortColumn(tc); table.setSortDirection(SWT.UP); } } } private Composite createVerticalButtonBar(Composite parent) { // Create composite. Composite composite = new Composite(parent, SWT.NONE); initializeDialogUnits(composite); // create a layout with spacing and margins appropriate for the font // size. GridLayout layout = new GridLayout(); layout.numColumns = 1; layout.marginWidth = 5; layout.marginHeight = 0; layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); composite.setLayout(layout); createVerticalButtons(composite); return composite; } private void createVerticalButtons(Composite parent) { addButton = createVerticalButton(parent, ProvUIMessages.RepositoryManipulationPage_Add, false); addButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { addRepository(); } }); editButton = createVerticalButton(parent, ProvUIMessages.RepositoryManipulationPage_Edit, false); editButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { changeRepositoryProperties(); } }); removeButton = createVerticalButton(parent, ProvUIMessages.RepositoryManipulationPage_Remove, false); removeButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { removeRepositories(); } }); refreshButton = createVerticalButton(parent, ProvUIMessages.RepositoryManipulationPage_RefreshConnection, false); refreshButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { refreshRepository(); } }); disableButton = createVerticalButton(parent, ProvUIMessages.RepositoryManipulationPage_DisableButton, false); disableButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { toggleRepositoryEnablement(); } }); Button button = createVerticalButton(parent, ProvUIMessages.RepositoryManipulationPage_Import, false); button.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { importRepositories(); } }); exportButton = createVerticalButton(parent, ProvUIMessages.RepositoryManipulationPage_Export, false); exportButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { exportRepositories(); } }); } CachedMetadataRepositories getInput() { if (input == null) input = new CachedMetadataRepositories(); return input; } public boolean performOk() { if (changed) ElementUtils.updateRepositoryUsingElements(getElements(), getShell()); return super.performOk(); } private StructuredViewerProvisioningListener getViewerProvisioningListener() { return new StructuredViewerProvisioningListener(repositoryViewer, ProvUIProvisioningListener.PROV_EVENT_METADATA_REPOSITORY) { protected void repositoryDiscovered(RepositoryEvent e) { RepositoryManipulationPage.this.asyncRefresh(null); } protected void repositoryChanged(RepositoryEvent e) { RepositoryManipulationPage.this.asyncRefresh(null); } }; } MetadataRepositoryElement[] getElements() { return (MetadataRepositoryElement[]) getInput().cachedElements.values().toArray(new MetadataRepositoryElement[getInput().cachedElements.size()]); } MetadataRepositoryElement[] getSelectedElements() { Object[] items = ((IStructuredSelection) repositoryViewer.getSelection()).toArray(); ArrayList list = new ArrayList(items.length); for (int i = 0; i < items.length; i++) { if (items[i] instanceof MetadataRepositoryElement) list.add(items[i]); } return (MetadataRepositoryElement[]) list.toArray(new MetadataRepositoryElement[list.size()]); } void validateButtons() { MetadataRepositoryElement[] elements = getSelectedElements(); exportButton.setEnabled(elements.length > 0); removeButton.setEnabled(elements.length > 0); editButton.setEnabled(elements.length == 1); refreshButton.setEnabled(elements.length == 1); if (elements.length >= 1) { if (toggleMeansDisable(elements)) disableButton.setText(ProvUIMessages.RepositoryManipulationPage_DisableButton); else disableButton.setText(ProvUIMessages.RepositoryManipulationPage_EnableButton); disableButton.setEnabled(true); } else { disableButton.setText(ProvUIMessages.RepositoryManipulationPage_EnableButton); disableButton.setEnabled(false); } } void addRepository() { AddRepositoryDialog dialog = new AddRepositoryDialog(getShell(), policy) { protected RepositoryManipulator getRepositoryManipulator() { return RepositoryManipulationPage.this.getRepositoryManipulator(); } }; dialog.setTitle(manipulator.getAddOperationLabel()); dialog.open(); } void refreshRepository() { final MetadataRepositoryElement[] selected = getSelectedElements(); final ProvisionException[] fail = new ProvisionException[1]; final boolean[] remove = new boolean[1]; remove[0] = false; if (selected.length != 1) return; final URI location = selected[0].getLocation(); ProgressMonitorDialog dialog = new ProgressMonitorDialog(getShell()); try { dialog.run(true, true, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) { SubMonitor mon = SubMonitor.convert(monitor, NLS.bind(ProvUIMessages.RepositoryManipulationPage_ContactingSiteMessage, location), 300); try { ProvUI.clearRepositoryNotFound(location); // If the manager doesn't know this repo, refreshing it will not work. // We temporarily add it, but we must remove it in case the user cancels out of this page. if (!includesRepo(manipulator.getKnownRepositories(), location)) { // Start a batch operation so we can swallow events ProvUI.startBatchOperation(); AddRepositoryOperation op = manipulator.getAddOperation(location); op.setNotify(false); op.execute(mon.newChild(100)); remove[0] = true; } ProvisioningUtil.refreshArtifactRepositories(new URI[] {location}, mon.newChild(100)); ProvisioningUtil.refreshMetadataRepositories(new URI[] {location}, mon.newChild(100)); } catch (ProvisionException e) { // Need to report after dialog is closed or the error dialog will disappear when progress // disappears fail[0] = e; } catch (OperationCanceledException e) { // Catch canceled login attempts fail[0] = new ProvisionException(new Status(IStatus.CANCEL, ProvUIActivator.PLUGIN_ID, ProvUIMessages.RepositoryManipulationPage_RefreshOperationCanceled, e)); } finally { // Check if the monitor was canceled if (fail[0] == null && mon.isCanceled()) fail[0] = new ProvisionException(new Status(IStatus.CANCEL, ProvUIActivator.PLUGIN_ID, ProvUIMessages.RepositoryManipulationPage_RefreshOperationCanceled)); // If we temporarily added a repo so we could read it, remove it. if (remove[0]) { RemoveRepositoryOperation op = manipulator.getRemoveOperation(new URI[] {location}); op.setNotify(false); try { op.execute(new NullProgressMonitor()); } catch (ProvisionException e) { // Don't report } // stop swallowing events ProvUI.endBatchOperation(false); } } } }); } catch (InvocationTargetException e) { // nothing to report } catch (InterruptedException e) { // nothing to report } if (fail[0] != null) { // If the repo was not found, tell ProvUI that we will be reporting it. // We are going to report problems directly to the status manager because we // do not want the automatic repo location editing to kick in. if (fail[0].getStatus().getCode() == ProvisionException.REPOSITORY_NOT_FOUND) { ProvUI.notFoundStatusReported(location); } if (!fail[0].getStatus().matches(IStatus.CANCEL)) { // An error is only shown if the dialog was not canceled ProvUI.handleException(fail[0], null, StatusManager.SHOW); } } else { // Confirm that it was successful MessageDialog.openInformation(getShell(), ProvUIMessages.RepositoryManipulationPage_TestConnectionTitle, NLS.bind(ProvUIMessages.RepositoryManipulationPage_TestConnectionSuccess, URIUtil.toUnencodedString(location))); } repositoryViewer.update(selected[0], null); setDetails(); } boolean includesRepo(URI[] repos, URI repo) { for (int i = 0; i < repos.length; i++) if (repos[i].equals(repo)) return true; return false; } void toggleRepositoryEnablement() { MetadataRepositoryElement[] selected = getSelectedElements(); if (selected.length >= 1) { boolean enableSites = !toggleMeansDisable(selected); for (int i = 0; i < selected.length; i++) selected[i].setEnabled(enableSites); if (comparator.getSortKey() == RepositoryDetailsLabelProvider.COL_ENABLEMENT) repositoryViewer.refresh(true); else for (int i = 0; i < selected.length; i++) repositoryViewer.update(selected[i], null); changed = true; } validateButtons(); } void importRepositories() { BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() { public void run() { MetadataRepositoryElement[] imported = UpdateManagerCompatibility.importSites(getShell()); if (imported.length > 0) { Hashtable repos = getInput().cachedElements; changed = true; for (int i = 0; i < imported.length; i++) repos.put(URIUtil.toUnencodedString(imported[i].getLocation()), imported[i]); asyncRefresh(null); } } }); } void exportRepositories() { BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() { public void run() { MetadataRepositoryElement[] elements = getSelectedElements(); if (elements.length == 0) elements = getElements(); UpdateManagerCompatibility.exportSites(getShell(), elements); } }); } void changeRepositoryProperties() { final MetadataRepositoryElement[] selected = getSelectedElements(); if (selected.length != 1) return; RepositoryNameAndLocationDialog dialog = new RepositoryNameAndLocationDialog(getShell(), policy) { protected String getInitialLocationText() { return URIUtil.toUnencodedString(selected[0].getLocation()); } protected String getInitialNameText() { return selected[0].getName(); } protected RepositoryLocationValidator getRepositoryLocationValidator() { return new RepositoryLocationValidator() { public IStatus validateRepositoryLocation(URI uri, boolean contactRepositories, IProgressMonitor monitor) { if (URIUtil.sameURI(uri, selected[0].getLocation())) return Status.OK_STATUS; return RepositoryManipulationPage.this.getRepositoryManipulator().getRepositoryLocationValidator(getShell()).validateRepositoryLocation(uri, contactRepositories, monitor); } }; } }; int retCode = dialog.open(); if (retCode == Window.OK) { selected[0].setNickname(dialog.getName()); selected[0].setLocation(dialog.getLocation()); changed = true; repositoryViewer.update(selected[0], null); setDetails(); } } void columnSelected(TableColumn tc) { TableColumn[] cols = table.getColumns(); for (int i = 0; i < cols.length; i++) { if (cols[i] == tc) { if (i != comparator.getSortKey()) { comparator.setSortKey(i); table.setSortColumn(tc); comparator.sortAscending(); table.setSortDirection(SWT.UP); } else { if (comparator.isAscending()) { table.setSortDirection(SWT.DOWN); comparator.sortDescending(); } else { table.setSortDirection(SWT.UP); comparator.sortAscending(); } } repositoryViewer.refresh(); break; } } } void asyncRefresh(final MetadataRepositoryElement elementToSelect) { display.asyncExec(new Runnable() { public void run() { repositoryViewer.refresh(); if (elementToSelect != null) repositoryViewer.setSelection(new StructuredSelection(elementToSelect), true); } }); } void applyFilter() { String text = pattern.getText(); if (text == DEFAULT_FILTER_TEXT) text = ""; //$NON-NLS-1$ if (text.length() == 0) filter.setPattern(null); else filter.setPattern(text); if (filterJob != null) filterJob.cancel(); filterJob = new WorkbenchJob("filter job") { //$NON-NLS-1$ public IStatus runInUIThread(IProgressMonitor monitor) { if (monitor.isCanceled()) return Status.CANCEL_STATUS; if (!repositoryViewer.getTable().isDisposed()) repositoryViewer.refresh(); return Status.OK_STATUS; } }; filterJob.setSystem(true); filterJob.schedule(FILTER_DELAY); } void setDetails() { MetadataRepositoryElement[] selections = getSelectedElements(); if (selections.length == 1) { details.setText(selections[0].getDescription()); } else { details.setText(""); //$NON-NLS-1$ } } /* (non-Javadoc) * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) */ public void init(IWorkbench workbench) { noDefaultAndApplyButton(); if (policy == null) setPolicy(Policy.getDefault()); } void removeRepositories() { MetadataRepositoryElement[] selections = getSelectedElements(); if (selections.length > 0) { String message = ProvUIMessages.RepositoryManipulationPage_RemoveConfirmMessage; if (selections.length == 1) message = NLS.bind(ProvUIMessages.RepositoryManipulationPage_RemoveConfirmSingleMessage, URIUtil.toUnencodedString(selections[0].getLocation())); if (MessageDialog.openQuestion(getShell(), ProvUIMessages.RepositoryManipulationPage_RemoveConfirmTitle, message)) { changed = true; for (int i = 0; i < selections.length; i++) { getInput().cachedElements.remove(URIUtil.toUnencodedString(selections[i].getLocation())); } asyncRefresh(null); } } } // Return a repo manipulator that only operates on the local cache. // Labels and other presentation info are used from the original manipulator. RepositoryManipulator getRepositoryManipulator() { if (localCacheRepoManipulator == null) localCacheRepoManipulator = new RepositoryManipulator() { public AddRepositoryOperation getAddOperation(URI location) { return new AddRepositoryOperation("Cached add repo operation", new URI[] {location}) { //$NON-NLS-1$ protected IStatus doExecute(IProgressMonitor monitor) { MetadataRepositoryElement element = null; for (int i = 0; i < locations.length; i++) { element = new MetadataRepositoryElement(getInput(), locations[i], true); if (nicknames != null) element.setNickname(nicknames[i]); getInput().cachedElements.put(URIUtil.toUnencodedString(locations[i]), element); } changed = true; asyncRefresh(element); return Status.OK_STATUS; } protected IStatus doBatchedExecute(IProgressMonitor monitor) { // Not called due to override of doExecute return null; } protected void setNickname(URI loc, String nickname) { // Not called due to override of doExecute } }; } public String getAddOperationLabel() { return manipulator.getAddOperationLabel(); } public URI[] getKnownRepositories() { return RepositoryManipulationPage.this.getKnownRepositories(); } public String getManipulatorButtonLabel() { return manipulator.getManipulatorButtonLabel(); } public String getManipulatorLinkLabel() { return manipulator.getManipulatorLinkLabel(); } public RemoveRepositoryOperation getRemoveOperation(URI[] repoLocations) { return new RemoveRepositoryOperation("Cached remove repo operation", repoLocations) { //$NON-NLS-1$ protected IStatus doBatchedExecute(IProgressMonitor monitor) { removeRepositories(); return Status.OK_STATUS; } }; } public String getRemoveOperationLabel() { return manipulator.getRemoveOperationLabel(); } public RepositoryLocationValidator getRepositoryLocationValidator(Shell shell) { return new DefaultMetadataURLValidator() { protected URI[] getKnownLocations() { return getKnownRepositories(); } }; } public boolean manipulateRepositories(Shell shell) { // we are the manipulator return true; } public String getManipulatorInstructionString() { // we are the manipulator return null; } public String getRepositoryNotFoundInstructionString() { // we are in the manipulator, no further instructions return null; } }; return localCacheRepoManipulator; } public void copyToClipboard(Control activeControl) { MetadataRepositoryElement[] elements = getSelectedElements(); if (elements.length == 0) elements = getElements(); String text = ""; //$NON-NLS-1$ StringBuffer buffer = new StringBuffer(); for (int i = 0; i < elements.length; i++) { buffer.append(labelProvider.getClipboardText(elements[i], CopyUtils.DELIMITER)); if (i > 0) buffer.append(CopyUtils.NEWLINE); } text = buffer.toString(); if (text.length() == 0) return; Clipboard clipboard = new Clipboard(PlatformUI.getWorkbench().getDisplay()); clipboard.setContents(new Object[] {text}, new Transfer[] {TextTransfer.getInstance()}); clipboard.dispose(); } // If more than half of the selected repos are enabled, toggle means disable. // Otherwise it means enable. private boolean toggleMeansDisable(MetadataRepositoryElement[] elements) { double count = 0; for (int i = 0; i < elements.length; i++) if (elements[i].isEnabled()) count++; return (count / elements.length) > 0.5; } URI[] getKnownRepositories() { MetadataRepositoryElement[] elements = getElements(); URI[] locations = new URI[elements.length]; for (int i = 0; i < elements.length; i++) locations[i] = elements[i].getLocation(); return locations; } }
true
true
protected Control createContents(Composite parent) { display = parent.getDisplay(); // The help refers to the full-blown dialog. No help if it's read only. if (manipulator != null) PlatformUI.getWorkbench().getHelpSystem().setHelp(parent.getShell(), IProvHelpContextIds.REPOSITORY_MANIPULATION_DIALOG); Composite composite = new Composite(parent, SWT.NONE); GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); composite.setLayoutData(gd); GridLayout layout = new GridLayout(); layout.numColumns = manipulator == null ? 1 : 2; layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); composite.setLayout(layout); // Filter box pattern = new Text(composite, SWT.SINGLE | SWT.BORDER | SWT.SEARCH | SWT.CANCEL); pattern.getAccessible().addAccessibleListener(new AccessibleAdapter() { public void getName(AccessibleEvent e) { e.result = DEFAULT_FILTER_TEXT; } }); pattern.setText(DEFAULT_FILTER_TEXT); pattern.selectAll(); pattern.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { applyFilter(); } }); pattern.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.keyCode == SWT.ARROW_DOWN) { if (table.getItemCount() > 0) { table.setFocus(); } else if (e.character == SWT.CR) { return; } } } }); pattern.addFocusListener(new FocusAdapter() { public void focusGained(FocusEvent e) { display.asyncExec(new Runnable() { public void run() { if (!pattern.isDisposed()) { if (DEFAULT_FILTER_TEXT.equals(pattern.getText().trim())) { pattern.selectAll(); } } } }); } }); gd = new GridData(SWT.FILL, SWT.FILL, true, false); pattern.setLayoutData(gd); // spacer to fill other column if (manipulator != null) new Label(composite, SWT.NONE); // Table of available repositories repositoryViewer = new TableViewer(composite, SWT.MULTI | SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); table = repositoryViewer.getTable(); // Key listener for delete table.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.keyCode == SWT.DEL) { removeRepositories(); } } }); setTableColumns(); CopyUtils.activateCopy(this, table); repositoryViewer.setComparer(new ProvElementComparer()); comparator = new MetadataRepositoryElementComparator(RepositoryDetailsLabelProvider.COL_NAME); repositoryViewer.setComparator(comparator); filter = new MetadataRepositoryPatternFilter(); repositoryViewer.setFilters(new ViewerFilter[] {filter}); // We don't need a deferred content provider because we are caching local results before // actually querying repositoryViewer.setContentProvider(new ProvElementContentProvider()); labelProvider = new RepositoryDetailsLabelProvider(); repositoryViewer.setLabelProvider(labelProvider); // Edit the nickname repositoryViewer.setCellModifier(new ICellModifier() { public boolean canModify(Object element, String property) { return true; } public Object getValue(Object element, String property) { return ((MetadataRepositoryElement) element).getName(); } public void modify(Object element, String property, Object value) { if (value != null && value.toString().length() >= 0) { MetadataRepositoryElement repo; if (element instanceof Item) { repo = (MetadataRepositoryElement) ((Item) element).getData(); } else if (element instanceof MetadataRepositoryElement) { repo = (MetadataRepositoryElement) element; } else { return; } changed = true; repo.setNickname(value.toString()); if (comparator.getSortKey() == RepositoryDetailsLabelProvider.COL_NAME) repositoryViewer.refresh(true); else repositoryViewer.update(repo, null); } } }); repositoryViewer.setColumnProperties(new String[] {"nickname"}); //$NON-NLS-1$ repositoryViewer.setCellEditors(new CellEditor[] {new TextCellEditor(repositoryViewer.getTable())}); repositoryViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { if (manipulator != null) validateButtons(); setDetails(); } }); // Input last repositoryViewer.setInput(getInput()); GridData data = new GridData(SWT.FILL, SWT.FILL, true, true); data.widthHint = convertWidthInCharsToPixels(ILayoutConstants.DEFAULT_TABLE_WIDTH); data.heightHint = convertHeightInCharsToPixels(ILayoutConstants.DEFAULT_TABLE_HEIGHT); table.setLayoutData(data); // Drop targets and vertical buttons only if repository manipulation is provided. if (manipulator != null) { DropTarget target = new DropTarget(table, DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK); target.setTransfer(new Transfer[] {URLTransfer.getInstance(), FileTransfer.getInstance()}); target.addDropListener(new RepositoryManipulatorDropTarget(getRepositoryManipulator(), table)); // Vertical buttons Composite verticalButtonBar = createVerticalButtonBar(composite); data = new GridData(SWT.FILL, SWT.FILL, false, false); data.verticalAlignment = SWT.TOP; data.verticalIndent = 0; verticalButtonBar.setLayoutData(data); listener = getViewerProvisioningListener(); ProvUI.addProvisioningListener(listener); composite.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent event) { ProvUI.removeProvisioningListener(listener); } }); validateButtons(); } // Details area details = new Text(composite, SWT.READ_ONLY | SWT.WRAP); data = new GridData(SWT.FILL, SWT.FILL, true, false); data.heightHint = convertHeightInCharsToPixels(ILayoutConstants.DEFAULT_SITEDETAILS_HEIGHT); details.setLayoutData(data); Dialog.applyDialogFont(composite); return composite; }
protected Control createContents(Composite parent) { display = parent.getDisplay(); // The help refers to the full-blown dialog. No help if it's read only. if (manipulator != null) PlatformUI.getWorkbench().getHelpSystem().setHelp(parent.getShell(), IProvHelpContextIds.REPOSITORY_MANIPULATION_DIALOG); Composite composite = new Composite(parent, SWT.NONE); GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); composite.setLayoutData(gd); GridLayout layout = new GridLayout(); layout.numColumns = manipulator == null ? 1 : 2; layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); composite.setLayout(layout); // Filter box pattern = new Text(composite, SWT.SINGLE | SWT.BORDER | SWT.SEARCH | SWT.CANCEL); pattern.getAccessible().addAccessibleListener(new AccessibleAdapter() { public void getName(AccessibleEvent e) { e.result = DEFAULT_FILTER_TEXT; } }); pattern.setText(DEFAULT_FILTER_TEXT); pattern.selectAll(); pattern.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { applyFilter(); } }); pattern.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.keyCode == SWT.ARROW_DOWN) { if (table.getItemCount() > 0) { table.setFocus(); } else if (e.character == SWT.CR) { return; } } } }); pattern.addFocusListener(new FocusAdapter() { public void focusGained(FocusEvent e) { display.asyncExec(new Runnable() { public void run() { if (!pattern.isDisposed()) { if (DEFAULT_FILTER_TEXT.equals(pattern.getText().trim())) { pattern.selectAll(); } } } }); } }); gd = new GridData(SWT.FILL, SWT.FILL, true, false); pattern.setLayoutData(gd); // spacer to fill other column if (manipulator != null) new Label(composite, SWT.NONE); // Table of available repositories repositoryViewer = new TableViewer(composite, SWT.MULTI | SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); table = repositoryViewer.getTable(); // Key listener for delete table.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.keyCode == SWT.DEL) { removeRepositories(); } } }); setTableColumns(); CopyUtils.activateCopy(this, table); repositoryViewer.setComparer(new ProvElementComparer()); comparator = new MetadataRepositoryElementComparator(RepositoryDetailsLabelProvider.COL_NAME); repositoryViewer.setComparator(comparator); filter = new MetadataRepositoryPatternFilter(); repositoryViewer.setFilters(new ViewerFilter[] {filter}); // We don't need a deferred content provider because we are caching local results before // actually querying repositoryViewer.setContentProvider(new ProvElementContentProvider()); labelProvider = new RepositoryDetailsLabelProvider(); repositoryViewer.setLabelProvider(labelProvider); // Edit the nickname repositoryViewer.setCellModifier(new ICellModifier() { public boolean canModify(Object element, String property) { return element instanceof MetadataRepositoryElement; } public Object getValue(Object element, String property) { return ((MetadataRepositoryElement) element).getName(); } public void modify(Object element, String property, Object value) { if (value != null && value.toString().length() >= 0) { MetadataRepositoryElement repo; if (element instanceof Item) { repo = (MetadataRepositoryElement) ((Item) element).getData(); } else if (element instanceof MetadataRepositoryElement) { repo = (MetadataRepositoryElement) element; } else { return; } changed = true; repo.setNickname(value.toString()); if (comparator.getSortKey() == RepositoryDetailsLabelProvider.COL_NAME) repositoryViewer.refresh(true); else repositoryViewer.update(repo, null); } } }); repositoryViewer.setColumnProperties(new String[] {"nickname"}); //$NON-NLS-1$ repositoryViewer.setCellEditors(new CellEditor[] {new TextCellEditor(repositoryViewer.getTable())}); repositoryViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { if (manipulator != null) validateButtons(); setDetails(); } }); // Input last repositoryViewer.setInput(getInput()); GridData data = new GridData(SWT.FILL, SWT.FILL, true, true); data.widthHint = convertWidthInCharsToPixels(ILayoutConstants.DEFAULT_TABLE_WIDTH); data.heightHint = convertHeightInCharsToPixels(ILayoutConstants.DEFAULT_TABLE_HEIGHT); table.setLayoutData(data); // Drop targets and vertical buttons only if repository manipulation is provided. if (manipulator != null) { DropTarget target = new DropTarget(table, DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK); target.setTransfer(new Transfer[] {URLTransfer.getInstance(), FileTransfer.getInstance()}); target.addDropListener(new RepositoryManipulatorDropTarget(getRepositoryManipulator(), table)); // Vertical buttons Composite verticalButtonBar = createVerticalButtonBar(composite); data = new GridData(SWT.FILL, SWT.FILL, false, false); data.verticalAlignment = SWT.TOP; data.verticalIndent = 0; verticalButtonBar.setLayoutData(data); listener = getViewerProvisioningListener(); ProvUI.addProvisioningListener(listener); composite.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent event) { ProvUI.removeProvisioningListener(listener); } }); validateButtons(); } // Details area details = new Text(composite, SWT.READ_ONLY | SWT.WRAP); data = new GridData(SWT.FILL, SWT.FILL, true, false); data.heightHint = convertHeightInCharsToPixels(ILayoutConstants.DEFAULT_SITEDETAILS_HEIGHT); details.setLayoutData(data); Dialog.applyDialogFont(composite); return composite; }
diff --git a/src/main/java/org/mapdb/StoreDirect.java b/src/main/java/org/mapdb/StoreDirect.java index 1c86d1a5..48ee605e 100644 --- a/src/main/java/org/mapdb/StoreDirect.java +++ b/src/main/java/org/mapdb/StoreDirect.java @@ -1,656 +1,656 @@ /* * Copyright (c) 2012 Jan Kotek * * 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.mapdb; import java.io.File; import java.io.IOError; import java.io.IOException; import java.util.Arrays; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * Storage Engine which saves record directly into file. * Is used when transaction journal is disabled. * * @author Jan Kotek */ public class StoreDirect implements Engine{ protected static final long MASK_OFFSET = 0x0000FFFFFFFFFFFFL; protected static final long MASK_SIZE = 0x7fff000000000000L; protected static final long MASK_IS_LINKED = 0x8000000000000000L; protected static final long HEADER = 9032094932889042394L; /** maximal non linked record size */ protected static final int MAX_REC_SIZE = 32767; /** number of free physical slots */ protected static final int PHYS_FREE_SLOTS_COUNT = 2048; /** index file offset where current size of index file is stored*/ protected static final int IO_INDEX_SIZE = 1*8; /** index file offset where current size of phys file is stored */ protected static final int IO_PHYS_SIZE = 2*8; /** index file offset where reference to longstack of free recid is stored*/ protected static final int IO_FREE_RECID = 15*8; /** index file offset where first recid available to user is stored */ protected static final int IO_USER_START = IO_FREE_RECID+PHYS_FREE_SLOTS_COUNT*8+8; public static final String DATA_FILE_EXT = ".p"; protected static final int CONCURRENCY_FACTOR = 32; static final int LONG_STACK_PER_PAGE = 204; static final int LONG_STACK_PAGE_SIZE = 8 + LONG_STACK_PER_PAGE * 6; protected final ReentrantReadWriteLock[] locks; protected final ReentrantLock structuralLock; protected Volume index; protected Volume phys; protected long physSize; protected long indexSize; protected final boolean deleteFilesAfterClose; protected final boolean readOnly; public StoreDirect(Volume.Factory volFac, boolean readOnly, boolean deleteFilesAfterClose) { this.readOnly = readOnly; this.deleteFilesAfterClose = deleteFilesAfterClose; locks = new ReentrantReadWriteLock[CONCURRENCY_FACTOR]; for(int i=0;i<locks.length;i++) locks[i] = new ReentrantReadWriteLock(); structuralLock = new ReentrantLock(); index = volFac.createIndexVolume(); phys = volFac.createPhysVolume(); if(index.isEmpty()){ createStructure(); }else{ checkHeaders(); indexSize = index.getLong(IO_INDEX_SIZE); physSize = index.getLong(IO_PHYS_SIZE); } } public StoreDirect(Volume.Factory volFac) { this(volFac, false,false); } protected void checkHeaders() { if(index.getLong(0)!=HEADER||phys.getLong(0)!=HEADER)throw new IOError(new IOException("storage has invalid header")); } protected void createStructure() { indexSize = IO_USER_START+Engine.LAST_RESERVED_RECID*8+8; index.ensureAvailable(indexSize); for(int i=0;i<indexSize;i+=8) index.putLong(i,0L); index.putLong(0, HEADER); index.putLong(IO_INDEX_SIZE,indexSize); physSize =16; phys.ensureAvailable(physSize); phys.putLong(0, HEADER); index.putLong(IO_PHYS_SIZE,physSize); } @Override public <A> long put(A value, Serializer<A> serializer) { DataOutput2 out = serialize(value, serializer); structuralLock.lock(); final long ioRecid; final long[] indexVals; try{ ioRecid = freeIoRecidTake(true) ; indexVals = physAllocate(out.pos,true); }finally { structuralLock.unlock(); } put2(out, ioRecid, indexVals); return (ioRecid-IO_USER_START)/8; } private void put2(DataOutput2 out, long ioRecid, long[] indexVals) { index.putLong(ioRecid, indexVals[0]); //write stuff if(indexVals.length==1||indexVals[1]==0){ //is more then one? ie linked //write single phys.putData(indexVals[0]&MASK_OFFSET, out.buf, 0, out.pos); }else{ int outPos = 0; //write linked for(int i=0;i<indexVals.length;i++){ final int c = ccc(indexVals.length, i); final long indexVal = indexVals[i]; final boolean isLast = (indexVal & MASK_IS_LINKED) ==0; if(isLast!=(i==indexVals.length-1)) throw new InternalError(); final int size = (int) ((indexVal& MASK_SIZE)>>48); final long offset = indexVal&MASK_OFFSET; //write data phys.putData(offset+c,out.buf,outPos, size-c); outPos+=size-c; if(c>0){ //write position of next linked record phys.putLong(offset, indexVals[i+1]); } if(c==12){ //write total size in first record phys.putInt(offset+8, out.pos); } } if(outPos!=out.pos) throw new InternalError(); } } @Override public <A> A get(long recid, Serializer<A> serializer) { final long ioRecid = IO_USER_START + recid*8; final Lock lock = locks[Utils.longHash(recid)%CONCURRENCY_FACTOR].readLock(); lock.lock(); try{ return get2(ioRecid,serializer); }catch(IOException e){ throw new IOError(e); }finally{ lock.unlock(); } } protected <A> A get2(long ioRecid,Serializer<A> serializer) throws IOException { long indexVal = index.getLong(ioRecid); int size = (int) ((indexVal&MASK_SIZE)>>>48); DataInput2 di; long offset = indexVal&MASK_OFFSET; if((indexVal&MASK_IS_LINKED)==0){ //read single record di = phys.getDataInput(offset, size); }else{ //is linked, first construct buffer we will read data to int totalSize = phys.getInt(offset+8); int pos = 0; int c = 12; byte[] buf = new byte[totalSize]; //read parts into segment for(;;){ DataInput2 in = phys.getDataInput(offset + c, size-c); in.readFully(buf,pos,size-c); pos+=size-c; if(c==0) break; //read next part long next = phys.getLong(offset); offset = next&MASK_OFFSET; size = (int) ((next&MASK_SIZE)>>>48); //is the next part last? c = ((next&MASK_IS_LINKED)==0)? 0 : 8; } if(pos!=totalSize) throw new InternalError(); di = new DataInput2(buf); size = totalSize; } int start = di.pos; A ret = serializer.deserialize(di,size); if(size+start>di.pos)throw new InternalError("data were not fully read, check your serializier"); if(size+start<di.pos)throw new InternalError("data were read beyond record size, check your serializier"); return ret; } @Override public <A> void update(long recid, A value, Serializer<A> serializer) { DataOutput2 out = serialize(value, serializer); final long ioRecid = IO_USER_START + recid*8; final Lock lock = locks[Utils.longHash(recid)%CONCURRENCY_FACTOR].writeLock(); lock.lock(); try{ final long[] indexVals; structuralLock.lock(); try{ indexVals = physAllocate(out.pos,true); }finally { structuralLock.unlock(); } put2(out, ioRecid, indexVals); }finally{ lock.unlock(); } } @Override public <A> boolean compareAndSwap(long recid, A expectedOldValue, A newValue, Serializer<A> serializer) { final long ioRecid = IO_USER_START + recid*8; final Lock lock = locks[Utils.longHash(recid)%CONCURRENCY_FACTOR].writeLock(); lock.lock(); try{ /* * deserialize old value */ A oldVal = get2(ioRecid,serializer); /* * compare oldValue and expected */ if((oldVal == null && expectedOldValue!=null) || (oldVal!=null && !oldVal.equals(expectedOldValue))) return false; /* * write new value */ DataOutput2 out = serialize(newValue, serializer); final long[] indexVals; structuralLock.lock(); try{ indexVals = physAllocate(out.pos,true); }finally { structuralLock.unlock(); } put2(out, ioRecid, indexVals); return true; }catch(IOException e){ throw new IOError(e); }finally{ lock.unlock(); } } @Override public <A> void delete(long recid, Serializer<A> serializer) { final long ioRecid = IO_USER_START + recid*8; final Lock lock = locks[Utils.longHash(recid)%CONCURRENCY_FACTOR].writeLock(); lock.lock(); try{ //get index val and zero it out final long indexVal = index.getLong(ioRecid); index.putLong(ioRecid,0L); long[] linkedRecords = null; int linkedPos = 0; if((indexVal&MASK_IS_LINKED)!=0){ //record is composed of multiple linked records, so collect all of them linkedRecords = new long[2]; //traverse linked records long linkedVal = phys.getLong(indexVal&MASK_OFFSET); for(;;){ if(linkedPos==linkedRecords.length) //grow if necessary linkedRecords = Arrays.copyOf(linkedRecords, linkedRecords.length*2); //store last linkedVal linkedRecords[linkedPos] = linkedVal; if((linkedVal&MASK_IS_LINKED)==0){ break; //this is last linked record, so break } //move and read to next linkedPos++; linkedVal = phys.getLong(linkedVal&MASK_OFFSET); } } //now lock everything and mark free space structuralLock.lock(); try{ //free recid freeIoRecidPut(ioRecid); //free first record pointed from indexVal freePhysPut(indexVal); //if there are more linked records, free those as well if(linkedRecords!=null){ for(int i=0;i<linkedPos;i++){ freePhysPut(linkedRecords[i]); } } }finally { structuralLock.unlock(); } }finally{ lock.unlock(); } } protected long[] physAllocate(int size, boolean ensureAvail) { //append to end of file if(size<MAX_REC_SIZE){ long indexVal = freePhysTake(size,ensureAvail); indexVal |= ((long)size)<<48; return new long[]{indexVal}; }else{ long[] ret = new long[2]; int retPos = 0; int c = 12; while(size>0){ if(retPos == ret.length) ret = Arrays.copyOf(ret, ret.length*2); int allocSize = Math.min(size, MAX_REC_SIZE); size -= allocSize - c; //append to end of file long indexVal = freePhysTake(allocSize, ensureAvail); indexVal |= (((long)allocSize)<<48); if(c!=0) indexVal|=MASK_IS_LINKED; ret[retPos++] = indexVal; c = size<=MAX_REC_SIZE ? 0 : 8; } if(size!=0) throw new InternalError(); return Arrays.copyOf(ret, retPos); } } protected static long roundTo16(long offset){ long rem = offset%16; if(rem!=0) offset +=16-rem; return offset; } protected static int ccc(int size, int i) { return (size==1|| i==size-1)? 0: (i==0?12:8); } @Override public void close() { structuralLock.lock(); for(ReentrantReadWriteLock l:locks) l.writeLock().lock(); if(!readOnly){ index.putLong(IO_PHYS_SIZE,physSize); index.putLong(IO_INDEX_SIZE,indexSize); } index.close(); phys.close(); if(deleteFilesAfterClose){ index.deleteFile(); phys.deleteFile(); } index = null; phys = null; for(ReentrantReadWriteLock l:locks) l.writeLock().unlock(); structuralLock.unlock(); } @Override public boolean isClosed() { return index==null; } @Override public void commit() { if(!readOnly){ index.putLong(IO_PHYS_SIZE,physSize); index.putLong(IO_INDEX_SIZE,indexSize); } index.sync(); phys.sync(); } @Override public void rollback() throws UnsupportedOperationException { throw new UnsupportedOperationException("rollback not supported with journal disabled"); } @Override public boolean isReadOnly() { return readOnly; } @Override public void compact() { if(readOnly) throw new IllegalAccessError(); index.putLong(IO_PHYS_SIZE,physSize); index.putLong(IO_INDEX_SIZE,indexSize); if(index.getFile()==null) throw new UnsupportedOperationException("compact not supported for memory storage yet"); structuralLock.lock(); for(ReentrantReadWriteLock l:locks) l.writeLock().lock(); try{ //create secondary files for compaction //TODO RAF //TODO memory based stores final File indexFile = index.getFile(); final File physFile = phys.getFile(); final boolean isRaf = index instanceof Volume.RandomAccessFileVol; Volume.Factory fab = Volume.fileFactory(false, isRaf, new File(indexFile+".compact")); StoreDirect store2 = new StoreDirect(fab); store2.structuralLock.lock(); //transfer stack of free recids for(long recid =longStackTake(IO_FREE_RECID); recid!=0; recid=longStackTake(IO_FREE_RECID)){ store2.longStackPut(recid, IO_FREE_RECID); } //iterate over recids and transfer physical records store2.index.putLong(IO_INDEX_SIZE, indexSize); for(long ioRecid = IO_USER_START; ioRecid<indexSize;ioRecid+=8){ byte[] bb = get2(ioRecid,Serializer.BYTE_ARRAY_SERIALIZER); long[] indexVals = store2.physAllocate(bb.length,true); DataOutput2 out = new DataOutput2(); out.buf = bb; out.pos = bb.length; store2.index.ensureAvailable(ioRecid+8); store2.put2(out, ioRecid,indexVals); } File indexFile2 = store2.index.getFile(); File physFile2 = store2.phys.getFile(); store2.structuralLock.unlock(); store2.close(); long time = System.currentTimeMillis(); File indexFile_ = new File(indexFile.getPath()+"_"+time+"_orig"); File physFile_ = new File(physFile.getPath()+"_"+time+"_orig"); index.close(); phys.close(); - if(!indexFile.renameTo(indexFile_))throw new InternalError(); - if(!physFile.renameTo(physFile_))throw new InternalError(); + if(!indexFile.renameTo(indexFile_))throw new InternalError("could not rename file"); + if(!physFile.renameTo(physFile_))throw new InternalError("could not rename file"); - if(!indexFile2.renameTo(indexFile))throw new InternalError(); + if(!indexFile2.renameTo(indexFile))throw new InternalError("could not rename file"); //TODO process may fail in middle of rename, analyze sequence and add recovery - if(!physFile2.renameTo(physFile))throw new InternalError(); + if(!physFile2.renameTo(physFile))throw new InternalError("could not rename file"); indexFile_.delete(); physFile_.delete(); Volume.Factory fac2 = Volume.fileFactory(false, isRaf, indexFile); index = fac2.createIndexVolume(); phys = fac2.createPhysVolume(); }catch(IOException e){ throw new IOError(e); }finally { structuralLock.unlock(); for(ReentrantReadWriteLock l:locks) l.writeLock().unlock(); } } protected long longStackTake(final long ioList) { if(!structuralLock.isLocked())throw new InternalError(); if(ioList<IO_FREE_RECID || ioList>=IO_USER_START) throw new IllegalArgumentException("wrong ioList: "+ioList); final long dataOffset = index.getLong(ioList) &MASK_OFFSET; if(dataOffset == 0) return 0; //there is no such list, so just return 0 final int numberOfRecordsInPage = phys.getUnsignedByte(dataOffset); if(numberOfRecordsInPage<=0) throw new InternalError(); if(numberOfRecordsInPage> LONG_STACK_PER_PAGE) throw new InternalError(); final long ret = phys.getSixLong(dataOffset + 2 + numberOfRecordsInPage * 6); //was it only record at that page? if(numberOfRecordsInPage == 1){ //yes, delete this page final long previousListPhysid =phys.getSixLong(dataOffset+2); if(previousListPhysid !=0){ //update index so it points to previous page index.putLong(ioList , previousListPhysid | (((long) LONG_STACK_PAGE_SIZE) << 48)); }else{ //zero out index index.putLong(ioList , 0L); } //put space used by this page into free list freePhysPut(dataOffset | (((long)LONG_STACK_PAGE_SIZE)<<48)); }else{ //no, it was not last record at this page, so just decrement the counter phys.putUnsignedByte(dataOffset, (byte) (numberOfRecordsInPage - 1)); } //System.out.println("longStackTake: "+ioList+" - "+ret); return ret; } protected void longStackPut(final long ioList, long offset){ offset = offset & MASK_OFFSET; if(!structuralLock.isLocked())throw new InternalError(); if(ioList<IO_FREE_RECID || ioList>=IO_USER_START) throw new InternalError("wrong ioList: "+ioList); //System.out.println("longStackPut: "+ioList+" - "+offset); //index position was cleared, put into free index list final long listPhysid2 = index.getLong(ioList) &MASK_OFFSET; if(listPhysid2 == 0){ //empty list? //yes empty, create new page and fill it with values final long listPhysid = freePhysTake(LONG_STACK_PAGE_SIZE,true) &MASK_OFFSET; if(listPhysid == 0) throw new InternalError(); //set previous Free Index List page to zero as this is first page phys.putSixLong(listPhysid + 2, 0L); //set number of free records in this page to 1 phys.putUnsignedByte(listPhysid, (byte) 1); //set record phys.putSixLong(listPhysid + 8, offset); //and update index file with new page location index.putLong(ioList , (((long) LONG_STACK_PAGE_SIZE) << 48) | listPhysid); }else{ final int numberOfRecordsInPage = phys.getUnsignedByte(listPhysid2); if(numberOfRecordsInPage == LONG_STACK_PER_PAGE){ //is current page full? //yes it is full, so we need to allocate new page and write our number there final long listPhysid = freePhysTake(LONG_STACK_PAGE_SIZE,true) &MASK_OFFSET; if(listPhysid == 0) throw new InternalError(); //final ByteBuffers dataBuf = dataBufs[((int) (listPhysid / BUF_SIZE))]; //set location to previous page phys.putSixLong(listPhysid + 2, listPhysid2); //set number of free records in this page to 1 phys.putUnsignedByte(listPhysid, (byte) 1); //set free record phys.putSixLong(listPhysid + 8, offset); //and update index file with new page location index.putLong(ioList , (((long) LONG_STACK_PAGE_SIZE) << 48) | listPhysid); }else{ //there is space on page, so just write released recid and increase the counter phys.putSixLong(listPhysid2 + 8 + 6 * numberOfRecordsInPage, offset); phys.putUnsignedByte(listPhysid2, (byte) (numberOfRecordsInPage + 1)); } } } protected void freeIoRecidPut(long ioRecid) { longStackPut(IO_FREE_RECID, ioRecid); } protected long freeIoRecidTake(boolean ensureAvail){ long ioRecid = longStackTake(IO_FREE_RECID); if(ioRecid!=0) return ioRecid; indexSize+=8; if(ensureAvail) index.ensureAvailable(indexSize); return indexSize-8; } protected static final long size2ListIoRecid(long size){ return IO_FREE_RECID + 8 + ((size-1)/16)*8; } protected void freePhysPut(long indexVal) { long size = (indexVal&MASK_SIZE) >>>48; longStackPut(size2ListIoRecid(size), indexVal & MASK_OFFSET); } protected long freePhysTake(int size, boolean ensureAvail) { //check free space long ret = longStackTake(size2ListIoRecid(size)); if(ret!=0) return ret; //not available, increase file size if(physSize%Volume.BUF_SIZE+size>Volume.BUF_SIZE) physSize += Volume.BUF_SIZE - physSize%Volume.BUF_SIZE; long physSize2 = physSize; physSize = roundTo16(physSize+size); if(ensureAvail) phys.ensureAvailable(physSize); return physSize2; } protected <A> DataOutput2 serialize(A value, Serializer<A> serializer) { try { DataOutput2 out = new DataOutput2(); serializer.serialize(out,value); return out; } catch (IOException e) { throw new IOError(e); } } }
false
true
public void compact() { if(readOnly) throw new IllegalAccessError(); index.putLong(IO_PHYS_SIZE,physSize); index.putLong(IO_INDEX_SIZE,indexSize); if(index.getFile()==null) throw new UnsupportedOperationException("compact not supported for memory storage yet"); structuralLock.lock(); for(ReentrantReadWriteLock l:locks) l.writeLock().lock(); try{ //create secondary files for compaction //TODO RAF //TODO memory based stores final File indexFile = index.getFile(); final File physFile = phys.getFile(); final boolean isRaf = index instanceof Volume.RandomAccessFileVol; Volume.Factory fab = Volume.fileFactory(false, isRaf, new File(indexFile+".compact")); StoreDirect store2 = new StoreDirect(fab); store2.structuralLock.lock(); //transfer stack of free recids for(long recid =longStackTake(IO_FREE_RECID); recid!=0; recid=longStackTake(IO_FREE_RECID)){ store2.longStackPut(recid, IO_FREE_RECID); } //iterate over recids and transfer physical records store2.index.putLong(IO_INDEX_SIZE, indexSize); for(long ioRecid = IO_USER_START; ioRecid<indexSize;ioRecid+=8){ byte[] bb = get2(ioRecid,Serializer.BYTE_ARRAY_SERIALIZER); long[] indexVals = store2.physAllocate(bb.length,true); DataOutput2 out = new DataOutput2(); out.buf = bb; out.pos = bb.length; store2.index.ensureAvailable(ioRecid+8); store2.put2(out, ioRecid,indexVals); } File indexFile2 = store2.index.getFile(); File physFile2 = store2.phys.getFile(); store2.structuralLock.unlock(); store2.close(); long time = System.currentTimeMillis(); File indexFile_ = new File(indexFile.getPath()+"_"+time+"_orig"); File physFile_ = new File(physFile.getPath()+"_"+time+"_orig"); index.close(); phys.close(); if(!indexFile.renameTo(indexFile_))throw new InternalError(); if(!physFile.renameTo(physFile_))throw new InternalError(); if(!indexFile2.renameTo(indexFile))throw new InternalError(); //TODO process may fail in middle of rename, analyze sequence and add recovery if(!physFile2.renameTo(physFile))throw new InternalError(); indexFile_.delete(); physFile_.delete(); Volume.Factory fac2 = Volume.fileFactory(false, isRaf, indexFile); index = fac2.createIndexVolume(); phys = fac2.createPhysVolume(); }catch(IOException e){ throw new IOError(e); }finally { structuralLock.unlock(); for(ReentrantReadWriteLock l:locks) l.writeLock().unlock(); } }
public void compact() { if(readOnly) throw new IllegalAccessError(); index.putLong(IO_PHYS_SIZE,physSize); index.putLong(IO_INDEX_SIZE,indexSize); if(index.getFile()==null) throw new UnsupportedOperationException("compact not supported for memory storage yet"); structuralLock.lock(); for(ReentrantReadWriteLock l:locks) l.writeLock().lock(); try{ //create secondary files for compaction //TODO RAF //TODO memory based stores final File indexFile = index.getFile(); final File physFile = phys.getFile(); final boolean isRaf = index instanceof Volume.RandomAccessFileVol; Volume.Factory fab = Volume.fileFactory(false, isRaf, new File(indexFile+".compact")); StoreDirect store2 = new StoreDirect(fab); store2.structuralLock.lock(); //transfer stack of free recids for(long recid =longStackTake(IO_FREE_RECID); recid!=0; recid=longStackTake(IO_FREE_RECID)){ store2.longStackPut(recid, IO_FREE_RECID); } //iterate over recids and transfer physical records store2.index.putLong(IO_INDEX_SIZE, indexSize); for(long ioRecid = IO_USER_START; ioRecid<indexSize;ioRecid+=8){ byte[] bb = get2(ioRecid,Serializer.BYTE_ARRAY_SERIALIZER); long[] indexVals = store2.physAllocate(bb.length,true); DataOutput2 out = new DataOutput2(); out.buf = bb; out.pos = bb.length; store2.index.ensureAvailable(ioRecid+8); store2.put2(out, ioRecid,indexVals); } File indexFile2 = store2.index.getFile(); File physFile2 = store2.phys.getFile(); store2.structuralLock.unlock(); store2.close(); long time = System.currentTimeMillis(); File indexFile_ = new File(indexFile.getPath()+"_"+time+"_orig"); File physFile_ = new File(physFile.getPath()+"_"+time+"_orig"); index.close(); phys.close(); if(!indexFile.renameTo(indexFile_))throw new InternalError("could not rename file"); if(!physFile.renameTo(physFile_))throw new InternalError("could not rename file"); if(!indexFile2.renameTo(indexFile))throw new InternalError("could not rename file"); //TODO process may fail in middle of rename, analyze sequence and add recovery if(!physFile2.renameTo(physFile))throw new InternalError("could not rename file"); indexFile_.delete(); physFile_.delete(); Volume.Factory fac2 = Volume.fileFactory(false, isRaf, indexFile); index = fac2.createIndexVolume(); phys = fac2.createPhysVolume(); }catch(IOException e){ throw new IOError(e); }finally { structuralLock.unlock(); for(ReentrantReadWriteLock l:locks) l.writeLock().unlock(); } }
diff --git a/kChat/src/me/KeybordPiano459/kChat/ChatColors.java b/kChat/src/me/KeybordPiano459/kChat/ChatColors.java index 3ff84f7..cd3c23f 100644 --- a/kChat/src/me/KeybordPiano459/kChat/ChatColors.java +++ b/kChat/src/me/KeybordPiano459/kChat/ChatColors.java @@ -1,26 +1,26 @@ package me.KeybordPiano459.kChat; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerChatEvent; public class ChatColors implements Listener { static kChat plugin; public ChatColors(kChat plugin) { ChatColors.plugin = plugin; } @EventHandler public void onChat(AsyncPlayerChatEvent event) { Player player = event.getPlayer(); String msg = event.getMessage(); if (plugin.colorallowed) { event.setMessage(ChatColor.translateAlternateColorCodes('&', msg)); - } // Add color symbols to chat messages + } if (player.isOp() && !plugin.opcolor.equals("none")) { - event.setFormat(ChatColor.translateAlternateColorCodes('&', "<" + player.getName() + "> " + msg)); + event.setFormat(ChatColor.translateAlternateColorCodes('&', "<" + plugin.opcolor + player.getName() + ChatColor.RESET + "> " + msg)); } } }
false
true
public void onChat(AsyncPlayerChatEvent event) { Player player = event.getPlayer(); String msg = event.getMessage(); if (plugin.colorallowed) { event.setMessage(ChatColor.translateAlternateColorCodes('&', msg)); } // Add color symbols to chat messages if (player.isOp() && !plugin.opcolor.equals("none")) { event.setFormat(ChatColor.translateAlternateColorCodes('&', "<" + player.getName() + "> " + msg)); } }
public void onChat(AsyncPlayerChatEvent event) { Player player = event.getPlayer(); String msg = event.getMessage(); if (plugin.colorallowed) { event.setMessage(ChatColor.translateAlternateColorCodes('&', msg)); } if (player.isOp() && !plugin.opcolor.equals("none")) { event.setFormat(ChatColor.translateAlternateColorCodes('&', "<" + plugin.opcolor + player.getName() + ChatColor.RESET + "> " + msg)); } }
diff --git a/src/net/sf/hajdbc/sync/DifferentialSynchronizationStrategy.java b/src/net/sf/hajdbc/sync/DifferentialSynchronizationStrategy.java index 0e3b1f62..7a1dfab2 100644 --- a/src/net/sf/hajdbc/sync/DifferentialSynchronizationStrategy.java +++ b/src/net/sf/hajdbc/sync/DifferentialSynchronizationStrategy.java @@ -1,520 +1,520 @@ /* * HA-JDBC: High-Availability JDBC * Copyright (c) 2004-2006 Paul Ferraro * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact: [email protected] */ package net.sf.hajdbc.sync; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import net.sf.hajdbc.DatabaseMetaDataCache; import net.sf.hajdbc.Dialect; import net.sf.hajdbc.ForeignKeyConstraint; import net.sf.hajdbc.Messages; import net.sf.hajdbc.SynchronizationStrategy; import net.sf.hajdbc.TableProperties; import net.sf.hajdbc.UniqueConstraint; import net.sf.hajdbc.util.Strings; import net.sf.hajdbc.util.concurrent.DaemonThreadFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Database-independent synchronization strategy that only updates differences between two databases. * This strategy is best used when there are <em>few</em> differences between the active database and the inactive database (i.e. barely out of sync). * The following algorithm is used: * <ol> * <li>Drop the foreign keys on the inactive database (to avoid integrity constraint violations)</li> * <li>For each database table: * <ol> * <li>Drop the unique constraints on the table (to avoid integrity constraint violations)</li> * <li>Find the primary key(s) of the table</li> * <li>Query all rows in the inactive database table, sorting by the primary key(s)</li> * <li>Query all rows on the active database table</li> * <li>For each row in table: * <ol> * <li>If primary key of the rows are the same, determine whether or not row needs to be updated</li> * <li>Otherwise, determine whether row should be deleted, or a new row is to be inserted</li> * </ol> * </li> * <li>Re-create the unique constraints on the table (to avoid integrity constraint violations)</li> * </ol> * </li> * <li>Re-create the foreign keys on the inactive database</li> * <li>Synchronize sequences</li> * </ol> * @author Paul Ferraro * @version $Revision$ * @since 1.0 */ public class DifferentialSynchronizationStrategy implements SynchronizationStrategy { private static Logger logger = LoggerFactory.getLogger(DifferentialSynchronizationStrategy.class); private ExecutorService executor = Executors.newSingleThreadExecutor(DaemonThreadFactory.getInstance()); private int fetchSize = 0; /** * @see net.sf.hajdbc.SynchronizationStrategy#synchronize(java.sql.Connection, java.sql.Connection, net.sf.hajdbc.DatabaseMetaDataCache, net.sf.hajdbc.Dialect) */ public void synchronize(Connection inactiveConnection, Connection activeConnection, DatabaseMetaDataCache metaData, Dialect dialect) throws SQLException { inactiveConnection.setAutoCommit(true); Statement statement = inactiveConnection.createStatement(); Collection<TableProperties> tables = metaData.getDatabaseProperties(inactiveConnection).getTables(); // Drop foreign key constraints on the inactive database for (TableProperties table: tables) { for (ForeignKeyConstraint constraint: table.getForeignKeyConstraints()) { String sql = dialect.getDropForeignKeyConstraintSQL(constraint); logger.debug(sql); statement.addBatch(sql); } } statement.executeBatch(); statement.clearBatch(); Map<Short, String> primaryKeyColumnMap = new TreeMap<Short, String>(); Set<Integer> primaryKeyColumnIndexSet = new LinkedHashSet<Integer>(); inactiveConnection.setAutoCommit(false); try { for (TableProperties table: tables) { primaryKeyColumnMap.clear(); primaryKeyColumnIndexSet.clear(); UniqueConstraint primaryKey = table.getPrimaryKey(); if (primaryKey == null) { throw new SQLException(Messages.getMessage(Messages.PRIMARY_KEY_REQUIRED, this.getClass().getName(), table.getName())); } List<String> primaryKeyColumnList = primaryKey.getColumnList(); Collection<UniqueConstraint> constraints = table.getUniqueConstraints(); constraints.remove(primaryKey); // Drop unique constraints on the current table for (UniqueConstraint constraint: constraints) { String sql = dialect.getDropUniqueConstraintSQL(constraint); logger.debug(sql); statement.addBatch(sql); } statement.executeBatch(); statement.clearBatch(); Collection<String> columns = table.getColumns(); // List of colums for select statement - starting with primary key - List<String> columnList = new ArrayList<String>(columns); + List<String> columnList = new ArrayList<String>(columns.size()); columnList.addAll(primaryKeyColumnList); for (String column: columns) { if (!primaryKeyColumnList.contains(column)) { columnList.add(column); } } List<String> nonPrimaryKeyColumnList = columnList.subList(primaryKeyColumnList.size(), columnList.size()); String commaDelimitedColumns = Strings.join(columnList, ", "); // Retrieve table rows in primary key order final String selectSQL = "SELECT " + commaDelimitedColumns + " FROM " + table.getName() + " ORDER BY " + Strings.join(primaryKeyColumnList, ", "); final Statement inactiveStatement = inactiveConnection.createStatement(); inactiveStatement.setFetchSize(this.fetchSize); logger.debug(selectSQL); Callable<ResultSet> callable = new Callable<ResultSet>() { public ResultSet call() throws java.sql.SQLException { return inactiveStatement.executeQuery(selectSQL); } }; Future<ResultSet> future = this.executor.submit(callable); - Statement activeStatement = activeConnection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); + Statement activeStatement = activeConnection.createStatement(); activeStatement.setFetchSize(this.fetchSize); ResultSet activeResultSet = activeStatement.executeQuery(selectSQL); ResultSet inactiveResultSet = future.get(); String primaryKeyWhereClause = " WHERE " + Strings.join(primaryKeyColumnList, " = ? AND ") + " = ?"; // Construct DELETE SQL String deleteSQL = "DELETE FROM " + table.getName() + primaryKeyWhereClause; logger.debug(deleteSQL.toString()); PreparedStatement deleteStatement = inactiveConnection.prepareStatement(deleteSQL); String[] parameters = new String[columnList.size()]; Arrays.fill(parameters, "?"); // Construct INSERT SQL String insertSQL = "INSERT INTO " + table.getName() + " (" + commaDelimitedColumns + ") VALUES (" + Strings.join(Arrays.asList(parameters), ", ") + ")"; logger.debug(insertSQL); PreparedStatement insertStatement = inactiveConnection.prepareStatement(insertSQL); // Construct UPDATE SQL String updateSQL = "UPDATE " + table.getName() + " SET " + Strings.join(nonPrimaryKeyColumnList, " = ?, ") + " = ?" + primaryKeyWhereClause; logger.debug(updateSQL); PreparedStatement updateStatement = inactiveConnection.prepareStatement(updateSQL); boolean hasMoreActiveResults = activeResultSet.next(); boolean hasMoreInactiveResults = inactiveResultSet.next(); int insertCount = 0; int updateCount = 0; int deleteCount = 0; while (hasMoreActiveResults || hasMoreInactiveResults) { int compare = 0; if (!hasMoreActiveResults) { compare = 1; } else if (!hasMoreInactiveResults) { compare = -1; } else { for (int i = 1; i <= primaryKeyColumnList.size(); ++i) { Object activeObject = activeResultSet.getObject(i); Object inactiveObject = inactiveResultSet.getObject(i); // We assume that the primary keys column types are Comparable compare = this.compare(activeObject, inactiveObject); if (compare != 0) { break; } } } if (compare > 0) { deleteStatement.clearParameters(); for (int i = 1; i <= primaryKeyColumnList.size(); ++i) { int type = dialect.getColumnType(table.getColumn(columnList.get(i - 1))); deleteStatement.setObject(i, inactiveResultSet.getObject(i), type); } deleteStatement.addBatch(); deleteCount += 1; } else if (compare < 0) { insertStatement.clearParameters(); for (int i = 1; i <= columnList.size(); ++i) { Object object = activeResultSet.getObject(i); int type = dialect.getColumnType(table.getColumn(columnList.get(i - 1))); if (activeResultSet.wasNull()) { insertStatement.setNull(i, type); } else { insertStatement.setObject(i, object, type); } } insertStatement.addBatch(); insertCount += 1; } else // if (compare == 0) { updateStatement.clearParameters(); boolean updated = false; for (int i = primaryKeyColumnList.size() + 1; i <= columnList.size(); ++i) { Object activeObject = activeResultSet.getObject(i); Object inactiveObject = inactiveResultSet.getObject(i); int type = dialect.getColumnType(table.getColumn(columnList.get(i - 1))); int index = i - primaryKeyColumnList.size(); if (activeResultSet.wasNull()) { updateStatement.setNull(index, type); updated |= !inactiveResultSet.wasNull(); } else { updateStatement.setObject(index, activeObject, type); updated |= inactiveResultSet.wasNull(); updated |= !equals(activeObject, inactiveObject); } } if (updated) { for (int i = 1; i <= primaryKeyColumnList.size(); ++i) { int type = dialect.getColumnType(table.getColumn(columnList.get(i - 1))); updateStatement.setObject(i + nonPrimaryKeyColumnList.size(), inactiveResultSet.getObject(i), type); } updateStatement.addBatch(); updateCount += 1; } } if (hasMoreActiveResults && (compare <= 0)) { hasMoreActiveResults = activeResultSet.next(); } if (hasMoreInactiveResults && (compare >= 0)) { hasMoreInactiveResults = inactiveResultSet.next(); } } if (deleteCount > 0) { deleteStatement.executeBatch(); } deleteStatement.close(); if (insertCount > 0) { insertStatement.executeBatch(); } insertStatement.close(); if (updateCount > 0) { updateStatement.executeBatch(); } updateStatement.close(); inactiveStatement.close(); activeStatement.close(); // Collect unique constraints on this table from the active database and re-create them on the inactive database for (UniqueConstraint constraint: constraints) { String sql = dialect.getCreateUniqueConstraintSQL(constraint); logger.debug(sql); statement.addBatch(sql); } statement.executeBatch(); statement.clearBatch(); inactiveConnection.commit(); logger.info(Messages.getMessage(Messages.INSERT_COUNT, insertCount, table.getName())); logger.info(Messages.getMessage(Messages.UPDATE_COUNT, updateCount, table.getName())); logger.info(Messages.getMessage(Messages.DELETE_COUNT, deleteCount, table.getName())); } } catch (ExecutionException e) { this.rollback(inactiveConnection); throw new net.sf.hajdbc.SQLException(e.getCause()); } catch (InterruptedException e) { this.rollback(inactiveConnection); throw new net.sf.hajdbc.SQLException(e); } catch (SQLException e) { this.rollback(inactiveConnection); throw e; } inactiveConnection.setAutoCommit(true); // Collect foreign key constraints from the active database and create them on the inactive database for (TableProperties table: tables) { for (ForeignKeyConstraint constraint: table.getForeignKeyConstraints()) { String sql = dialect.getCreateForeignKeyConstraintSQL(constraint); logger.debug(sql); statement.addBatch(sql); } } statement.executeBatch(); statement.clearBatch(); Map<String, Long> activeSequenceMap = dialect.getSequences(activeConnection); Map<String, Long> inactiveSequenceMap = dialect.getSequences(inactiveConnection); for (String sequence: activeSequenceMap.keySet()) { long activeValue = activeSequenceMap.get(sequence); long inactiveValue = inactiveSequenceMap.get(sequence); if (activeValue != inactiveValue) { String sql = dialect.getAlterSequenceSQL(sequence, activeValue); logger.debug(sql); statement.addBatch(sql); } } statement.executeBatch(); statement.close(); } private boolean equals(Object object1, Object object2) { if (byte[].class.isInstance(object1) && byte[].class.isInstance(object2)) { byte[] bytes1 = (byte[]) object1; byte[] bytes2 = (byte[]) object2; if (bytes1.length != bytes2.length) { return false; } return Arrays.equals(bytes1, bytes2); } return object1.equals(object2); } @SuppressWarnings("unchecked") private int compare(Object object1, Object object2) { return Comparable.class.cast(object1).compareTo(object2); } /** * @see net.sf.hajdbc.SynchronizationStrategy#requiresTableLocking() */ public boolean requiresTableLocking() { return true; } private void rollback(Connection connection) { try { connection.rollback(); connection.setAutoCommit(true); } catch (java.sql.SQLException e) { logger.warn(e.toString(), e); } } /** * @return the fetchSize. */ public int getFetchSize() { return this.fetchSize; } /** * @param fetchSize the fetchSize to set. */ public void setFetchSize(int fetchSize) { this.fetchSize = fetchSize; } }
false
true
public void synchronize(Connection inactiveConnection, Connection activeConnection, DatabaseMetaDataCache metaData, Dialect dialect) throws SQLException { inactiveConnection.setAutoCommit(true); Statement statement = inactiveConnection.createStatement(); Collection<TableProperties> tables = metaData.getDatabaseProperties(inactiveConnection).getTables(); // Drop foreign key constraints on the inactive database for (TableProperties table: tables) { for (ForeignKeyConstraint constraint: table.getForeignKeyConstraints()) { String sql = dialect.getDropForeignKeyConstraintSQL(constraint); logger.debug(sql); statement.addBatch(sql); } } statement.executeBatch(); statement.clearBatch(); Map<Short, String> primaryKeyColumnMap = new TreeMap<Short, String>(); Set<Integer> primaryKeyColumnIndexSet = new LinkedHashSet<Integer>(); inactiveConnection.setAutoCommit(false); try { for (TableProperties table: tables) { primaryKeyColumnMap.clear(); primaryKeyColumnIndexSet.clear(); UniqueConstraint primaryKey = table.getPrimaryKey(); if (primaryKey == null) { throw new SQLException(Messages.getMessage(Messages.PRIMARY_KEY_REQUIRED, this.getClass().getName(), table.getName())); } List<String> primaryKeyColumnList = primaryKey.getColumnList(); Collection<UniqueConstraint> constraints = table.getUniqueConstraints(); constraints.remove(primaryKey); // Drop unique constraints on the current table for (UniqueConstraint constraint: constraints) { String sql = dialect.getDropUniqueConstraintSQL(constraint); logger.debug(sql); statement.addBatch(sql); } statement.executeBatch(); statement.clearBatch(); Collection<String> columns = table.getColumns(); // List of colums for select statement - starting with primary key List<String> columnList = new ArrayList<String>(columns); columnList.addAll(primaryKeyColumnList); for (String column: columns) { if (!primaryKeyColumnList.contains(column)) { columnList.add(column); } } List<String> nonPrimaryKeyColumnList = columnList.subList(primaryKeyColumnList.size(), columnList.size()); String commaDelimitedColumns = Strings.join(columnList, ", "); // Retrieve table rows in primary key order final String selectSQL = "SELECT " + commaDelimitedColumns + " FROM " + table.getName() + " ORDER BY " + Strings.join(primaryKeyColumnList, ", "); final Statement inactiveStatement = inactiveConnection.createStatement(); inactiveStatement.setFetchSize(this.fetchSize); logger.debug(selectSQL); Callable<ResultSet> callable = new Callable<ResultSet>() { public ResultSet call() throws java.sql.SQLException { return inactiveStatement.executeQuery(selectSQL); } }; Future<ResultSet> future = this.executor.submit(callable); Statement activeStatement = activeConnection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); activeStatement.setFetchSize(this.fetchSize); ResultSet activeResultSet = activeStatement.executeQuery(selectSQL); ResultSet inactiveResultSet = future.get(); String primaryKeyWhereClause = " WHERE " + Strings.join(primaryKeyColumnList, " = ? AND ") + " = ?"; // Construct DELETE SQL String deleteSQL = "DELETE FROM " + table.getName() + primaryKeyWhereClause; logger.debug(deleteSQL.toString()); PreparedStatement deleteStatement = inactiveConnection.prepareStatement(deleteSQL); String[] parameters = new String[columnList.size()]; Arrays.fill(parameters, "?"); // Construct INSERT SQL String insertSQL = "INSERT INTO " + table.getName() + " (" + commaDelimitedColumns + ") VALUES (" + Strings.join(Arrays.asList(parameters), ", ") + ")"; logger.debug(insertSQL); PreparedStatement insertStatement = inactiveConnection.prepareStatement(insertSQL); // Construct UPDATE SQL String updateSQL = "UPDATE " + table.getName() + " SET " + Strings.join(nonPrimaryKeyColumnList, " = ?, ") + " = ?" + primaryKeyWhereClause; logger.debug(updateSQL); PreparedStatement updateStatement = inactiveConnection.prepareStatement(updateSQL); boolean hasMoreActiveResults = activeResultSet.next(); boolean hasMoreInactiveResults = inactiveResultSet.next(); int insertCount = 0; int updateCount = 0; int deleteCount = 0; while (hasMoreActiveResults || hasMoreInactiveResults) { int compare = 0; if (!hasMoreActiveResults) { compare = 1; } else if (!hasMoreInactiveResults) { compare = -1; } else { for (int i = 1; i <= primaryKeyColumnList.size(); ++i) { Object activeObject = activeResultSet.getObject(i); Object inactiveObject = inactiveResultSet.getObject(i); // We assume that the primary keys column types are Comparable compare = this.compare(activeObject, inactiveObject); if (compare != 0) { break; } } } if (compare > 0) { deleteStatement.clearParameters(); for (int i = 1; i <= primaryKeyColumnList.size(); ++i) { int type = dialect.getColumnType(table.getColumn(columnList.get(i - 1))); deleteStatement.setObject(i, inactiveResultSet.getObject(i), type); } deleteStatement.addBatch(); deleteCount += 1; } else if (compare < 0) { insertStatement.clearParameters(); for (int i = 1; i <= columnList.size(); ++i) { Object object = activeResultSet.getObject(i); int type = dialect.getColumnType(table.getColumn(columnList.get(i - 1))); if (activeResultSet.wasNull()) { insertStatement.setNull(i, type); } else { insertStatement.setObject(i, object, type); } } insertStatement.addBatch(); insertCount += 1; } else // if (compare == 0) { updateStatement.clearParameters(); boolean updated = false; for (int i = primaryKeyColumnList.size() + 1; i <= columnList.size(); ++i) { Object activeObject = activeResultSet.getObject(i); Object inactiveObject = inactiveResultSet.getObject(i); int type = dialect.getColumnType(table.getColumn(columnList.get(i - 1))); int index = i - primaryKeyColumnList.size(); if (activeResultSet.wasNull()) { updateStatement.setNull(index, type); updated |= !inactiveResultSet.wasNull(); } else { updateStatement.setObject(index, activeObject, type); updated |= inactiveResultSet.wasNull(); updated |= !equals(activeObject, inactiveObject); } } if (updated) { for (int i = 1; i <= primaryKeyColumnList.size(); ++i) { int type = dialect.getColumnType(table.getColumn(columnList.get(i - 1))); updateStatement.setObject(i + nonPrimaryKeyColumnList.size(), inactiveResultSet.getObject(i), type); } updateStatement.addBatch(); updateCount += 1; } } if (hasMoreActiveResults && (compare <= 0)) { hasMoreActiveResults = activeResultSet.next(); } if (hasMoreInactiveResults && (compare >= 0)) { hasMoreInactiveResults = inactiveResultSet.next(); } } if (deleteCount > 0) { deleteStatement.executeBatch(); } deleteStatement.close(); if (insertCount > 0) { insertStatement.executeBatch(); } insertStatement.close(); if (updateCount > 0) { updateStatement.executeBatch(); } updateStatement.close(); inactiveStatement.close(); activeStatement.close(); // Collect unique constraints on this table from the active database and re-create them on the inactive database for (UniqueConstraint constraint: constraints) { String sql = dialect.getCreateUniqueConstraintSQL(constraint); logger.debug(sql); statement.addBatch(sql); } statement.executeBatch(); statement.clearBatch(); inactiveConnection.commit(); logger.info(Messages.getMessage(Messages.INSERT_COUNT, insertCount, table.getName())); logger.info(Messages.getMessage(Messages.UPDATE_COUNT, updateCount, table.getName())); logger.info(Messages.getMessage(Messages.DELETE_COUNT, deleteCount, table.getName())); } } catch (ExecutionException e) { this.rollback(inactiveConnection); throw new net.sf.hajdbc.SQLException(e.getCause()); } catch (InterruptedException e) { this.rollback(inactiveConnection); throw new net.sf.hajdbc.SQLException(e); } catch (SQLException e) { this.rollback(inactiveConnection); throw e; } inactiveConnection.setAutoCommit(true); // Collect foreign key constraints from the active database and create them on the inactive database for (TableProperties table: tables) { for (ForeignKeyConstraint constraint: table.getForeignKeyConstraints()) { String sql = dialect.getCreateForeignKeyConstraintSQL(constraint); logger.debug(sql); statement.addBatch(sql); } } statement.executeBatch(); statement.clearBatch(); Map<String, Long> activeSequenceMap = dialect.getSequences(activeConnection); Map<String, Long> inactiveSequenceMap = dialect.getSequences(inactiveConnection); for (String sequence: activeSequenceMap.keySet()) { long activeValue = activeSequenceMap.get(sequence); long inactiveValue = inactiveSequenceMap.get(sequence); if (activeValue != inactiveValue) { String sql = dialect.getAlterSequenceSQL(sequence, activeValue); logger.debug(sql); statement.addBatch(sql); } } statement.executeBatch(); statement.close(); }
public void synchronize(Connection inactiveConnection, Connection activeConnection, DatabaseMetaDataCache metaData, Dialect dialect) throws SQLException { inactiveConnection.setAutoCommit(true); Statement statement = inactiveConnection.createStatement(); Collection<TableProperties> tables = metaData.getDatabaseProperties(inactiveConnection).getTables(); // Drop foreign key constraints on the inactive database for (TableProperties table: tables) { for (ForeignKeyConstraint constraint: table.getForeignKeyConstraints()) { String sql = dialect.getDropForeignKeyConstraintSQL(constraint); logger.debug(sql); statement.addBatch(sql); } } statement.executeBatch(); statement.clearBatch(); Map<Short, String> primaryKeyColumnMap = new TreeMap<Short, String>(); Set<Integer> primaryKeyColumnIndexSet = new LinkedHashSet<Integer>(); inactiveConnection.setAutoCommit(false); try { for (TableProperties table: tables) { primaryKeyColumnMap.clear(); primaryKeyColumnIndexSet.clear(); UniqueConstraint primaryKey = table.getPrimaryKey(); if (primaryKey == null) { throw new SQLException(Messages.getMessage(Messages.PRIMARY_KEY_REQUIRED, this.getClass().getName(), table.getName())); } List<String> primaryKeyColumnList = primaryKey.getColumnList(); Collection<UniqueConstraint> constraints = table.getUniqueConstraints(); constraints.remove(primaryKey); // Drop unique constraints on the current table for (UniqueConstraint constraint: constraints) { String sql = dialect.getDropUniqueConstraintSQL(constraint); logger.debug(sql); statement.addBatch(sql); } statement.executeBatch(); statement.clearBatch(); Collection<String> columns = table.getColumns(); // List of colums for select statement - starting with primary key List<String> columnList = new ArrayList<String>(columns.size()); columnList.addAll(primaryKeyColumnList); for (String column: columns) { if (!primaryKeyColumnList.contains(column)) { columnList.add(column); } } List<String> nonPrimaryKeyColumnList = columnList.subList(primaryKeyColumnList.size(), columnList.size()); String commaDelimitedColumns = Strings.join(columnList, ", "); // Retrieve table rows in primary key order final String selectSQL = "SELECT " + commaDelimitedColumns + " FROM " + table.getName() + " ORDER BY " + Strings.join(primaryKeyColumnList, ", "); final Statement inactiveStatement = inactiveConnection.createStatement(); inactiveStatement.setFetchSize(this.fetchSize); logger.debug(selectSQL); Callable<ResultSet> callable = new Callable<ResultSet>() { public ResultSet call() throws java.sql.SQLException { return inactiveStatement.executeQuery(selectSQL); } }; Future<ResultSet> future = this.executor.submit(callable); Statement activeStatement = activeConnection.createStatement(); activeStatement.setFetchSize(this.fetchSize); ResultSet activeResultSet = activeStatement.executeQuery(selectSQL); ResultSet inactiveResultSet = future.get(); String primaryKeyWhereClause = " WHERE " + Strings.join(primaryKeyColumnList, " = ? AND ") + " = ?"; // Construct DELETE SQL String deleteSQL = "DELETE FROM " + table.getName() + primaryKeyWhereClause; logger.debug(deleteSQL.toString()); PreparedStatement deleteStatement = inactiveConnection.prepareStatement(deleteSQL); String[] parameters = new String[columnList.size()]; Arrays.fill(parameters, "?"); // Construct INSERT SQL String insertSQL = "INSERT INTO " + table.getName() + " (" + commaDelimitedColumns + ") VALUES (" + Strings.join(Arrays.asList(parameters), ", ") + ")"; logger.debug(insertSQL); PreparedStatement insertStatement = inactiveConnection.prepareStatement(insertSQL); // Construct UPDATE SQL String updateSQL = "UPDATE " + table.getName() + " SET " + Strings.join(nonPrimaryKeyColumnList, " = ?, ") + " = ?" + primaryKeyWhereClause; logger.debug(updateSQL); PreparedStatement updateStatement = inactiveConnection.prepareStatement(updateSQL); boolean hasMoreActiveResults = activeResultSet.next(); boolean hasMoreInactiveResults = inactiveResultSet.next(); int insertCount = 0; int updateCount = 0; int deleteCount = 0; while (hasMoreActiveResults || hasMoreInactiveResults) { int compare = 0; if (!hasMoreActiveResults) { compare = 1; } else if (!hasMoreInactiveResults) { compare = -1; } else { for (int i = 1; i <= primaryKeyColumnList.size(); ++i) { Object activeObject = activeResultSet.getObject(i); Object inactiveObject = inactiveResultSet.getObject(i); // We assume that the primary keys column types are Comparable compare = this.compare(activeObject, inactiveObject); if (compare != 0) { break; } } } if (compare > 0) { deleteStatement.clearParameters(); for (int i = 1; i <= primaryKeyColumnList.size(); ++i) { int type = dialect.getColumnType(table.getColumn(columnList.get(i - 1))); deleteStatement.setObject(i, inactiveResultSet.getObject(i), type); } deleteStatement.addBatch(); deleteCount += 1; } else if (compare < 0) { insertStatement.clearParameters(); for (int i = 1; i <= columnList.size(); ++i) { Object object = activeResultSet.getObject(i); int type = dialect.getColumnType(table.getColumn(columnList.get(i - 1))); if (activeResultSet.wasNull()) { insertStatement.setNull(i, type); } else { insertStatement.setObject(i, object, type); } } insertStatement.addBatch(); insertCount += 1; } else // if (compare == 0) { updateStatement.clearParameters(); boolean updated = false; for (int i = primaryKeyColumnList.size() + 1; i <= columnList.size(); ++i) { Object activeObject = activeResultSet.getObject(i); Object inactiveObject = inactiveResultSet.getObject(i); int type = dialect.getColumnType(table.getColumn(columnList.get(i - 1))); int index = i - primaryKeyColumnList.size(); if (activeResultSet.wasNull()) { updateStatement.setNull(index, type); updated |= !inactiveResultSet.wasNull(); } else { updateStatement.setObject(index, activeObject, type); updated |= inactiveResultSet.wasNull(); updated |= !equals(activeObject, inactiveObject); } } if (updated) { for (int i = 1; i <= primaryKeyColumnList.size(); ++i) { int type = dialect.getColumnType(table.getColumn(columnList.get(i - 1))); updateStatement.setObject(i + nonPrimaryKeyColumnList.size(), inactiveResultSet.getObject(i), type); } updateStatement.addBatch(); updateCount += 1; } } if (hasMoreActiveResults && (compare <= 0)) { hasMoreActiveResults = activeResultSet.next(); } if (hasMoreInactiveResults && (compare >= 0)) { hasMoreInactiveResults = inactiveResultSet.next(); } } if (deleteCount > 0) { deleteStatement.executeBatch(); } deleteStatement.close(); if (insertCount > 0) { insertStatement.executeBatch(); } insertStatement.close(); if (updateCount > 0) { updateStatement.executeBatch(); } updateStatement.close(); inactiveStatement.close(); activeStatement.close(); // Collect unique constraints on this table from the active database and re-create them on the inactive database for (UniqueConstraint constraint: constraints) { String sql = dialect.getCreateUniqueConstraintSQL(constraint); logger.debug(sql); statement.addBatch(sql); } statement.executeBatch(); statement.clearBatch(); inactiveConnection.commit(); logger.info(Messages.getMessage(Messages.INSERT_COUNT, insertCount, table.getName())); logger.info(Messages.getMessage(Messages.UPDATE_COUNT, updateCount, table.getName())); logger.info(Messages.getMessage(Messages.DELETE_COUNT, deleteCount, table.getName())); } } catch (ExecutionException e) { this.rollback(inactiveConnection); throw new net.sf.hajdbc.SQLException(e.getCause()); } catch (InterruptedException e) { this.rollback(inactiveConnection); throw new net.sf.hajdbc.SQLException(e); } catch (SQLException e) { this.rollback(inactiveConnection); throw e; } inactiveConnection.setAutoCommit(true); // Collect foreign key constraints from the active database and create them on the inactive database for (TableProperties table: tables) { for (ForeignKeyConstraint constraint: table.getForeignKeyConstraints()) { String sql = dialect.getCreateForeignKeyConstraintSQL(constraint); logger.debug(sql); statement.addBatch(sql); } } statement.executeBatch(); statement.clearBatch(); Map<String, Long> activeSequenceMap = dialect.getSequences(activeConnection); Map<String, Long> inactiveSequenceMap = dialect.getSequences(inactiveConnection); for (String sequence: activeSequenceMap.keySet()) { long activeValue = activeSequenceMap.get(sequence); long inactiveValue = inactiveSequenceMap.get(sequence); if (activeValue != inactiveValue) { String sql = dialect.getAlterSequenceSQL(sequence, activeValue); logger.debug(sql); statement.addBatch(sql); } } statement.executeBatch(); statement.close(); }
diff --git a/src/java/org/jamwiki/servlets/MoveServlet.java b/src/java/org/jamwiki/servlets/MoveServlet.java index 385b8255..7f9616fc 100644 --- a/src/java/org/jamwiki/servlets/MoveServlet.java +++ b/src/java/org/jamwiki/servlets/MoveServlet.java @@ -1,117 +1,118 @@ /** * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, version 2.1, dated February 1999. * * This program is free software; you can redistribute it and/or modify * it under the terms of the latest version of the GNU Lesser General * Public License as published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program (LICENSE.txt); if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.jamwiki.servlets; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.jamwiki.WikiBase; import org.jamwiki.model.Topic; import org.jamwiki.model.TopicVersion; import org.jamwiki.model.WikiUser; import org.jamwiki.utils.Utilities; import org.springframework.util.StringUtils; import org.springframework.web.servlet.ModelAndView; /** * */ public class MoveServlet extends JAMWikiServlet { private static final Logger logger = Logger.getLogger(MoveServlet.class); /** * */ public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) { ModelAndView next = new ModelAndView("wiki"); WikiPageInfo pageInfo = new WikiPageInfo(); try { if (request.getParameter("move") != null) { // FIXME - temporarily make admin only if (!Utilities.isAdmin(request)) { WikiMessage errorMessage = new WikiMessage("admin.message.loginrequired"); return viewLogin(request, JAMWikiServlet.getTopicFromURI(request), errorMessage); } move(request, next, pageInfo); } else { view(request, next, pageInfo); } } catch (Exception e) { return viewError(request, e); } loadDefaults(request, next, pageInfo); return next; } /** * */ private void move(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) throws Exception { String virtualWiki = JAMWikiServlet.getVirtualWikiFromURI(request); String topicName = JAMWikiServlet.getTopicFromRequest(request); if (!StringUtils.hasText(topicName)) { throw new WikiException(new WikiMessage("common.exception.notopic")); } WikiMessage pageTitle = new WikiMessage("move.title", topicName); pageInfo.setPageTitle(pageTitle); - pageInfo.setAction(WikiPageInfo.ACTION_MOVE); pageInfo.setTopicName(topicName); Topic topic = WikiBase.getHandler().lookupTopic(virtualWiki, topicName); if (topic == null) { throw new WikiException(new WikiMessage("common.exception.notopic")); } String moveDestination = request.getParameter("moveDestination"); if (!StringUtils.hasText(moveDestination)) { + pageInfo.setAction(WikiPageInfo.ACTION_MOVE); next.addObject("errorMessage", new WikiMessage("move.exception.nodestination")); return; } Topic oldTopic = WikiBase.getHandler().lookupTopic(virtualWiki, moveDestination); // FIXME - allow overwriting a deleted topic if (oldTopic != null) { + pageInfo.setAction(WikiPageInfo.ACTION_MOVE); next.addObject("errorMessage", new WikiMessage("move.exception.destinationexists", moveDestination)); return; } WikiUser user = Utilities.currentUser(request); Integer authorId = null; if (user != null) { authorId = new Integer(user.getUserId()); } String moveComment = Utilities.getMessage("move.editcomment", request.getLocale()) + " " + topicName; if (StringUtils.hasText(request.getParameter("moveComment"))) { moveComment += ": " + request.getParameter("moveComment"); } TopicVersion topicVersion = new TopicVersion(authorId, request.getRemoteAddr(), moveComment, topic.getTopicContent()); topicVersion.setEditType(TopicVersion.EDIT_MOVE); WikiBase.getHandler().moveTopic(topic, topicVersion, moveDestination); viewTopic(request, next, pageInfo, moveDestination); } /** * */ private void view(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) throws Exception { String topicName = JAMWikiServlet.getTopicFromRequest(request); if (!StringUtils.hasText(topicName)) { throw new WikiException(new WikiMessage("common.exception.notopic")); } WikiMessage pageTitle = new WikiMessage("move.title", topicName); pageInfo.setPageTitle(pageTitle); pageInfo.setAction(WikiPageInfo.ACTION_MOVE); pageInfo.setTopicName(topicName); } }
false
true
private void move(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) throws Exception { String virtualWiki = JAMWikiServlet.getVirtualWikiFromURI(request); String topicName = JAMWikiServlet.getTopicFromRequest(request); if (!StringUtils.hasText(topicName)) { throw new WikiException(new WikiMessage("common.exception.notopic")); } WikiMessage pageTitle = new WikiMessage("move.title", topicName); pageInfo.setPageTitle(pageTitle); pageInfo.setAction(WikiPageInfo.ACTION_MOVE); pageInfo.setTopicName(topicName); Topic topic = WikiBase.getHandler().lookupTopic(virtualWiki, topicName); if (topic == null) { throw new WikiException(new WikiMessage("common.exception.notopic")); } String moveDestination = request.getParameter("moveDestination"); if (!StringUtils.hasText(moveDestination)) { next.addObject("errorMessage", new WikiMessage("move.exception.nodestination")); return; } Topic oldTopic = WikiBase.getHandler().lookupTopic(virtualWiki, moveDestination); // FIXME - allow overwriting a deleted topic if (oldTopic != null) { next.addObject("errorMessage", new WikiMessage("move.exception.destinationexists", moveDestination)); return; } WikiUser user = Utilities.currentUser(request); Integer authorId = null; if (user != null) { authorId = new Integer(user.getUserId()); } String moveComment = Utilities.getMessage("move.editcomment", request.getLocale()) + " " + topicName; if (StringUtils.hasText(request.getParameter("moveComment"))) { moveComment += ": " + request.getParameter("moveComment"); } TopicVersion topicVersion = new TopicVersion(authorId, request.getRemoteAddr(), moveComment, topic.getTopicContent()); topicVersion.setEditType(TopicVersion.EDIT_MOVE); WikiBase.getHandler().moveTopic(topic, topicVersion, moveDestination); viewTopic(request, next, pageInfo, moveDestination); }
private void move(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) throws Exception { String virtualWiki = JAMWikiServlet.getVirtualWikiFromURI(request); String topicName = JAMWikiServlet.getTopicFromRequest(request); if (!StringUtils.hasText(topicName)) { throw new WikiException(new WikiMessage("common.exception.notopic")); } WikiMessage pageTitle = new WikiMessage("move.title", topicName); pageInfo.setPageTitle(pageTitle); pageInfo.setTopicName(topicName); Topic topic = WikiBase.getHandler().lookupTopic(virtualWiki, topicName); if (topic == null) { throw new WikiException(new WikiMessage("common.exception.notopic")); } String moveDestination = request.getParameter("moveDestination"); if (!StringUtils.hasText(moveDestination)) { pageInfo.setAction(WikiPageInfo.ACTION_MOVE); next.addObject("errorMessage", new WikiMessage("move.exception.nodestination")); return; } Topic oldTopic = WikiBase.getHandler().lookupTopic(virtualWiki, moveDestination); // FIXME - allow overwriting a deleted topic if (oldTopic != null) { pageInfo.setAction(WikiPageInfo.ACTION_MOVE); next.addObject("errorMessage", new WikiMessage("move.exception.destinationexists", moveDestination)); return; } WikiUser user = Utilities.currentUser(request); Integer authorId = null; if (user != null) { authorId = new Integer(user.getUserId()); } String moveComment = Utilities.getMessage("move.editcomment", request.getLocale()) + " " + topicName; if (StringUtils.hasText(request.getParameter("moveComment"))) { moveComment += ": " + request.getParameter("moveComment"); } TopicVersion topicVersion = new TopicVersion(authorId, request.getRemoteAddr(), moveComment, topic.getTopicContent()); topicVersion.setEditType(TopicVersion.EDIT_MOVE); WikiBase.getHandler().moveTopic(topic, topicVersion, moveDestination); viewTopic(request, next, pageInfo, moveDestination); }
diff --git a/xbean-server/src/main/java/org/apache/xbean/server/spring/configuration/ClassLoaderXmlPreprocessor.java b/xbean-server/src/main/java/org/apache/xbean/server/spring/configuration/ClassLoaderXmlPreprocessor.java index 2481e833..dbc39df2 100644 --- a/xbean-server/src/main/java/org/apache/xbean/server/spring/configuration/ClassLoaderXmlPreprocessor.java +++ b/xbean-server/src/main/java/org/apache/xbean/server/spring/configuration/ClassLoaderXmlPreprocessor.java @@ -1,119 +1,123 @@ /** * * Copyright 2005-2006 The Apache Software Foundation or its licensors, as applicable. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xbean.server.spring.configuration; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import org.apache.xbean.server.classloader.MultiParentClassLoader; import org.apache.xbean.server.repository.Repository; import org.apache.xbean.server.spring.loader.SpringLoader; import org.apache.xbean.spring.context.SpringXmlPreprocessor; import org.apache.xbean.spring.context.SpringApplicationContext; import org.springframework.beans.FatalBeanException; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.w3c.dom.Text; /** * ClassLoaderXmlPreprocessor extracts a ClassLoader definition from the xml document, builds a class loader, assigns * the class loader to the application context and xml reader, and removes the classpath element from document. * * @org.apache.xbean.XBean namespace="http://xbean.apache.org/schemas/server" element="class-loader-xml-preprocessor" * description="Extracts a ClassLoader definition from the xml document." * * @author Dain Sundstrom * @version $Id$ * @since 2.0 */ public class ClassLoaderXmlPreprocessor implements SpringXmlPreprocessor { private final Repository repository; /** * Creates a ClassLoaderXmlPreprocessor that uses the specified repository to resolve the class path locations. * @param repository the repository used to resolve the class path locations */ public ClassLoaderXmlPreprocessor(Repository repository) { this.repository = repository; } /** * Extracts a ClassLoader definition from the xml document, builds a class loader, assigns * the class loader to the application context and xml reader, and removes the classpath element from document. * * @param applicationContext the application context on which the class loader will be set * @param reader the xml reader on which the class loader will be set * @param document the xml document to inspect */ public void preprocess(SpringApplicationContext applicationContext, XmlBeanDefinitionReader reader, Document document) { // determine the classLoader ClassLoader classLoader; NodeList classpathElements = document.getDocumentElement().getElementsByTagName("classpath"); if (classpathElements.getLength() < 1) { classLoader = getClassLoader(applicationContext); } else if (classpathElements.getLength() > 1) { throw new FatalBeanException("Expected only classpath element but found " + classpathElements.getLength()); } else { Element classpathElement = (Element) classpathElements.item(0); // build the classpath List classpath = new ArrayList(); NodeList locations = classpathElement.getElementsByTagName("location"); for (int i = 0; i < locations.getLength(); i++) { Element locationElement = (Element) locations.item(i); String location = ((Text) locationElement.getFirstChild()).getData().trim(); classpath.add(location); } // convert the paths to URLS URL[] urls = new URL[classpath.size()]; for (ListIterator iterator = classpath.listIterator(); iterator.hasNext();) { String location = (String) iterator.next(); - urls[iterator.previousIndex()] = repository.getResource(location); + URL url = repository.getResource(location); + if (url == null) { + throw new FatalBeanException("Unable to resolve classpath location " + location); + } + urls[iterator.previousIndex()] = url; } // create the classloader ClassLoader parentLoader = getClassLoader(applicationContext); classLoader = new MultiParentClassLoader(applicationContext.getDisplayName(), urls, parentLoader); // remove the classpath element so Spring doesn't get confused document.getDocumentElement().removeChild(classpathElement); } // assign the class loader to the xml reader and the application context reader.setBeanClassLoader(classLoader); applicationContext.setClassLoader(classLoader); Thread.currentThread().setContextClassLoader(classLoader); } private static ClassLoader getClassLoader(SpringApplicationContext applicationContext) { ClassLoader classLoader = applicationContext.getClassLoader(); if (classLoader == null) { classLoader = Thread.currentThread().getContextClassLoader(); } if (classLoader == null) { classLoader = SpringLoader.class.getClassLoader(); } return classLoader; } }
true
true
public void preprocess(SpringApplicationContext applicationContext, XmlBeanDefinitionReader reader, Document document) { // determine the classLoader ClassLoader classLoader; NodeList classpathElements = document.getDocumentElement().getElementsByTagName("classpath"); if (classpathElements.getLength() < 1) { classLoader = getClassLoader(applicationContext); } else if (classpathElements.getLength() > 1) { throw new FatalBeanException("Expected only classpath element but found " + classpathElements.getLength()); } else { Element classpathElement = (Element) classpathElements.item(0); // build the classpath List classpath = new ArrayList(); NodeList locations = classpathElement.getElementsByTagName("location"); for (int i = 0; i < locations.getLength(); i++) { Element locationElement = (Element) locations.item(i); String location = ((Text) locationElement.getFirstChild()).getData().trim(); classpath.add(location); } // convert the paths to URLS URL[] urls = new URL[classpath.size()]; for (ListIterator iterator = classpath.listIterator(); iterator.hasNext();) { String location = (String) iterator.next(); urls[iterator.previousIndex()] = repository.getResource(location); } // create the classloader ClassLoader parentLoader = getClassLoader(applicationContext); classLoader = new MultiParentClassLoader(applicationContext.getDisplayName(), urls, parentLoader); // remove the classpath element so Spring doesn't get confused document.getDocumentElement().removeChild(classpathElement); } // assign the class loader to the xml reader and the application context reader.setBeanClassLoader(classLoader); applicationContext.setClassLoader(classLoader); Thread.currentThread().setContextClassLoader(classLoader); }
public void preprocess(SpringApplicationContext applicationContext, XmlBeanDefinitionReader reader, Document document) { // determine the classLoader ClassLoader classLoader; NodeList classpathElements = document.getDocumentElement().getElementsByTagName("classpath"); if (classpathElements.getLength() < 1) { classLoader = getClassLoader(applicationContext); } else if (classpathElements.getLength() > 1) { throw new FatalBeanException("Expected only classpath element but found " + classpathElements.getLength()); } else { Element classpathElement = (Element) classpathElements.item(0); // build the classpath List classpath = new ArrayList(); NodeList locations = classpathElement.getElementsByTagName("location"); for (int i = 0; i < locations.getLength(); i++) { Element locationElement = (Element) locations.item(i); String location = ((Text) locationElement.getFirstChild()).getData().trim(); classpath.add(location); } // convert the paths to URLS URL[] urls = new URL[classpath.size()]; for (ListIterator iterator = classpath.listIterator(); iterator.hasNext();) { String location = (String) iterator.next(); URL url = repository.getResource(location); if (url == null) { throw new FatalBeanException("Unable to resolve classpath location " + location); } urls[iterator.previousIndex()] = url; } // create the classloader ClassLoader parentLoader = getClassLoader(applicationContext); classLoader = new MultiParentClassLoader(applicationContext.getDisplayName(), urls, parentLoader); // remove the classpath element so Spring doesn't get confused document.getDocumentElement().removeChild(classpathElement); } // assign the class loader to the xml reader and the application context reader.setBeanClassLoader(classLoader); applicationContext.setClassLoader(classLoader); Thread.currentThread().setContextClassLoader(classLoader); }
diff --git a/src/ece5984/phase2/truerandomstudy/Grapher.java b/src/ece5984/phase2/truerandomstudy/Grapher.java index 4ee9261..59dafa8 100644 --- a/src/ece5984/phase2/truerandomstudy/Grapher.java +++ b/src/ece5984/phase2/truerandomstudy/Grapher.java @@ -1,81 +1,81 @@ package ece5984.phase2.truerandomstudy; import java.text.DecimalFormat; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Align; import android.view.SurfaceView; public class Grapher { public static Bitmap graph(Analysis analysis) { DecimalFormat df = new DecimalFormat("#.#"); Bitmap bmp = Bitmap.createBitmap(200, 200, Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bmp); Paint paintBlack = new Paint(); paintBlack.setColor(Color.WHITE); paintBlack.setTextAlign(Align.LEFT); Paint paint = new Paint(); paint.setColor(Color.RED); paint.setTextAlign(Align.CENTER); canvas.drawLine(0, 180, 200, 180, paint); canvas.drawText("0", 10, 200, paint); float percentage = (((float)analysis.zeros)/(analysis.ones+analysis.zeros)); canvas.drawRect(0, 180-percentage*170, 20, 180, paint); canvas.save(); canvas.rotate(90, 0, 100); canvas.drawText(df.format(percentage*100)+"%", 0, 100, paintBlack); canvas.restore(); canvas.drawText("1", 30, 200, paint); percentage = (((float)analysis.ones)/(analysis.ones+analysis.zeros)); canvas.drawRect(20, 180-percentage*170, 40, 180, paint); canvas.save(); - canvas.rotate(90, 0, 100); - canvas.drawText(df.format(percentage*100)+"%", 0, 100, paintBlack); + canvas.rotate(90, 20, 100); + canvas.drawText(df.format(percentage*100)+"%", 20, 100, paintBlack); canvas.restore(); paint.setColor(Color.BLUE); int sum = 0; for (int i=0;i<4;i++) { canvas.drawText(""+i, 50+i*20, 200, paint); sum += analysis.pairs[i]; } for (int i=0;i<4;i++) { percentage = (((float)analysis.pairs[i])/sum); float left = 40+i*20; float top = 180-percentage*170; canvas.drawRect(left,top,left+20,180, paint); canvas.save(); canvas.rotate(90, left, 100); canvas.drawText(df.format(percentage*100)+"%", left, 100, paintBlack); canvas.restore(); } paint.setColor(Color.GREEN); sum = 0; for (int i=0;i<8;i++) { canvas.drawText(""+i, 125+i*10, 200, paint); sum += analysis.triples[i]; } for (int i=0;i<8;i++) { percentage = (((float)analysis.triples[i])/sum); float left = 120+i*10; float top = 180-percentage*170; canvas.save(); canvas.drawRect(left,top,left+10,180, paint); canvas.rotate(90, left, 100); canvas.drawText(df.format(percentage*100)+"%", left, 100, paintBlack); canvas.restore(); } return bmp; } }
true
true
public static Bitmap graph(Analysis analysis) { DecimalFormat df = new DecimalFormat("#.#"); Bitmap bmp = Bitmap.createBitmap(200, 200, Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bmp); Paint paintBlack = new Paint(); paintBlack.setColor(Color.WHITE); paintBlack.setTextAlign(Align.LEFT); Paint paint = new Paint(); paint.setColor(Color.RED); paint.setTextAlign(Align.CENTER); canvas.drawLine(0, 180, 200, 180, paint); canvas.drawText("0", 10, 200, paint); float percentage = (((float)analysis.zeros)/(analysis.ones+analysis.zeros)); canvas.drawRect(0, 180-percentage*170, 20, 180, paint); canvas.save(); canvas.rotate(90, 0, 100); canvas.drawText(df.format(percentage*100)+"%", 0, 100, paintBlack); canvas.restore(); canvas.drawText("1", 30, 200, paint); percentage = (((float)analysis.ones)/(analysis.ones+analysis.zeros)); canvas.drawRect(20, 180-percentage*170, 40, 180, paint); canvas.save(); canvas.rotate(90, 0, 100); canvas.drawText(df.format(percentage*100)+"%", 0, 100, paintBlack); canvas.restore(); paint.setColor(Color.BLUE); int sum = 0; for (int i=0;i<4;i++) { canvas.drawText(""+i, 50+i*20, 200, paint); sum += analysis.pairs[i]; } for (int i=0;i<4;i++) { percentage = (((float)analysis.pairs[i])/sum); float left = 40+i*20; float top = 180-percentage*170; canvas.drawRect(left,top,left+20,180, paint); canvas.save(); canvas.rotate(90, left, 100); canvas.drawText(df.format(percentage*100)+"%", left, 100, paintBlack); canvas.restore(); } paint.setColor(Color.GREEN); sum = 0; for (int i=0;i<8;i++) { canvas.drawText(""+i, 125+i*10, 200, paint); sum += analysis.triples[i]; } for (int i=0;i<8;i++) { percentage = (((float)analysis.triples[i])/sum); float left = 120+i*10; float top = 180-percentage*170; canvas.save(); canvas.drawRect(left,top,left+10,180, paint); canvas.rotate(90, left, 100); canvas.drawText(df.format(percentage*100)+"%", left, 100, paintBlack); canvas.restore(); } return bmp; }
public static Bitmap graph(Analysis analysis) { DecimalFormat df = new DecimalFormat("#.#"); Bitmap bmp = Bitmap.createBitmap(200, 200, Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bmp); Paint paintBlack = new Paint(); paintBlack.setColor(Color.WHITE); paintBlack.setTextAlign(Align.LEFT); Paint paint = new Paint(); paint.setColor(Color.RED); paint.setTextAlign(Align.CENTER); canvas.drawLine(0, 180, 200, 180, paint); canvas.drawText("0", 10, 200, paint); float percentage = (((float)analysis.zeros)/(analysis.ones+analysis.zeros)); canvas.drawRect(0, 180-percentage*170, 20, 180, paint); canvas.save(); canvas.rotate(90, 0, 100); canvas.drawText(df.format(percentage*100)+"%", 0, 100, paintBlack); canvas.restore(); canvas.drawText("1", 30, 200, paint); percentage = (((float)analysis.ones)/(analysis.ones+analysis.zeros)); canvas.drawRect(20, 180-percentage*170, 40, 180, paint); canvas.save(); canvas.rotate(90, 20, 100); canvas.drawText(df.format(percentage*100)+"%", 20, 100, paintBlack); canvas.restore(); paint.setColor(Color.BLUE); int sum = 0; for (int i=0;i<4;i++) { canvas.drawText(""+i, 50+i*20, 200, paint); sum += analysis.pairs[i]; } for (int i=0;i<4;i++) { percentage = (((float)analysis.pairs[i])/sum); float left = 40+i*20; float top = 180-percentage*170; canvas.drawRect(left,top,left+20,180, paint); canvas.save(); canvas.rotate(90, left, 100); canvas.drawText(df.format(percentage*100)+"%", left, 100, paintBlack); canvas.restore(); } paint.setColor(Color.GREEN); sum = 0; for (int i=0;i<8;i++) { canvas.drawText(""+i, 125+i*10, 200, paint); sum += analysis.triples[i]; } for (int i=0;i<8;i++) { percentage = (((float)analysis.triples[i])/sum); float left = 120+i*10; float top = 180-percentage*170; canvas.save(); canvas.drawRect(left,top,left+10,180, paint); canvas.rotate(90, left, 100); canvas.drawText(df.format(percentage*100)+"%", left, 100, paintBlack); canvas.restore(); } return bmp; }
diff --git a/modules/unsupported/jdbc-teradata/src/test/java/org/geotools/data/teradata/TeradataTestSetup.java b/modules/unsupported/jdbc-teradata/src/test/java/org/geotools/data/teradata/TeradataTestSetup.java index c13e7fde5..eeb8516b6 100644 --- a/modules/unsupported/jdbc-teradata/src/test/java/org/geotools/data/teradata/TeradataTestSetup.java +++ b/modules/unsupported/jdbc-teradata/src/test/java/org/geotools/data/teradata/TeradataTestSetup.java @@ -1,131 +1,131 @@ /* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2002-2009, Open Source Geospatial Foundation (OSGeo) * * 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. */ package org.geotools.data.teradata; import java.util.Properties; import org.geotools.jdbc.JDBCDataStore; import org.geotools.jdbc.JDBCDataStoreFactory; import org.geotools.jdbc.JDBCTestSetup; public class TeradataTestSetup extends JDBCTestSetup { private static boolean first = true; protected void setUpDataStore(JDBCDataStore dataStore) { super.setUpDataStore(dataStore); if (first) { // uncomment to turn up logging // java.util.logging.ConsoleHandler handler = new java.util.logging.ConsoleHandler(); // handler.setLevel(java.util.logging.Level.FINE); // org.geotools.util.logging.Logging.getLogger("org.geotools.data.jdbc").setLevel(java.util.logging.Level.FINE); // org.geotools.util.logging.Logging.getLogger("org.geotools.data.jdbc").addHandler(handler); // org.geotools.util.logging.Logging.getLogger("org.geotools.jdbc").setLevel(java.util.logging.Level.FINE); // org.geotools.util.logging.Logging.getLogger("org.geotools.jdbc").addHandler(handler); first = false; } // the unit tests assume a non loose behaviour ((TeradataGISDialect) dataStore.getSQLDialect()).setLooseBBOXEnabled(false); // let's work with the most common schema please dataStore.setDatabaseSchema(fixture.getProperty("schema")); } protected Properties createExampleFixture() { Properties fixture = new Properties(); fixture.put("driver", "com.teradata.jdbc.TeraDriver"); fixture.put("url", "jdbc:teradata://localhost/DATABASE=geotools,PORT=1025,TMODE=ANSI,CHARSET=UTF8"); fixture.put("host", "localhost"); fixture.put("database", "geotools"); fixture.put("schema", "geotools"); fixture.put("port", "1025"); fixture.put("user", "dbc"); fixture.put("password", "dbc"); return fixture; } @Override public void setUp() throws Exception { super.setUp(); } protected void setUpData() throws Exception { runSafe("DELETE FROM SYSSPATIAL.GEOMETRY_COLUMNS WHERE F_TABLE_NAME = 'ft1'"); runSafe("DELETE FROM SYSSPATIAL.GEOMETRY_COLUMNS WHERE F_TABLE_NAME = 'ft2'"); runSafe("DROP TRIGGER \"ft1_geometry_mi\""); runSafe("DROP TRIGGER \"ft1_geometry_mu\""); runSafe("DROP TRIGGER \"ft1_geometry_md\""); runSafe("DROP TABLE \"ft1_geometry_idx\""); runSafe("DROP TABLE \"ft1\""); runSafe("DROP TRIGGER \"ft2_geometry_mi\""); runSafe("DROP TRIGGER \"ft2_geometry_mu\""); runSafe("DROP TRIGGER \"ft2_geometry_md\""); runSafe("DROP TABLE \"ft2_geometry_idx\""); runSafe("DROP TABLE \"ft2\""); run("CREATE TABLE \"ft1\"(" // + "\"id\" PRIMARY KEY not null integer, " // + "\"geometry\" ST_GEOMETRY, " // + "\"intProperty\" int," // + "\"doubleProperty\" double precision, " // + "\"stringProperty\" varchar(200) casespecific)"); run("INSERT INTO SYSSPATIAL.GEOMETRY_COLUMNS (F_TABLE_CATALOG, F_TABLE_SCHEMA, F_TABLE_NAME, F_GEOMETRY_COLUMN, COORD_DIMENSION, SRID, GEOM_TYPE) VALUES ('" + fixture.getProperty("database") + "', '" + fixture.getProperty("schema") + "', 'ft1', 'geometry', 2, 1619, 'POINT')"); run("CREATE MULTISET TABLE \"ft1_geometry_idx\"" + " (id INTEGER NOT NULL, cellid INTEGER NOT NULL) PRIMARY INDEX (cellid)"); run("CREATE TRIGGER \"ft1_geometry_mi\" AFTER INSERT ON ft1" + " REFERENCING NEW TABLE AS nt" + " FOR EACH STATEMENT" + " BEGIN ATOMIC" + " (" + " INSERT INTO \"ft1_geometry_idx\"" + " SELECT" + " id," + " sysspatial.tessellate_index (" - + " \"geom\".ST_Envelope().ST_ExteriorRing().ST_PointN(1).ST_X()," - + " \"geom\".ST_Envelope().ST_ExteriorRing().ST_PointN(1).ST_Y()," - + " \"geom\".ST_Envelope().ST_ExteriorRing().ST_PointN(3).ST_X()," - + " \"geom\".ST_Envelope().ST_ExteriorRing().ST_PointN(3).ST_Y()," + + " \"geometry\".ST_Envelope().ST_ExteriorRing().ST_PointN(1).ST_X()," + + " \"geometry\".ST_Envelope().ST_ExteriorRing().ST_PointN(1).ST_Y()," + + " \"geometry\".ST_Envelope().ST_ExteriorRing().ST_PointN(3).ST_X()," + + " \"geometry\".ST_Envelope().ST_ExteriorRing().ST_PointN(3).ST_Y()," + " -180, -90, 180, 90, 100, 100, 1, 0.01, 0)" + " FROM nt;" + " ) " + "END"); run("CREATE TRIGGER \"ft1_geometry_md\" AFTER DELETE ON \"ft1\"" + " REFERENCING OLD TABLE AS ot" + " FOR EACH STATEMENT" + " BEGIN ATOMIC" + " (" + " DELETE FROM \"ft1_geometry_idx\" WHERE ID IN (SELECT ID from ot);" + " )" + "END"); run("INSERT INTO \"ft1\" VALUES(0, 'POINT(0 0)', 0, 0.0, 'zero')"); run("INSERT INTO \"ft1\" VALUES(1, 'POINT(1 1)', 1, 1.1, 'one')"); run("INSERT INTO \"ft1\" VALUES(2, 'POINT(2 2)', 2, 2.2, 'two')"); } protected JDBCDataStoreFactory createDataStoreFactory() { return new TeradataDataStoreFactory(); } }
true
true
protected void setUpData() throws Exception { runSafe("DELETE FROM SYSSPATIAL.GEOMETRY_COLUMNS WHERE F_TABLE_NAME = 'ft1'"); runSafe("DELETE FROM SYSSPATIAL.GEOMETRY_COLUMNS WHERE F_TABLE_NAME = 'ft2'"); runSafe("DROP TRIGGER \"ft1_geometry_mi\""); runSafe("DROP TRIGGER \"ft1_geometry_mu\""); runSafe("DROP TRIGGER \"ft1_geometry_md\""); runSafe("DROP TABLE \"ft1_geometry_idx\""); runSafe("DROP TABLE \"ft1\""); runSafe("DROP TRIGGER \"ft2_geometry_mi\""); runSafe("DROP TRIGGER \"ft2_geometry_mu\""); runSafe("DROP TRIGGER \"ft2_geometry_md\""); runSafe("DROP TABLE \"ft2_geometry_idx\""); runSafe("DROP TABLE \"ft2\""); run("CREATE TABLE \"ft1\"(" // + "\"id\" PRIMARY KEY not null integer, " // + "\"geometry\" ST_GEOMETRY, " // + "\"intProperty\" int," // + "\"doubleProperty\" double precision, " // + "\"stringProperty\" varchar(200) casespecific)"); run("INSERT INTO SYSSPATIAL.GEOMETRY_COLUMNS (F_TABLE_CATALOG, F_TABLE_SCHEMA, F_TABLE_NAME, F_GEOMETRY_COLUMN, COORD_DIMENSION, SRID, GEOM_TYPE) VALUES ('" + fixture.getProperty("database") + "', '" + fixture.getProperty("schema") + "', 'ft1', 'geometry', 2, 1619, 'POINT')"); run("CREATE MULTISET TABLE \"ft1_geometry_idx\"" + " (id INTEGER NOT NULL, cellid INTEGER NOT NULL) PRIMARY INDEX (cellid)"); run("CREATE TRIGGER \"ft1_geometry_mi\" AFTER INSERT ON ft1" + " REFERENCING NEW TABLE AS nt" + " FOR EACH STATEMENT" + " BEGIN ATOMIC" + " (" + " INSERT INTO \"ft1_geometry_idx\"" + " SELECT" + " id," + " sysspatial.tessellate_index (" + " \"geom\".ST_Envelope().ST_ExteriorRing().ST_PointN(1).ST_X()," + " \"geom\".ST_Envelope().ST_ExteriorRing().ST_PointN(1).ST_Y()," + " \"geom\".ST_Envelope().ST_ExteriorRing().ST_PointN(3).ST_X()," + " \"geom\".ST_Envelope().ST_ExteriorRing().ST_PointN(3).ST_Y()," + " -180, -90, 180, 90, 100, 100, 1, 0.01, 0)" + " FROM nt;" + " ) " + "END"); run("CREATE TRIGGER \"ft1_geometry_md\" AFTER DELETE ON \"ft1\"" + " REFERENCING OLD TABLE AS ot" + " FOR EACH STATEMENT" + " BEGIN ATOMIC" + " (" + " DELETE FROM \"ft1_geometry_idx\" WHERE ID IN (SELECT ID from ot);" + " )" + "END"); run("INSERT INTO \"ft1\" VALUES(0, 'POINT(0 0)', 0, 0.0, 'zero')"); run("INSERT INTO \"ft1\" VALUES(1, 'POINT(1 1)', 1, 1.1, 'one')"); run("INSERT INTO \"ft1\" VALUES(2, 'POINT(2 2)', 2, 2.2, 'two')"); }
protected void setUpData() throws Exception { runSafe("DELETE FROM SYSSPATIAL.GEOMETRY_COLUMNS WHERE F_TABLE_NAME = 'ft1'"); runSafe("DELETE FROM SYSSPATIAL.GEOMETRY_COLUMNS WHERE F_TABLE_NAME = 'ft2'"); runSafe("DROP TRIGGER \"ft1_geometry_mi\""); runSafe("DROP TRIGGER \"ft1_geometry_mu\""); runSafe("DROP TRIGGER \"ft1_geometry_md\""); runSafe("DROP TABLE \"ft1_geometry_idx\""); runSafe("DROP TABLE \"ft1\""); runSafe("DROP TRIGGER \"ft2_geometry_mi\""); runSafe("DROP TRIGGER \"ft2_geometry_mu\""); runSafe("DROP TRIGGER \"ft2_geometry_md\""); runSafe("DROP TABLE \"ft2_geometry_idx\""); runSafe("DROP TABLE \"ft2\""); run("CREATE TABLE \"ft1\"(" // + "\"id\" PRIMARY KEY not null integer, " // + "\"geometry\" ST_GEOMETRY, " // + "\"intProperty\" int," // + "\"doubleProperty\" double precision, " // + "\"stringProperty\" varchar(200) casespecific)"); run("INSERT INTO SYSSPATIAL.GEOMETRY_COLUMNS (F_TABLE_CATALOG, F_TABLE_SCHEMA, F_TABLE_NAME, F_GEOMETRY_COLUMN, COORD_DIMENSION, SRID, GEOM_TYPE) VALUES ('" + fixture.getProperty("database") + "', '" + fixture.getProperty("schema") + "', 'ft1', 'geometry', 2, 1619, 'POINT')"); run("CREATE MULTISET TABLE \"ft1_geometry_idx\"" + " (id INTEGER NOT NULL, cellid INTEGER NOT NULL) PRIMARY INDEX (cellid)"); run("CREATE TRIGGER \"ft1_geometry_mi\" AFTER INSERT ON ft1" + " REFERENCING NEW TABLE AS nt" + " FOR EACH STATEMENT" + " BEGIN ATOMIC" + " (" + " INSERT INTO \"ft1_geometry_idx\"" + " SELECT" + " id," + " sysspatial.tessellate_index (" + " \"geometry\".ST_Envelope().ST_ExteriorRing().ST_PointN(1).ST_X()," + " \"geometry\".ST_Envelope().ST_ExteriorRing().ST_PointN(1).ST_Y()," + " \"geometry\".ST_Envelope().ST_ExteriorRing().ST_PointN(3).ST_X()," + " \"geometry\".ST_Envelope().ST_ExteriorRing().ST_PointN(3).ST_Y()," + " -180, -90, 180, 90, 100, 100, 1, 0.01, 0)" + " FROM nt;" + " ) " + "END"); run("CREATE TRIGGER \"ft1_geometry_md\" AFTER DELETE ON \"ft1\"" + " REFERENCING OLD TABLE AS ot" + " FOR EACH STATEMENT" + " BEGIN ATOMIC" + " (" + " DELETE FROM \"ft1_geometry_idx\" WHERE ID IN (SELECT ID from ot);" + " )" + "END"); run("INSERT INTO \"ft1\" VALUES(0, 'POINT(0 0)', 0, 0.0, 'zero')"); run("INSERT INTO \"ft1\" VALUES(1, 'POINT(1 1)', 1, 1.1, 'one')"); run("INSERT INTO \"ft1\" VALUES(2, 'POINT(2 2)', 2, 2.2, 'two')"); }
diff --git a/src/pg13/presentation/PuzzlePropertiesWidget.java b/src/pg13/presentation/PuzzlePropertiesWidget.java index 948aaeb..ba9e2d5 100644 --- a/src/pg13/presentation/PuzzlePropertiesWidget.java +++ b/src/pg13/presentation/PuzzlePropertiesWidget.java @@ -1,366 +1,366 @@ package pg13.presentation; import java.util.Enumeration; import org.eclipse.swt.widgets.Composite; import pg13.org.eclipse.wb.swt.SWTResourceManager; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.MessageBox; import pg13.business.PuzzleManager; import pg13.models.Category; import pg13.models.Cryptogram; import pg13.models.Difficulty; import pg13.models.Puzzle; import pg13.models.PuzzleValidationException; import acceptanceTests.Register; public class PuzzlePropertiesWidget extends Composite { boolean editMode; // can we edit the properties of the puzzle? private Text txtPuzzleName; private Text txtDescription; private Label lblCategory; private Label lblCategoryFixedText; private Label lblDifficulty; private Label lblDifficultyFixedText; private Combo cmbDificulty; private Combo cmbCategory; private Button btnSavePuzzle; private Button btnCheckSolution; private Puzzle displayingPuzzle; public PuzzlePropertiesWidget(Composite parent, int style, Puzzle displayingPuzzle, boolean editMode) { super(parent, style); - Register.newWindow(this); + Register.newWindow(this, "PuzzlePropertiesWidget" + (editMode == true? "Edit" : "View" )); this.displayingPuzzle = displayingPuzzle; setLayout(new FormLayout()); // puzzle name txtPuzzleName = new Text(this, SWT.BORDER); txtPuzzleName.setFont(SWTResourceManager.getFont("Segoe UI", 16, SWT.NORMAL)); FormData fd_txtPuzzleName = new FormData(); fd_txtPuzzleName.top = new FormAttachment(0, 10); fd_txtPuzzleName.left = new FormAttachment(0, 10); fd_txtPuzzleName.bottom = new FormAttachment(0, 49); fd_txtPuzzleName.right = new FormAttachment(100, -10); txtPuzzleName.setLayoutData(fd_txtPuzzleName); txtPuzzleName.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { updatePuzzleTitle(); } }); // puzzle description label Label lblDescription = new Label(this, SWT.NONE); FormData fd_lblDescription = new FormData(); fd_lblDescription.top = new FormAttachment(txtPuzzleName, 10); fd_lblDescription.left = new FormAttachment(0, 10); lblDescription.setLayoutData(fd_lblDescription); lblDescription.setText(Constants.DESCRIPTION); // puzzle description text field txtDescription = new Text(this, SWT.BORDER | SWT.WRAP); FormData fd_txtDescription = new FormData(); fd_txtDescription.bottom = new FormAttachment(lblDescription, 134, SWT.BOTTOM); fd_txtDescription.right = new FormAttachment(100, -10); fd_txtDescription.top = new FormAttachment(lblDescription, 4); fd_txtDescription.left = new FormAttachment(0, 10); txtDescription.setLayoutData(fd_txtDescription); txtDescription.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { updatePuzzleDescription(); } }); txtDescription.setTextLimit(Constants.MAX_DESCRIPTION_CHARS); // category label lblCategory = new Label(this, SWT.NONE); FormData fd_lblCategory = new FormData(); fd_lblCategory.left = new FormAttachment(0, 10); fd_lblCategory.top = new FormAttachment(txtDescription, 10); lblCategory.setLayoutData(fd_lblCategory); lblCategory.setText(Constants.CATEGORY); // category selection box cmbCategory = new Combo(this, SWT.READ_ONLY); cmbCategory.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.NORMAL)); cmbCategory.setItems(getCategories(Category.values())); FormData fd_cmbCategory = new FormData(); fd_cmbCategory.right = new FormAttachment(60); fd_cmbCategory.top = new FormAttachment(lblCategory, 4); fd_cmbCategory.left = new FormAttachment(0, 10); cmbCategory.setLayoutData(fd_cmbCategory); cmbCategory.select(0); cmbCategory.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { updatePuzzleCategory(); } }); // category fixed label lblCategoryFixedText = new Label(this, SWT.BORDER); lblCategoryFixedText.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL)); FormData fd_lblCategoryFixedText = new FormData(); fd_lblCategoryFixedText.height = 21; fd_lblCategoryFixedText.right = new FormAttachment(60); fd_lblCategoryFixedText.top = new FormAttachment(lblCategory, 4); fd_lblCategoryFixedText.left = new FormAttachment(0, 10); lblCategoryFixedText.setLayoutData(fd_lblCategoryFixedText); // difficulty label lblDifficulty = new Label(this, SWT.NONE); FormData fd_lblDifficulty = new FormData(); fd_lblDifficulty.top = new FormAttachment(cmbCategory, 10); fd_lblDifficulty.left = new FormAttachment(0, 10); lblDifficulty.setLayoutData(fd_lblDifficulty); lblDifficulty.setText(Constants.DIFFICULTY); // difficulty selection box cmbDificulty = new Combo(this, SWT.READ_ONLY); cmbDificulty.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.NORMAL)); cmbDificulty.setItems(getCategories(Difficulty.values())); FormData fd_cmbDificulty = new FormData(); fd_cmbDificulty.right = new FormAttachment(60); fd_cmbDificulty.top = new FormAttachment(lblDifficulty, 4); fd_cmbDificulty.left = new FormAttachment(0, 10); cmbDificulty.setLayoutData(fd_cmbDificulty); cmbDificulty.select(0); cmbDificulty.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { updatePuzzleDifficulty(); } }); // difficulty fixed label lblDifficultyFixedText = new Label(this, SWT.BORDER); lblDifficultyFixedText.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL)); FormData fd_lblDifficultyFixedText = new FormData(); fd_lblDifficultyFixedText.height = 21; fd_lblDifficultyFixedText.right = new FormAttachment(60); fd_lblDifficultyFixedText.top = new FormAttachment(lblDifficulty, 4); fd_lblDifficultyFixedText.left = new FormAttachment(0, 10); lblDifficultyFixedText.setLayoutData(fd_lblDifficultyFixedText); // save puzzle button this.btnSavePuzzle = new Button(this, SWT.NONE); FormData fd_btnSavePuzzle = new FormData(); fd_btnSavePuzzle.top = new FormAttachment(100, -40); fd_btnSavePuzzle.bottom = new FormAttachment(100, -10); fd_btnSavePuzzle.left = new FormAttachment(50, -70); fd_btnSavePuzzle.right = new FormAttachment(50, 70); btnSavePuzzle.setLayoutData(fd_btnSavePuzzle); btnSavePuzzle.setText(MessageConstants.SAVE_PUZZLE); btnSavePuzzle.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { savePuzzle(); } @Override public void widgetDefaultSelected(SelectionEvent e) { savePuzzle(); } }); // check solution button this.btnCheckSolution = new Button(this, SWT.NONE); btnCheckSolution.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { checkSolution(); } @Override public void widgetDefaultSelected(SelectionEvent e) { checkSolution(); } }); FormData fd_btnCheckSolution = new FormData(); fd_btnCheckSolution.top = new FormAttachment(100, -40); fd_btnCheckSolution.bottom = new FormAttachment(100, -10); fd_btnCheckSolution.left = new FormAttachment(50, -70); fd_btnCheckSolution.right = new FormAttachment(50, 70); btnCheckSolution.setLayoutData(fd_btnCheckSolution); btnCheckSolution.setText(MessageConstants.CHECK_SOLUTION); this.setEditMode(editMode); } public void setPuzzle(Cryptogram newPuzzle) { this.displayingPuzzle = newPuzzle; updateFields(); } private void updateFields() { this.txtPuzzleName.setText((displayingPuzzle.getTitle() == null ? "" : displayingPuzzle.getTitle())); this.txtDescription.setText((displayingPuzzle.getDescription() == null ? "" : displayingPuzzle.getDescription())); this.cmbCategory.select(getComboIndex(displayingPuzzle.getCategory(), Category.values())); this.lblCategoryFixedText.setText(cmbCategory.getText()); this.cmbDificulty.select(getComboIndex(displayingPuzzle.getDifficulty(), Difficulty.values())); this.lblDifficultyFixedText.setText(cmbDificulty.getText()); } @SuppressWarnings("rawtypes") private String[] getCategories(Enumeration[] catEnum) { String[] categories = new String[catEnum.length]; for (int i = 0; i < catEnum.length; i++) { categories[i] = catEnum[i].toString(); } return categories; } @SuppressWarnings("rawtypes") private int getComboIndex(Enumeration key, Enumeration[] list) { int result = -1; for (int i = 0; i < list.length; i++) { if (list[i].equals(key)) { result = i; } } return result; } private void setEditMode(boolean editMode) { this.editMode = editMode; this.cmbCategory.setVisible(this.editMode); this.lblCategoryFixedText.setVisible(!this.editMode); this.cmbDificulty.setVisible(this.editMode); this.lblDifficultyFixedText.setVisible(!this.editMode); this.txtDescription.setEditable(this.editMode); this.txtPuzzleName.setEditable(this.editMode); this.btnSavePuzzle.setVisible(this.editMode); this.btnCheckSolution.setVisible(!this.editMode); } private void savePuzzle() { MessageBox dialog; try { // make sure the puzzle is valid to save displayingPuzzle.validate(); displayingPuzzle.setUser(MainWindow.getInstance().getLoggedInUser()); displayingPuzzle.prepareForSave(); new PuzzleManager().save(displayingPuzzle); dialog = new MessageBox(this.getShell(), SWT.ICON_INFORMATION | SWT.OK); dialog.setText(MessageConstants.SAVE_SUCCESS); dialog.setMessage(MessageConstants.SAVE_SUCCESS_MSG); dialog.open(); MainWindow.getInstance().switchToWelcomeScreen(); } catch (PuzzleValidationException e) { dialog = new MessageBox(this.getShell(), SWT.ICON_ERROR | SWT.OK); dialog.setText(MessageConstants.SAVE_ERROR); dialog.setMessage(e.getMessage()); dialog.open(); } } private void updatePuzzleTitle() { displayingPuzzle.setTitle(txtPuzzleName.getText()); } private void updatePuzzleDescription() { displayingPuzzle.setDescription(txtDescription.getText()); } private void updatePuzzleCategory() { displayingPuzzle.setCategory(Category.valueOf(cmbCategory.getText())); lblCategoryFixedText.setText(cmbCategory.getText()); } private void updatePuzzleDifficulty() { displayingPuzzle.setDifficulty(Difficulty.valueOf(cmbDificulty .getText())); lblDifficultyFixedText.setText(cmbDificulty.getText()); } private void checkSolution() { String msg; MessageBox dialog; if (this.displayingPuzzle != null && this.displayingPuzzle.isCompleted()) { msg = MessageConstants.PUZZLE_SOLVED; } else { msg = MessageConstants.PUZZLE_UNSOLVED; } dialog = new MessageBox(this.getShell(), SWT.ICON_QUESTION | SWT.OK); dialog.setText(Constants.PUZZLE_SOLUTION); dialog.setMessage(msg); dialog.open(); } @Override protected void checkSubclass() { // Disable the check that prevents subclassing of SWT components } }
true
true
public PuzzlePropertiesWidget(Composite parent, int style, Puzzle displayingPuzzle, boolean editMode) { super(parent, style); Register.newWindow(this); this.displayingPuzzle = displayingPuzzle; setLayout(new FormLayout()); // puzzle name txtPuzzleName = new Text(this, SWT.BORDER); txtPuzzleName.setFont(SWTResourceManager.getFont("Segoe UI", 16, SWT.NORMAL)); FormData fd_txtPuzzleName = new FormData(); fd_txtPuzzleName.top = new FormAttachment(0, 10); fd_txtPuzzleName.left = new FormAttachment(0, 10); fd_txtPuzzleName.bottom = new FormAttachment(0, 49); fd_txtPuzzleName.right = new FormAttachment(100, -10); txtPuzzleName.setLayoutData(fd_txtPuzzleName); txtPuzzleName.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { updatePuzzleTitle(); } }); // puzzle description label Label lblDescription = new Label(this, SWT.NONE); FormData fd_lblDescription = new FormData(); fd_lblDescription.top = new FormAttachment(txtPuzzleName, 10); fd_lblDescription.left = new FormAttachment(0, 10); lblDescription.setLayoutData(fd_lblDescription); lblDescription.setText(Constants.DESCRIPTION); // puzzle description text field txtDescription = new Text(this, SWT.BORDER | SWT.WRAP); FormData fd_txtDescription = new FormData(); fd_txtDescription.bottom = new FormAttachment(lblDescription, 134, SWT.BOTTOM); fd_txtDescription.right = new FormAttachment(100, -10); fd_txtDescription.top = new FormAttachment(lblDescription, 4); fd_txtDescription.left = new FormAttachment(0, 10); txtDescription.setLayoutData(fd_txtDescription); txtDescription.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { updatePuzzleDescription(); } }); txtDescription.setTextLimit(Constants.MAX_DESCRIPTION_CHARS); // category label lblCategory = new Label(this, SWT.NONE); FormData fd_lblCategory = new FormData(); fd_lblCategory.left = new FormAttachment(0, 10); fd_lblCategory.top = new FormAttachment(txtDescription, 10); lblCategory.setLayoutData(fd_lblCategory); lblCategory.setText(Constants.CATEGORY); // category selection box cmbCategory = new Combo(this, SWT.READ_ONLY); cmbCategory.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.NORMAL)); cmbCategory.setItems(getCategories(Category.values())); FormData fd_cmbCategory = new FormData(); fd_cmbCategory.right = new FormAttachment(60); fd_cmbCategory.top = new FormAttachment(lblCategory, 4); fd_cmbCategory.left = new FormAttachment(0, 10); cmbCategory.setLayoutData(fd_cmbCategory); cmbCategory.select(0); cmbCategory.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { updatePuzzleCategory(); } }); // category fixed label lblCategoryFixedText = new Label(this, SWT.BORDER); lblCategoryFixedText.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL)); FormData fd_lblCategoryFixedText = new FormData(); fd_lblCategoryFixedText.height = 21; fd_lblCategoryFixedText.right = new FormAttachment(60); fd_lblCategoryFixedText.top = new FormAttachment(lblCategory, 4); fd_lblCategoryFixedText.left = new FormAttachment(0, 10); lblCategoryFixedText.setLayoutData(fd_lblCategoryFixedText); // difficulty label lblDifficulty = new Label(this, SWT.NONE); FormData fd_lblDifficulty = new FormData(); fd_lblDifficulty.top = new FormAttachment(cmbCategory, 10); fd_lblDifficulty.left = new FormAttachment(0, 10); lblDifficulty.setLayoutData(fd_lblDifficulty); lblDifficulty.setText(Constants.DIFFICULTY); // difficulty selection box cmbDificulty = new Combo(this, SWT.READ_ONLY); cmbDificulty.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.NORMAL)); cmbDificulty.setItems(getCategories(Difficulty.values())); FormData fd_cmbDificulty = new FormData(); fd_cmbDificulty.right = new FormAttachment(60); fd_cmbDificulty.top = new FormAttachment(lblDifficulty, 4); fd_cmbDificulty.left = new FormAttachment(0, 10); cmbDificulty.setLayoutData(fd_cmbDificulty); cmbDificulty.select(0); cmbDificulty.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { updatePuzzleDifficulty(); } }); // difficulty fixed label lblDifficultyFixedText = new Label(this, SWT.BORDER); lblDifficultyFixedText.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL)); FormData fd_lblDifficultyFixedText = new FormData(); fd_lblDifficultyFixedText.height = 21; fd_lblDifficultyFixedText.right = new FormAttachment(60); fd_lblDifficultyFixedText.top = new FormAttachment(lblDifficulty, 4); fd_lblDifficultyFixedText.left = new FormAttachment(0, 10); lblDifficultyFixedText.setLayoutData(fd_lblDifficultyFixedText); // save puzzle button this.btnSavePuzzle = new Button(this, SWT.NONE); FormData fd_btnSavePuzzle = new FormData(); fd_btnSavePuzzle.top = new FormAttachment(100, -40); fd_btnSavePuzzle.bottom = new FormAttachment(100, -10); fd_btnSavePuzzle.left = new FormAttachment(50, -70); fd_btnSavePuzzle.right = new FormAttachment(50, 70); btnSavePuzzle.setLayoutData(fd_btnSavePuzzle); btnSavePuzzle.setText(MessageConstants.SAVE_PUZZLE); btnSavePuzzle.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { savePuzzle(); } @Override public void widgetDefaultSelected(SelectionEvent e) { savePuzzle(); } }); // check solution button this.btnCheckSolution = new Button(this, SWT.NONE); btnCheckSolution.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { checkSolution(); } @Override public void widgetDefaultSelected(SelectionEvent e) { checkSolution(); } }); FormData fd_btnCheckSolution = new FormData(); fd_btnCheckSolution.top = new FormAttachment(100, -40); fd_btnCheckSolution.bottom = new FormAttachment(100, -10); fd_btnCheckSolution.left = new FormAttachment(50, -70); fd_btnCheckSolution.right = new FormAttachment(50, 70); btnCheckSolution.setLayoutData(fd_btnCheckSolution); btnCheckSolution.setText(MessageConstants.CHECK_SOLUTION); this.setEditMode(editMode); }
public PuzzlePropertiesWidget(Composite parent, int style, Puzzle displayingPuzzle, boolean editMode) { super(parent, style); Register.newWindow(this, "PuzzlePropertiesWidget" + (editMode == true? "Edit" : "View" )); this.displayingPuzzle = displayingPuzzle; setLayout(new FormLayout()); // puzzle name txtPuzzleName = new Text(this, SWT.BORDER); txtPuzzleName.setFont(SWTResourceManager.getFont("Segoe UI", 16, SWT.NORMAL)); FormData fd_txtPuzzleName = new FormData(); fd_txtPuzzleName.top = new FormAttachment(0, 10); fd_txtPuzzleName.left = new FormAttachment(0, 10); fd_txtPuzzleName.bottom = new FormAttachment(0, 49); fd_txtPuzzleName.right = new FormAttachment(100, -10); txtPuzzleName.setLayoutData(fd_txtPuzzleName); txtPuzzleName.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { updatePuzzleTitle(); } }); // puzzle description label Label lblDescription = new Label(this, SWT.NONE); FormData fd_lblDescription = new FormData(); fd_lblDescription.top = new FormAttachment(txtPuzzleName, 10); fd_lblDescription.left = new FormAttachment(0, 10); lblDescription.setLayoutData(fd_lblDescription); lblDescription.setText(Constants.DESCRIPTION); // puzzle description text field txtDescription = new Text(this, SWT.BORDER | SWT.WRAP); FormData fd_txtDescription = new FormData(); fd_txtDescription.bottom = new FormAttachment(lblDescription, 134, SWT.BOTTOM); fd_txtDescription.right = new FormAttachment(100, -10); fd_txtDescription.top = new FormAttachment(lblDescription, 4); fd_txtDescription.left = new FormAttachment(0, 10); txtDescription.setLayoutData(fd_txtDescription); txtDescription.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { updatePuzzleDescription(); } }); txtDescription.setTextLimit(Constants.MAX_DESCRIPTION_CHARS); // category label lblCategory = new Label(this, SWT.NONE); FormData fd_lblCategory = new FormData(); fd_lblCategory.left = new FormAttachment(0, 10); fd_lblCategory.top = new FormAttachment(txtDescription, 10); lblCategory.setLayoutData(fd_lblCategory); lblCategory.setText(Constants.CATEGORY); // category selection box cmbCategory = new Combo(this, SWT.READ_ONLY); cmbCategory.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.NORMAL)); cmbCategory.setItems(getCategories(Category.values())); FormData fd_cmbCategory = new FormData(); fd_cmbCategory.right = new FormAttachment(60); fd_cmbCategory.top = new FormAttachment(lblCategory, 4); fd_cmbCategory.left = new FormAttachment(0, 10); cmbCategory.setLayoutData(fd_cmbCategory); cmbCategory.select(0); cmbCategory.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { updatePuzzleCategory(); } }); // category fixed label lblCategoryFixedText = new Label(this, SWT.BORDER); lblCategoryFixedText.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL)); FormData fd_lblCategoryFixedText = new FormData(); fd_lblCategoryFixedText.height = 21; fd_lblCategoryFixedText.right = new FormAttachment(60); fd_lblCategoryFixedText.top = new FormAttachment(lblCategory, 4); fd_lblCategoryFixedText.left = new FormAttachment(0, 10); lblCategoryFixedText.setLayoutData(fd_lblCategoryFixedText); // difficulty label lblDifficulty = new Label(this, SWT.NONE); FormData fd_lblDifficulty = new FormData(); fd_lblDifficulty.top = new FormAttachment(cmbCategory, 10); fd_lblDifficulty.left = new FormAttachment(0, 10); lblDifficulty.setLayoutData(fd_lblDifficulty); lblDifficulty.setText(Constants.DIFFICULTY); // difficulty selection box cmbDificulty = new Combo(this, SWT.READ_ONLY); cmbDificulty.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.NORMAL)); cmbDificulty.setItems(getCategories(Difficulty.values())); FormData fd_cmbDificulty = new FormData(); fd_cmbDificulty.right = new FormAttachment(60); fd_cmbDificulty.top = new FormAttachment(lblDifficulty, 4); fd_cmbDificulty.left = new FormAttachment(0, 10); cmbDificulty.setLayoutData(fd_cmbDificulty); cmbDificulty.select(0); cmbDificulty.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { updatePuzzleDifficulty(); } }); // difficulty fixed label lblDifficultyFixedText = new Label(this, SWT.BORDER); lblDifficultyFixedText.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL)); FormData fd_lblDifficultyFixedText = new FormData(); fd_lblDifficultyFixedText.height = 21; fd_lblDifficultyFixedText.right = new FormAttachment(60); fd_lblDifficultyFixedText.top = new FormAttachment(lblDifficulty, 4); fd_lblDifficultyFixedText.left = new FormAttachment(0, 10); lblDifficultyFixedText.setLayoutData(fd_lblDifficultyFixedText); // save puzzle button this.btnSavePuzzle = new Button(this, SWT.NONE); FormData fd_btnSavePuzzle = new FormData(); fd_btnSavePuzzle.top = new FormAttachment(100, -40); fd_btnSavePuzzle.bottom = new FormAttachment(100, -10); fd_btnSavePuzzle.left = new FormAttachment(50, -70); fd_btnSavePuzzle.right = new FormAttachment(50, 70); btnSavePuzzle.setLayoutData(fd_btnSavePuzzle); btnSavePuzzle.setText(MessageConstants.SAVE_PUZZLE); btnSavePuzzle.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { savePuzzle(); } @Override public void widgetDefaultSelected(SelectionEvent e) { savePuzzle(); } }); // check solution button this.btnCheckSolution = new Button(this, SWT.NONE); btnCheckSolution.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { checkSolution(); } @Override public void widgetDefaultSelected(SelectionEvent e) { checkSolution(); } }); FormData fd_btnCheckSolution = new FormData(); fd_btnCheckSolution.top = new FormAttachment(100, -40); fd_btnCheckSolution.bottom = new FormAttachment(100, -10); fd_btnCheckSolution.left = new FormAttachment(50, -70); fd_btnCheckSolution.right = new FormAttachment(50, 70); btnCheckSolution.setLayoutData(fd_btnCheckSolution); btnCheckSolution.setText(MessageConstants.CHECK_SOLUTION); this.setEditMode(editMode); }
diff --git a/plugins/org.eclipse.emf.compare.ui/src/org/eclipse/emf/compare/ui/viewer/content/part/ModelContentMergeViewerPart.java b/plugins/org.eclipse.emf.compare.ui/src/org/eclipse/emf/compare/ui/viewer/content/part/ModelContentMergeViewerPart.java index 9450037d4..5a1ad5373 100755 --- a/plugins/org.eclipse.emf.compare.ui/src/org/eclipse/emf/compare/ui/viewer/content/part/ModelContentMergeViewerPart.java +++ b/plugins/org.eclipse.emf.compare.ui/src/org/eclipse/emf/compare/ui/viewer/content/part/ModelContentMergeViewerPart.java @@ -1,844 +1,844 @@ /******************************************************************************* * Copyright (c) 2006, 2007 Obeo. * 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: * Obeo - initial API and implementation *******************************************************************************/ package org.eclipse.emf.compare.ui.viewer.content.part; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.eclipse.emf.common.util.TreeIterator; import org.eclipse.emf.compare.diff.metamodel.AddModelElement; import org.eclipse.emf.compare.diff.metamodel.AttributeChange; import org.eclipse.emf.compare.diff.metamodel.ConflictingDiffElement; import org.eclipse.emf.compare.diff.metamodel.DiffElement; import org.eclipse.emf.compare.diff.metamodel.DiffGroup; import org.eclipse.emf.compare.diff.metamodel.ReferenceChange; import org.eclipse.emf.compare.diff.metamodel.RemoteAddModelElement; import org.eclipse.emf.compare.diff.metamodel.RemoteRemoveModelElement; import org.eclipse.emf.compare.diff.metamodel.RemoveModelElement; import org.eclipse.emf.compare.diff.metamodel.util.DiffAdapterFactory; import org.eclipse.emf.compare.match.metamodel.Match2Elements; import org.eclipse.emf.compare.match.metamodel.MatchModel; import org.eclipse.emf.compare.match.metamodel.UnMatchElement; import org.eclipse.emf.compare.ui.EMFCompareUIMessages; import org.eclipse.emf.compare.ui.ICompareEditorPartListener; import org.eclipse.emf.compare.ui.ModelCompareInput; import org.eclipse.emf.compare.ui.util.EMFAdapterFactoryProvider; import org.eclipse.emf.compare.ui.util.EMFCompareConstants; import org.eclipse.emf.compare.ui.util.EMFCompareEObjectUtils; import org.eclipse.emf.compare.ui.viewer.content.ModelContentMergeViewer; import org.eclipse.emf.compare.ui.viewer.content.part.property.ModelContentMergePropertyPart; import org.eclipse.emf.compare.ui.viewer.content.part.property.PropertyContentProvider; import org.eclipse.emf.compare.ui.viewer.content.part.tree.ModelContentMergeTreePart; import org.eclipse.emf.compare.util.EMFCompareMap; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.edit.ui.provider.AdapterFactoryContentProvider; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.events.TreeEvent; import org.eclipse.swt.events.TreeListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Item; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.swt.widgets.Widget; /** * Describes a part of a {@link ModelContentMergeViewer}. * * @author Cedric Brun <a href="mailto:[email protected]">[email protected]</a> */ public class ModelContentMergeViewerPart { /** This {@link String} is used as an error message when an unexisting tab is accessed. */ private static final String INVALID_TAB = EMFCompareUIMessages.getString("IllegalTab"); //$NON-NLS-1$ /** This keeps track of the parent viewer of this viewer part. */ protected final ModelContentMergeViewer parentViewer; /** * This <code>int</code> represents the side of this viewer part. Must be one of * <ul> * <li>{@link EMFCompareConstants#RIGHT}</li> * <li>{@link EMFCompareConstants#LEFT}</li> * <li>{@link EMFCompareConstants#ANCESTOR}</li> * </ul> */ protected final int partSide; /** This is the content of the properties tab for this viewer part. */ protected ModelContentMergePropertyPart properties; /** This is the view displayed by this viewer part. */ protected CTabFolder tabFolder; /** This is the content of the tree tab for this viewer part. */ protected ModelContentMergeTreePart tree; /** Indicates that the tree has been expanded since last time we mapped the TreeItems. */ /* package */boolean expanded = true; /** This contains all the listeners registered for this viewer part. */ private final List<ICompareEditorPartListener> editorPartListeners = new ArrayList<ICompareEditorPartListener>(); /** * Currently selected tab for this viewer. Must be one of * <ul> * <li>{@link ModelContentMergeViewer#TREE_TAB}</li> * <li>{@link ModelContentMergeViewer#PROPERTIES_TAB}</li> * </ul> */ private int selectedTab; /** This Map will allow us to avoid iteration through all diffs for each paint operation. */ private final Map<String, DiffElement> treeItemToDiff = new EMFCompareMap<String, DiffElement>(101); /** * Instantiates a {@link ModelContentMergeViewerPart} given its parent {@link Composite} and its side. * * @param viewer * Parent viewer of this viewer part. * @param composite * Parent {@link Composite} for this part. * @param side * Comparison side of this part. Must be one of * {@link EMFCompareConstants#LEFT EMFCompareConstants.RIGHT}, * {@link EMFCompareConstants#RIGHT EMFCompareConstants.LEFT} or * {@link EMFCompareConstants#ANCESTOR EMFCompareConstants.ANCESTOR}. */ public ModelContentMergeViewerPart(ModelContentMergeViewer viewer, Composite composite, int side) { if (side != EMFCompareConstants.RIGHT && side != EMFCompareConstants.LEFT && side != EMFCompareConstants.ANCESTOR) throw new IllegalArgumentException(EMFCompareUIMessages.getString("IllegalSide", side)); //$NON-NLS-1$ parentViewer = viewer; selectedTab = ModelContentMergeViewer.TREE_TAB; partSide = side; createContents(composite); } /** * Registers the given listener for notification. If the identical listener is already registered the * method has no effect. * * @param listener * The listener to register for changes of this input. */ public void addCompareEditorPartListener(ICompareEditorPartListener listener) { editorPartListeners.add(listener); } /** * Creates the contents of this viewer part given its parent composite. * * @param composite * Parent composite of this viewer parts's widgets. */ public void createContents(Composite composite) { tabFolder = new CTabFolder(composite, SWT.BOTTOM); final CTabItem treeTab = new CTabItem(tabFolder, SWT.NONE); treeTab.setText(EMFCompareUIMessages.getString("ModelContentMergeViewerPart.tab1.name")); //$NON-NLS-1$ final CTabItem propertiesTab = new CTabItem(tabFolder, SWT.NONE); propertiesTab.setText(EMFCompareUIMessages.getString("ModelContentMergeViewerPart.tab2.name")); //$NON-NLS-1$ final Composite treePanel = new Composite(tabFolder, SWT.NONE); treePanel.setLayout(new GridLayout()); treePanel.setLayoutData(new GridData(GridData.FILL_BOTH)); treePanel.setFont(composite.getFont()); tree = createTreePart(treePanel); treeTab.setControl(treePanel); final Composite propertyPanel = new Composite(tabFolder, SWT.NONE); propertyPanel.setLayout(new GridLayout()); propertyPanel.setLayoutData(new GridData(GridData.FILL_BOTH)); propertyPanel.setFont(composite.getFont()); properties = createPropertiesPart(propertyPanel); propertiesTab.setControl(propertyPanel); tabFolder.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } public void widgetSelected(SelectionEvent e) { if (e.item.equals(treeTab)) { setSelectedTab(ModelContentMergeViewer.TREE_TAB); } else { if (e.item.equals(propertiesTab)) { setSelectedTab(ModelContentMergeViewer.PROPERTIES_TAB); } } fireSelectedtabChanged(); } }); tabFolder.setSelection(treeTab); } /** * Returns the {@link Widget} representing the given element or <code>null</code> if it cannot be found. * * @param element * Element to find the {@link Widget} for. * @return The {@link Widget} representing the given element. */ public Widget find(EObject element) { Widget widget = null; if (element != null) { if (selectedTab == ModelContentMergeViewer.TREE_TAB) { widget = tree.find(element); } else if (selectedTab == ModelContentMergeViewer.PROPERTIES_TAB) { if (element instanceof DiffElement) widget = properties.find(((PropertyContentProvider)properties.getContentProvider()) .getInputEObject(), (DiffElement)element); } else { throw new IllegalStateException(EMFCompareUIMessages.getString(INVALID_TAB, selectedTab)); } } return widget; } /** * This will return the {@link DiffElement} for a given {@link Item} or <code>null</code> if that * particular item doesn't map to a difference. * * @param item * {@link Item} we seek the {@link DiffElement} for. * @return The {@link DiffElement} for a given {@link Item} or <code>null</code> if that particular item * doesn't map to a difference. */ public DiffElement findDiffForTreeItem(Item item) { final StringBuilder itemKey = new StringBuilder(); itemKey.append(partSide).append(item.getText()).append(item.hashCode()); if (expanded) mapTreeItemToDiff(); return treeItemToDiff.get(itemKey.toString()); } /** * Returns the properties part of this viewer part. * * @return The properties part of this viewer part. */ public ModelContentMergePropertyPart getPropertyPart() { return properties; } /** * Returns the height of the tab control's header. * * @return The height of the tab control's header. */ public int getHeaderHeight() { int headerHeight = 0; if (selectedTab == ModelContentMergeViewer.TREE_TAB) { headerHeight = tree.getTree().getHeaderHeight(); } else if (selectedTab == ModelContentMergeViewer.PROPERTIES_TAB) { headerHeight = properties.getTable().getHeaderHeight(); } else { throw new IllegalStateException(INVALID_TAB); } return headerHeight; } /** * Returns a list of the selected tab's selected Elements. * * @return The selected tab's selected Elements. */ public List<TreeItem> getSelectedElements() { List<TreeItem> selectedElements = null; if (selectedTab == ModelContentMergeViewer.TREE_TAB) { selectedElements = tree.getSelectedElements(); } else if (selectedTab != ModelContentMergeViewer.PROPERTIES_TAB) { throw new IllegalStateException(INVALID_TAB); } return selectedElements; } /** * Returns the width of the columns shown on the properties tab. * * @return The width of the columns shown on the properties tab. */ public int getTotalColumnsWidth() { int width = 0; if (selectedTab == ModelContentMergeViewer.PROPERTIES_TAB) { for (final TableColumn col : properties.getTable().getColumns()) { width += col.getWidth(); } } return width; } /** * Returns the tree part of this viewer part. * * @return The tree part of this viewer part. */ public ModelContentMergeTreePart getTreePart() { return tree; } /** * Returns the first root of the tree. * * @return The first root of the tree. */ public TreeItem getTreeRoot() { if (tree.getVisibleElements().size() > 0) return tree.getVisibleElements().get(0); return null; } /** * Checks wether a given {@link Item} is visible. * * @param item * Item to check. * @return <code>True</code> if the item is visible, <code>False</code> otherwise. */ public boolean isVisible(Item item) { boolean visible = false; if (item instanceof TreeItem) { final TreeItem treeItem = (TreeItem)item; // First we check that the treeItem is contained within the tree's client area visible = tree.getTree().getClientArea().contains(treeItem.getBounds().x, treeItem.getBounds().y); // Then we check that the treeItem's parent is expanded if (visible && treeItem.getParentItem() != null) visible = treeItem.getParentItem().getExpanded(); } return visible; } /** * Redraws this viewer part. */ public void layout() { if (selectedTab == ModelContentMergeViewer.TREE_TAB) { tree.getTree().redraw(); } else if (selectedTab == ModelContentMergeViewer.PROPERTIES_TAB) { properties.getTable().redraw(); } else { throw new IllegalStateException(INVALID_TAB); } } /** * Shows the given item on the tree tab or its properties on the property tab. * * @param diff * Item to scroll to. */ public void navigateToDiff(DiffElement diff) { final List<DiffElement> diffs = new ArrayList<DiffElement>(); diffs.add(diff); navigateToDiff(diffs); } /** * Ensures the first item of the given list of {@link DiffElement}s is visible, and sets the selection of the tree to all those items. * * @param diffs * Items to select. */ public void navigateToDiff(List<DiffElement> diffs) { EObject target = null; if (partSide == EMFCompareConstants.LEFT) { target = EMFCompareEObjectUtils.getLeftElement(diffs.get(0)); final TreeItem treeItem = (TreeItem)find(target); if (diffs.get(0) instanceof AddModelElement && treeItem != null) treeItem.setExpanded(true); } else if (partSide == EMFCompareConstants.RIGHT) { target = EMFCompareEObjectUtils.getRightElement(diffs.get(0)); final TreeItem treeItem = (TreeItem)find(target); if (diffs.get(0) instanceof RemoveModelElement && treeItem != null) treeItem.setExpanded(true); } else if (partSide == EMFCompareConstants.ANCESTOR) { target = EMFCompareEObjectUtils.getAncestorElement(diffs.get(0).eContainer()); } if (selectedTab == ModelContentMergeViewer.TREE_TAB) { tree.showItem(getTreeItemsDataFor(diffs)); properties.setInput(findMatchFromElement(target)); } else if (selectedTab == ModelContentMergeViewer.PROPERTIES_TAB) { properties.setInput(findMatchFromElement(target)); properties.showItem(((PropertyContentProvider)properties.getContentProvider()).getInputEObject(), diffs.get(0)); } else { throw new IllegalStateException(INVALID_TAB); } parentViewer.getConfiguration().setProperty(EMFCompareConstants.PROPERTY_CONTENT_SELECTION, diffs.get(0)); parentViewer.updateCenter(); // We'll assume the tree has been expanded or collapsed during the process expanded = true; } /** * Retrieve the list of tree items data corresponding to the given {@link DiffElement}s. * @param diffs {@link DiffElement}s we seek the tree items for. * @return The list of tree items corresponding to the given {@link DiffElement}s. */ public List<EObject> getTreeItemsDataFor(List<DiffElement> diffs) { final List<EObject> result = new ArrayList<EObject>(diffs.size()); for (DiffElement diff : diffs) { if (partSide == EMFCompareConstants.RIGHT) { final EObject data = EMFCompareEObjectUtils.getRightElement(diff); if (data != null && !result.contains(data)) result.add(data); } else if (partSide == EMFCompareConstants.LEFT) { final EObject data = EMFCompareEObjectUtils.getLeftElement(diff); if (data != null && !result.contains(data)) result.add(data); } else if (partSide == EMFCompareConstants.ANCESTOR) { final EObject data = EMFCompareEObjectUtils.getRightElement(diff); if (data != null && !result.contains(data)) result.add(data); } } return result; } /** * Sets the receiver's size and location to the rectangular area specified by the arguments. * * @param x * Desired x coordinate of the part. * @param y * Desired y coordinate of the part. * @param width * Desired width of the part. * @param height * Desired height of the part. */ public void setBounds(int x, int y, int width, int height) { setBounds(new Rectangle(x, y, width, height)); } /** * Sets the receiver's size and location to given rectangular area. * * @param bounds * Desired bounds for this receiver. */ public void setBounds(Rectangle bounds) { tabFolder.setBounds(bounds); resizeBounds(); } /** * Sets the input of this viewer part. * * @param input * New input of this viewer part. */ public void setInput(Object input) { if (selectedTab == ModelContentMergeViewer.TREE_TAB) { tree.setReflectiveInput((EObject)input); } else if (selectedTab == ModelContentMergeViewer.PROPERTIES_TAB) { properties.setInput(input); } else { throw new IllegalStateException(INVALID_TAB); } } /** * Changes the current tab. * * @param index * New tab to set selected. */ public void setSelectedTab(int index) { selectedTab = index; tabFolder.setSelection(selectedTab); resizeBounds(); } /** * Returns the {@link Match2Elements} containing the given {@link EObject} as its left or right element. * * @param element * Element we seek the {@link Match2Elements} for. * @return The {@link Match2Elements} containing the given {@link EObject} as its left or right element. */ protected Object findMatchFromElement(EObject element) { Object theElement = null; final MatchModel match = ((ModelCompareInput)parentViewer.getInput()).getMatch(); for (final TreeIterator iterator = match.eAllContents(); iterator.hasNext(); ) { final Object object = iterator.next(); if (object instanceof Match2Elements) { final Match2Elements matchElement = (Match2Elements)object; if (matchElement.getLeftElement().equals(element) || matchElement.getRightElement().equals(element)) { theElement = matchElement; } } else if (object instanceof UnMatchElement) { final UnMatchElement matchElement = (UnMatchElement)object; if (matchElement.getElement().equals(element)) { theElement = matchElement; } } } return theElement; } /** * Notifies All {@link ICompareEditorPartListener listeners} registered for this viewer part that the tab * selection has been changed. */ protected void fireSelectedtabChanged() { for (ICompareEditorPartListener listener : editorPartListeners) { listener.selectedTabChanged(selectedTab); } } /** * Notifies All {@link ICompareEditorPartListener listeners} registered for this viewer part that the user * selection has changed on the properties or tree tab. * * @param event * Source {@link SelectionChangedEvent Selection changed event} of the notification. */ protected void fireSelectionChanged(SelectionChangedEvent event) { for (ICompareEditorPartListener listener : editorPartListeners) { listener.selectionChanged(event); } } /** * Notifies All {@link ICompareEditorPartListener listeners} registered for this viewer part that the * center part needs to be refreshed. */ protected void fireUpdateCenter() { for (ICompareEditorPartListener listener : editorPartListeners) { listener.updateCenter(); } } /** * Maps TreeItems to DiffElements. Called each time a {@link TreeItem} is expanded. */ protected void mapTreeItemToDiff() { final List<DiffElement> diffList = ((ModelCompareInput)parentViewer.getInput()).getDiffAsList(); treeItemToDiff.clear(); for (final DiffElement diff : diffList) { final Item storedItem; if (partSide == EMFCompareConstants.LEFT) storedItem = parentViewer.getLeftItem(diff); else if (partSide == EMFCompareConstants.RIGHT) storedItem = parentViewer.getRightItem(diff); else storedItem = parentViewer.getAncestorItem(diff); final StringBuilder diffItemKey = new StringBuilder(); diffItemKey.append(partSide).append(storedItem.getText()).append(storedItem.hashCode()); treeItemToDiff.put(diffItemKey.toString(), diff); } expanded = false; } /** * This will resize the tabs displayed by this content merge viewer. */ protected void resizeBounds() { if (selectedTab == ModelContentMergeViewer.TREE_TAB) { tree.getTree().setBounds(tabFolder.getClientArea()); } else if (selectedTab == ModelContentMergeViewer.PROPERTIES_TAB) { properties.getTable().setBounds(tabFolder.getClientArea()); } else { throw new IllegalStateException(INVALID_TAB); } } /** * Handles the creation of the properties tab of this viewer part given the parent {@link Composite} under * which to create it. * * @param composite * Parent {@link Composite} of the table to create. * @return The properties part displayed by this viewer part's properties tab. */ private ModelContentMergePropertyPart createPropertiesPart(Composite composite) { final ModelContentMergePropertyPart propertiesPart = new ModelContentMergePropertyPart(composite, SWT.NONE, partSide); propertiesPart.setContentProvider(new PropertyContentProvider()); propertiesPart.getTable().setHeaderVisible(true); propertiesPart.getTable().addPaintListener(new PropertyPaintListener()); propertiesPart.getTable().getVerticalBar().addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } public void widgetSelected(SelectionEvent e) { parentViewer.updateCenter(); } }); propertiesPart.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { fireSelectionChanged(event); } }); return propertiesPart; } /** * Handles the creation of the tree tab of this viewer part given the parent {@link Composite} under which * to create it. * * @param composite * Parent {@link Composite} of the tree to create. * @return The tree part displayed by this viewer part's tree tab. */ private ModelContentMergeTreePart createTreePart(Composite composite) { final ModelContentMergeTreePart treePart = new ModelContentMergeTreePart(composite); treePart.setContentProvider(new AdapterFactoryContentProvider(EMFAdapterFactoryProvider .getAdapterFactory())); treePart.getTree().addPaintListener(new TreePaintListener()); treePart.getTree().getVerticalBar().addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } public void widgetSelected(SelectionEvent e) { fireUpdateCenter(); } }); treePart.getTree().addTreeListener(new TreeListener() { public void treeCollapsed(TreeEvent e) { ((TreeItem)e.item).setExpanded(false); e.doit = false; parentViewer.update(); expanded = true; } public void treeExpanded(TreeEvent e) { ((TreeItem)e.item).setExpanded(true); e.doit = false; parentViewer.update(); expanded = true; } }); treePart.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { fireSelectionChanged(event); } }); treePart.getTree().addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (tree.getSelectedElements().size() > 0) { final TreeItem selected = tree.getSelectedElements().get(0); for (final DiffElement diff : ((ModelCompareInput)parentViewer.getInput()) .getDiffAsList()) { if (!(diff instanceof DiffGroup) && partSide == EMFCompareConstants.LEFT) { if (selected.getData().equals(EMFCompareEObjectUtils.getLeftElement(diff))) parentViewer.setSelection(diff); } else if (!(diff instanceof DiffGroup) && partSide == EMFCompareConstants.RIGHT) { if (selected.getData().equals(EMFCompareEObjectUtils.getRightElement(diff))) parentViewer.setSelection(diff); } } if (!selected.isDisposed() && selected.getData() instanceof EObject) properties.setInput(findMatchFromElement((EObject)selected.getData())); } } }); return treePart; } /** * This implementation of {@link PaintListener} handles the drawing of blocks around modified members in * the properties tab. */ class PropertyPaintListener implements PaintListener { /** * {@inheritDoc} * * @see org.eclipse.swt.events.PaintListener#paintControl(org.eclipse.swt.events.PaintEvent) */ public void paintControl(PaintEvent event) { if (parentViewer.shouldDrawDiffMarkers()) { for (final DiffElement diff : ((ModelCompareInput)parentViewer.getInput()).getDiffAsList()) { if ((diff instanceof AttributeChange || diff instanceof ReferenceChange) && find(diff) != null && partSide == EMFCompareConstants.LEFT) { drawLine(event, (TableItem)parentViewer.getLeftItem(diff)); } } } } /** * Handles the drawing itself. * * @param event * {@link PaintEvent} that triggered this operation. * @param tableItem * Item we want connected to the center part. */ private void drawLine(PaintEvent event, TableItem tableItem) { final Rectangle tableBounds = properties.getTable().getBounds(); final Rectangle tableItemBounds = tableItem.getBounds(); tableItem.setBackground(new Color(tableItem.getDisplay(), parentViewer.getHighlightColor())); final int lineY = tableItemBounds.y + tableItemBounds.height / 2; event.gc.setLineWidth(2); event.gc.setForeground(new Color(tableItem.getDisplay(), parentViewer.getChangedColor())); event.gc.drawLine(getTotalColumnsWidth(), lineY, tableBounds.width, lineY); } } /** * This implementation of {@link PaintListener} handles the drawing of blocks around modified members in * the tree tab. */ class TreePaintListener implements PaintListener { /** * {@inheritDoc} * * @see org.eclipse.swt.events.PaintListener#paintControl(org.eclipse.swt.events.PaintEvent) */ public void paintControl(PaintEvent event) { // This will avoid strange random resize behavior on linux OS if (tree.getTree().getBounds() != tabFolder.getClientArea()) resizeBounds(); if (parentViewer.shouldDrawDiffMarkers()) { for (TreeItem item : tree.getVisibleElements()) { final DiffElement element = findDiffForTreeItem(item); if (element != null) drawRectangle(event, item, element); } } } /** * Handles the drawing itself. * * @param event * {@link PaintEvent} that triggered this operation. * @param treeItem * {@link TreeItem} that need to be circled and connected to the center part. * @param diff * {@link DiffElement} we're circling this {@link TreeItem} for. */ private void drawRectangle(PaintEvent event, TreeItem treeItem, DiffElement diff) { final Rectangle treeBounds = tree.getTree().getClientArea(); final Rectangle treeItemBounds = treeItem.getBounds(); if (DiffAdapterFactory.shouldBeHidden(diff)) return; // Defines the circling Color RGB color = parentViewer.getChangedColor(); if (diff instanceof ConflictingDiffElement || diff.eContainer() instanceof ConflictingDiffElement) { color = parentViewer.getConflictingColor(); } else if (diff instanceof AddModelElement || diff instanceof RemoteAddModelElement) { color = parentViewer.getAddedColor(); } else if (diff instanceof RemoveModelElement || diff instanceof RemoteRemoveModelElement) { color = parentViewer.getRemovedColor(); } /* * We add a margin before the rectangle to circle the "+" as well as the tree line. */ final int margin = 60; // Defines all variables needed for drawing the rectangle. final int rectangleX = treeItemBounds.x - margin; final int rectangleY = treeItemBounds.y; final int rectangleWidth = treeItemBounds.width + margin; final int rectangleHeight = treeItemBounds.height - 1; final int rectangleArcWidth = 5; final int rectangleArcHeight = 5; int lineWidth = 1; // if the item is selected, we set a bigger line width if (getSelectedElements().contains(treeItem)) { lineWidth = 2; } // Performs the actual drawing event.gc.setLineWidth(lineWidth); event.gc.setForeground(new Color(treeItem.getDisplay(), color)); if (partSide == EMFCompareConstants.LEFT) { if (!treeItem.getData().equals(EMFCompareEObjectUtils.getLeftElement(diff)) || diff instanceof AddModelElement || diff instanceof RemoteRemoveModelElement) { event.gc.setLineStyle(SWT.LINE_SOLID); - event.gc.drawLine(rectangleX, rectangleY + rectangleHeight, treeBounds.width, rectangleY + event.gc.drawLine(rectangleX, rectangleY + rectangleHeight, treeBounds.width + treeBounds.x, rectangleY + rectangleHeight); } else { event.gc.setLineStyle(SWT.LINE_DASHDOT); event.gc.drawRoundRectangle(rectangleX, rectangleY, rectangleWidth, rectangleHeight, rectangleArcWidth, rectangleArcHeight); event.gc.setLineStyle(SWT.LINE_SOLID); event.gc.drawLine(rectangleX + rectangleWidth, rectangleY + rectangleHeight / 2, - treeBounds.width, rectangleY + rectangleHeight / 2); + treeBounds.width + treeBounds.x, rectangleY + rectangleHeight / 2); } } else if (partSide == EMFCompareConstants.RIGHT) { if (!treeItem.getData().equals(EMFCompareEObjectUtils.getRightElement(diff)) || diff instanceof RemoveModelElement || diff instanceof RemoteAddModelElement) { event.gc.setLineStyle(SWT.LINE_SOLID); event.gc.drawLine(rectangleX + rectangleWidth, rectangleY + rectangleHeight, treeBounds.x, rectangleY + rectangleHeight); } else { event.gc.setLineStyle(SWT.LINE_DASHDOT); event.gc.drawRoundRectangle(rectangleX, rectangleY, rectangleWidth, rectangleHeight, rectangleArcWidth, rectangleArcHeight); event.gc.setLineStyle(SWT.LINE_SOLID); event.gc.drawLine(rectangleX, rectangleY + rectangleHeight / 2, treeBounds.x, rectangleY + rectangleHeight / 2); } } else { if (!treeItem.getData().equals(EMFCompareEObjectUtils.getAncestorElement(diff))) { event.gc.setLineStyle(SWT.LINE_SOLID); event.gc.drawLine(rectangleX + rectangleWidth, rectangleY + rectangleHeight, rectangleX, rectangleY + rectangleHeight); } else { event.gc.setLineStyle(SWT.LINE_DASHDOT); event.gc.drawRoundRectangle(rectangleX, rectangleY, rectangleWidth, rectangleHeight, rectangleArcWidth, rectangleArcHeight); } } } } }
false
true
private void drawRectangle(PaintEvent event, TreeItem treeItem, DiffElement diff) { final Rectangle treeBounds = tree.getTree().getClientArea(); final Rectangle treeItemBounds = treeItem.getBounds(); if (DiffAdapterFactory.shouldBeHidden(diff)) return; // Defines the circling Color RGB color = parentViewer.getChangedColor(); if (diff instanceof ConflictingDiffElement || diff.eContainer() instanceof ConflictingDiffElement) { color = parentViewer.getConflictingColor(); } else if (diff instanceof AddModelElement || diff instanceof RemoteAddModelElement) { color = parentViewer.getAddedColor(); } else if (diff instanceof RemoveModelElement || diff instanceof RemoteRemoveModelElement) { color = parentViewer.getRemovedColor(); } /* * We add a margin before the rectangle to circle the "+" as well as the tree line. */ final int margin = 60; // Defines all variables needed for drawing the rectangle. final int rectangleX = treeItemBounds.x - margin; final int rectangleY = treeItemBounds.y; final int rectangleWidth = treeItemBounds.width + margin; final int rectangleHeight = treeItemBounds.height - 1; final int rectangleArcWidth = 5; final int rectangleArcHeight = 5; int lineWidth = 1; // if the item is selected, we set a bigger line width if (getSelectedElements().contains(treeItem)) { lineWidth = 2; } // Performs the actual drawing event.gc.setLineWidth(lineWidth); event.gc.setForeground(new Color(treeItem.getDisplay(), color)); if (partSide == EMFCompareConstants.LEFT) { if (!treeItem.getData().equals(EMFCompareEObjectUtils.getLeftElement(diff)) || diff instanceof AddModelElement || diff instanceof RemoteRemoveModelElement) { event.gc.setLineStyle(SWT.LINE_SOLID); event.gc.drawLine(rectangleX, rectangleY + rectangleHeight, treeBounds.width, rectangleY + rectangleHeight); } else { event.gc.setLineStyle(SWT.LINE_DASHDOT); event.gc.drawRoundRectangle(rectangleX, rectangleY, rectangleWidth, rectangleHeight, rectangleArcWidth, rectangleArcHeight); event.gc.setLineStyle(SWT.LINE_SOLID); event.gc.drawLine(rectangleX + rectangleWidth, rectangleY + rectangleHeight / 2, treeBounds.width, rectangleY + rectangleHeight / 2); } } else if (partSide == EMFCompareConstants.RIGHT) { if (!treeItem.getData().equals(EMFCompareEObjectUtils.getRightElement(diff)) || diff instanceof RemoveModelElement || diff instanceof RemoteAddModelElement) { event.gc.setLineStyle(SWT.LINE_SOLID); event.gc.drawLine(rectangleX + rectangleWidth, rectangleY + rectangleHeight, treeBounds.x, rectangleY + rectangleHeight); } else { event.gc.setLineStyle(SWT.LINE_DASHDOT); event.gc.drawRoundRectangle(rectangleX, rectangleY, rectangleWidth, rectangleHeight, rectangleArcWidth, rectangleArcHeight); event.gc.setLineStyle(SWT.LINE_SOLID); event.gc.drawLine(rectangleX, rectangleY + rectangleHeight / 2, treeBounds.x, rectangleY + rectangleHeight / 2); } } else { if (!treeItem.getData().equals(EMFCompareEObjectUtils.getAncestorElement(diff))) { event.gc.setLineStyle(SWT.LINE_SOLID); event.gc.drawLine(rectangleX + rectangleWidth, rectangleY + rectangleHeight, rectangleX, rectangleY + rectangleHeight); } else { event.gc.setLineStyle(SWT.LINE_DASHDOT); event.gc.drawRoundRectangle(rectangleX, rectangleY, rectangleWidth, rectangleHeight, rectangleArcWidth, rectangleArcHeight); } } }
private void drawRectangle(PaintEvent event, TreeItem treeItem, DiffElement diff) { final Rectangle treeBounds = tree.getTree().getClientArea(); final Rectangle treeItemBounds = treeItem.getBounds(); if (DiffAdapterFactory.shouldBeHidden(diff)) return; // Defines the circling Color RGB color = parentViewer.getChangedColor(); if (diff instanceof ConflictingDiffElement || diff.eContainer() instanceof ConflictingDiffElement) { color = parentViewer.getConflictingColor(); } else if (diff instanceof AddModelElement || diff instanceof RemoteAddModelElement) { color = parentViewer.getAddedColor(); } else if (diff instanceof RemoveModelElement || diff instanceof RemoteRemoveModelElement) { color = parentViewer.getRemovedColor(); } /* * We add a margin before the rectangle to circle the "+" as well as the tree line. */ final int margin = 60; // Defines all variables needed for drawing the rectangle. final int rectangleX = treeItemBounds.x - margin; final int rectangleY = treeItemBounds.y; final int rectangleWidth = treeItemBounds.width + margin; final int rectangleHeight = treeItemBounds.height - 1; final int rectangleArcWidth = 5; final int rectangleArcHeight = 5; int lineWidth = 1; // if the item is selected, we set a bigger line width if (getSelectedElements().contains(treeItem)) { lineWidth = 2; } // Performs the actual drawing event.gc.setLineWidth(lineWidth); event.gc.setForeground(new Color(treeItem.getDisplay(), color)); if (partSide == EMFCompareConstants.LEFT) { if (!treeItem.getData().equals(EMFCompareEObjectUtils.getLeftElement(diff)) || diff instanceof AddModelElement || diff instanceof RemoteRemoveModelElement) { event.gc.setLineStyle(SWT.LINE_SOLID); event.gc.drawLine(rectangleX, rectangleY + rectangleHeight, treeBounds.width + treeBounds.x, rectangleY + rectangleHeight); } else { event.gc.setLineStyle(SWT.LINE_DASHDOT); event.gc.drawRoundRectangle(rectangleX, rectangleY, rectangleWidth, rectangleHeight, rectangleArcWidth, rectangleArcHeight); event.gc.setLineStyle(SWT.LINE_SOLID); event.gc.drawLine(rectangleX + rectangleWidth, rectangleY + rectangleHeight / 2, treeBounds.width + treeBounds.x, rectangleY + rectangleHeight / 2); } } else if (partSide == EMFCompareConstants.RIGHT) { if (!treeItem.getData().equals(EMFCompareEObjectUtils.getRightElement(diff)) || diff instanceof RemoveModelElement || diff instanceof RemoteAddModelElement) { event.gc.setLineStyle(SWT.LINE_SOLID); event.gc.drawLine(rectangleX + rectangleWidth, rectangleY + rectangleHeight, treeBounds.x, rectangleY + rectangleHeight); } else { event.gc.setLineStyle(SWT.LINE_DASHDOT); event.gc.drawRoundRectangle(rectangleX, rectangleY, rectangleWidth, rectangleHeight, rectangleArcWidth, rectangleArcHeight); event.gc.setLineStyle(SWT.LINE_SOLID); event.gc.drawLine(rectangleX, rectangleY + rectangleHeight / 2, treeBounds.x, rectangleY + rectangleHeight / 2); } } else { if (!treeItem.getData().equals(EMFCompareEObjectUtils.getAncestorElement(diff))) { event.gc.setLineStyle(SWT.LINE_SOLID); event.gc.drawLine(rectangleX + rectangleWidth, rectangleY + rectangleHeight, rectangleX, rectangleY + rectangleHeight); } else { event.gc.setLineStyle(SWT.LINE_DASHDOT); event.gc.drawRoundRectangle(rectangleX, rectangleY, rectangleWidth, rectangleHeight, rectangleArcWidth, rectangleArcHeight); } } }
diff --git a/deegree-core/deegree-core-base/src/main/java/org/deegree/feature/xpath/TypedObjectNodeXPathEvaluator.java b/deegree-core/deegree-core-base/src/main/java/org/deegree/feature/xpath/TypedObjectNodeXPathEvaluator.java index d16f5b01b9..4788ae04e4 100644 --- a/deegree-core/deegree-core-base/src/main/java/org/deegree/feature/xpath/TypedObjectNodeXPathEvaluator.java +++ b/deegree-core/deegree-core-base/src/main/java/org/deegree/feature/xpath/TypedObjectNodeXPathEvaluator.java @@ -1,210 +1,210 @@ //$HeadURL$ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2009 by: - Department of Geography, University of Bonn - and - lat/lon GmbH - This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: [email protected] ----------------------------------------------------------------------------*/ package org.deegree.feature.xpath; import java.util.List; import java.util.Map; import javax.xml.namespace.QName; import org.deegree.commons.tom.ElementNode; import org.deegree.commons.tom.TypedObjectNode; import org.deegree.commons.tom.gml.GMLObject; import org.deegree.commons.tom.gml.property.Property; import org.deegree.commons.tom.primitive.PrimitiveValue; import org.deegree.feature.xpath.node.GMLObjectNode; import org.deegree.feature.xpath.node.PropertyNode; import org.deegree.feature.xpath.node.XMLElementNode; import org.deegree.feature.xpath.node.XPathNode; import org.deegree.filter.FilterEvaluationException; import org.deegree.filter.XPathEvaluator; import org.deegree.filter.expression.ValueReference; import org.jaxen.JaxenException; import org.jaxen.XPath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * {@link XPathEvaluator} implementation for {@link TypedObjectNode} graphs. * * @author <a href="mailto:[email protected]">Markus Schneider</a> * @author last edited by: $Author$ * * @version $Revision$, $Date$ */ public class TypedObjectNodeXPathEvaluator implements XPathEvaluator<TypedObjectNode> { private static Logger LOG = LoggerFactory.getLogger( TypedObjectNodeXPathEvaluator.class ); private Map<String, QName> bindings; public TypedObjectNodeXPathEvaluator() { // default constructor } /** * @param bindings * a mapping from local name to qname to use for repairing broken filters, may be null */ public TypedObjectNodeXPathEvaluator( Map<String, QName> bindings ) { this.bindings = bindings; } @Override public TypedObjectNode[] eval( TypedObjectNode particle, ValueReference path ) throws FilterEvaluationException { if ( particle instanceof GMLObject ) { return eval( (GMLObject) particle, path ); } if ( particle instanceof ElementNode ) { return eval( (ElementNode) particle, path ); } throw new FilterEvaluationException( "Evaluation of XPath expressions on '" + particle.getClass() + "' is not supported." ); } public TypedObjectNode[] eval( GMLObject context, ValueReference propName ) throws FilterEvaluationException { // simple property with just a simple element step? QName simplePropName = propName.getAsQName(); - if ( bindings != null + if ( bindings != null && simplePropName != null && ( simplePropName.getNamespaceURI() == null || simplePropName.getNamespaceURI().isEmpty() ) ) { QName altName = bindings.get( simplePropName.getLocalPart() ); if ( altName != null ) { LOG.debug( "Repairing namespace binding for property {}", simplePropName.getLocalPart() ); simplePropName = altName; } } if ( simplePropName != null ) { List<Property> props = context.getProperties( simplePropName ); TypedObjectNode[] propArray = new TypedObjectNode[props.size()]; return props.toArray( propArray ); } TypedObjectNode[] resultValues = null; try { synchronized ( context ) { XPath xpath = new GMLObjectXPath( propName.getAsText(), context ); xpath.setNamespaceContext( propName.getNsContext() ); List<?> selectedNodes; selectedNodes = xpath.selectNodes( new GMLObjectNode<GMLObject, GMLObject>( null, context ) ); resultValues = new TypedObjectNode[selectedNodes.size()]; int i = 0; for ( Object node : selectedNodes ) { if ( node instanceof XPathNode<?> ) { resultValues[i++] = ( (XPathNode<?>) node ).getValue(); } else if ( node instanceof String || node instanceof Double || node instanceof Boolean ) { resultValues[i++] = new PrimitiveValue( node ); } else { throw new RuntimeException( "Internal error. Encountered unexpected value of type '" + node.getClass().getName() + "' (=" + node + ") during XPath-evaluation." ); } } } } catch ( JaxenException e ) { e.printStackTrace(); throw new FilterEvaluationException( e.getMessage() ); } return resultValues; } public TypedObjectNode[] eval( ElementNode element, ValueReference propName ) throws FilterEvaluationException { TypedObjectNode[] resultValues = null; try { XPath xpath = new GMLObjectXPath( propName.getAsText(), null ); xpath.setNamespaceContext( propName.getNsContext() ); List<?> selectedNodes; selectedNodes = xpath.selectNodes( new XMLElementNode( null, element ) ); resultValues = new TypedObjectNode[selectedNodes.size()]; int i = 0; for ( Object node : selectedNodes ) { if ( node instanceof XPathNode<?> ) { resultValues[i++] = ( (XPathNode<?>) node ).getValue(); } else if ( node instanceof String || node instanceof Double || node instanceof Boolean ) { resultValues[i++] = new PrimitiveValue( node ); } else { throw new RuntimeException( "Internal error. Encountered unexpected value of type '" + node.getClass().getName() + "' (=" + node + ") during XPath-evaluation." ); } } } catch ( JaxenException e ) { throw new FilterEvaluationException( e.getMessage() ); } return resultValues; } public TypedObjectNode[] eval( Property element, ValueReference propName ) throws FilterEvaluationException { TypedObjectNode[] resultValues = null; try { XPath xpath = new GMLObjectXPath( propName.getAsText(), null ); xpath.setNamespaceContext( propName.getNsContext() ); List<?> selectedNodes; selectedNodes = xpath.selectNodes( new PropertyNode( null, element ) ); resultValues = new TypedObjectNode[selectedNodes.size()]; int i = 0; for ( Object node : selectedNodes ) { if ( node instanceof XPathNode<?> ) { resultValues[i++] = ( (XPathNode<?>) node ).getValue(); } else if ( node instanceof String || node instanceof Double || node instanceof Boolean ) { resultValues[i++] = new PrimitiveValue( node ); } else { throw new RuntimeException( "Internal error. Encountered unexpected value of type '" + node.getClass().getName() + "' (=" + node + ") during XPath-evaluation." ); } } } catch ( JaxenException e ) { throw new FilterEvaluationException( e.getMessage() ); } return resultValues; } @Override public String getId( TypedObjectNode context ) { if ( context instanceof GMLObject ) { return ( (GMLObject) context ).getId(); } // TODO implement fallback to generic gml:id attribute return null; } }
true
true
public TypedObjectNode[] eval( GMLObject context, ValueReference propName ) throws FilterEvaluationException { // simple property with just a simple element step? QName simplePropName = propName.getAsQName(); if ( bindings != null && ( simplePropName.getNamespaceURI() == null || simplePropName.getNamespaceURI().isEmpty() ) ) { QName altName = bindings.get( simplePropName.getLocalPart() ); if ( altName != null ) { LOG.debug( "Repairing namespace binding for property {}", simplePropName.getLocalPart() ); simplePropName = altName; } } if ( simplePropName != null ) { List<Property> props = context.getProperties( simplePropName ); TypedObjectNode[] propArray = new TypedObjectNode[props.size()]; return props.toArray( propArray ); } TypedObjectNode[] resultValues = null; try { synchronized ( context ) { XPath xpath = new GMLObjectXPath( propName.getAsText(), context ); xpath.setNamespaceContext( propName.getNsContext() ); List<?> selectedNodes; selectedNodes = xpath.selectNodes( new GMLObjectNode<GMLObject, GMLObject>( null, context ) ); resultValues = new TypedObjectNode[selectedNodes.size()]; int i = 0; for ( Object node : selectedNodes ) { if ( node instanceof XPathNode<?> ) { resultValues[i++] = ( (XPathNode<?>) node ).getValue(); } else if ( node instanceof String || node instanceof Double || node instanceof Boolean ) { resultValues[i++] = new PrimitiveValue( node ); } else { throw new RuntimeException( "Internal error. Encountered unexpected value of type '" + node.getClass().getName() + "' (=" + node + ") during XPath-evaluation." ); } } } } catch ( JaxenException e ) { e.printStackTrace(); throw new FilterEvaluationException( e.getMessage() ); } return resultValues; }
public TypedObjectNode[] eval( GMLObject context, ValueReference propName ) throws FilterEvaluationException { // simple property with just a simple element step? QName simplePropName = propName.getAsQName(); if ( bindings != null && simplePropName != null && ( simplePropName.getNamespaceURI() == null || simplePropName.getNamespaceURI().isEmpty() ) ) { QName altName = bindings.get( simplePropName.getLocalPart() ); if ( altName != null ) { LOG.debug( "Repairing namespace binding for property {}", simplePropName.getLocalPart() ); simplePropName = altName; } } if ( simplePropName != null ) { List<Property> props = context.getProperties( simplePropName ); TypedObjectNode[] propArray = new TypedObjectNode[props.size()]; return props.toArray( propArray ); } TypedObjectNode[] resultValues = null; try { synchronized ( context ) { XPath xpath = new GMLObjectXPath( propName.getAsText(), context ); xpath.setNamespaceContext( propName.getNsContext() ); List<?> selectedNodes; selectedNodes = xpath.selectNodes( new GMLObjectNode<GMLObject, GMLObject>( null, context ) ); resultValues = new TypedObjectNode[selectedNodes.size()]; int i = 0; for ( Object node : selectedNodes ) { if ( node instanceof XPathNode<?> ) { resultValues[i++] = ( (XPathNode<?>) node ).getValue(); } else if ( node instanceof String || node instanceof Double || node instanceof Boolean ) { resultValues[i++] = new PrimitiveValue( node ); } else { throw new RuntimeException( "Internal error. Encountered unexpected value of type '" + node.getClass().getName() + "' (=" + node + ") during XPath-evaluation." ); } } } } catch ( JaxenException e ) { e.printStackTrace(); throw new FilterEvaluationException( e.getMessage() ); } return resultValues; }
diff --git a/src/test/java/org/test/streaming/VideoRegistrationFullCycleTest.java b/src/test/java/org/test/streaming/VideoRegistrationFullCycleTest.java index adc2f57..dac269e 100644 --- a/src/test/java/org/test/streaming/VideoRegistrationFullCycleTest.java +++ b/src/test/java/org/test/streaming/VideoRegistrationFullCycleTest.java @@ -1,119 +1,119 @@ package org.test.streaming; import java.io.File; import java.util.Collection; import java.util.List; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.Transformer; import org.apache.commons.lang.StringUtils; import org.junit.Assert; import org.junit.Test; import org.test.streaming.monitor.CachoRegistration; import org.test.streaming.monitor.Notifier; import org.test.streaming.monitor.RegistrationResponse; import org.test.streaming.monitor.UserRegistration; import org.test.streaming.monitor.VideoRegistration; public class VideoRegistrationFullCycleTest { String videoChunks; /** * El indice tiene que estar levantado. */ @Test public void testRestrievalPlan(){ Conf conf = new Conf("/alt-test-conf.properties"); String videoFileName = conf.get("test.video.file.name"); File video = new File(conf.getCachosDir(), videoFileName); Assert.assertTrue("file: "+video.getAbsolutePath()+" does not exist", video.exists()); Notifier notifier = new Notifier(conf); /* * parte 1: * registro usuario * el usuario regitra un video * pide el retrieval plan para ese video */ Assert.assertTrue(StringUtils.isNotEmpty(conf.get("test.user.id"))); - User user = new User(conf.get("test.user.id"), "[email protected]", "localhost", "8080"); + User user = new User(conf.get("test.user.id"), "[email protected]", "localhost", "8080", "10002"); UserRegistration userRegistration = new UserRegistration(user, conf); userRegistration.go(); VideoRegistration videoRegistration = new VideoRegistration(video, conf); RegistrationResponse videoRegistrationResponse = videoRegistration.register(); Assert.assertNotNull(videoRegistrationResponse); /* * no hay error de conexion (CONN_ERROR) */ Assert.assertTrue(videoRegistrationResponse.getCode().equals("OK") || videoRegistrationResponse.getCode().equals("ERROR")); WatchMovieRetrievalPlan retrievalPlan = (WatchMovieRetrievalPlan) notifier.getRetrievalPlan(videoRegistrationResponse.getId(), conf.get("test.user.id")); Assert.assertEquals(retrievalPlan.getRequests().size(), 1); Assert.assertEquals(retrievalPlan.getRequests().get(0).getHost(), user.getIp()); Assert.assertEquals(retrievalPlan.getVideoId(), videoRegistrationResponse.getId()); Assert.assertEquals(video.length(), retrievalPlan.getRequests().get(0).getRequest().getLength()); /* * registro otro usuario * el usuario registra un cacho del mismo video * pido el retrieval plan */ - User otroUser = new User("otro-user-test", "[email protected]", "1.1.1.1", "8080"); + User otroUser = new User("otro-user-test", "[email protected]", "1.1.1.1", "8080", "10002"); UserRegistration otherUserRegistration = new UserRegistration(otroUser, conf); otherUserRegistration.go(); int chunkLenght = 1024*1024; MovieCachoFile movieCachoFile = new MovieCachoFile(new MovieCacho(0,chunkLenght), video); CachoRegistration cachoRegistration = new CachoRegistration(conf, movieCachoFile, new MovieCachoHasher().hashMovieCachoFile(movieCachoFile, chunkLenght)); cachoRegistration.setUserId(otroUser.getId()); RegistrationResponse cachoRegistrationResponse = cachoRegistration.register(); Assert.assertNotNull(cachoRegistrationResponse); /* * no hay error de conexion (CONN_ERROR) */ Assert.assertTrue(cachoRegistrationResponse.getCode().equals("OK") || cachoRegistrationResponse.getCode().equals("ERROR")); WatchMovieRetrievalPlan secondRetrievalPlan = (WatchMovieRetrievalPlan) notifier.getRetrievalPlan(videoRegistrationResponse.getId(), otroUser.getId()); Assert.assertEquals(secondRetrievalPlan.getRequests().size(), 2); Assert.assertNotSame(secondRetrievalPlan.getVideoId(), cachoRegistrationResponse.getId()); List<String> ips = (List<String>) CollectionUtils.collect(secondRetrievalPlan.getRequests(), new Transformer(){ @Override public Object transform(Object input) { CachoRetrieval cachoRetrieval = (CachoRetrieval)input; return cachoRetrieval.getHost(); } }); Assert.assertTrue(ips.contains(user.getIp())); Assert.assertTrue(ips.contains(otroUser.getIp())); Collection<Integer> lenghts = CollectionUtils.collect(secondRetrievalPlan.getRequests(), new Transformer(){ @Override public Object transform(Object input) { CachoRetrieval cachoRetrieval = (CachoRetrieval)input; return cachoRetrieval.getRequest().getLength(); } }); Assert.assertTrue(lenghts.contains(chunkLenght)); Assert.assertTrue(lenghts.contains(((int)video.length() - chunkLenght))); } }
false
true
public void testRestrievalPlan(){ Conf conf = new Conf("/alt-test-conf.properties"); String videoFileName = conf.get("test.video.file.name"); File video = new File(conf.getCachosDir(), videoFileName); Assert.assertTrue("file: "+video.getAbsolutePath()+" does not exist", video.exists()); Notifier notifier = new Notifier(conf); /* * parte 1: * registro usuario * el usuario regitra un video * pide el retrieval plan para ese video */ Assert.assertTrue(StringUtils.isNotEmpty(conf.get("test.user.id"))); User user = new User(conf.get("test.user.id"), "[email protected]", "localhost", "8080"); UserRegistration userRegistration = new UserRegistration(user, conf); userRegistration.go(); VideoRegistration videoRegistration = new VideoRegistration(video, conf); RegistrationResponse videoRegistrationResponse = videoRegistration.register(); Assert.assertNotNull(videoRegistrationResponse); /* * no hay error de conexion (CONN_ERROR) */ Assert.assertTrue(videoRegistrationResponse.getCode().equals("OK") || videoRegistrationResponse.getCode().equals("ERROR")); WatchMovieRetrievalPlan retrievalPlan = (WatchMovieRetrievalPlan) notifier.getRetrievalPlan(videoRegistrationResponse.getId(), conf.get("test.user.id")); Assert.assertEquals(retrievalPlan.getRequests().size(), 1); Assert.assertEquals(retrievalPlan.getRequests().get(0).getHost(), user.getIp()); Assert.assertEquals(retrievalPlan.getVideoId(), videoRegistrationResponse.getId()); Assert.assertEquals(video.length(), retrievalPlan.getRequests().get(0).getRequest().getLength()); /* * registro otro usuario * el usuario registra un cacho del mismo video * pido el retrieval plan */ User otroUser = new User("otro-user-test", "[email protected]", "1.1.1.1", "8080"); UserRegistration otherUserRegistration = new UserRegistration(otroUser, conf); otherUserRegistration.go(); int chunkLenght = 1024*1024; MovieCachoFile movieCachoFile = new MovieCachoFile(new MovieCacho(0,chunkLenght), video); CachoRegistration cachoRegistration = new CachoRegistration(conf, movieCachoFile, new MovieCachoHasher().hashMovieCachoFile(movieCachoFile, chunkLenght)); cachoRegistration.setUserId(otroUser.getId()); RegistrationResponse cachoRegistrationResponse = cachoRegistration.register(); Assert.assertNotNull(cachoRegistrationResponse); /* * no hay error de conexion (CONN_ERROR) */ Assert.assertTrue(cachoRegistrationResponse.getCode().equals("OK") || cachoRegistrationResponse.getCode().equals("ERROR")); WatchMovieRetrievalPlan secondRetrievalPlan = (WatchMovieRetrievalPlan) notifier.getRetrievalPlan(videoRegistrationResponse.getId(), otroUser.getId()); Assert.assertEquals(secondRetrievalPlan.getRequests().size(), 2); Assert.assertNotSame(secondRetrievalPlan.getVideoId(), cachoRegistrationResponse.getId()); List<String> ips = (List<String>) CollectionUtils.collect(secondRetrievalPlan.getRequests(), new Transformer(){ @Override public Object transform(Object input) { CachoRetrieval cachoRetrieval = (CachoRetrieval)input; return cachoRetrieval.getHost(); } }); Assert.assertTrue(ips.contains(user.getIp())); Assert.assertTrue(ips.contains(otroUser.getIp())); Collection<Integer> lenghts = CollectionUtils.collect(secondRetrievalPlan.getRequests(), new Transformer(){ @Override public Object transform(Object input) { CachoRetrieval cachoRetrieval = (CachoRetrieval)input; return cachoRetrieval.getRequest().getLength(); } }); Assert.assertTrue(lenghts.contains(chunkLenght)); Assert.assertTrue(lenghts.contains(((int)video.length() - chunkLenght))); }
public void testRestrievalPlan(){ Conf conf = new Conf("/alt-test-conf.properties"); String videoFileName = conf.get("test.video.file.name"); File video = new File(conf.getCachosDir(), videoFileName); Assert.assertTrue("file: "+video.getAbsolutePath()+" does not exist", video.exists()); Notifier notifier = new Notifier(conf); /* * parte 1: * registro usuario * el usuario regitra un video * pide el retrieval plan para ese video */ Assert.assertTrue(StringUtils.isNotEmpty(conf.get("test.user.id"))); User user = new User(conf.get("test.user.id"), "[email protected]", "localhost", "8080", "10002"); UserRegistration userRegistration = new UserRegistration(user, conf); userRegistration.go(); VideoRegistration videoRegistration = new VideoRegistration(video, conf); RegistrationResponse videoRegistrationResponse = videoRegistration.register(); Assert.assertNotNull(videoRegistrationResponse); /* * no hay error de conexion (CONN_ERROR) */ Assert.assertTrue(videoRegistrationResponse.getCode().equals("OK") || videoRegistrationResponse.getCode().equals("ERROR")); WatchMovieRetrievalPlan retrievalPlan = (WatchMovieRetrievalPlan) notifier.getRetrievalPlan(videoRegistrationResponse.getId(), conf.get("test.user.id")); Assert.assertEquals(retrievalPlan.getRequests().size(), 1); Assert.assertEquals(retrievalPlan.getRequests().get(0).getHost(), user.getIp()); Assert.assertEquals(retrievalPlan.getVideoId(), videoRegistrationResponse.getId()); Assert.assertEquals(video.length(), retrievalPlan.getRequests().get(0).getRequest().getLength()); /* * registro otro usuario * el usuario registra un cacho del mismo video * pido el retrieval plan */ User otroUser = new User("otro-user-test", "[email protected]", "1.1.1.1", "8080", "10002"); UserRegistration otherUserRegistration = new UserRegistration(otroUser, conf); otherUserRegistration.go(); int chunkLenght = 1024*1024; MovieCachoFile movieCachoFile = new MovieCachoFile(new MovieCacho(0,chunkLenght), video); CachoRegistration cachoRegistration = new CachoRegistration(conf, movieCachoFile, new MovieCachoHasher().hashMovieCachoFile(movieCachoFile, chunkLenght)); cachoRegistration.setUserId(otroUser.getId()); RegistrationResponse cachoRegistrationResponse = cachoRegistration.register(); Assert.assertNotNull(cachoRegistrationResponse); /* * no hay error de conexion (CONN_ERROR) */ Assert.assertTrue(cachoRegistrationResponse.getCode().equals("OK") || cachoRegistrationResponse.getCode().equals("ERROR")); WatchMovieRetrievalPlan secondRetrievalPlan = (WatchMovieRetrievalPlan) notifier.getRetrievalPlan(videoRegistrationResponse.getId(), otroUser.getId()); Assert.assertEquals(secondRetrievalPlan.getRequests().size(), 2); Assert.assertNotSame(secondRetrievalPlan.getVideoId(), cachoRegistrationResponse.getId()); List<String> ips = (List<String>) CollectionUtils.collect(secondRetrievalPlan.getRequests(), new Transformer(){ @Override public Object transform(Object input) { CachoRetrieval cachoRetrieval = (CachoRetrieval)input; return cachoRetrieval.getHost(); } }); Assert.assertTrue(ips.contains(user.getIp())); Assert.assertTrue(ips.contains(otroUser.getIp())); Collection<Integer> lenghts = CollectionUtils.collect(secondRetrievalPlan.getRequests(), new Transformer(){ @Override public Object transform(Object input) { CachoRetrieval cachoRetrieval = (CachoRetrieval)input; return cachoRetrieval.getRequest().getLength(); } }); Assert.assertTrue(lenghts.contains(chunkLenght)); Assert.assertTrue(lenghts.contains(((int)video.length() - chunkLenght))); }
diff --git a/feed/src/main/java/org/apache/falcon/workflow/OozieFeedWorkflowBuilder.java b/feed/src/main/java/org/apache/falcon/workflow/OozieFeedWorkflowBuilder.java index 0cbdf771..7b9095f8 100644 --- a/feed/src/main/java/org/apache/falcon/workflow/OozieFeedWorkflowBuilder.java +++ b/feed/src/main/java/org/apache/falcon/workflow/OozieFeedWorkflowBuilder.java @@ -1,91 +1,91 @@ /** * 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.falcon.workflow; import org.apache.falcon.FalconException; import org.apache.falcon.Tag; import org.apache.falcon.converter.AbstractOozieEntityMapper; import org.apache.falcon.converter.OozieFeedMapper; import org.apache.falcon.entity.ClusterHelper; import org.apache.falcon.entity.EntityUtil; import org.apache.falcon.entity.FeedHelper; import org.apache.falcon.entity.v0.EntityType; import org.apache.falcon.entity.v0.cluster.Cluster; import org.apache.falcon.entity.v0.feed.Feed; import org.apache.falcon.security.CurrentUser; import org.apache.hadoop.fs.Path; import java.util.*; /** * Workflow definition builder for feed replication & retention. */ public class OozieFeedWorkflowBuilder extends OozieWorkflowBuilder<Feed> { @Override public Map<String, Properties> newWorkflowSchedule(Feed feed, List<String> clusters) throws FalconException { Map<String, Properties> propertiesMap = new HashMap<String, Properties>(); for (String clusterName : clusters) { org.apache.falcon.entity.v0.feed.Cluster feedCluster = FeedHelper.getCluster(feed, clusterName); Properties properties = newWorkflowSchedule(feed, feedCluster.getValidity().getStart(), clusterName, CurrentUser.getUser()); if (properties == null) { continue; } propertiesMap.put(clusterName, properties); } return propertiesMap; } @Override public Properties newWorkflowSchedule(Feed feed, Date startDate, String clusterName, String user) throws FalconException { org.apache.falcon.entity.v0.feed.Cluster feedCluster = FeedHelper.getCluster(feed, clusterName); if (!startDate.before(feedCluster.getValidity().getEnd())) { return null; } - Cluster cluster = configStore.get(EntityType.CLUSTER, feedCluster.getName()); + Cluster cluster = CONFIG_STORE.get(EntityType.CLUSTER, feedCluster.getName()); Path bundlePath = new Path(ClusterHelper.getLocation(cluster, "staging"), EntityUtil.getStagingPath(feed)); Feed feedClone = (Feed) feed.copy(); EntityUtil.setStartDate(feedClone, clusterName, startDate); AbstractOozieEntityMapper<Feed> mapper = new OozieFeedMapper(feedClone); if (!mapper.map(cluster, bundlePath)) { return null; } return createAppProperties(clusterName, bundlePath, user); } @Override public Date getNextStartTime(Feed feed, String cluster, Date now) throws FalconException { org.apache.falcon.entity.v0.feed.Cluster feedCluster = FeedHelper.getCluster(feed, cluster); return EntityUtil.getNextStartTime(feedCluster.getValidity().getStart(), feed.getFrequency(), feed.getTimezone(), now); } @Override public String[] getWorkflowNames(Feed entity) { return new String[]{ EntityUtil.getWorkflowName(Tag.RETENTION, entity).toString(), EntityUtil.getWorkflowName(Tag.REPLICATION, entity).toString(), }; } }
true
true
public Properties newWorkflowSchedule(Feed feed, Date startDate, String clusterName, String user) throws FalconException { org.apache.falcon.entity.v0.feed.Cluster feedCluster = FeedHelper.getCluster(feed, clusterName); if (!startDate.before(feedCluster.getValidity().getEnd())) { return null; } Cluster cluster = configStore.get(EntityType.CLUSTER, feedCluster.getName()); Path bundlePath = new Path(ClusterHelper.getLocation(cluster, "staging"), EntityUtil.getStagingPath(feed)); Feed feedClone = (Feed) feed.copy(); EntityUtil.setStartDate(feedClone, clusterName, startDate); AbstractOozieEntityMapper<Feed> mapper = new OozieFeedMapper(feedClone); if (!mapper.map(cluster, bundlePath)) { return null; } return createAppProperties(clusterName, bundlePath, user); }
public Properties newWorkflowSchedule(Feed feed, Date startDate, String clusterName, String user) throws FalconException { org.apache.falcon.entity.v0.feed.Cluster feedCluster = FeedHelper.getCluster(feed, clusterName); if (!startDate.before(feedCluster.getValidity().getEnd())) { return null; } Cluster cluster = CONFIG_STORE.get(EntityType.CLUSTER, feedCluster.getName()); Path bundlePath = new Path(ClusterHelper.getLocation(cluster, "staging"), EntityUtil.getStagingPath(feed)); Feed feedClone = (Feed) feed.copy(); EntityUtil.setStartDate(feedClone, clusterName, startDate); AbstractOozieEntityMapper<Feed> mapper = new OozieFeedMapper(feedClone); if (!mapper.map(cluster, bundlePath)) { return null; } return createAppProperties(clusterName, bundlePath, user); }
diff --git a/caGrid/projects/introduce-buildtools/src/gov/nih/nci/cagrid/introduce/servicetasks/deployment/validator/DeploymentValidatorTask.java b/caGrid/projects/introduce-buildtools/src/gov/nih/nci/cagrid/introduce/servicetasks/deployment/validator/DeploymentValidatorTask.java index 0337566f..7d00ae20 100644 --- a/caGrid/projects/introduce-buildtools/src/gov/nih/nci/cagrid/introduce/servicetasks/deployment/validator/DeploymentValidatorTask.java +++ b/caGrid/projects/introduce-buildtools/src/gov/nih/nci/cagrid/introduce/servicetasks/deployment/validator/DeploymentValidatorTask.java @@ -1,86 +1,90 @@ package gov.nih.nci.cagrid.introduce.servicetasks.deployment.validator; import gov.nih.nci.cagrid.common.Utils; import gov.nih.nci.cagrid.common.XMLUtilities; import java.io.File; import java.lang.reflect.Constructor; import java.util.Iterator; import java.util.List; import java.util.Properties; import javax.xml.namespace.QName; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.jdom.Element; /** * DeploymentValidatorTask * Validates a deployment by executing the deployment validator classes specified * in a service's deployment descriptor. * * <note>This class used to deserialize a bean to handle this, however that causes * problems when the code is executed out of the caGrid installer under * Windows XP sp 3. For more details, see https://jira.citih.osumc.edu/browse/CAGRID-404</note> * * @author David */ public class DeploymentValidatorTask extends Task { public static final String DEPLOYMENT_VALIDATOR_FILE = "deploymentValidator.xml"; public static final QName DEPLOYMENT_VALIDATOR_QNAME = new QName( "gme://gov.nih.nci.cagrid.introduce/1/DeploymentValidator", "DeploymentValidatorDescriptor"); public void execute() throws BuildException { super.execute(); try { Properties properties = new Properties(); properties.putAll(this.getProject().getProperties()); String baseDir = this.getProject().getBaseDir().getAbsolutePath(); File deploymentDescriptor = new File(baseDir, "tools" + File.separator + DeploymentValidatorTask.DEPLOYMENT_VALIDATOR_FILE); if (!deploymentDescriptor.exists() || !deploymentDescriptor.canRead()) { String message = "Deployment descriptor (" + deploymentDescriptor.getAbsolutePath() + ") doesn't exist or can't be read!"; System.out.println(message); throw new Exception(message + " Service does not seem to be an Introduce generated service or file system permissions are preventing access."); } Element deploymentValidatorDescriptorElem = null; try { StringBuffer buff = Utils.fileToStringBuffer(deploymentDescriptor); deploymentValidatorDescriptorElem = XMLUtilities.stringToDocument(buff.toString()).getRootElement(); } catch (Exception e) { throw new Exception("Cannot deserialize deployment validator descriptor: " + deploymentDescriptor, e); } + // get the validator elements, regardless of their namespace List validatorDescriptorElements = deploymentValidatorDescriptorElem.getChildren( - "ValidatorDescriptor", deploymentValidatorDescriptorElem.getNamespace()); + "ValidatorDescriptor", null); if (validatorDescriptorElements != null && validatorDescriptorElements.size() != 0) { + System.out.println("Found " + validatorDescriptorElements.size() + " validator descriptors"); Iterator<Element> validatorDescriptorElemIter = validatorDescriptorElements.iterator(); while (validatorDescriptorElemIter.hasNext()) { Element validatorDescriptorElem = validatorDescriptorElemIter.next(); String validatorClass = validatorDescriptorElem.getAttributeValue("validationClass"); if (validatorClass != null) { + System.out.println("Loading validator " + validatorClass); Class clazz = Class.forName(validatorClass); Constructor con = clazz.getConstructor(new Class[]{String.class}); DeploymentValidator validator = (DeploymentValidator) con.newInstance(new Object[]{baseDir}); + System.out.println("\tExecuing validator..."); validator.validate(); } } } } catch (Exception e) { e.printStackTrace(); throw new BuildException(e.getMessage(), e); } System.out.println("Done"); } }
false
true
public void execute() throws BuildException { super.execute(); try { Properties properties = new Properties(); properties.putAll(this.getProject().getProperties()); String baseDir = this.getProject().getBaseDir().getAbsolutePath(); File deploymentDescriptor = new File(baseDir, "tools" + File.separator + DeploymentValidatorTask.DEPLOYMENT_VALIDATOR_FILE); if (!deploymentDescriptor.exists() || !deploymentDescriptor.canRead()) { String message = "Deployment descriptor (" + deploymentDescriptor.getAbsolutePath() + ") doesn't exist or can't be read!"; System.out.println(message); throw new Exception(message + " Service does not seem to be an Introduce generated service or file system permissions are preventing access."); } Element deploymentValidatorDescriptorElem = null; try { StringBuffer buff = Utils.fileToStringBuffer(deploymentDescriptor); deploymentValidatorDescriptorElem = XMLUtilities.stringToDocument(buff.toString()).getRootElement(); } catch (Exception e) { throw new Exception("Cannot deserialize deployment validator descriptor: " + deploymentDescriptor, e); } List validatorDescriptorElements = deploymentValidatorDescriptorElem.getChildren( "ValidatorDescriptor", deploymentValidatorDescriptorElem.getNamespace()); if (validatorDescriptorElements != null && validatorDescriptorElements.size() != 0) { Iterator<Element> validatorDescriptorElemIter = validatorDescriptorElements.iterator(); while (validatorDescriptorElemIter.hasNext()) { Element validatorDescriptorElem = validatorDescriptorElemIter.next(); String validatorClass = validatorDescriptorElem.getAttributeValue("validationClass"); if (validatorClass != null) { Class clazz = Class.forName(validatorClass); Constructor con = clazz.getConstructor(new Class[]{String.class}); DeploymentValidator validator = (DeploymentValidator) con.newInstance(new Object[]{baseDir}); validator.validate(); } } } } catch (Exception e) { e.printStackTrace(); throw new BuildException(e.getMessage(), e); } System.out.println("Done"); }
public void execute() throws BuildException { super.execute(); try { Properties properties = new Properties(); properties.putAll(this.getProject().getProperties()); String baseDir = this.getProject().getBaseDir().getAbsolutePath(); File deploymentDescriptor = new File(baseDir, "tools" + File.separator + DeploymentValidatorTask.DEPLOYMENT_VALIDATOR_FILE); if (!deploymentDescriptor.exists() || !deploymentDescriptor.canRead()) { String message = "Deployment descriptor (" + deploymentDescriptor.getAbsolutePath() + ") doesn't exist or can't be read!"; System.out.println(message); throw new Exception(message + " Service does not seem to be an Introduce generated service or file system permissions are preventing access."); } Element deploymentValidatorDescriptorElem = null; try { StringBuffer buff = Utils.fileToStringBuffer(deploymentDescriptor); deploymentValidatorDescriptorElem = XMLUtilities.stringToDocument(buff.toString()).getRootElement(); } catch (Exception e) { throw new Exception("Cannot deserialize deployment validator descriptor: " + deploymentDescriptor, e); } // get the validator elements, regardless of their namespace List validatorDescriptorElements = deploymentValidatorDescriptorElem.getChildren( "ValidatorDescriptor", null); if (validatorDescriptorElements != null && validatorDescriptorElements.size() != 0) { System.out.println("Found " + validatorDescriptorElements.size() + " validator descriptors"); Iterator<Element> validatorDescriptorElemIter = validatorDescriptorElements.iterator(); while (validatorDescriptorElemIter.hasNext()) { Element validatorDescriptorElem = validatorDescriptorElemIter.next(); String validatorClass = validatorDescriptorElem.getAttributeValue("validationClass"); if (validatorClass != null) { System.out.println("Loading validator " + validatorClass); Class clazz = Class.forName(validatorClass); Constructor con = clazz.getConstructor(new Class[]{String.class}); DeploymentValidator validator = (DeploymentValidator) con.newInstance(new Object[]{baseDir}); System.out.println("\tExecuing validator..."); validator.validate(); } } } } catch (Exception e) { e.printStackTrace(); throw new BuildException(e.getMessage(), e); } System.out.println("Done"); }
diff --git a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/modes/commandline/CommandLineParser.java b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/modes/commandline/CommandLineParser.java index 4d5d66ec..624747e4 100644 --- a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/modes/commandline/CommandLineParser.java +++ b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/modes/commandline/CommandLineParser.java @@ -1,286 +1,288 @@ package net.sourceforge.vrapper.vim.modes.commandline; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; import net.sourceforge.vrapper.platform.Configuration.Option; import net.sourceforge.vrapper.utils.Search; import net.sourceforge.vrapper.vim.EditorAdaptor; import net.sourceforge.vrapper.vim.Options; import net.sourceforge.vrapper.vim.commands.CloseCommand; import net.sourceforge.vrapper.vim.commands.Command; import net.sourceforge.vrapper.vim.commands.ConfigCommand; import net.sourceforge.vrapper.vim.commands.LineRangeOperationCommand; import net.sourceforge.vrapper.vim.commands.MotionCommand; import net.sourceforge.vrapper.vim.commands.RedoCommand; import net.sourceforge.vrapper.vim.commands.SaveAllCommand; import net.sourceforge.vrapper.vim.commands.SaveCommand; import net.sourceforge.vrapper.vim.commands.SetOptionCommand; import net.sourceforge.vrapper.vim.commands.SedSubstitutionCommand; import net.sourceforge.vrapper.vim.commands.UndoCommand; import net.sourceforge.vrapper.vim.commands.VimCommandSequence; import net.sourceforge.vrapper.vim.commands.motions.GoToLineMotion; import net.sourceforge.vrapper.vim.modes.AbstractVisualMode; import net.sourceforge.vrapper.vim.modes.InsertMode; import net.sourceforge.vrapper.vim.modes.NormalMode; import net.sourceforge.vrapper.vim.modes.VisualMode; /** * Command Line Mode, activated with ':'. * * @author Matthias Radig */ public class CommandLineParser extends AbstractCommandParser { private static final EvaluatorMapping mapping; static { Evaluator noremap = new KeyMapper.Map(false, AbstractVisualMode.KEYMAP_NAME, NormalMode.KEYMAP_NAME); Evaluator map = new KeyMapper.Map(true, AbstractVisualMode.KEYMAP_NAME, NormalMode.KEYMAP_NAME); Evaluator nnoremap = new KeyMapper.Map(false, NormalMode.KEYMAP_NAME); Evaluator nmap = new KeyMapper.Map(true, NormalMode.KEYMAP_NAME); Evaluator vnoremap = new KeyMapper.Map(false, VisualMode.KEYMAP_NAME); Evaluator vmap = new KeyMapper.Map(true, VisualMode.KEYMAP_NAME); Evaluator inoremap = new KeyMapper.Map(false, InsertMode.KEYMAP_NAME); Evaluator imap = new KeyMapper.Map(true, InsertMode.KEYMAP_NAME); Command save = SaveCommand.INSTANCE; Command saveAll = SaveAllCommand.INSTANCE; CloseCommand close = CloseCommand.CLOSE; Command saveAndClose = new VimCommandSequence(save, close); Evaluator unmap = new KeyMapper.Unmap(AbstractVisualMode.KEYMAP_NAME, NormalMode.KEYMAP_NAME); Evaluator nunmap = new KeyMapper.Unmap(NormalMode.KEYMAP_NAME); Evaluator vunmap = new KeyMapper.Unmap(AbstractVisualMode.KEYMAP_NAME); Evaluator iunmap = new KeyMapper.Unmap(InsertMode.KEYMAP_NAME); Evaluator clear = new KeyMapper.Clear(AbstractVisualMode.KEYMAP_NAME, NormalMode.KEYMAP_NAME); Evaluator nclear = new KeyMapper.Clear(NormalMode.KEYMAP_NAME); Evaluator vclear = new KeyMapper.Clear(AbstractVisualMode.KEYMAP_NAME); Evaluator iclear = new KeyMapper.Clear(InsertMode.KEYMAP_NAME); Command gotoEOF = new MotionCommand(GoToLineMotion.LAST_LINE); Evaluator nohlsearch = new Evaluator() { public Object evaluate(EditorAdaptor vim, Queue<String> command) { vim.getSearchAndReplaceService().removeHighlighting(); return null; } }; Evaluator hlsearch = new Evaluator() { public Object evaluate(EditorAdaptor vim, Queue<String> command) { Search search = vim.getRegisterManager().getSearch(); if (search != null) vim.getSearchAndReplaceService().highlight(search); return null; } }; mapping = new EvaluatorMapping(); // options mapping.add("set", buildConfigEvaluator()); // save, close mapping.add("w", save); mapping.add("wq", saveAndClose); mapping.add("x", saveAndClose); mapping.add("q", close); mapping.add("q!", CloseCommand.FORCED_CLOSE); mapping.add("wa", saveAll); mapping.add("wal", saveAll); mapping.add("wall", saveAll); // non-recursive mapping mapping.add("noremap", noremap); mapping.add("no", noremap); mapping.add("nnoremap", nnoremap); mapping.add("nn", nnoremap); mapping.add("inoremap", inoremap); mapping.add("ino", inoremap); mapping.add("vnoremap", vnoremap); mapping.add("vn", vnoremap); // recursive mapping mapping.add("map", map); mapping.add("nmap", nmap); mapping.add("nm", nmap); mapping.add("imap", imap); mapping.add("im", imap); mapping.add("vmap", vmap); mapping.add("vm", vmap); // unmapping mapping.add("unmap", unmap); mapping.add("unm", unmap); mapping.add("nunmap", nunmap); mapping.add("nun", nunmap); mapping.add("vunmap", vunmap); mapping.add("vu", vunmap); mapping.add("iunmap", iunmap); mapping.add("iu", iunmap); // clearing maps mapping.add("mapclear", clear); mapping.add("mapc", clear); mapping.add("nmapclear", nclear); mapping.add("nmapc", nclear); mapping.add("vmapclear", vclear); mapping.add("vmapc", vclear); mapping.add("imapclear", iclear); mapping.add("imapc", iclear); UndoCommand undo = UndoCommand.INSTANCE; RedoCommand redo = RedoCommand.INSTANCE; mapping.add("red", redo); mapping.add("redo", redo); mapping.add("undo", undo); mapping.add("u", undo); mapping.add("$", new CommandWrapper(gotoEOF)); mapping.add("nohlsearch", nohlsearch); mapping.add("nohls", nohlsearch); mapping.add("noh", nohlsearch); mapping.add("hlsearch", hlsearch); mapping.add("hls", hlsearch); } private static Evaluator buildConfigEvaluator() { EvaluatorMapping config = new EvaluatorMapping(new ComplexOptionEvaluator()); // boolean options for (Option<Boolean> o: Options.BOOLEAN_OPTIONS) { ConfigCommand<Boolean> enable = new SetOptionCommand<Boolean>(o, Boolean.TRUE); ConfigCommand<Boolean> disable = new SetOptionCommand<Boolean>(o, Boolean.FALSE); ConfigCommand<Boolean> toggle = new ToggleOptionCommand(o); ConfigCommand<Boolean> status = new PrintOptionCommand<Boolean>(o); for (String alias: o.getAllNames()) { config.add(alias, enable); config.add("no"+alias, disable); config.add(alias+"!", toggle); config.add(alias+"?", status); } } // overwrites hlsearch/nohlsearch commands Evaluator numberToggle = new OptionDependentEvaluator(Options.LINE_NUMBERS, ConfigAction.NO_LINE_NUMBERS, ConfigAction.LINE_NUMBERS); Evaluator listToggle = new OptionDependentEvaluator(Options.SHOW_WHITESPACE, ConfigAction.NO_SHOW_WHITESPACE, ConfigAction.SHOW_WHITESPACE); config.add("globalregisters", ConfigAction.GLOBAL_REGISTERS); config.add("noglobalregisters", ConfigAction.NO_GLOBAL_REGISTERS); config.add("localregisters", ConfigAction.NO_GLOBAL_REGISTERS); config.add("nolocalregisters", ConfigAction.GLOBAL_REGISTERS); config.add("number", ConfigAction.LINE_NUMBERS); config.add("nonumber", ConfigAction.NO_LINE_NUMBERS); config.add("nu", ConfigAction.LINE_NUMBERS); config.add("nonu", ConfigAction.NO_LINE_NUMBERS); config.add("number!", numberToggle); config.add("nu!", numberToggle); config.add("list", ConfigAction.SHOW_WHITESPACE); config.add("nolist", ConfigAction.NO_SHOW_WHITESPACE); config.add("list!", listToggle); return config; } public CommandLineParser(EditorAdaptor vim) { super(vim); } @Override public Command parseAndExecute(String first, String command) { try { // if the command is a number, jump to the given line int line = Integer.parseInt(command); return new MotionCommand(GoToLineMotion.FIRST_LINE.withCount(line)); } catch (NumberFormatException e) { // do nothing } //not a number but starts with a number, $, . (dot), , (comma), or ' (quote) //might be a line range operation if(command.length() > 1 && command.matches("^\\d.*|^\\$.*|^,.*|^\\..*|^'.*")) { return new LineRangeOperationCommand(command); } StringTokenizer nizer = new StringTokenizer(command); Queue<String> tokens = new LinkedList<String>(); while (nizer.hasMoreTokens()) { tokens.add(nizer.nextToken().trim()); } EvaluatorMapping platformCommands = editor.getPlatformSpecificStateProvider().getCommands(); if (platformCommands != null && platformCommands.contains(tokens.peek())) { platformCommands.evaluate(editor, tokens); } else { mapping.evaluate(editor, tokens); } - if(command.length() > 1) { + //how can I reliably tell the difference between :set and :s/? + //what if we add another command that starts with 's'? + if(command.length() > 1 && !command.startsWith("set")) { if(command.startsWith("s")) { return new SedSubstitutionCommand(command, true); } else if(command.startsWith("%s")) { return new SedSubstitutionCommand(command, false); } } return null; } public boolean addCommand(String commandName, Command command, boolean overwrite) { if (overwrite || !mapping.contains(commandName)) { mapping.add(commandName, command); return true; } return false; } private enum ConfigAction implements Evaluator { GLOBAL_REGISTERS { public Object evaluate(EditorAdaptor vim, Queue<String> command) { vim.useGlobalRegisters(); return null; } }, NO_GLOBAL_REGISTERS { public Object evaluate(EditorAdaptor vim, Queue<String> command) { vim.useLocalRegisters(); return null; } }, LINE_NUMBERS { public Object evaluate(EditorAdaptor vim, Queue<String> command) { vim.getConfiguration().set(Options.LINE_NUMBERS, Boolean.TRUE); vim.getEditorSettings().setShowLineNumbers(true); return null; } }, NO_LINE_NUMBERS { public Object evaluate(EditorAdaptor vim, Queue<String> command) { vim.getConfiguration().set(Options.LINE_NUMBERS, Boolean.FALSE); vim.getEditorSettings().setShowLineNumbers(false); return null; } }, SHOW_WHITESPACE { public Object evaluate(EditorAdaptor vim, Queue<String> command) { vim.getConfiguration().set(Options.SHOW_WHITESPACE, Boolean.TRUE); vim.getEditorSettings().setShowWhitespace(true); return null; } }, NO_SHOW_WHITESPACE { public Object evaluate(EditorAdaptor vim, Queue<String> command) { vim.getConfiguration().set(Options.SHOW_WHITESPACE, Boolean.FALSE); vim.getEditorSettings().setShowWhitespace(false); return null; } } ; } private static class OptionDependentEvaluator implements Evaluator { private final Option<Boolean> option; private final Evaluator onTrue; private final Evaluator onFalse; private OptionDependentEvaluator(Option<Boolean> option, Evaluator onTrue, Evaluator onFalse) { super(); this.option = option; this.onTrue = onTrue; this.onFalse = onFalse; } public Object evaluate(EditorAdaptor vim, Queue<String> command) { return vim.getConfiguration().get(option) ? onTrue.evaluate(vim, command) : onFalse.evaluate(vim, command); } } }
true
true
public Command parseAndExecute(String first, String command) { try { // if the command is a number, jump to the given line int line = Integer.parseInt(command); return new MotionCommand(GoToLineMotion.FIRST_LINE.withCount(line)); } catch (NumberFormatException e) { // do nothing } //not a number but starts with a number, $, . (dot), , (comma), or ' (quote) //might be a line range operation if(command.length() > 1 && command.matches("^\\d.*|^\\$.*|^,.*|^\\..*|^'.*")) { return new LineRangeOperationCommand(command); } StringTokenizer nizer = new StringTokenizer(command); Queue<String> tokens = new LinkedList<String>(); while (nizer.hasMoreTokens()) { tokens.add(nizer.nextToken().trim()); } EvaluatorMapping platformCommands = editor.getPlatformSpecificStateProvider().getCommands(); if (platformCommands != null && platformCommands.contains(tokens.peek())) { platformCommands.evaluate(editor, tokens); } else { mapping.evaluate(editor, tokens); } if(command.length() > 1) { if(command.startsWith("s")) { return new SedSubstitutionCommand(command, true); } else if(command.startsWith("%s")) { return new SedSubstitutionCommand(command, false); } } return null; }
public Command parseAndExecute(String first, String command) { try { // if the command is a number, jump to the given line int line = Integer.parseInt(command); return new MotionCommand(GoToLineMotion.FIRST_LINE.withCount(line)); } catch (NumberFormatException e) { // do nothing } //not a number but starts with a number, $, . (dot), , (comma), or ' (quote) //might be a line range operation if(command.length() > 1 && command.matches("^\\d.*|^\\$.*|^,.*|^\\..*|^'.*")) { return new LineRangeOperationCommand(command); } StringTokenizer nizer = new StringTokenizer(command); Queue<String> tokens = new LinkedList<String>(); while (nizer.hasMoreTokens()) { tokens.add(nizer.nextToken().trim()); } EvaluatorMapping platformCommands = editor.getPlatformSpecificStateProvider().getCommands(); if (platformCommands != null && platformCommands.contains(tokens.peek())) { platformCommands.evaluate(editor, tokens); } else { mapping.evaluate(editor, tokens); } //how can I reliably tell the difference between :set and :s/? //what if we add another command that starts with 's'? if(command.length() > 1 && !command.startsWith("set")) { if(command.startsWith("s")) { return new SedSubstitutionCommand(command, true); } else if(command.startsWith("%s")) { return new SedSubstitutionCommand(command, false); } } return null; }
diff --git a/main/src/main/java/com/bloatit/web/linkable/login/SignUpAction.java b/main/src/main/java/com/bloatit/web/linkable/login/SignUpAction.java index 793b19f13..2bd0ae96e 100644 --- a/main/src/main/java/com/bloatit/web/linkable/login/SignUpAction.java +++ b/main/src/main/java/com/bloatit/web/linkable/login/SignUpAction.java @@ -1,138 +1,138 @@ /** * */ package com.bloatit.web.linkable.login; import java.util.Locale; import com.bloatit.framework.mailsender.Mail; import com.bloatit.framework.mailsender.MailServer; import com.bloatit.framework.utils.MailUtils; import com.bloatit.framework.webprocessor.annotations.Optional; import com.bloatit.framework.webprocessor.annotations.ParamConstraint; import com.bloatit.framework.webprocessor.annotations.ParamContainer; import com.bloatit.framework.webprocessor.annotations.RequestParam; import com.bloatit.framework.webprocessor.annotations.RequestParam.Role; import com.bloatit.framework.webprocessor.annotations.tr; import com.bloatit.framework.webprocessor.context.Context; import com.bloatit.framework.webprocessor.masters.Action; import com.bloatit.framework.webprocessor.url.Url; import com.bloatit.model.Member; import com.bloatit.model.managers.MemberManager; import com.bloatit.web.url.MemberActivationActionUrl; import com.bloatit.web.url.SignUpActionUrl; import com.bloatit.web.url.SignUpPageUrl; /** * A response to a form used sign into the website (creation of a new user) */ @ParamContainer("member/dosignup") public class SignUpAction extends Action { @RequestParam(name = "bloatit_login", role = Role.POST) @ParamConstraint(min = "4", minErrorMsg = @tr("Number of characters for login has to be superior to 4"),// max = "15", maxErrorMsg = @tr("Number of characters for login has to be inferior to 15")) private final String login; @RequestParam(name = "bloatit_password", role = Role.POST) @ParamConstraint(min = "4", minErrorMsg = @tr("Number of characters for password has to be superior to 4"),// max = "15", maxErrorMsg = @tr("Number of characters for password has to be inferior to 15")) private final String password; @RequestParam(name = "bloatit_password_check", role = Role.POST) @ParamConstraint(min = "4", minErrorMsg = @tr("Number of characters for password has to be superior to 4"),// max = "15", maxErrorMsg = @tr("Number of characters for password has to be inferior to 15")) private final String passwordCheck; @RequestParam(name = "bloatit_fullname", role = Role.POST) @ParamConstraint(min = "4", minErrorMsg = @tr("Number of characters for fullname has to be superior to 4"),// max = "15", maxErrorMsg = @tr("Number of characters for password has to be inferior to 15")) @Optional private final String fullname; @RequestParam(name = "bloatit_email", role = Role.POST) @ParamConstraint(min = "4", minErrorMsg = @tr("Number of characters for email has to be superior to 5"),// max = "30", maxErrorMsg = @tr("Number of characters for email address has to be inferior to 30")) private final String email; @RequestParam(name = "bloatit_country", role = Role.POST) private final String country; @RequestParam(name = "bloatit_lang", role = Role.POST) private final String lang; private final SignUpActionUrl url; public SignUpAction(final SignUpActionUrl url) { super(url); this.url = url; this.login = url.getLogin(); this.password = url.getPassword(); this.passwordCheck = url.getPasswordCheck(); this.fullname = url.getFullname(); this.email = url.getEmail(); this.lang = url.getLang(); this.country = url.getCountry(); } @Override protected final Url doProcess() { - if (password != passwordCheck) { + if (!password.equals(passwordCheck)) { transmitParameters(); session.notifyError("Password doesn't match confirmation."); return new SignUpPageUrl(); } final Locale locale = new Locale(lang, country); final Member m = new Member(login, password, email, fullname, locale); final String activationKey = m.getActivationKey(); final MemberActivationActionUrl url = new MemberActivationActionUrl(login, activationKey); final String content = Context.tr("Your Elveos.org account ''{0}'' was created. Please click on the following link to activate your account: \n\n {1}", login, url.externalUrlString(Context.getHeader().getHttpHeader())); final Mail activationMail = new Mail(email, Context.tr("Elveos.org account activation"), content, "member-docreate"); MailServer.getInstance().send(activationMail); session.notifyGood(Context.tr("Account created, you will receive a mail to activate it.")); return session.pickPreferredPage(); } @Override protected final Url doProcessErrors() { return new SignUpPageUrl(); } @Override protected Url checkRightsAndEverything() { if (MemberManager.loginExists(login)) { session.notifyError(Context.tr("Login ''{0}''already used. Find another login", login)); return doProcessErrors(); } if (MemberManager.emailExists(email)) { session.notifyError(Context.tr("Email ''{0}''already used. Find another email or use your old account !", email)); return doProcessErrors(); } final String userEmail = email.trim(); if (!MailUtils.isValidEmail(userEmail)) { session.notifyError(Context.tr("Invalid email address : " + userEmail)); return doProcessErrors(); } return NO_ERROR; } @Override protected void transmitParameters() { session.addParameter(url.getEmailParameter()); session.addParameter(url.getLoginParameter()); session.addParameter(url.getPasswordParameter()); session.addParameter(url.getCountryParameter()); session.addParameter(url.getLangParameter()); session.addParameter(url.getFullnameParameter()); session.addParameter(url.getPasswordCheckParameter()); } }
true
true
protected final Url doProcess() { if (password != passwordCheck) { transmitParameters(); session.notifyError("Password doesn't match confirmation."); return new SignUpPageUrl(); } final Locale locale = new Locale(lang, country); final Member m = new Member(login, password, email, fullname, locale); final String activationKey = m.getActivationKey(); final MemberActivationActionUrl url = new MemberActivationActionUrl(login, activationKey); final String content = Context.tr("Your Elveos.org account ''{0}'' was created. Please click on the following link to activate your account: \n\n {1}", login, url.externalUrlString(Context.getHeader().getHttpHeader())); final Mail activationMail = new Mail(email, Context.tr("Elveos.org account activation"), content, "member-docreate"); MailServer.getInstance().send(activationMail); session.notifyGood(Context.tr("Account created, you will receive a mail to activate it.")); return session.pickPreferredPage(); }
protected final Url doProcess() { if (!password.equals(passwordCheck)) { transmitParameters(); session.notifyError("Password doesn't match confirmation."); return new SignUpPageUrl(); } final Locale locale = new Locale(lang, country); final Member m = new Member(login, password, email, fullname, locale); final String activationKey = m.getActivationKey(); final MemberActivationActionUrl url = new MemberActivationActionUrl(login, activationKey); final String content = Context.tr("Your Elveos.org account ''{0}'' was created. Please click on the following link to activate your account: \n\n {1}", login, url.externalUrlString(Context.getHeader().getHttpHeader())); final Mail activationMail = new Mail(email, Context.tr("Elveos.org account activation"), content, "member-docreate"); MailServer.getInstance().send(activationMail); session.notifyGood(Context.tr("Account created, you will receive a mail to activate it.")); return session.pickPreferredPage(); }
diff --git a/src/com/herocraftonline/dev/heroes/spout/SpoutInventoryListener.java b/src/com/herocraftonline/dev/heroes/spout/SpoutInventoryListener.java index dc3e3c10..7bdcdd36 100644 --- a/src/com/herocraftonline/dev/heroes/spout/SpoutInventoryListener.java +++ b/src/com/herocraftonline/dev/heroes/spout/SpoutInventoryListener.java @@ -1,60 +1,60 @@ package com.herocraftonline.dev.heroes.spout; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.inventory.ItemStack; import org.getspout.spoutapi.event.inventory.InventoryCraftEvent; import com.herocraftonline.dev.heroes.Heroes; import com.herocraftonline.dev.heroes.classes.HeroClass.ExperienceType; import com.herocraftonline.dev.heroes.hero.Hero; import com.herocraftonline.dev.heroes.util.Messaging; public class SpoutInventoryListener implements Listener { private Heroes plugin; public SpoutInventoryListener(Heroes heroes) { plugin = heroes; Bukkit.getServer().getPluginManager().registerEvents(this, plugin); } @EventHandler(priority = EventPriority.HIGHEST) public void onInventoryCraft(InventoryCraftEvent event) { - if (event.getResult() == null || event.isCancelled()) { + if (event.getResult() == null || event.isCancelled() || Heroes.properties.disabledWorlds.contains(event.getPlayer().getWorld().getName())) { return; } if (event.isShiftClick() && event.getPlayer().getInventory().firstEmpty() == -1) { return; } ItemStack cursor = event.getCursor(); ItemStack result = event.getResult(); int amountCrafted = result.getAmount(); if (!event.isShiftClick() && cursor != null) { if (cursor.getType() != result.getType() || cursor.getType().getMaxStackSize() <= cursor.getAmount() + amountCrafted) { return; } } Player player = event.getPlayer(); Hero hero = plugin.getHeroManager().getHero(player); if (!hero.canCraft(result)) { Messaging.send(hero.getPlayer(), "You don't know how to craft $1", result.getType().name().toLowerCase().replace("_", " ")); event.setCancelled(true); return; } if (Heroes.properties.craftingExp.containsKey(result.getType())) { if (hero.canGain(ExperienceType.CRAFTING)) { hero.gainExp(Heroes.properties.craftingExp.get(result.getType()) * amountCrafted, ExperienceType.CRAFTING); return; } } } }
true
true
public void onInventoryCraft(InventoryCraftEvent event) { if (event.getResult() == null || event.isCancelled()) { return; } if (event.isShiftClick() && event.getPlayer().getInventory().firstEmpty() == -1) { return; } ItemStack cursor = event.getCursor(); ItemStack result = event.getResult(); int amountCrafted = result.getAmount(); if (!event.isShiftClick() && cursor != null) { if (cursor.getType() != result.getType() || cursor.getType().getMaxStackSize() <= cursor.getAmount() + amountCrafted) { return; } } Player player = event.getPlayer(); Hero hero = plugin.getHeroManager().getHero(player); if (!hero.canCraft(result)) { Messaging.send(hero.getPlayer(), "You don't know how to craft $1", result.getType().name().toLowerCase().replace("_", " ")); event.setCancelled(true); return; } if (Heroes.properties.craftingExp.containsKey(result.getType())) { if (hero.canGain(ExperienceType.CRAFTING)) { hero.gainExp(Heroes.properties.craftingExp.get(result.getType()) * amountCrafted, ExperienceType.CRAFTING); return; } } }
public void onInventoryCraft(InventoryCraftEvent event) { if (event.getResult() == null || event.isCancelled() || Heroes.properties.disabledWorlds.contains(event.getPlayer().getWorld().getName())) { return; } if (event.isShiftClick() && event.getPlayer().getInventory().firstEmpty() == -1) { return; } ItemStack cursor = event.getCursor(); ItemStack result = event.getResult(); int amountCrafted = result.getAmount(); if (!event.isShiftClick() && cursor != null) { if (cursor.getType() != result.getType() || cursor.getType().getMaxStackSize() <= cursor.getAmount() + amountCrafted) { return; } } Player player = event.getPlayer(); Hero hero = plugin.getHeroManager().getHero(player); if (!hero.canCraft(result)) { Messaging.send(hero.getPlayer(), "You don't know how to craft $1", result.getType().name().toLowerCase().replace("_", " ")); event.setCancelled(true); return; } if (Heroes.properties.craftingExp.containsKey(result.getType())) { if (hero.canGain(ExperienceType.CRAFTING)) { hero.gainExp(Heroes.properties.craftingExp.get(result.getType()) * amountCrafted, ExperienceType.CRAFTING); return; } } }
diff --git a/src/org/mozilla/javascript/CompilerEnvirons.java b/src/org/mozilla/javascript/CompilerEnvirons.java index 14bf5af8..8ed1444a 100644 --- a/src/org/mozilla/javascript/CompilerEnvirons.java +++ b/src/org/mozilla/javascript/CompilerEnvirons.java @@ -1,187 +1,187 @@ /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov, [email protected] * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; import java.util.Hashtable; public class CompilerEnvirons { public CompilerEnvirons() { errorReporter = DefaultErrorReporter.instance; languageVersion = Context.VERSION_DEFAULT; generateDebugInfo = true; useDynamicScope = false; reservedKeywordAsIdentifier = false; allowMemberExprAsFunctionName = false; xmlAvailable = true; optimizationLevel = 0; generatingSource = true; } public void initFromContext(Context cx) { setErrorReporter(cx.getErrorReporter()); this.languageVersion = cx.getLanguageVersion(); - useDynamicScope = cx.compileFunctionsWithDynamicScopeFlag; + useDynamicScope = cx.hasFeature(Context.FEATURE_DYNAMIC_SCOPE); generateDebugInfo = (!cx.isGeneratingDebugChanged() || cx.isGeneratingDebug()); reservedKeywordAsIdentifier = cx.hasFeature(Context.FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER); allowMemberExprAsFunctionName = cx.hasFeature(Context.FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME); xmlAvailable = cx.hasFeature(Context.FEATURE_E4X); optimizationLevel = cx.getOptimizationLevel(); generatingSource = cx.isGeneratingSource(); activationNames = cx.activationNames; } public final ErrorReporter getErrorReporter() { return errorReporter; } public void setErrorReporter(ErrorReporter errorReporter) { if (errorReporter == null) throw new IllegalArgumentException(); this.errorReporter = errorReporter; } public final int getLanguageVersion() { return languageVersion; } public void setLanguageVersion(int languageVersion) { Context.checkLanguageVersion(languageVersion); this.languageVersion = languageVersion; } public final boolean isGenerateDebugInfo() { return generateDebugInfo; } public void setGenerateDebugInfo(boolean flag) { this.generateDebugInfo = flag; } public final boolean isUseDynamicScope() { return useDynamicScope; } public final boolean isReservedKeywordAsIdentifier() { return reservedKeywordAsIdentifier; } public void setReservedKeywordAsIdentifier(boolean flag) { reservedKeywordAsIdentifier = flag; } public final boolean isAllowMemberExprAsFunctionName() { return allowMemberExprAsFunctionName; } public void setAllowMemberExprAsFunctionName(boolean flag) { allowMemberExprAsFunctionName = flag; } public final boolean isXmlAvailable() { return xmlAvailable; } public void setXmlAvailable(boolean flag) { xmlAvailable = flag; } public final int getOptimizationLevel() { return optimizationLevel; } public void setOptimizationLevel(int level) { Context.checkOptimizationLevel(level); this.optimizationLevel = level; } public final boolean isGeneratingSource() { return generatingSource; } /** * Specify whether or not source information should be generated. * <p> * Without source information, evaluating the "toString" method * on JavaScript functions produces only "[native code]" for * the body of the function. * Note that code generated without source is not fully ECMA * conformant. */ public void setGeneratingSource(boolean generatingSource) { this.generatingSource = generatingSource; } private ErrorReporter errorReporter; private int languageVersion; private boolean generateDebugInfo; private boolean useDynamicScope; private boolean reservedKeywordAsIdentifier; private boolean allowMemberExprAsFunctionName; private boolean xmlAvailable; private int optimizationLevel; private boolean generatingSource; Hashtable activationNames; }
true
true
public void initFromContext(Context cx) { setErrorReporter(cx.getErrorReporter()); this.languageVersion = cx.getLanguageVersion(); useDynamicScope = cx.compileFunctionsWithDynamicScopeFlag; generateDebugInfo = (!cx.isGeneratingDebugChanged() || cx.isGeneratingDebug()); reservedKeywordAsIdentifier = cx.hasFeature(Context.FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER); allowMemberExprAsFunctionName = cx.hasFeature(Context.FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME); xmlAvailable = cx.hasFeature(Context.FEATURE_E4X); optimizationLevel = cx.getOptimizationLevel(); generatingSource = cx.isGeneratingSource(); activationNames = cx.activationNames; }
public void initFromContext(Context cx) { setErrorReporter(cx.getErrorReporter()); this.languageVersion = cx.getLanguageVersion(); useDynamicScope = cx.hasFeature(Context.FEATURE_DYNAMIC_SCOPE); generateDebugInfo = (!cx.isGeneratingDebugChanged() || cx.isGeneratingDebug()); reservedKeywordAsIdentifier = cx.hasFeature(Context.FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER); allowMemberExprAsFunctionName = cx.hasFeature(Context.FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME); xmlAvailable = cx.hasFeature(Context.FEATURE_E4X); optimizationLevel = cx.getOptimizationLevel(); generatingSource = cx.isGeneratingSource(); activationNames = cx.activationNames; }
diff --git a/tests/org.eclipse.dltk.ruby.core.tests/src/org/eclipse/dltk/ruby/tests/parser/jruby/ZippedParserSuite.java b/tests/org.eclipse.dltk.ruby.core.tests/src/org/eclipse/dltk/ruby/tests/parser/jruby/ZippedParserSuite.java index cbbd5822..99d4aba1 100644 --- a/tests/org.eclipse.dltk.ruby.core.tests/src/org/eclipse/dltk/ruby/tests/parser/jruby/ZippedParserSuite.java +++ b/tests/org.eclipse.dltk.ruby.core.tests/src/org/eclipse/dltk/ruby/tests/parser/jruby/ZippedParserSuite.java @@ -1,62 +1,63 @@ package org.eclipse.dltk.ruby.tests.parser.jruby; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; import junit.framework.TestCase; import junit.framework.TestSuite; import org.eclipse.dltk.ast.declarations.ModuleDeclaration; import org.eclipse.dltk.core.tests.model.AbstractModelTests; import org.eclipse.dltk.ruby.internal.parser.JRubySourceParser; import org.eclipse.dltk.ruby.tests.Activator; public class ZippedParserSuite extends TestSuite { public ZippedParserSuite(String testsZip) { super(testsZip); ZipFile zipFile; try { zipFile = new ZipFile(AbstractModelTests.storeToMetadata(Activator .getDefault().getBundle(), "parser.zip", testsZip)); Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); final String content = loadContent(zipFile .getInputStream(entry)); addTest(new TestCase(entry.getName()) { public void setUp() { } protected void runTest() throws Throwable { JRubySourceParser parser = new JRubySourceParser(null); + JRubySourceParser.setSilentState(false); ModuleDeclaration module = parser.parse(content); assertNotNull(module); } }); } } catch (ZipException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static String loadContent(InputStream stream) throws IOException { int length = stream.available(); byte[] data = new byte[length]; stream.read(data); stream.close(); return new String(data, "utf-8"); } }
true
true
public ZippedParserSuite(String testsZip) { super(testsZip); ZipFile zipFile; try { zipFile = new ZipFile(AbstractModelTests.storeToMetadata(Activator .getDefault().getBundle(), "parser.zip", testsZip)); Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); final String content = loadContent(zipFile .getInputStream(entry)); addTest(new TestCase(entry.getName()) { public void setUp() { } protected void runTest() throws Throwable { JRubySourceParser parser = new JRubySourceParser(null); ModuleDeclaration module = parser.parse(content); assertNotNull(module); } }); } } catch (ZipException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public ZippedParserSuite(String testsZip) { super(testsZip); ZipFile zipFile; try { zipFile = new ZipFile(AbstractModelTests.storeToMetadata(Activator .getDefault().getBundle(), "parser.zip", testsZip)); Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); final String content = loadContent(zipFile .getInputStream(entry)); addTest(new TestCase(entry.getName()) { public void setUp() { } protected void runTest() throws Throwable { JRubySourceParser parser = new JRubySourceParser(null); JRubySourceParser.setSilentState(false); ModuleDeclaration module = parser.parse(content); assertNotNull(module); } }); } } catch (ZipException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
diff --git a/src/edu/sc/seis/sod/editor/SimpleGUIEditor.java b/src/edu/sc/seis/sod/editor/SimpleGUIEditor.java index 9a17c595d..672f8b37c 100644 --- a/src/edu/sc/seis/sod/editor/SimpleGUIEditor.java +++ b/src/edu/sc/seis/sod/editor/SimpleGUIEditor.java @@ -1,362 +1,363 @@ /** * SimpleGUI.java * * @author Created by Omnicore CodeGuide */ package edu.sc.seis.sod.editor; import java.io.*; import javax.swing.*; import org.w3c.dom.*; import edu.sc.seis.fissuresUtil.exceptionHandler.FilterReporter; import edu.sc.seis.fissuresUtil.exceptionHandler.GUIReporter; import edu.sc.seis.fissuresUtil.exceptionHandler.GlobalExceptionHandler; import edu.sc.seis.fissuresUtil.xml.Writer; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FileDialog; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.List; import java.util.Properties; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import org.omg.CORBA.COMM_FAILURE; import org.xml.sax.SAXException; public class SimpleGUIEditor extends CommandLineEditor { static { List ignoreList = new ArrayList(); // silently eat CommFailure ignoreList.add(COMM_FAILURE.class); GlobalExceptionHandler.add(new FilterReporter(new GUIReporter(), ignoreList)); GlobalExceptionHandler.registerWithAWTThread(); } public SimpleGUIEditor(String[] args) throws TransformerException, ParserConfigurationException, IOException, DOMException, SAXException { super(args); GlobalExceptionHandler.add(new GUIReporter()); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { //Oh well, go with the default look and feel } for (int i = 0; i < args.length; i++) { if (args[i].equals("-tabs")) { tabs = true; } } } public void start() { frame = new JFrame(frameName); JMenuBar menubar = new JMenuBar(); frame.setJMenuBar(menubar); JMenu fileMenu = new JMenu("File"); menubar.add(fileMenu); final JMenuItem saveAs = new JMenuItem("Save As..."); saveAs.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { FileDialog fileDialog = new FileDialog(frame); fileDialog.setMode(FileDialog.SAVE); fileDialog.show(); String outfiledir = fileDialog.getDirectory(); String outfilename = fileDialog.getFile(); if (outfilename != null) { File outfile = new File(outfiledir, outfilename); try { save(outfile); } catch (IOException ex) { GlobalExceptionHandler.handle("Unable to save to "+outfile, ex); } } } }); JMenuItem save = new JMenuItem("Save"); save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(getConfigFilename().startsWith("jar")){ saveAs.doClick(); }else{ File configFile = new File(getConfigFilename()); try { save(configFile); } catch (IOException ex) { GlobalExceptionHandler.handle("Unable to save "+configFile, ex); } } } }); fileMenu.add(save); fileMenu.add(saveAs); fileMenu.addSeparator(); JMenuItem load = new JMenuItem("Open"); fileMenu.add(load); load.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { FileDialog fileDialog = new FileDialog(frame, "Load a SOD config file"); fileDialog.setDirectory("."); fileDialog.show(); + String infileDir = fileDialog.getDirectory(); String inFile = fileDialog.getFile(); if (inFile != null) { try { - setConfigFile(inFile); + setConfigFile(infileDir + "/" + inFile); loadGUI(); } catch (Exception ex) { GlobalExceptionHandler.handle("Unable to open "+inFile, ex); } } } }); JMenuItem loadTutorial = new JMenuItem("Open Tutorial"); loadTutorial.addActionListener(tutorialLoader); fileMenu.add(loadTutorial); JMenuItem loadWeed = new JMenuItem("Open WEED"); loadWeed.addActionListener(new FileLoader(configFileBase + "weed.xml")); fileMenu.add(loadWeed); fileMenu.addSeparator(); JMenuItem quit = new JMenuItem("Quit"); fileMenu.add(quit); quit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); frame.getContentPane().setLayout(new BorderLayout()); loadGUI(); } private class FileLoader implements ActionListener{ public FileLoader(String filename){ this.filename = filename; } public void actionPerformed(ActionEvent e) { try { setConfigFile(filename); loadGUI(); } catch (Exception ex) { GlobalExceptionHandler.handle(ex); } } private String filename; } public void loadGUI(){ Document doc = getDocument(); if(doc == null){ tutorialLoader.actionPerformed(null); }else{ frame.getContentPane().removeAll(); if (tabs) { JTabbedPane tabPane = new JTabbedPane(); frame.getContentPane().add(tabPane, BorderLayout.CENTER); // put each top level sod element in a panel NodeList list = doc.getDocumentElement().getChildNodes(); for (int j = 0; j < list.getLength(); j++) { if (list.item(j) instanceof Element) { Element el = (Element)list.item(j); JComponent panel = null; if(el.getTagName().equals("properties")){ try { panel = propEditor.getGUI(el); } catch (TransformerException e) { GlobalExceptionHandler.handle(e); } }else{ panel = new JPanel(new BorderLayout()); Box box = Box.createVerticalBox(); NodeList sublist = ((Element)list.item(j)).getChildNodes(); JComponent[] subComponents = getCompsForNodeList(sublist); for (int i = 0; i < subComponents.length; i++) { box.add(subComponents[i]); box.add(Box.createVerticalStrut(10)); } panel.add(box, BorderLayout.NORTH); } String tabName = getDisplayName(el.getTagName()); JScrollPane scrollPane = new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrollPane.getVerticalScrollBar().setBlockIncrement(50); scrollPane.getVerticalScrollBar().setUnitIncrement(10); tabPane.add(EditorUtil.capFirstLetter(tabName),scrollPane); } } } else { JComponent comp = getCompForElement(doc.getDocumentElement()); Box box = Box.createVerticalBox(); box.add(comp); box.add(Box.createGlue()); frame.getContentPane().add(new JScrollPane(box, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER), BorderLayout.CENTER); } } frame.pack(); frame.show(); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } JComponent[] getCompsForNodeList(NodeList nl){ List comps = new ArrayList(); for (int i = 0; i < nl.getLength(); i++) { if (nl.item(i) instanceof Element) { comps.add(getCompForElement((Element)nl.item(i))); } } return (JComponent[])comps.toArray(new JComponent[comps.size()]); } protected void save(File file) throws FileNotFoundException, IOException { FileOutputStream fos = new FileOutputStream(file); setConfigFileLocation(file.getAbsolutePath()); save(fos); fos.close(); } protected void save(OutputStream out) { BufferedWriter buf = new BufferedWriter(new OutputStreamWriter(out)); Writer xmlWriter = new Writer(); xmlWriter.setOutput(buf); xmlWriter.write(getDocument()); } JComponent getCompForElement(Element element) { return getDefaultCompForElement(element); } JComponent getDefaultCompForElement(Element element) { JLabel label = new JLabel(getDisplayName(element.getTagName())); Box box = Box.createVerticalBox(); JComponent comp = getCompForAttributes(element); if (comp != null) { box.add(comp); } NamedNodeMap attrList = element.getAttributes(); NodeList list = element.getChildNodes(); // simple case of only 1 child Text node and no attributes if (list.getLength() == 1 && list.item(0) instanceof Text && attrList.getLength() == 0) { comp = getCompForTextNode((Text)list.item(0)); if (comp != null) { box = Box.createHorizontalBox(); box.add(Box.createHorizontalStrut(10)); box.add(label); box.add(new JLabel(" = ")); box.add(comp); return box; } } else { for (int i = 0; i < list.getLength(); i++) { if (list.item(i) instanceof Element) { box.add(getCompForElement((Element)list.item(i))); } else if (list.item(i) instanceof Text) { Text text = (Text)list.item(i); comp = getCompForTextNode(text); if (comp != null) { box.add(comp); } } } } return indent(label, box); } JComponent getCompForAttributes(Element element) { Box box = Box.createHorizontalBox(); Box nameCol = Box.createVerticalBox(); box.add(nameCol); Box valCol = Box.createVerticalBox(); box.add(valCol); NamedNodeMap list = element.getAttributes(); for (int i = 0; i < list.getLength(); i++) { if (list.item(i) instanceof Attr) { Attr attr = (Attr)list.item(i); valCol.add(EditorUtil.getLabeledTextField(attr)); } } return box; } JComponent getCompForTextNode(Text text) { if (text.getNodeValue().trim().equals("")) { return null; } JTextField textField = new JTextField(); textField.setText(text.getNodeValue().trim()); TextListener textListen = new TextListener(text); textField.getDocument().addDocumentListener(textListen); return textField; } /** creates a JPanel with the bottom component slightly indented relative to the bottome one. */ public Box indent(JComponent top, JComponent bottom) { Box box = Box.createVerticalBox(); Box topRow = Box.createHorizontalBox(); box.add(topRow); Box botRow = Box.createHorizontalBox(); box.add(botRow); topRow.add(Box.createHorizontalStrut(5)); topRow.add(top); topRow.add(Box.createGlue()); botRow.add(Box.createRigidArea(new Dimension(15, 10))); botRow.add(bottom); botRow.add(Box.createGlue()); return box; } private PropertyEditor propEditor = new PropertyEditor(); public void setTabbed(boolean tabbed){ this.tabs = tabbed; } public static String getDisplayName(String tagName) { return nameProps.getProperty(tagName, tagName); } public static void main(String[] args) throws Exception { BasicConfigurator.configure(); SimpleGUIEditor gui = new SimpleGUIEditor(args); gui.start(); } private static final String configFileBase = "jar:edu/sc/seis/sod/data/configFiles/"; public static final String TUTORIAL_LOC = configFileBase + "tutorial.xml"; private FileLoader tutorialLoader = new FileLoader(TUTORIAL_LOC); protected String frameName = "Simple XML Editor GUI"; private boolean tabs = false; private JFrame frame; static Properties nameProps = new Properties(); private static String NAME_PROPS = "edu/sc/seis/sod/editor/names.prop"; private static Logger logger = Logger.getLogger(SimpleGUIEditor.class); static { try { nameProps.load(SimpleGUIEditor.class.getClassLoader().getResourceAsStream(NAME_PROPS )); }catch(IOException e) { GlobalExceptionHandler.handle("Error in loading names Prop file",e); } } }
false
true
public void start() { frame = new JFrame(frameName); JMenuBar menubar = new JMenuBar(); frame.setJMenuBar(menubar); JMenu fileMenu = new JMenu("File"); menubar.add(fileMenu); final JMenuItem saveAs = new JMenuItem("Save As..."); saveAs.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { FileDialog fileDialog = new FileDialog(frame); fileDialog.setMode(FileDialog.SAVE); fileDialog.show(); String outfiledir = fileDialog.getDirectory(); String outfilename = fileDialog.getFile(); if (outfilename != null) { File outfile = new File(outfiledir, outfilename); try { save(outfile); } catch (IOException ex) { GlobalExceptionHandler.handle("Unable to save to "+outfile, ex); } } } }); JMenuItem save = new JMenuItem("Save"); save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(getConfigFilename().startsWith("jar")){ saveAs.doClick(); }else{ File configFile = new File(getConfigFilename()); try { save(configFile); } catch (IOException ex) { GlobalExceptionHandler.handle("Unable to save "+configFile, ex); } } } }); fileMenu.add(save); fileMenu.add(saveAs); fileMenu.addSeparator(); JMenuItem load = new JMenuItem("Open"); fileMenu.add(load); load.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { FileDialog fileDialog = new FileDialog(frame, "Load a SOD config file"); fileDialog.setDirectory("."); fileDialog.show(); String inFile = fileDialog.getFile(); if (inFile != null) { try { setConfigFile(inFile); loadGUI(); } catch (Exception ex) { GlobalExceptionHandler.handle("Unable to open "+inFile, ex); } } } }); JMenuItem loadTutorial = new JMenuItem("Open Tutorial"); loadTutorial.addActionListener(tutorialLoader); fileMenu.add(loadTutorial); JMenuItem loadWeed = new JMenuItem("Open WEED"); loadWeed.addActionListener(new FileLoader(configFileBase + "weed.xml")); fileMenu.add(loadWeed); fileMenu.addSeparator(); JMenuItem quit = new JMenuItem("Quit"); fileMenu.add(quit); quit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); frame.getContentPane().setLayout(new BorderLayout()); loadGUI(); }
public void start() { frame = new JFrame(frameName); JMenuBar menubar = new JMenuBar(); frame.setJMenuBar(menubar); JMenu fileMenu = new JMenu("File"); menubar.add(fileMenu); final JMenuItem saveAs = new JMenuItem("Save As..."); saveAs.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { FileDialog fileDialog = new FileDialog(frame); fileDialog.setMode(FileDialog.SAVE); fileDialog.show(); String outfiledir = fileDialog.getDirectory(); String outfilename = fileDialog.getFile(); if (outfilename != null) { File outfile = new File(outfiledir, outfilename); try { save(outfile); } catch (IOException ex) { GlobalExceptionHandler.handle("Unable to save to "+outfile, ex); } } } }); JMenuItem save = new JMenuItem("Save"); save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(getConfigFilename().startsWith("jar")){ saveAs.doClick(); }else{ File configFile = new File(getConfigFilename()); try { save(configFile); } catch (IOException ex) { GlobalExceptionHandler.handle("Unable to save "+configFile, ex); } } } }); fileMenu.add(save); fileMenu.add(saveAs); fileMenu.addSeparator(); JMenuItem load = new JMenuItem("Open"); fileMenu.add(load); load.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { FileDialog fileDialog = new FileDialog(frame, "Load a SOD config file"); fileDialog.setDirectory("."); fileDialog.show(); String infileDir = fileDialog.getDirectory(); String inFile = fileDialog.getFile(); if (inFile != null) { try { setConfigFile(infileDir + "/" + inFile); loadGUI(); } catch (Exception ex) { GlobalExceptionHandler.handle("Unable to open "+inFile, ex); } } } }); JMenuItem loadTutorial = new JMenuItem("Open Tutorial"); loadTutorial.addActionListener(tutorialLoader); fileMenu.add(loadTutorial); JMenuItem loadWeed = new JMenuItem("Open WEED"); loadWeed.addActionListener(new FileLoader(configFileBase + "weed.xml")); fileMenu.add(loadWeed); fileMenu.addSeparator(); JMenuItem quit = new JMenuItem("Quit"); fileMenu.add(quit); quit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); frame.getContentPane().setLayout(new BorderLayout()); loadGUI(); }
diff --git a/src/main/java/org/dynmap/JsonFileClientUpdateComponent.java b/src/main/java/org/dynmap/JsonFileClientUpdateComponent.java index 748755b9..0515c662 100644 --- a/src/main/java/org/dynmap/JsonFileClientUpdateComponent.java +++ b/src/main/java/org/dynmap/JsonFileClientUpdateComponent.java @@ -1,151 +1,151 @@ package org.dynmap; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import java.util.Timer; import java.util.TimerTask; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import org.dynmap.web.Json; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import static org.dynmap.JSONUtils.*; public class JsonFileClientUpdateComponent extends ClientUpdateComponent { protected TimerTask task; protected Timer timer; protected long jsonInterval; protected long lastTimestamp = 0; protected JSONParser parser = new JSONParser(); public JsonFileClientUpdateComponent(final DynmapPlugin plugin, final ConfigurationNode configuration) { super(plugin, configuration); final boolean allowwebchat = configuration.getBoolean("allowwebchat", false); jsonInterval = (long)(configuration.getFloat("writeinterval", 1) * 1000); task = new TimerTask() { @Override public void run() { writeUpdates(); if (allowwebchat) { handleWebChat(); } } }; timer = new Timer(); timer.scheduleAtFixedRate(task, jsonInterval, jsonInterval); plugin.events.addListener("buildclientconfiguration", new Event.Listener<JSONObject>() { @Override public void triggered(JSONObject t) { s(t, "jsonfile", true); s(t, "allowwebchat", allowwebchat); } }); plugin.events.addListener("initialized", new Event.Listener<Object>() { @Override public void triggered(Object t) { writeConfiguration(); } }); } protected File getStandaloneFile(String filename) { File webpath = new File(plugin.configuration.getString("webpath", "web"), "standalone/" + filename); if (webpath.isAbsolute()) return webpath; else return new File(plugin.getDataFolder(), webpath.toString()); } protected void writeConfiguration() { File outputFile; JSONObject clientConfiguration = new JSONObject(); plugin.events.trigger("buildclientconfiguration", clientConfiguration); outputFile = getStandaloneFile("dynmap_config.json"); try { FileOutputStream fos = new FileOutputStream(outputFile); fos.write(clientConfiguration.toJSONString().getBytes()); fos.close(); } catch (FileNotFoundException ex) { Log.severe("Exception while writing JSON-configuration-file.", ex); } catch (IOException ioe) { Log.severe("Exception while writing JSON-configuration-file.", ioe); } } protected void writeUpdates() { long current = System.currentTimeMillis(); File outputFile; //Handles Updates for (DynmapWorld dynmapWorld : plugin.mapManager.worlds.values()) { World world = dynmapWorld.world; current = System.currentTimeMillis(); JSONObject update = new JSONObject(); update.put("timestamp", current); - ClientUpdateEvent clientUpdate = new ClientUpdateEvent(current, dynmapWorld, update); + ClientUpdateEvent clientUpdate = new ClientUpdateEvent(lastTimestamp, dynmapWorld, update); plugin.events.trigger("buildclientupdate", clientUpdate); outputFile = getStandaloneFile("dynmap_" + world.getName() + ".json"); try { FileOutputStream fos = new FileOutputStream(outputFile); fos.write(Json.stringifyJson(update).getBytes()); fos.close(); } catch (FileNotFoundException ex) { Log.severe("Exception while writing JSON-file.", ex); } catch (IOException ioe) { Log.severe("Exception while writing JSON-file.", ioe); } plugin.events.<ClientUpdateEvent>trigger("clientupdatewritten", clientUpdate); } lastTimestamp = System.currentTimeMillis(); plugin.events.<Object>trigger("clientupdateswritten", null); } protected void handleWebChat() { File webchatFile = getStandaloneFile("dynmap_webchat.json"); if (webchatFile.exists() && lastTimestamp != 0) { JSONArray jsonMsgs = null; try { FileReader inputFileReader = new FileReader(webchatFile); jsonMsgs = (JSONArray) parser.parse(inputFileReader); inputFileReader.close(); } catch (IOException ex) { Log.severe("Exception while reading JSON-file.", ex); } catch (ParseException ex) { Log.severe("Exception while parsing JSON-file.", ex); } if (jsonMsgs != null) { Iterator<?> iter = jsonMsgs.iterator(); while (iter.hasNext()) { JSONObject o = (JSONObject) iter.next(); if (Long.parseLong(String.valueOf(o.get("timestamp"))) >= (lastTimestamp)) { String name = String.valueOf(o.get("name")); String message = String.valueOf(o.get("message")); webChat(name, message); } } } } } protected void webChat(String name, String message) { // TODO: Change null to something meaningful. plugin.mapManager.pushUpdate(new Client.ChatMessage("web", null, name, message, null)); Log.info("[WEB]" + name + ": " + message); ChatEvent event = new ChatEvent("web", name, message); plugin.events.trigger("webchat", event); } }
true
true
protected void writeUpdates() { long current = System.currentTimeMillis(); File outputFile; //Handles Updates for (DynmapWorld dynmapWorld : plugin.mapManager.worlds.values()) { World world = dynmapWorld.world; current = System.currentTimeMillis(); JSONObject update = new JSONObject(); update.put("timestamp", current); ClientUpdateEvent clientUpdate = new ClientUpdateEvent(current, dynmapWorld, update); plugin.events.trigger("buildclientupdate", clientUpdate); outputFile = getStandaloneFile("dynmap_" + world.getName() + ".json"); try { FileOutputStream fos = new FileOutputStream(outputFile); fos.write(Json.stringifyJson(update).getBytes()); fos.close(); } catch (FileNotFoundException ex) { Log.severe("Exception while writing JSON-file.", ex); } catch (IOException ioe) { Log.severe("Exception while writing JSON-file.", ioe); } plugin.events.<ClientUpdateEvent>trigger("clientupdatewritten", clientUpdate); } lastTimestamp = System.currentTimeMillis(); plugin.events.<Object>trigger("clientupdateswritten", null); }
protected void writeUpdates() { long current = System.currentTimeMillis(); File outputFile; //Handles Updates for (DynmapWorld dynmapWorld : plugin.mapManager.worlds.values()) { World world = dynmapWorld.world; current = System.currentTimeMillis(); JSONObject update = new JSONObject(); update.put("timestamp", current); ClientUpdateEvent clientUpdate = new ClientUpdateEvent(lastTimestamp, dynmapWorld, update); plugin.events.trigger("buildclientupdate", clientUpdate); outputFile = getStandaloneFile("dynmap_" + world.getName() + ".json"); try { FileOutputStream fos = new FileOutputStream(outputFile); fos.write(Json.stringifyJson(update).getBytes()); fos.close(); } catch (FileNotFoundException ex) { Log.severe("Exception while writing JSON-file.", ex); } catch (IOException ioe) { Log.severe("Exception while writing JSON-file.", ioe); } plugin.events.<ClientUpdateEvent>trigger("clientupdatewritten", clientUpdate); } lastTimestamp = System.currentTimeMillis(); plugin.events.<Object>trigger("clientupdateswritten", null); }
diff --git a/src/cli/src/main/java/org/geogit/cli/porcelain/Merge.java b/src/cli/src/main/java/org/geogit/cli/porcelain/Merge.java index fec44b91..d0a29fd4 100644 --- a/src/cli/src/main/java/org/geogit/cli/porcelain/Merge.java +++ b/src/cli/src/main/java/org/geogit/cli/porcelain/Merge.java @@ -1,150 +1,150 @@ /* Copyright (c) 2013 OpenPlans. All rights reserved. * This code is licensed under the BSD New License, available at the root * application directory. */ package org.geogit.cli.porcelain; import java.io.IOException; import java.util.Iterator; import java.util.List; import jline.console.ConsoleReader; import org.fusesource.jansi.Ansi; import org.fusesource.jansi.Ansi.Color; import org.geogit.api.GeoGIT; import org.geogit.api.ObjectId; import org.geogit.api.Ref; import org.geogit.api.RevCommit; import org.geogit.api.plumbing.RefParse; import org.geogit.api.plumbing.RevParse; import org.geogit.api.plumbing.diff.DiffEntry; import org.geogit.api.porcelain.DiffOp; import org.geogit.api.porcelain.MergeOp; import org.geogit.api.porcelain.MergeOp.MergeReport; import org.geogit.api.porcelain.NothingToCommitException; import org.geogit.api.porcelain.ResetOp; import org.geogit.api.porcelain.ResetOp.ResetMode; import org.geogit.cli.AbstractCommand; import org.geogit.cli.CLICommand; import org.geogit.cli.CommandFailedException; import org.geogit.cli.GeogitCLI; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.google.common.base.Optional; import com.google.common.base.Suppliers; import com.google.common.collect.Lists; /** * Incorporates changes from the named commits (since the time their histories diverged from the * current branch) into the current branch. * <p> * CLI proxy for {@link MergeOp} * <p> * Usage: * <ul> * <li> {@code geogit merge [-m <msg>] [--ours] [--theirs] <commitish>...} * </ul> * * @see MergeOp */ @Parameters(commandNames = "merge", commandDescription = "Merge two or more histories into one") public class Merge extends AbstractCommand implements CLICommand { @Parameter(names = "-m", description = "Commit message") private String message; @Parameter(names = "--ours", description = "Use 'ours' strategy") private boolean ours; @Parameter(names = "--theirs", description = "Use 'theirs' strategy") private boolean theirs; @Parameter(names = "--no-commit", description = "Do not perform a commit after merging") private boolean noCommit; @Parameter(names = "--abort", description = "Aborts the current merge") private boolean abort; @Parameter(description = "<commitish>...") private List<String> commits = Lists.newArrayList(); /** * Executes the merge command using the provided options. */ @Override public void runInternal(GeogitCLI cli) throws IOException { - checkParameter(commits.size() > 0, "No commits provided to merge."); + checkParameter(commits.size() > 0 || abort, "No commits provided to merge."); ConsoleReader console = cli.getConsole(); final GeoGIT geogit = cli.getGeogit(); Ansi ansi = newAnsi(console.getTerminal()); if (abort) { Optional<Ref> ref = geogit.command(RefParse.class).setName(Ref.ORIG_HEAD).call(); if (!ref.isPresent()) { throw new CommandFailedException("There is no merge to abort <ORIG_HEAD missing>."); } geogit.command(ResetOp.class).setMode(ResetMode.HARD) .setCommit(Suppliers.ofInstance(ref.get().getObjectId())).call(); console.println("Merge aborted successfully."); return; } RevCommit commit; try { MergeOp merge = geogit.command(MergeOp.class); merge.setOurs(ours).setTheirs(theirs).setNoCommit(noCommit); merge.setMessage(message).setProgressListener(cli.getProgressListener()); for (String commitish : commits) { Optional<ObjectId> commitId; commitId = geogit.command(RevParse.class).setRefSpec(commitish).call(); checkParameter(commitId.isPresent(), "Commit not found '%s'", commitish); merge.addCommit(Suppliers.ofInstance(commitId.get())); } MergeReport report = merge.call(); commit = report.getMergeCommit(); } catch (RuntimeException e) { if (e instanceof NothingToCommitException || e instanceof IllegalArgumentException || e instanceof IllegalStateException) { throw new CommandFailedException(e.getMessage(), e); } throw e; } final ObjectId parentId = commit.parentN(0).or(ObjectId.NULL); console.println("[" + commit.getId() + "] " + commit.getMessage()); console.print("Committed, counting objects..."); Iterator<DiffEntry> diff = geogit.command(DiffOp.class).setOldVersion(parentId) .setNewVersion(commit.getId()).call(); int adds = 0, deletes = 0, changes = 0; DiffEntry diffEntry; while (diff.hasNext()) { diffEntry = diff.next(); switch (diffEntry.changeType()) { case ADDED: ++adds; break; case REMOVED: ++deletes; break; case MODIFIED: ++changes; break; } } ansi.fg(Color.GREEN).a(adds).reset().a(" features added, ").fg(Color.YELLOW).a(changes) .reset().a(" changed, ").fg(Color.RED).a(deletes).reset().a(" deleted.").reset() .newline(); console.print(ansi.toString()); } }
true
true
public void runInternal(GeogitCLI cli) throws IOException { checkParameter(commits.size() > 0, "No commits provided to merge."); ConsoleReader console = cli.getConsole(); final GeoGIT geogit = cli.getGeogit(); Ansi ansi = newAnsi(console.getTerminal()); if (abort) { Optional<Ref> ref = geogit.command(RefParse.class).setName(Ref.ORIG_HEAD).call(); if (!ref.isPresent()) { throw new CommandFailedException("There is no merge to abort <ORIG_HEAD missing>."); } geogit.command(ResetOp.class).setMode(ResetMode.HARD) .setCommit(Suppliers.ofInstance(ref.get().getObjectId())).call(); console.println("Merge aborted successfully."); return; } RevCommit commit; try { MergeOp merge = geogit.command(MergeOp.class); merge.setOurs(ours).setTheirs(theirs).setNoCommit(noCommit); merge.setMessage(message).setProgressListener(cli.getProgressListener()); for (String commitish : commits) { Optional<ObjectId> commitId; commitId = geogit.command(RevParse.class).setRefSpec(commitish).call(); checkParameter(commitId.isPresent(), "Commit not found '%s'", commitish); merge.addCommit(Suppliers.ofInstance(commitId.get())); } MergeReport report = merge.call(); commit = report.getMergeCommit(); } catch (RuntimeException e) { if (e instanceof NothingToCommitException || e instanceof IllegalArgumentException || e instanceof IllegalStateException) { throw new CommandFailedException(e.getMessage(), e); } throw e; } final ObjectId parentId = commit.parentN(0).or(ObjectId.NULL); console.println("[" + commit.getId() + "] " + commit.getMessage()); console.print("Committed, counting objects..."); Iterator<DiffEntry> diff = geogit.command(DiffOp.class).setOldVersion(parentId) .setNewVersion(commit.getId()).call(); int adds = 0, deletes = 0, changes = 0; DiffEntry diffEntry; while (diff.hasNext()) { diffEntry = diff.next(); switch (diffEntry.changeType()) { case ADDED: ++adds; break; case REMOVED: ++deletes; break; case MODIFIED: ++changes; break; } } ansi.fg(Color.GREEN).a(adds).reset().a(" features added, ").fg(Color.YELLOW).a(changes) .reset().a(" changed, ").fg(Color.RED).a(deletes).reset().a(" deleted.").reset() .newline(); console.print(ansi.toString()); }
public void runInternal(GeogitCLI cli) throws IOException { checkParameter(commits.size() > 0 || abort, "No commits provided to merge."); ConsoleReader console = cli.getConsole(); final GeoGIT geogit = cli.getGeogit(); Ansi ansi = newAnsi(console.getTerminal()); if (abort) { Optional<Ref> ref = geogit.command(RefParse.class).setName(Ref.ORIG_HEAD).call(); if (!ref.isPresent()) { throw new CommandFailedException("There is no merge to abort <ORIG_HEAD missing>."); } geogit.command(ResetOp.class).setMode(ResetMode.HARD) .setCommit(Suppliers.ofInstance(ref.get().getObjectId())).call(); console.println("Merge aborted successfully."); return; } RevCommit commit; try { MergeOp merge = geogit.command(MergeOp.class); merge.setOurs(ours).setTheirs(theirs).setNoCommit(noCommit); merge.setMessage(message).setProgressListener(cli.getProgressListener()); for (String commitish : commits) { Optional<ObjectId> commitId; commitId = geogit.command(RevParse.class).setRefSpec(commitish).call(); checkParameter(commitId.isPresent(), "Commit not found '%s'", commitish); merge.addCommit(Suppliers.ofInstance(commitId.get())); } MergeReport report = merge.call(); commit = report.getMergeCommit(); } catch (RuntimeException e) { if (e instanceof NothingToCommitException || e instanceof IllegalArgumentException || e instanceof IllegalStateException) { throw new CommandFailedException(e.getMessage(), e); } throw e; } final ObjectId parentId = commit.parentN(0).or(ObjectId.NULL); console.println("[" + commit.getId() + "] " + commit.getMessage()); console.print("Committed, counting objects..."); Iterator<DiffEntry> diff = geogit.command(DiffOp.class).setOldVersion(parentId) .setNewVersion(commit.getId()).call(); int adds = 0, deletes = 0, changes = 0; DiffEntry diffEntry; while (diff.hasNext()) { diffEntry = diff.next(); switch (diffEntry.changeType()) { case ADDED: ++adds; break; case REMOVED: ++deletes; break; case MODIFIED: ++changes; break; } } ansi.fg(Color.GREEN).a(adds).reset().a(" features added, ").fg(Color.YELLOW).a(changes) .reset().a(" changed, ").fg(Color.RED).a(deletes).reset().a(" deleted.").reset() .newline(); console.print(ansi.toString()); }
diff --git a/src/com/leafdigital/hawthorn/server/HttpServer.java b/src/com/leafdigital/hawthorn/server/HttpServer.java index a7a4c94..4093b04 100644 --- a/src/com/leafdigital/hawthorn/server/HttpServer.java +++ b/src/com/leafdigital/hawthorn/server/HttpServer.java @@ -1,896 +1,904 @@ /* Copyright 2009 Samuel Marshall http://www.leafdigital.com/software/hawthorn/ This file is part of Hawthorn. Hawthorn is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Hawthorn is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Hawthorn. If not, see <http://www.gnu.org/licenses/>. */ package com.leafdigital.hawthorn.server; import java.io.*; import java.net.*; import java.nio.ByteBuffer; import java.nio.channels.*; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.*; import com.leafdigital.hawthorn.util.*; /** Server that accepts incoming HTTP requests and dispatches them as events. */ public final class HttpServer extends HawthornObject implements Statistics.InstantStatisticHandler { private final static int CONNECTION_TIMEOUT = 90000, CLEANUP_EVERY = 30000, LOGTIME_EVERY = 10000; private final static String STATISTIC_CONNECTION_COUNT = "CONNECTION_COUNT"; /** How long the 'ages' items will be cached by browser (30 days) */ private final static long HOW_LONG_IS_AGES = 30L * 24L * 60L * 60L * 1000L; /** Content type for UTF-8 JavaScript */ final static String CONTENT_TYPE_JAVASCRIPT = "application/javascript; charset=UTF-8"; /** Content type for UTF-8 HTML */ final static String CONTENT_TYPE_HTML = "text/html; charset=UTF-8"; /** Psuedo-content type for redirects */ final static String CONTENT_TYPE_REDIRECT = "[redirect]"; /** Content type for Windows icons */ final static String CONTENT_TYPE_ICON = "image/vnd.microsoft.icon"; /** Statistic: request time for all HTTP events from users */ final static String STATISTIC_USER_REQUEST_TIME = "USER_REQUEST_TIME"; /** Statistic: request time for all HTTP events from servers */ final static String STATISTIC_SERVER_REQUEST_TIME = "SERVER_REQUEST_TIME"; /** Statistic: size of close queue */ final static String STATISTIC_CLOSE_QUEUE_SIZE = "CLOSE_QUEUE_SIZE"; /** Statistic: request time for specific type */ final static String STATISTIC_SPECIFIC_REQUEST = "REQUEST_TIME_"; /** Statistic: main thread busy percentage */ final static String STATISTIC_MAIN_THREAD_BUSY_PERCENT = "MAIN_THREAD_BUSY_PERCENT"; private final static int BACKLOG = 256; private final static Pattern REGEXP_HTTPREQUEST = Pattern.compile("GET (.+) HTTP/1\\.[01]"); private final static Pattern REGEXP_SERVERAUTH = Pattern.compile("\\*([0-9]{1,18})\\*([a-f0-9]{40})"); private Selector selector; private ServerSocketChannel server; private HashMap<SelectionKey, Connection> connections = new HashMap<SelectionKey, Connection>(); private LinkedList<SelectionKey> keysToClose = new LinkedList<SelectionKey>(); private LinkedList<SelectableChannel> channelsToClose = new LinkedList<SelectableChannel>(); private Object closeSynch = new Object(), timeLogSynch = new Object(); private boolean close, closed, closeThreadClosed; private int timeBusy, timeInSelect; /** * @param app Main app object * @throws StartupException If there is a problem binding the socket */ public HttpServer(Hawthorn app) throws StartupException { super(app); getStatistics().registerInstantStatistic(STATISTIC_CONNECTION_COUNT, this); getStatistics().registerTimeStatistic(STATISTIC_USER_REQUEST_TIME); if(getConfig().getOtherServers().length > 0) { getStatistics().registerTimeStatistic(STATISTIC_SERVER_REQUEST_TIME); } if(getConfig().isDetailedStats()) { getStatistics().registerTimeStatistic(STATISTIC_SPECIFIC_REQUEST + HttpEvent.SAY); getStatistics().registerTimeStatistic(STATISTIC_SPECIFIC_REQUEST + HttpEvent.BAN); getStatistics().registerTimeStatistic(STATISTIC_SPECIFIC_REQUEST + HttpEvent.LEAVE); getStatistics().registerTimeStatistic(STATISTIC_SPECIFIC_REQUEST + HttpEvent.POLL); getStatistics().registerTimeStatistic(STATISTIC_SPECIFIC_REQUEST + HttpEvent.WAIT); getStatistics().registerTimeStatistic(STATISTIC_SPECIFIC_REQUEST + HttpEvent.RECENT); getStatistics().registerTimeStatistic(STATISTIC_SPECIFIC_REQUEST + HttpEvent.LOG); getStatistics().registerTimeStatistic(STATISTIC_SPECIFIC_REQUEST + HttpEvent.STATISTICS); getStatistics().registerTimeStatistic(STATISTIC_SPECIFIC_REQUEST + HttpEvent.FAVICON); } getStatistics().registerInstantStatistic(STATISTIC_CLOSE_QUEUE_SIZE, new Statistics.InstantStatisticHandler() { public int getValue() { synchronized(connections) { return channelsToClose.size() + keysToClose.size(); } } }); getStatistics().registerInstantStatistic(STATISTIC_MAIN_THREAD_BUSY_PERCENT, new Statistics.InstantStatisticHandler() { public int getValue() { synchronized(timeLogSynch) { int total = timeBusy + timeInSelect; int percent = total==0 ? 0 : (timeBusy*100 + total/2) / total; timeBusy = 0; timeInSelect = 0; return percent; } } }); try { selector = Selector.open(); server = ServerSocketChannel.open(); server.configureBlocking(false); server.socket().bind( new InetSocketAddress(getConfig().getThisServer().getAddress(), getConfig().getThisServer().getPort()), BACKLOG); server.register(selector, SelectionKey.OP_ACCEPT); } catch(IOException e) { throw new StartupException(ErrorCode.STARTUP_CANNOTBIND, "Failed to initialise server socket.", e); } Thread t = new Thread(new Runnable() { public void run() { serverThread(); } }, "Main server thread"); Thread t2 = new Thread(new Runnable() { public void run() { closeThread(); } }, "Connection closer thread"); // Increase the main server thread priority (this is because there is only // one main server thread versus numerous event threads; and I want the // recorded time from connect to HTTP result handling to be as accurate // as possible). t.setPriority(Thread.MAX_PRIORITY); t2.setPriority(Thread.MAX_PRIORITY); t.start(); t2.start(); } /** * A single connection to the HTTP server. */ public class Connection { private final static int BUFFERSIZE = 8192; private SelectionKey key; private SocketChannel channel; private ByteBuffer buffer; private long lastAction, startTime; private String hostAddress; private boolean otherServer, serverAuthenticated; private final static String CRLF = "\r\n"; /** * @param key Selection key */ private Connection(SelectionKey key) { this.key = key; this.channel = (SocketChannel)key.channel(); lastAction = System.currentTimeMillis(); startTime = lastAction; buffer = ByteBuffer.allocate(BUFFERSIZE); hostAddress = channel.socket().getInetAddress().getHostAddress(); } /** @return Time at which connection was accepted */ public long getStartTime() { return startTime; } /** Closes the connection */ public void close() { closeChannel(key); } /** * Sends an HTTP response on this connection and closes it. Note that all * responses, even errors, use HTTP 200 OK. This is because we want the * JavaScript, not browser, to handle the error. * * @param data Data to send (will be turned into UTF-8) */ public void send(String data) { send(200, data, CONTENT_TYPE_JAVASCRIPT); } /** * Sends an HTTP response on this connection and closes it. * * @param code HTTP code. Use 200 except for fatal errors where we don't * know which callback function to call * @param data Data to send (will be turned into UTF-8); or URL for * CONTENT_TYPE_REDIRECT * @param contentType Content type to send * @throws IllegalArgumentException If the HTTP code isn't supported */ public void send(int code, String data, String contentType) throws IllegalArgumentException { try { String location = null; if(code == 302) { location = data; data = XML.getXHTML("Redirect", "", "<p><a href=\"" + XML.esc(location) + "\">" + XML.esc(location) + "</a></p>"); } // Get data byte[] dataBytes = data.getBytes("UTF-8"); // Send bytes send(code, dataBytes, contentType, location, false); } catch(UnsupportedEncodingException e) { throw new Error("Basic encoding not supported?!", e); } } /** * Sends an HTTP response on this connection and closes it. * * @param code HTTP code. Use 200 except for fatal errors where we don't * know which callback function to call * @param dataBytes Data to send (will be turned into UTF-8); or URL for * CONTENT_TYPE_REDIRECT * @param contentType Content type to send * @param location Location header (null = none) * @param cacheForAges If true, caches data for ages * @throws IllegalArgumentException If the HTTP code isn't supported */ public void send(int code, byte[] dataBytes, String contentType, String location, boolean cacheForAges) throws IllegalArgumentException { try { // Get header StringBuilder header = new StringBuilder(); String codeText; switch(code) { case 200: codeText = "OK"; break; case 302: codeText = "Redirect"; break; case 403: codeText = "Access denied"; break; case 404: codeText = "Not found"; break; case 500: codeText = "Internal server error"; break; default: throw new IllegalArgumentException("Unsupported HTTP code " + code); } header.append("HTTP/1.1 "); header.append(code); header.append(' '); header.append(codeText); header.append(CRLF); header.append("Connection: close"); header.append(CRLF); header.append("Content-Type: "); header.append(contentType); header.append(CRLF); header.append("Content-Length: "); header.append(dataBytes.length); header.append(CRLF); if(location!=null) { header.append("Location: "); header.append(location); header.append(CRLF); } if(cacheForAges) { SimpleDateFormat sdf = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); header.append("Expires: "); header.append(sdf.format(new Date(System.currentTimeMillis() + HOW_LONG_IS_AGES))); header.append(" GMT"); header.append(CRLF); } header.append(CRLF); byte[] headerBytes = header.toString().getBytes("US-ASCII"); // Combine the two ByteBuffer response = ByteBuffer.allocate(dataBytes.length + headerBytes.length); response.put(headerBytes); response.put(dataBytes); response.flip(); // Send data while(true) { try { channel.write(response); } catch(IOException e) { - getLogger().log(Logger.SYSTEM_LOG, Logger.Level.NORMAL, - "ERROR " + this + " Error writing data"); + if(e instanceof ClosedChannelException) + { + getLogger().log(Logger.SYSTEM_LOG, Logger.Level.NORMAL, + "ERROR " + this + " User cancelled request"); + } + else + { + getLogger().log(Logger.SYSTEM_LOG, Logger.Level.NORMAL, + "ERROR " + this + " Error writing data", e); + } close(); return; } // Close connection if needed if(!response.hasRemaining()) { close(); return; } // Still some data? OK, wait a bit and try again (yay polling - // but this should hardly ever really happen, because usually // the responses we send are far smaller than network buffers; // exception is usually the statistics page). try { getLogger().log(Logger.SYSTEM_LOG, Logger.Level.NORMAL, "WARNING Event thread blocked for 10ms (this is OK if rare)"); Thread.sleep(10); } catch(InterruptedException ie) { } } } catch(UnsupportedEncodingException e) { throw new Error("Basic encoding not supported?!", e); } } private void read() { if(buffer == null) { close(); return; } int read; try { read = channel.read(buffer); } catch(IOException e) { // Connection got closed, or something else went wrong close(); return; } if(read == -1) { close(); return; } if(read == 0) { return; } lastAction = System.currentTimeMillis(); byte[] array = buffer.array(); int bufferPos = buffer.position(); // Might this be another server introducing itself? if(!otherServer && bufferPos > 0 && array[0] == '*') { if(!getConfig().isOtherServer(channel.socket().getInetAddress())) { getLogger().log(Logger.SYSTEM_LOG, Logger.Level.NORMAL, "SECURITY " + this + " Remote server connection from disallowed IP"); close(); return; } otherServer = true; } if(otherServer) { handleServer(array, bufferPos); } else { handleUser(array, bufferPos); } } /** * User communication follows HTTP. * * @param array Data buffer * @param bufferPos Length of buffer that is filled */ private void handleUser(byte[] array, int bufferPos) { if(array[bufferPos - 1] == '\n' && array[bufferPos - 2] == '\r' && array[bufferPos - 3] == '\n' && array[bufferPos - 4] == '\r') { // Obtain GET/POST line int i; for(i = 0; array[i] != '\r'; i++) { ; } try { String firstLine = new String(array, 0, i, "US-ASCII"); Matcher m = REGEXP_HTTPREQUEST.matcher(firstLine); if(!m.matches()) { getLogger().log(Logger.SYSTEM_LOG, Logger.Level.NORMAL, "SECURITY " + this + " Invalid request line: " + firstLine); close(); return; } String ipHeader = getConfig().getIpHeader(); if(ipHeader != null) { // Get rest of header in lower-case String remainingHeader = new String(array, i+2, bufferPos-(i+2), "US-ASCII").toLowerCase(); // Find header int pos = remainingHeader.indexOf(ipHeader.toLowerCase()+":"); if(pos != -1) { int cr = remainingHeader.indexOf('\r', pos + ipHeader.length() + 1); if(cr != -1) { hostAddress = remainingHeader.substring( pos + ipHeader.length() + 1, cr).trim(); } } } buffer = null; receivedRequest(m.group(1)); return; } catch(UnsupportedEncodingException e) { throw new Error("Missing US-ASCII support", e); } } else { // Not received valid request yet. If we've received the full buffer, // give up on it. if(bufferPos == BUFFERSIZE) { getLogger().log(Logger.SYSTEM_LOG, Logger.Level.NORMAL, "SECURITY " + this + " Received large invalid request"); close(); return; } } } /** * * @param array Data buffer * @param bufferPos Length of buffer that is filled */ private void handleServer(byte[] array, int bufferPos) { int pos = 0; while(true) { int linefeed; for(linefeed = pos; linefeed < bufferPos; linefeed++) { if(array[linefeed] == '\n') { break; } } // If there are no more lines, exit if(linefeed == bufferPos) { // Clean up the buffer to remove used data. System.arraycopy(array, pos, array, 0, bufferPos - pos); buffer.position(bufferPos - pos); // Exit return; } // Process line [UTF-8] try { String line = new String(array, pos, linefeed - pos, "UTF-8"); pos = linefeed + 1; if(serverAuthenticated) { // Pass this to event-handler getEventHandler().addEvent(new ServerEvent(getApp(), line, this)); } else { // This must be authentication method Matcher m = REGEXP_SERVERAUTH.matcher(line); if(m.matches()) { // Check time. This is there both to ensure the security check // isn't easily reproducible - which it's a bit crap for, since // I didn't make sure that times aren't reused - and to ensure // that clocks are in synch, because if they aren't, behaviour // will be weird. long time = Long.parseLong(m.group(1)); if(Math.abs(time - System.currentTimeMillis()) > 5000) { getLogger().log(Logger.SYSTEM_LOG, Logger.Level.ERROR, "SERVERFROM " + this + "ERROR Remote server reports incorrect " + "time (>5 seconds out). Install NTP on all servers."); close(); return; } // Build hash using time and IP address String valid = getApp().getValidKey("remote server", toString(), "", "", Auth.getPermissionSet(""), time); if(!valid.equals(m.group(2))) { getLogger().log(Logger.SYSTEM_LOG, Logger.Level.ERROR, "SECURITY " + this + " Invalid server authorisation key: " + line); } serverAuthenticated = true; getLogger().log(Logger.SYSTEM_LOG, Logger.Level.NORMAL, "SERVERFROM " + this + " CONNECTED"); } else { getLogger().log(Logger.SYSTEM_LOG, Logger.Level.ERROR, "SECURITY " + this + " Invalid remote server auth: " + line); close(); return; } } } catch(UnsupportedEncodingException e) { throw new Error("Missing UTF-8 support", e); } } } @Override /** * @return Internet address (numeric) of this connection */ public String toString() { return hostAddress; } private void receivedRequest(String request) { getLogger().log(Logger.SYSTEM_LOG, Logger.Level.DETAIL, "REQUEST " + this + " " + request); getEventHandler().addEvent(new HttpEvent(getApp(), request, this)); } private boolean checkTimeout(long now) { if(!serverAuthenticated && now - lastAction > CONNECTION_TIMEOUT) { getLogger().log(Logger.SYSTEM_LOG, Logger.Level.NORMAL, "SECURITY " + this + " (timeout)"); close(); return true; } else { return false; } } } private void serverThread() { long lastCleanup = System.currentTimeMillis(); long lastTime = lastCleanup; int localTimeInSelect = 0, localTimeBusy = 0; try { while(true) { cancelKeys(); long beforeSelect = System.currentTimeMillis(); localTimeBusy += (int)(beforeSelect - lastTime); selector.select(5000); lastTime = System.currentTimeMillis(); localTimeInSelect += (int)(lastTime - beforeSelect); if(close) { closed = true; return; } for(SelectionKey key : selector.selectedKeys()) { if((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) { try { Socket newSocket = server.socket().accept(); newSocket.getChannel().configureBlocking(false); SelectionKey newKey = newSocket.getChannel().register(selector, SelectionKey.OP_READ); Connection newConnection = new Connection(newKey); synchronized (connections) { connections.put(newKey, newConnection); } } catch(IOException e) { getLogger().log(Logger.SYSTEM_LOG, Logger.Level.ERROR, "ERROR Failed to accept connection", e); } } if((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) { Connection c; synchronized (connections) { c = connections.get(key); if(c == null) { continue; } } c.read(); } } selector.selectedKeys().clear(); if(lastTime - lastCleanup > CLEANUP_EVERY) { lastCleanup = lastTime; LinkedList<Connection> consider; synchronized (connections) { consider = new LinkedList<Connection>(connections.values()); } for(Connection connection : consider) { connection.checkTimeout(lastTime); } } if(localTimeBusy + localTimeInSelect > LOGTIME_EVERY) { synchronized (timeLogSynch) { timeBusy += localTimeBusy; timeInSelect += localTimeInSelect; localTimeBusy = 0; localTimeInSelect = 0; } } } } catch(Throwable t) { getLogger().log(Logger.SYSTEM_LOG, Logger.Level.FATAL_ERROR, "ERROR Fatal error in main server thread", t); // If the main thread crashed, better exit the whole server closed = true; getApp().close(); } } private void cancelKeys() { boolean some = false; synchronized (connections) { while(!keysToClose.isEmpty()) { SelectionKey key = keysToClose.removeFirst(); key.cancel(); channelsToClose.add(key.channel()); some = true; } } if(some) { synchronized (closeSynch) { closeSynch.notify(); } } } private void closeThread() { try { while(true) { // Wait for notification synchronized (closeSynch) { try { if(!close) { closeSynch.wait(); } } catch(InterruptedException e) { } if(close) { return; } } // Close all channels SelectableChannel[] channels; synchronized (connections) { channels = channelsToClose.toArray( new SelectableChannel[channelsToClose.size()]); channelsToClose.clear(); } for(SelectableChannel channel : channels) { try { ((SocketChannel)channel).socket().shutdownOutput(); channel.close(); } catch(Throwable t) { } } } } finally { synchronized(closeSynch) { closeThreadClosed = true; closeSynch.notifyAll(); } } } /** * Adds the key to a list which the selector thread will cancel. Once it * is cancelled, the channel will be closed in a separate thread (in case * it blocks). * @param key Key to cancel */ private void closeChannel(SelectionKey key) { synchronized (connections) { keysToClose.add(key); connections.remove(key); } } /** * Closes the HTTP server. Note that this will block for a little while. */ public void close() { close = true; while(!closed) { try { Thread.sleep(100); } catch(InterruptedException ie) { } } synchronized (closeSynch) { closeSynch.notifyAll(); while(!closeThreadClosed) { try { closeSynch.wait(); } catch(InterruptedException e) { } } } } public int getValue() { synchronized (connections) { return connections.size(); } } }
true
true
public void send(int code, byte[] dataBytes, String contentType, String location, boolean cacheForAges) throws IllegalArgumentException { try { // Get header StringBuilder header = new StringBuilder(); String codeText; switch(code) { case 200: codeText = "OK"; break; case 302: codeText = "Redirect"; break; case 403: codeText = "Access denied"; break; case 404: codeText = "Not found"; break; case 500: codeText = "Internal server error"; break; default: throw new IllegalArgumentException("Unsupported HTTP code " + code); } header.append("HTTP/1.1 "); header.append(code); header.append(' '); header.append(codeText); header.append(CRLF); header.append("Connection: close"); header.append(CRLF); header.append("Content-Type: "); header.append(contentType); header.append(CRLF); header.append("Content-Length: "); header.append(dataBytes.length); header.append(CRLF); if(location!=null) { header.append("Location: "); header.append(location); header.append(CRLF); } if(cacheForAges) { SimpleDateFormat sdf = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); header.append("Expires: "); header.append(sdf.format(new Date(System.currentTimeMillis() + HOW_LONG_IS_AGES))); header.append(" GMT"); header.append(CRLF); } header.append(CRLF); byte[] headerBytes = header.toString().getBytes("US-ASCII"); // Combine the two ByteBuffer response = ByteBuffer.allocate(dataBytes.length + headerBytes.length); response.put(headerBytes); response.put(dataBytes); response.flip(); // Send data while(true) { try { channel.write(response); } catch(IOException e) { getLogger().log(Logger.SYSTEM_LOG, Logger.Level.NORMAL, "ERROR " + this + " Error writing data"); close(); return; } // Close connection if needed if(!response.hasRemaining()) { close(); return; } // Still some data? OK, wait a bit and try again (yay polling - // but this should hardly ever really happen, because usually // the responses we send are far smaller than network buffers; // exception is usually the statistics page). try { getLogger().log(Logger.SYSTEM_LOG, Logger.Level.NORMAL, "WARNING Event thread blocked for 10ms (this is OK if rare)"); Thread.sleep(10); } catch(InterruptedException ie) { } } } catch(UnsupportedEncodingException e) { throw new Error("Basic encoding not supported?!", e); } }
public void send(int code, byte[] dataBytes, String contentType, String location, boolean cacheForAges) throws IllegalArgumentException { try { // Get header StringBuilder header = new StringBuilder(); String codeText; switch(code) { case 200: codeText = "OK"; break; case 302: codeText = "Redirect"; break; case 403: codeText = "Access denied"; break; case 404: codeText = "Not found"; break; case 500: codeText = "Internal server error"; break; default: throw new IllegalArgumentException("Unsupported HTTP code " + code); } header.append("HTTP/1.1 "); header.append(code); header.append(' '); header.append(codeText); header.append(CRLF); header.append("Connection: close"); header.append(CRLF); header.append("Content-Type: "); header.append(contentType); header.append(CRLF); header.append("Content-Length: "); header.append(dataBytes.length); header.append(CRLF); if(location!=null) { header.append("Location: "); header.append(location); header.append(CRLF); } if(cacheForAges) { SimpleDateFormat sdf = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); header.append("Expires: "); header.append(sdf.format(new Date(System.currentTimeMillis() + HOW_LONG_IS_AGES))); header.append(" GMT"); header.append(CRLF); } header.append(CRLF); byte[] headerBytes = header.toString().getBytes("US-ASCII"); // Combine the two ByteBuffer response = ByteBuffer.allocate(dataBytes.length + headerBytes.length); response.put(headerBytes); response.put(dataBytes); response.flip(); // Send data while(true) { try { channel.write(response); } catch(IOException e) { if(e instanceof ClosedChannelException) { getLogger().log(Logger.SYSTEM_LOG, Logger.Level.NORMAL, "ERROR " + this + " User cancelled request"); } else { getLogger().log(Logger.SYSTEM_LOG, Logger.Level.NORMAL, "ERROR " + this + " Error writing data", e); } close(); return; } // Close connection if needed if(!response.hasRemaining()) { close(); return; } // Still some data? OK, wait a bit and try again (yay polling - // but this should hardly ever really happen, because usually // the responses we send are far smaller than network buffers; // exception is usually the statistics page). try { getLogger().log(Logger.SYSTEM_LOG, Logger.Level.NORMAL, "WARNING Event thread blocked for 10ms (this is OK if rare)"); Thread.sleep(10); } catch(InterruptedException ie) { } } } catch(UnsupportedEncodingException e) { throw new Error("Basic encoding not supported?!", e); } }
diff --git a/src/impl/com/sun/ws/rest/impl/modelapi/validation/BasicValidator.java b/src/impl/com/sun/ws/rest/impl/modelapi/validation/BasicValidator.java index 96131b88..2b2d5968 100644 --- a/src/impl/com/sun/ws/rest/impl/modelapi/validation/BasicValidator.java +++ b/src/impl/com/sun/ws/rest/impl/modelapi/validation/BasicValidator.java @@ -1,90 +1,90 @@ /* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * http://www.opensource.org/licenses/cddl1.php * See the License for the specific language governing * permissions and limitations under the License. */ package com.sun.ws.rest.impl.modelapi.validation; import com.sun.ws.rest.api.core.HttpRequestContext; import com.sun.ws.rest.api.core.HttpResponseContext; import com.sun.ws.rest.api.model.AbstractResource; import com.sun.ws.rest.api.model.AbstractResourceConstructor; import com.sun.ws.rest.api.model.AbstractResourceMethod; import com.sun.ws.rest.api.model.AbstractSubResourceLocator; import com.sun.ws.rest.api.model.AbstractSubResourceMethod; import com.sun.ws.rest.api.model.ResourceModelIssue; import com.sun.ws.rest.impl.ImplMessages; /** * * @author japod */ public class BasicValidator extends AbstractModelValidator { public void visitAbstractResource(AbstractResource resource) { // resource should have at least one resource method, subresource method or subresource locator if ((resource.getResourceMethods().size() + resource.getSubResourceMethods().size() + resource.getSubResourceLocators().size()) == 0) { issueList.add(new ResourceModelIssue( resource, ImplMessages.ERROR_NO_SUB_RES_METHOD_LOCATOR_FOUND(resource.getResourceClass()), - true)); + false)); // there might still be Views associated with the resource } - // uri template of the resource, if present should not contain null or empty value + // uri template of the resource, if present should not contain null value if (resource.isRootResource() && ((null == resource.getUriPath()) || (null == resource.getUriPath().getValue()))) { issueList.add(new ResourceModelIssue( resource, ImplMessages.ERROR_RES_URI_PATH_INVALID(resource.getResourceClass(), resource.getUriPath()), true)); // TODO: is it really a fatal issue? } } public void visitAbstractResourceMethod(AbstractResourceMethod method) { // TODO: check in req/resp case the method has both req and resp params if (!isRequestResponseMethod(method) && ("GET".equals(method.getHttpMethod()) && (void.class == method.getMethod().getReturnType()))) { issueList.add(new ResourceModelIssue( method, ImplMessages.ERROR_GET_RETURNS_VOID(method.getMethod()), true)); } // TODO: anything else ? } public void visitAbstractSubResourceMethod(AbstractSubResourceMethod method) { visitAbstractResourceMethod(method); if ((null == method.getUriPath()) || (null == method.getUriPath().getValue()) || (method.getUriPath().getValue().length() == 0)) { issueList.add(new ResourceModelIssue( method, ImplMessages.ERROR_SUBRES_METHOD_URI_PATH_INVALID(method.getMethod(), method.getUriPath()), true)); } } public void visitAbstractSubResourceLocator(AbstractSubResourceLocator locator) { if (void.class == locator.getMethod().getReturnType()) { issueList.add(new ResourceModelIssue( locator, ImplMessages.ERROR_SUBRES_LOC_RETURNS_VOID(locator.getMethod()), true)); } if ((null == locator.getUriPath()) || (null == locator.getUriPath().getValue()) || (locator.getUriPath().getValue().length() == 0)) { issueList.add(new ResourceModelIssue( locator, ImplMessages.ERROR_SUBRES_LOC_URI_PATH_INVALID(locator.getMethod(), locator.getUriPath()), true)); } } public void visitAbstractResourceConstructor(AbstractResourceConstructor constructor) { } // TODO: the method could probably have more then 2 params... private boolean isRequestResponseMethod(AbstractResourceMethod method) { return (method.getMethod().getParameterTypes().length == 2) && (HttpRequestContext.class == method.getMethod().getParameterTypes()[0]) && (HttpResponseContext.class == method.getMethod().getParameterTypes()[1]); } }
false
true
public void visitAbstractResource(AbstractResource resource) { // resource should have at least one resource method, subresource method or subresource locator if ((resource.getResourceMethods().size() + resource.getSubResourceMethods().size() + resource.getSubResourceLocators().size()) == 0) { issueList.add(new ResourceModelIssue( resource, ImplMessages.ERROR_NO_SUB_RES_METHOD_LOCATOR_FOUND(resource.getResourceClass()), true)); } // uri template of the resource, if present should not contain null or empty value if (resource.isRootResource() && ((null == resource.getUriPath()) || (null == resource.getUriPath().getValue()))) { issueList.add(new ResourceModelIssue( resource, ImplMessages.ERROR_RES_URI_PATH_INVALID(resource.getResourceClass(), resource.getUriPath()), true)); // TODO: is it really a fatal issue? } }
public void visitAbstractResource(AbstractResource resource) { // resource should have at least one resource method, subresource method or subresource locator if ((resource.getResourceMethods().size() + resource.getSubResourceMethods().size() + resource.getSubResourceLocators().size()) == 0) { issueList.add(new ResourceModelIssue( resource, ImplMessages.ERROR_NO_SUB_RES_METHOD_LOCATOR_FOUND(resource.getResourceClass()), false)); // there might still be Views associated with the resource } // uri template of the resource, if present should not contain null value if (resource.isRootResource() && ((null == resource.getUriPath()) || (null == resource.getUriPath().getValue()))) { issueList.add(new ResourceModelIssue( resource, ImplMessages.ERROR_RES_URI_PATH_INVALID(resource.getResourceClass(), resource.getUriPath()), true)); // TODO: is it really a fatal issue? } }
diff --git a/optaplanner-core/src/main/java/org/optaplanner/core/config/score/director/ScoreDirectorFactoryConfig.java b/optaplanner-core/src/main/java/org/optaplanner/core/config/score/director/ScoreDirectorFactoryConfig.java index e28ca7861..7a941dc1f 100644 --- a/optaplanner-core/src/main/java/org/optaplanner/core/config/score/director/ScoreDirectorFactoryConfig.java +++ b/optaplanner-core/src/main/java/org/optaplanner/core/config/score/director/ScoreDirectorFactoryConfig.java @@ -1,395 +1,396 @@ /* * Copyright 2010 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.optaplanner.core.config.score.director; import java.io.InputStream; import java.util.List; import java.util.Map; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamConverter; import com.thoughtworks.xstream.annotations.XStreamImplicit; import com.thoughtworks.xstream.annotations.XStreamOmitField; import org.apache.commons.collections.CollectionUtils; import org.kie.api.KieBase; import org.kie.api.KieBaseConfiguration; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; import org.kie.api.builder.Message; import org.kie.api.builder.Results; import org.kie.api.io.KieResources; import org.kie.api.runtime.KieContainer; import org.kie.internal.builder.conf.RuleEngineOption; import org.optaplanner.core.config.solver.EnvironmentMode; import org.optaplanner.core.config.util.ConfigUtils; import org.optaplanner.core.config.util.KeyAsElementMapConverter; import org.optaplanner.core.impl.domain.solution.descriptor.SolutionDescriptor; import org.optaplanner.core.impl.score.buildin.bendable.BendableScoreDefinition; import org.optaplanner.core.impl.score.buildin.hardmediumsoft.HardMediumSoftScoreDefinition; import org.optaplanner.core.impl.score.buildin.hardmediumsoftlong.HardMediumSoftLongScoreDefinition; import org.optaplanner.core.impl.score.buildin.hardsoft.HardSoftScoreDefinition; import org.optaplanner.core.impl.score.buildin.hardsoftbigdecimal.HardSoftBigDecimalScoreDefinition; import org.optaplanner.core.impl.score.buildin.hardsoftdouble.HardSoftDoubleScoreDefinition; import org.optaplanner.core.impl.score.buildin.hardsoftlong.HardSoftLongScoreDefinition; import org.optaplanner.core.impl.score.buildin.simple.SimpleScoreDefinition; import org.optaplanner.core.impl.score.buildin.simplebigdecimal.SimpleBigDecimalScoreDefinition; import org.optaplanner.core.impl.score.buildin.simpledouble.SimpleDoubleScoreDefinition; import org.optaplanner.core.impl.score.buildin.simplelong.SimpleLongScoreDefinition; import org.optaplanner.core.impl.score.definition.ScoreDefinition; import org.optaplanner.core.impl.score.director.AbstractScoreDirectorFactory; import org.optaplanner.core.impl.score.director.ScoreDirectorFactory; import org.optaplanner.core.impl.score.director.drools.DroolsScoreDirectorFactory; import org.optaplanner.core.impl.score.director.incremental.IncrementalScoreCalculator; import org.optaplanner.core.impl.score.director.incremental.IncrementalScoreDirectorFactory; import org.optaplanner.core.impl.score.director.simple.SimpleScoreCalculator; import org.optaplanner.core.impl.score.director.simple.SimpleScoreDirectorFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @XStreamAlias("scoreDirectorFactory") public class ScoreDirectorFactoryConfig { protected final transient Logger logger = LoggerFactory.getLogger(getClass()); protected Class<? extends ScoreDefinition> scoreDefinitionClass = null; protected ScoreDefinitionType scoreDefinitionType = null; protected Integer bendableHardLevelCount = null; protected Integer bendableSoftLevelCount = null; protected Class<? extends SimpleScoreCalculator> simpleScoreCalculatorClass = null; protected Class<? extends IncrementalScoreCalculator> incrementalScoreCalculatorClass = null; @XStreamOmitField protected KieBase kieBase = null; @XStreamImplicit(itemFieldName = "scoreDrl") protected List<String> scoreDrlList = null; @XStreamConverter(value = KeyAsElementMapConverter.class) protected Map<String, String> kieBaseConfigurationProperties = null; @XStreamAlias("assertionScoreDirectorFactory") protected ScoreDirectorFactoryConfig assertionScoreDirectorFactory = null; public Class<? extends ScoreDefinition> getScoreDefinitionClass() { return scoreDefinitionClass; } public void setScoreDefinitionClass(Class<? extends ScoreDefinition> scoreDefinitionClass) { this.scoreDefinitionClass = scoreDefinitionClass; } public ScoreDefinitionType getScoreDefinitionType() { return scoreDefinitionType; } public void setScoreDefinitionType(ScoreDefinitionType scoreDefinitionType) { this.scoreDefinitionType = scoreDefinitionType; } public Integer getBendableHardLevelCount() { return bendableHardLevelCount; } public void setBendableHardLevelCount(Integer bendableHardLevelCount) { this.bendableHardLevelCount = bendableHardLevelCount; } public Integer getBendableSoftLevelCount() { return bendableSoftLevelCount; } public void setBendableSoftLevelCount(Integer bendableSoftLevelCount) { this.bendableSoftLevelCount = bendableSoftLevelCount; } public Class<? extends SimpleScoreCalculator> getSimpleScoreCalculatorClass() { return simpleScoreCalculatorClass; } public void setSimpleScoreCalculatorClass(Class<? extends SimpleScoreCalculator> simpleScoreCalculatorClass) { this.simpleScoreCalculatorClass = simpleScoreCalculatorClass; } public Class<? extends IncrementalScoreCalculator> getIncrementalScoreCalculatorClass() { return incrementalScoreCalculatorClass; } public void setIncrementalScoreCalculatorClass(Class<? extends IncrementalScoreCalculator> incrementalScoreCalculatorClass) { this.incrementalScoreCalculatorClass = incrementalScoreCalculatorClass; } public KieBase getKieBase() { return kieBase; } public void setKieBase(KieBase kieBase) { this.kieBase = kieBase; } public List<String> getScoreDrlList() { return scoreDrlList; } public void setScoreDrlList(List<String> scoreDrlList) { this.scoreDrlList = scoreDrlList; } public Map<String, String> getKieBaseConfigurationProperties() { return kieBaseConfigurationProperties; } public void setKieBaseConfigurationProperties(Map<String, String> kieBaseConfigurationProperties) { this.kieBaseConfigurationProperties = kieBaseConfigurationProperties; } public ScoreDirectorFactoryConfig getAssertionScoreDirectorFactory() { return assertionScoreDirectorFactory; } public void setAssertionScoreDirectorFactory(ScoreDirectorFactoryConfig assertionScoreDirectorFactory) { this.assertionScoreDirectorFactory = assertionScoreDirectorFactory; } // ************************************************************************ // Builder methods // ************************************************************************ public ScoreDirectorFactory buildScoreDirectorFactory(EnvironmentMode environmentMode, SolutionDescriptor solutionDescriptor) { ScoreDefinition scoreDefinition = buildScoreDefinition(); return buildScoreDirectorFactory(environmentMode, solutionDescriptor, scoreDefinition); } protected ScoreDirectorFactory buildScoreDirectorFactory(EnvironmentMode environmentMode, SolutionDescriptor solutionDescriptor, ScoreDefinition scoreDefinition) { AbstractScoreDirectorFactory scoreDirectorFactory; // TODO this should fail-fast if multiple scoreDirectorFactory's are configured or if none are configured scoreDirectorFactory = buildSimpleScoreDirectorFactory(); if (scoreDirectorFactory == null) { scoreDirectorFactory = buildIncrementalScoreDirectorFactory(); } if (scoreDirectorFactory == null) { scoreDirectorFactory = buildDroolsScoreDirectorFactory(); } scoreDirectorFactory.setSolutionDescriptor(solutionDescriptor); scoreDirectorFactory.setScoreDefinition(scoreDefinition); if (assertionScoreDirectorFactory != null) { if (assertionScoreDirectorFactory.getAssertionScoreDirectorFactory() != null) { throw new IllegalArgumentException("A assertionScoreDirectorFactory (" + assertionScoreDirectorFactory + ") cannot have a non-null assertionScoreDirectorFactory (" + assertionScoreDirectorFactory.getAssertionScoreDirectorFactory() + ")."); } if (assertionScoreDirectorFactory.getScoreDefinitionClass() != null || assertionScoreDirectorFactory.getScoreDefinitionType() != null) { throw new IllegalArgumentException("A assertionScoreDirectorFactory (" + assertionScoreDirectorFactory + ") must reuse the scoreDefinition of its parent." + " It cannot have a non-null scoreDefinition* property."); } if (environmentMode.compareTo(EnvironmentMode.FAST_ASSERT) > 0) { throw new IllegalArgumentException("A non-null assertionScoreDirectorFactory (" + assertionScoreDirectorFactory + ") requires an environmentMode (" + environmentMode + ") of " + EnvironmentMode.FAST_ASSERT + " or lower."); } scoreDirectorFactory.setAssertionScoreDirectorFactory( assertionScoreDirectorFactory.buildScoreDirectorFactory( EnvironmentMode.PRODUCTION, solutionDescriptor, scoreDefinition)); } return scoreDirectorFactory; } public ScoreDefinition buildScoreDefinition() { if ((bendableHardLevelCount != null || bendableSoftLevelCount != null) && scoreDefinitionType != ScoreDefinitionType.BENDABLE) { throw new IllegalArgumentException("With scoreDefinitionType (" + scoreDefinitionType + ") there must be no bendableHardLevelCount (" + bendableHardLevelCount + ") or bendableSoftLevelCount (" + bendableSoftLevelCount + ")."); } if (scoreDefinitionClass != null) { return ConfigUtils.newInstance(this, "scoreDefinitionClass", scoreDefinitionClass); } else if (scoreDefinitionType != null) { switch (scoreDefinitionType) { case SIMPLE: return new SimpleScoreDefinition(); case SIMPLE_LONG: return new SimpleLongScoreDefinition(); case SIMPLE_DOUBLE: return new SimpleDoubleScoreDefinition(); case SIMPLE_BIG_DECIMAL: return new SimpleBigDecimalScoreDefinition(); case HARD_SOFT: return new HardSoftScoreDefinition(); case HARD_SOFT_LONG: return new HardSoftLongScoreDefinition(); case HARD_SOFT_DOUBLE: return new HardSoftDoubleScoreDefinition(); case HARD_SOFT_BIG_DECIMAL: return new HardSoftBigDecimalScoreDefinition(); case HARD_MEDIUM_SOFT: return new HardMediumSoftScoreDefinition(); case HARD_MEDIUM_SOFT_LONG: return new HardMediumSoftLongScoreDefinition(); case BENDABLE: if (bendableHardLevelCount == null || bendableSoftLevelCount == null) { throw new IllegalArgumentException("With scoreDefinitionType (" + scoreDefinitionType + ") there must be a bendableHardLevelCount (" + bendableHardLevelCount + ") and a bendableSoftLevelCount (" + bendableSoftLevelCount + ")."); } return new BendableScoreDefinition(bendableHardLevelCount, bendableSoftLevelCount); default: throw new IllegalStateException("The scoreDefinitionType (" + scoreDefinitionType + ") is not implemented."); } } else { return new SimpleScoreDefinition(); } } private AbstractScoreDirectorFactory buildSimpleScoreDirectorFactory() { if (simpleScoreCalculatorClass != null) { SimpleScoreCalculator simpleScoreCalculator = ConfigUtils.newInstance(this, "simpleScoreCalculatorClass", simpleScoreCalculatorClass); return new SimpleScoreDirectorFactory(simpleScoreCalculator); } else { return null; } } private AbstractScoreDirectorFactory buildIncrementalScoreDirectorFactory() { if (incrementalScoreCalculatorClass != null) { return new IncrementalScoreDirectorFactory(incrementalScoreCalculatorClass); } else { return null; } } private AbstractScoreDirectorFactory buildDroolsScoreDirectorFactory() { DroolsScoreDirectorFactory scoreDirectorFactory = new DroolsScoreDirectorFactory(); scoreDirectorFactory.setKieBase(buildKieBase()); return scoreDirectorFactory; } private KieBase buildKieBase() { if (kieBase != null) { if (!CollectionUtils.isEmpty(scoreDrlList)) { throw new IllegalArgumentException("If kieBase is not null, the scoreDrlList (" + scoreDrlList + ") must be empty."); } if (kieBaseConfigurationProperties != null) { throw new IllegalArgumentException("If kieBase is not null, the kieBaseConfigurationProperties (" + kieBaseConfigurationProperties + ") must be null."); } return kieBase; } else { if (CollectionUtils.isEmpty(scoreDrlList)) { throw new IllegalArgumentException("The scoreDrlList (" + scoreDrlList + ") cannot be empty."); } KieServices kieServices = KieServices.Factory.get(); KieResources kieResources = kieServices.getResources(); KieFileSystem kieFileSystem = kieServices.newKieFileSystem(); for (String scoreDrl : scoreDrlList) { InputStream scoreDrlIn = getClass().getResourceAsStream(scoreDrl); if (scoreDrlIn == null) { throw new IllegalArgumentException("The scoreDrl (" + scoreDrl - + ") does not exist as a classpath resource."); + + ") does not exist as a classpath resource." + + "Note that nor a file, nor a URL, nor a webapp resource are a valid classpath resource."); } String path = "src/main/resources/optaplanner-kie-namespace/" + scoreDrl; kieFileSystem.write(path, kieResources.newInputStreamResource(scoreDrlIn, "UTF-8")); // TODO use getResource() and newClassPathResource() instead // URL scoreDrlURL = getClass().getResource(scoreDrl); // if (scoreDrlURL == null) { // throw new IllegalArgumentException("The scoreDrl (" + scoreDrl // + ") does not exist as a classpath resource."); // } // kieFileSystem.write(kieResources.newClassPathResource(scoreDrl, "UTF-8")); } KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem); kieBuilder.buildAll(); Results results = kieBuilder.getResults(); if (results.hasMessages(Message.Level.ERROR)) { throw new IllegalStateException("There are errors in the scoreDrl's:\n" + results.toString()); } else if (results.hasMessages(Message.Level.WARNING)) { logger.warn("There are warning in the scoreDrl's:\n" + results.toString()); } KieContainer kieContainer = kieServices.newKieContainer(kieBuilder.getKieModule().getReleaseId()); KieBaseConfiguration kieBaseConfiguration = kieServices.newKieBaseConfiguration(); if (kieBaseConfigurationProperties != null) { for (Map.Entry<String, String> entry : kieBaseConfigurationProperties.entrySet()) { kieBaseConfiguration.setProperty(entry.getKey(), entry.getValue()); } } // TODO remove this line once Phreak is the default kieBaseConfiguration.setOption(RuleEngineOption.PHREAK); KieBase kieBase = kieContainer.newKieBase(kieBaseConfiguration); return kieBase; } } public void inherit(ScoreDirectorFactoryConfig inheritedConfig) { if (scoreDefinitionClass == null && scoreDefinitionType == null && bendableHardLevelCount == null && bendableSoftLevelCount == null) { scoreDefinitionClass = inheritedConfig.getScoreDefinitionClass(); scoreDefinitionType = inheritedConfig.getScoreDefinitionType(); bendableHardLevelCount = inheritedConfig.getBendableHardLevelCount(); bendableSoftLevelCount = inheritedConfig.getBendableSoftLevelCount(); } if (simpleScoreCalculatorClass == null) { simpleScoreCalculatorClass = inheritedConfig.getSimpleScoreCalculatorClass(); } if (incrementalScoreCalculatorClass == null) { incrementalScoreCalculatorClass = inheritedConfig.getIncrementalScoreCalculatorClass(); } if (kieBase == null) { kieBase = inheritedConfig.getKieBase(); } scoreDrlList = ConfigUtils.inheritMergeableListProperty( scoreDrlList, inheritedConfig.getScoreDrlList()); kieBaseConfigurationProperties = ConfigUtils.inheritMergeableMapProperty( kieBaseConfigurationProperties, inheritedConfig.getKieBaseConfigurationProperties()); if (assertionScoreDirectorFactory == null) { assertionScoreDirectorFactory = inheritedConfig.getAssertionScoreDirectorFactory(); } } public static enum ScoreDefinitionType { SIMPLE, SIMPLE_LONG, /** * WARNING: NOT RECOMMENDED TO USE DUE TO ROUNDING ERRORS THAT CAUSE SCORE CORRUPTION. * Use {@link #SIMPLE_BIG_DECIMAL} instead. */ SIMPLE_DOUBLE, SIMPLE_BIG_DECIMAL, HARD_SOFT, HARD_SOFT_LONG, /** * WARNING: NOT RECOMMENDED TO USE DUE TO ROUNDING ERRORS THAT CAUSE SCORE CORRUPTION. * Use {@link #HARD_SOFT_BIG_DECIMAL} instead. */ HARD_SOFT_DOUBLE, HARD_SOFT_BIG_DECIMAL, HARD_MEDIUM_SOFT, HARD_MEDIUM_SOFT_LONG, BENDABLE, } }
true
true
private KieBase buildKieBase() { if (kieBase != null) { if (!CollectionUtils.isEmpty(scoreDrlList)) { throw new IllegalArgumentException("If kieBase is not null, the scoreDrlList (" + scoreDrlList + ") must be empty."); } if (kieBaseConfigurationProperties != null) { throw new IllegalArgumentException("If kieBase is not null, the kieBaseConfigurationProperties (" + kieBaseConfigurationProperties + ") must be null."); } return kieBase; } else { if (CollectionUtils.isEmpty(scoreDrlList)) { throw new IllegalArgumentException("The scoreDrlList (" + scoreDrlList + ") cannot be empty."); } KieServices kieServices = KieServices.Factory.get(); KieResources kieResources = kieServices.getResources(); KieFileSystem kieFileSystem = kieServices.newKieFileSystem(); for (String scoreDrl : scoreDrlList) { InputStream scoreDrlIn = getClass().getResourceAsStream(scoreDrl); if (scoreDrlIn == null) { throw new IllegalArgumentException("The scoreDrl (" + scoreDrl + ") does not exist as a classpath resource."); } String path = "src/main/resources/optaplanner-kie-namespace/" + scoreDrl; kieFileSystem.write(path, kieResources.newInputStreamResource(scoreDrlIn, "UTF-8")); // TODO use getResource() and newClassPathResource() instead // URL scoreDrlURL = getClass().getResource(scoreDrl); // if (scoreDrlURL == null) { // throw new IllegalArgumentException("The scoreDrl (" + scoreDrl // + ") does not exist as a classpath resource."); // } // kieFileSystem.write(kieResources.newClassPathResource(scoreDrl, "UTF-8")); } KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem); kieBuilder.buildAll(); Results results = kieBuilder.getResults(); if (results.hasMessages(Message.Level.ERROR)) { throw new IllegalStateException("There are errors in the scoreDrl's:\n" + results.toString()); } else if (results.hasMessages(Message.Level.WARNING)) { logger.warn("There are warning in the scoreDrl's:\n" + results.toString()); } KieContainer kieContainer = kieServices.newKieContainer(kieBuilder.getKieModule().getReleaseId()); KieBaseConfiguration kieBaseConfiguration = kieServices.newKieBaseConfiguration(); if (kieBaseConfigurationProperties != null) { for (Map.Entry<String, String> entry : kieBaseConfigurationProperties.entrySet()) { kieBaseConfiguration.setProperty(entry.getKey(), entry.getValue()); } } // TODO remove this line once Phreak is the default kieBaseConfiguration.setOption(RuleEngineOption.PHREAK); KieBase kieBase = kieContainer.newKieBase(kieBaseConfiguration); return kieBase; } }
private KieBase buildKieBase() { if (kieBase != null) { if (!CollectionUtils.isEmpty(scoreDrlList)) { throw new IllegalArgumentException("If kieBase is not null, the scoreDrlList (" + scoreDrlList + ") must be empty."); } if (kieBaseConfigurationProperties != null) { throw new IllegalArgumentException("If kieBase is not null, the kieBaseConfigurationProperties (" + kieBaseConfigurationProperties + ") must be null."); } return kieBase; } else { if (CollectionUtils.isEmpty(scoreDrlList)) { throw new IllegalArgumentException("The scoreDrlList (" + scoreDrlList + ") cannot be empty."); } KieServices kieServices = KieServices.Factory.get(); KieResources kieResources = kieServices.getResources(); KieFileSystem kieFileSystem = kieServices.newKieFileSystem(); for (String scoreDrl : scoreDrlList) { InputStream scoreDrlIn = getClass().getResourceAsStream(scoreDrl); if (scoreDrlIn == null) { throw new IllegalArgumentException("The scoreDrl (" + scoreDrl + ") does not exist as a classpath resource." + "Note that nor a file, nor a URL, nor a webapp resource are a valid classpath resource."); } String path = "src/main/resources/optaplanner-kie-namespace/" + scoreDrl; kieFileSystem.write(path, kieResources.newInputStreamResource(scoreDrlIn, "UTF-8")); // TODO use getResource() and newClassPathResource() instead // URL scoreDrlURL = getClass().getResource(scoreDrl); // if (scoreDrlURL == null) { // throw new IllegalArgumentException("The scoreDrl (" + scoreDrl // + ") does not exist as a classpath resource."); // } // kieFileSystem.write(kieResources.newClassPathResource(scoreDrl, "UTF-8")); } KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem); kieBuilder.buildAll(); Results results = kieBuilder.getResults(); if (results.hasMessages(Message.Level.ERROR)) { throw new IllegalStateException("There are errors in the scoreDrl's:\n" + results.toString()); } else if (results.hasMessages(Message.Level.WARNING)) { logger.warn("There are warning in the scoreDrl's:\n" + results.toString()); } KieContainer kieContainer = kieServices.newKieContainer(kieBuilder.getKieModule().getReleaseId()); KieBaseConfiguration kieBaseConfiguration = kieServices.newKieBaseConfiguration(); if (kieBaseConfigurationProperties != null) { for (Map.Entry<String, String> entry : kieBaseConfigurationProperties.entrySet()) { kieBaseConfiguration.setProperty(entry.getKey(), entry.getValue()); } } // TODO remove this line once Phreak is the default kieBaseConfiguration.setOption(RuleEngineOption.PHREAK); KieBase kieBase = kieContainer.newKieBase(kieBaseConfiguration); return kieBase; } }
diff --git a/plugins/org.bigraph.model/src/org/bigraph/model/loaders/XMLLoader.java b/plugins/org.bigraph.model/src/org/bigraph/model/loaders/XMLLoader.java index 1260dc21..3bd0d42e 100644 --- a/plugins/org.bigraph.model/src/org/bigraph/model/loaders/XMLLoader.java +++ b/plugins/org.bigraph.model/src/org/bigraph/model/loaders/XMLLoader.java @@ -1,272 +1,274 @@ package org.bigraph.model.loaders; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.dom.DOMSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import org.bigraph.model.ModelObject; import org.bigraph.model.changes.IChangeExecutor; import org.bigraph.model.loaders.internal.SchemaResolver; import org.bigraph.model.resources.IFileWrapper; import org.bigraph.model.resources.IOpenable; import org.bigraph.model.resources.IResourceWrapper; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.SAXException; public abstract class XMLLoader extends ChangeLoader implements IXMLLoader { public XMLLoader() { } public XMLLoader(Loader parent) { super(parent); if (parent instanceof XMLLoader) addNewUndecorators(((XMLLoader)parent).getUndecorators()); } private static final SchemaFactory sf; private static final DocumentBuilderFactory dbf; private static final DocumentBuilder db; static { sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); sf.setResourceResolver(SchemaResolver.getInstance()); dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db_ = null; try { db_ = dbf.newDocumentBuilder(); } catch (ParserConfigurationException pce) { /* do nothing */ } db = db_; } public static SchemaFactory getSharedSchemaFactory() { return sf; } public static DocumentBuilder getSharedDocumentBuilder() { return db; } public static void registerSchema(String namespaceURI, IOpenable of) { SchemaResolver.getInstance().registerSchema(namespaceURI, of); } public static void unregisterSchema(String namespaceURI) { SchemaResolver.getInstance().unregisterSchema(namespaceURI); } public static String getAttributeNS(Element d, String nsURI, String n) { String r = d.getAttributeNS(nsURI, n); if (r.length() == 0 && d.getNamespaceURI().equals(nsURI)) r = d.getAttributeNS(null, n); return (r.length() != 0 ? r : null); } public static int getIntAttribute(Element d, String nsURI, String n) { try { return Integer.parseInt(getAttributeNS(d, nsURI, n)); } catch (Exception e) { return 0; } } public static double getDoubleAttribute( Element d, String nsURI, String n) { try { return Double.parseDouble(getAttributeNS(d, nsURI, n)); } catch (Exception e) { return 0; } } protected static <T extends Node> T validate(T d, Schema schema) throws LoadFailedException { try { schema.newValidator().validate(new DOMSource(d)); return d; } catch (SAXException e) { throw new LoadFailedException(e); } catch (IOException e) { throw new LoadFailedException(e); } } /** * Attempts to parse the specified {@link InputStream} into a DOM {@link * Document}. * @param is an InputStream, which will be closed &mdash; even in the * event of an exception * @return a Document * @throws SAXException as {@link DocumentBuilder#parse(File)} * @throws IOException as {@link DocumentBuilder#parse(File)} or * {@link InputStream#close} */ protected static Document parse(InputStream is) throws SAXException, IOException { try { return getSharedDocumentBuilder().parse(is); } finally { is.close(); } } /** * Returns all the child {@link Node}s of the specified {@link Element} * which are themselves {@link Element}s. * @param e an Element containing children * @return a list of child {@link Element}s */ public static List<Element> getChildElements(Element e) { ArrayList<Element> children = new ArrayList<Element>(); int length = e.getChildNodes().getLength(); for (int h = 0; h < length; h++) { Node i = e.getChildNodes().item(h); if (i instanceof Element) children.add((Element)i); } return children; } /** * Gets all the children of the specified element with the given name and * namespace. * (Note that this method only searches immediate children.) * @param d an Element containing children * @param nsURI the namespace to search in * @param n the tag name to search for * @return an ArrayList of child elements */ protected static ArrayList<Element> getNamedChildElements( Element d, String ns, String n) { ArrayList<Element> r = new ArrayList<Element>(); for (Element t : getChildElements(d)) if (t.getNamespaceURI().equals(ns) && t.getLocalName().equals(n)) r.add(t); return r; } /** * Returns the unique child of the specified Element which has the given * tag name. * @param d an Element containing children * @param n the tag name to search for * @return the unique named child, or <code>null</code> if there were zero * or more than one matches * @see XMLLoader#getNamedChildElements */ protected static Element getNamedChildElement( Element d, String nsURI, String n) { ArrayList<Element> r = getNamedChildElements(d, nsURI, n); if (r.size() == 1) return r.get(0); else return null; } protected <T extends ModelObject> T loadRelative(String replacement, Class<? extends T> klass, XMLLoader loader) throws LoadFailedException { if (replacement != null) { if (getFile() == null) throw new Error("BUG: relative path to resolve, " + "but no IFileWrapper set on " + this); IResourceWrapper rw = getFile().getParent().getResource(replacement); if (rw instanceof IFileWrapper) { IFileWrapper fw = (IFileWrapper)rw; loader.setFile(fw).setInputStream(fw.getContents()); ModelObject mo = loader.importObject(); if (klass.isInstance(mo)) { return klass.cast(mo); } else throw new LoadFailedException( - "Referenced document is not of the correct type"); + "Referenced document \"" + replacement + + "\" is not of the correct type"); } else throw new LoadFailedException( - "Referenced document is not valid"); + "Referenced document \"" + replacement + + "\" is not valid"); } else return null; } protected abstract ModelObject makeObject(Element el) throws LoadFailedException; protected static <T> T selectFirst(T... objects) { for (T i : objects) if (i != null) return i; return null; } protected <T extends ModelObject> T loadSub( Element el, String myNS, Class<T> klass, XMLLoader loader) throws LoadFailedException { if (el == null) return null; String src = getAttributeNS(el, myNS, "src"), theirNS = el.getNamespaceURI(); /* If this element is foreign, or if it doesn't have a src attribute, * then let the loader do everything */ if (!(myNS != null ? myNS.equals(theirNS) : theirNS == null) || src == null) { try { return klass.cast(loader.makeObject(el)); } catch (ClassCastException cce) { throw new LoadFailedException(cce); } /* Otherwise, interpret the src attribute (which can't be null) */ } else return loadRelative(src, klass, loader); } private List<IXMLUndecorator> undecorators = null; protected List<IXMLUndecorator> getUndecorators() { return (undecorators != null ? undecorators : Collections.<IXMLUndecorator>emptyList()); } public void addUndecorator(IXMLUndecorator one) { if (one == null) return; if (undecorators == null) undecorators = new ArrayList<IXMLUndecorator>(); undecorators.add(one); one.setLoader(this); } public XMLLoader addNewUndecorators( Collection<? extends IXMLUndecorator> many) { if (many != null) for (IXMLUndecorator i : many) addUndecorator(i.newInstance()); return this; } protected <T extends ModelObject> T executeUndecorators(T mo, Element el) { if (mo != null && el != null) for (IXMLUndecorator d : getUndecorators()) d.undecorate(mo, el); return mo; } @Override protected void executeChanges(IChangeExecutor ex) throws LoadFailedException { for (IXMLUndecorator d : getUndecorators()) d.finish(ex); super.executeChanges(ex); } }
false
true
protected <T extends ModelObject> T loadRelative(String replacement, Class<? extends T> klass, XMLLoader loader) throws LoadFailedException { if (replacement != null) { if (getFile() == null) throw new Error("BUG: relative path to resolve, " + "but no IFileWrapper set on " + this); IResourceWrapper rw = getFile().getParent().getResource(replacement); if (rw instanceof IFileWrapper) { IFileWrapper fw = (IFileWrapper)rw; loader.setFile(fw).setInputStream(fw.getContents()); ModelObject mo = loader.importObject(); if (klass.isInstance(mo)) { return klass.cast(mo); } else throw new LoadFailedException( "Referenced document is not of the correct type"); } else throw new LoadFailedException( "Referenced document is not valid"); } else return null; }
protected <T extends ModelObject> T loadRelative(String replacement, Class<? extends T> klass, XMLLoader loader) throws LoadFailedException { if (replacement != null) { if (getFile() == null) throw new Error("BUG: relative path to resolve, " + "but no IFileWrapper set on " + this); IResourceWrapper rw = getFile().getParent().getResource(replacement); if (rw instanceof IFileWrapper) { IFileWrapper fw = (IFileWrapper)rw; loader.setFile(fw).setInputStream(fw.getContents()); ModelObject mo = loader.importObject(); if (klass.isInstance(mo)) { return klass.cast(mo); } else throw new LoadFailedException( "Referenced document \"" + replacement + "\" is not of the correct type"); } else throw new LoadFailedException( "Referenced document \"" + replacement + "\" is not valid"); } else return null; }
diff --git a/src/test/acceptanceTest/java/GreeterTest.java b/src/test/acceptanceTest/java/GreeterTest.java index 5b493cc..51e59c4 100644 --- a/src/test/acceptanceTest/java/GreeterTest.java +++ b/src/test/acceptanceTest/java/GreeterTest.java @@ -1,12 +1,12 @@ import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class GreeterTest { @Test public void says_hello_to_the_world() { Greeter greeter = new Greeter(); - assertThat("", is("a")); + assertThat("", is("")); } }
true
true
public void says_hello_to_the_world() { Greeter greeter = new Greeter(); assertThat("", is("a")); }
public void says_hello_to_the_world() { Greeter greeter = new Greeter(); assertThat("", is("")); }
diff --git a/src/keepcalm/mods/bukkit/forgeHandler/BukkitCraftingHandler.java b/src/keepcalm/mods/bukkit/forgeHandler/BukkitCraftingHandler.java index b5574e4..4d1243f 100644 --- a/src/keepcalm/mods/bukkit/forgeHandler/BukkitCraftingHandler.java +++ b/src/keepcalm/mods/bukkit/forgeHandler/BukkitCraftingHandler.java @@ -1,78 +1,80 @@ package keepcalm.mods.bukkit.forgeHandler; import java.util.Iterator; import keepcalm.mods.bukkit.BukkitContainer; import keepcalm.mods.bukkit.bukkitAPI.entity.BukkitPlayer; import keepcalm.mods.bukkit.bukkitAPI.inventory.BukkitInventoryCrafting; import keepcalm.mods.bukkit.bukkitAPI.inventory.BukkitInventoryView; import keepcalm.mods.bukkit.bukkitAPI.inventory.BukkitRecipe; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.ContainerWorkbench; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryCraftResult; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.item.crafting.IRecipe; import org.bukkit.Bukkit; import org.bukkit.event.inventory.CraftItemEvent; import org.bukkit.event.inventory.InventoryType.SlotType; import org.bukkit.inventory.InventoryView; import org.bukkit.inventory.Recipe; import cpw.mods.fml.common.ICraftingHandler; // TODO public class BukkitCraftingHandler implements ICraftingHandler { @Override public void onCrafting(EntityPlayer player, ItemStack item, IInventory craftMatrix) { if (craftMatrix instanceof InventoryCrafting) { EntityPlayerMP fp; if (player instanceof EntityPlayerMP) fp = (EntityPlayerMP) player; else fp = BukkitContainer.MOD_PLAYER; InventoryCrafting inv = (InventoryCrafting) craftMatrix; Iterator<IRecipe> irec = (Iterator<IRecipe>) CraftingManager.getInstance().recipes.iterator(); IRecipe targ = null; while (irec.hasNext()) { IRecipe r = irec.next(); if (r.matches(inv, player.worldObj)) { targ = r; break; } } if (targ == null) return; Recipe recipe = new BukkitRecipe(targ); InventoryView what = new BukkitInventoryView(new BukkitPlayer(fp), new BukkitInventoryCrafting(inv, player.inventory), inv.eventHandler); CraftItemEvent ev = new CraftItemEvent(recipe, what, SlotType.CRAFTING, -1, false, false); Bukkit.getPluginManager().callEvent(ev); if (ev.isCancelled()) { + // failure! + if (!(inv.eventHandler instanceof ContainerWorkbench)) return; ContainerWorkbench cc = (ContainerWorkbench) inv.eventHandler; InventoryCraftResult iv = (InventoryCraftResult) cc.craftResult; iv.setInventorySlotContents(0, null); } } } @Override public void onSmelting(EntityPlayer player, ItemStack item) { } }
true
true
public void onCrafting(EntityPlayer player, ItemStack item, IInventory craftMatrix) { if (craftMatrix instanceof InventoryCrafting) { EntityPlayerMP fp; if (player instanceof EntityPlayerMP) fp = (EntityPlayerMP) player; else fp = BukkitContainer.MOD_PLAYER; InventoryCrafting inv = (InventoryCrafting) craftMatrix; Iterator<IRecipe> irec = (Iterator<IRecipe>) CraftingManager.getInstance().recipes.iterator(); IRecipe targ = null; while (irec.hasNext()) { IRecipe r = irec.next(); if (r.matches(inv, player.worldObj)) { targ = r; break; } } if (targ == null) return; Recipe recipe = new BukkitRecipe(targ); InventoryView what = new BukkitInventoryView(new BukkitPlayer(fp), new BukkitInventoryCrafting(inv, player.inventory), inv.eventHandler); CraftItemEvent ev = new CraftItemEvent(recipe, what, SlotType.CRAFTING, -1, false, false); Bukkit.getPluginManager().callEvent(ev); if (ev.isCancelled()) { ContainerWorkbench cc = (ContainerWorkbench) inv.eventHandler; InventoryCraftResult iv = (InventoryCraftResult) cc.craftResult; iv.setInventorySlotContents(0, null); } } }
public void onCrafting(EntityPlayer player, ItemStack item, IInventory craftMatrix) { if (craftMatrix instanceof InventoryCrafting) { EntityPlayerMP fp; if (player instanceof EntityPlayerMP) fp = (EntityPlayerMP) player; else fp = BukkitContainer.MOD_PLAYER; InventoryCrafting inv = (InventoryCrafting) craftMatrix; Iterator<IRecipe> irec = (Iterator<IRecipe>) CraftingManager.getInstance().recipes.iterator(); IRecipe targ = null; while (irec.hasNext()) { IRecipe r = irec.next(); if (r.matches(inv, player.worldObj)) { targ = r; break; } } if (targ == null) return; Recipe recipe = new BukkitRecipe(targ); InventoryView what = new BukkitInventoryView(new BukkitPlayer(fp), new BukkitInventoryCrafting(inv, player.inventory), inv.eventHandler); CraftItemEvent ev = new CraftItemEvent(recipe, what, SlotType.CRAFTING, -1, false, false); Bukkit.getPluginManager().callEvent(ev); if (ev.isCancelled()) { // failure! if (!(inv.eventHandler instanceof ContainerWorkbench)) return; ContainerWorkbench cc = (ContainerWorkbench) inv.eventHandler; InventoryCraftResult iv = (InventoryCraftResult) cc.craftResult; iv.setInventorySlotContents(0, null); } } }
diff --git a/jslint4java/src/test/java/com/googlecode/jslint4java/formatter/CheckstyleXmlFormatterTest.java b/jslint4java/src/test/java/com/googlecode/jslint4java/formatter/CheckstyleXmlFormatterTest.java index 0b15185..9f2400a 100644 --- a/jslint4java/src/test/java/com/googlecode/jslint4java/formatter/CheckstyleXmlFormatterTest.java +++ b/jslint4java/src/test/java/com/googlecode/jslint4java/formatter/CheckstyleXmlFormatterTest.java @@ -1,52 +1,52 @@ package com.googlecode.jslint4java.formatter; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import org.custommonkey.xmlunit.XMLAssert; import org.custommonkey.xmlunit.XMLUnit; import org.junit.Before; import org.junit.Test; import com.googlecode.jslint4java.Issue; import com.googlecode.jslint4java.JSLintResult; public class CheckstyleXmlFormatterTest { private final JSLintResultFormatter form = new CheckstyleXmlFormatter(); @Before public void setUp() { // This is why you need a proper testing library… XMLUnit.setIgnoreWhitespace(true); } @Test public void shouldHaveCheckstyleFooter() { assertThat(form.footer(), is("</checkstyle>")); } @Test public void shouldHaveCheckstyleHeader() { assertThat(form.header(), is("<checkstyle>")); } @Test public void shouldHaveNoProblems() throws Exception { JSLintResult result = new JSLintResult.ResultBuilder("hello.js").duration(0).build(); String expected = "<file name=\"hello.js\" />"; XMLAssert.assertXMLEqual(expected, form.format(result)); } @Test public void shouldHaveOneProblem() throws Exception { String name = "bad.js"; Issue issue = new Issue.IssueBuilder(name, 1, 1, "this is not a daffodil").build(); JSLintResult result = new JSLintResult.ResultBuilder(name).addIssue(issue).build(); - String expected = "<file name=\"bad.js\">" + - "<error line='1' column='1' severity='warning' message='this is not a daffodil'" + - " source='com.googlecode.jslint4java.JSLint' />" + - "</file>"; + String expected = "<file name=\"bad.js\">" + + "<error line='1' column='1' severity='warning' message='this is not a daffodil'" + + " source='com.googlecode.jslint4java.JSLint' />" + + "</file>"; XMLAssert.assertXMLEqual(expected, form.format(result)); } }
true
true
public void shouldHaveOneProblem() throws Exception { String name = "bad.js"; Issue issue = new Issue.IssueBuilder(name, 1, 1, "this is not a daffodil").build(); JSLintResult result = new JSLintResult.ResultBuilder(name).addIssue(issue).build(); String expected = "<file name=\"bad.js\">" + "<error line='1' column='1' severity='warning' message='this is not a daffodil'" + " source='com.googlecode.jslint4java.JSLint' />" + "</file>"; XMLAssert.assertXMLEqual(expected, form.format(result)); }
public void shouldHaveOneProblem() throws Exception { String name = "bad.js"; Issue issue = new Issue.IssueBuilder(name, 1, 1, "this is not a daffodil").build(); JSLintResult result = new JSLintResult.ResultBuilder(name).addIssue(issue).build(); String expected = "<file name=\"bad.js\">" + "<error line='1' column='1' severity='warning' message='this is not a daffodil'" + " source='com.googlecode.jslint4java.JSLint' />" + "</file>"; XMLAssert.assertXMLEqual(expected, form.format(result)); }
diff --git a/temp2/CA/src/Datapath.java b/temp2/CA/src/Datapath.java index 391ac1a..0399153 100644 --- a/temp2/CA/src/Datapath.java +++ b/temp2/CA/src/Datapath.java @@ -1,307 +1,307 @@ public class Datapath { long pc = 0; Adder adder = new Adder(); Control control = new Control(); IM im = new IM(); Registers registerFile = new Registers(); ALU alu = new ALU(); DM dm = new DM(); Mux mux = new Mux(); reg $zero = new reg(); reg $at = new reg(); reg $v0 = new reg(); reg $v1 = new reg(); reg $a0 = new reg(); reg $a1 = new reg(); reg $a2 = new reg(); reg $a3 = new reg(); reg $t0 = new reg(); reg $t1 = new reg(); reg $t2 = new reg(); reg $t3 = new reg(); reg $t4 = new reg(); reg $t5 = new reg(); reg $t6 = new reg(); reg $t7 = new reg(); reg $s0 = new reg(); reg $s1 = new reg(); reg $s2 = new reg(); reg $s3 = new reg(); reg $s4 = new reg(); reg $s5 = new reg(); reg $s6 = new reg(); reg $s7 = new reg(); reg $t8 = new reg(); reg $t9 = new reg(); reg $k0 = new reg(); reg $k1 = new reg(); reg $gp = new reg(); reg $sp = new reg(); reg $fp = new reg(); reg $ra = new reg(); boolean zero = false; public void performInstruction(String ins) { // String Instruction = im.getInstruction(pc); pc = adder.add(pc, 4); String[] z = ins.split(" "); String in = z[0]; if (z.length == 2) { control.set_controler("000010"); if (z[0].equals("000011")) { long y = pc + 4; String x = Long.toBinaryString(y); this.$ra.data = x; } String nPC = Long.toBinaryString(pc); nPC = nPC.charAt(0) + nPC.charAt(1) + nPC.charAt(2) + nPC.charAt(3) + z[1] + "00"; String w=Long.toBinaryString(pc); String q = mux.select(w, nPC, control.jump); long PC=Long.parseLong(q); pc=PC; } else { control.set_controler(in); registerFile.setRregister1(this.findRegByOpcode(z[1])); registerFile.setRregister2(this.findRegByOpcode(z[2])); String resultMux = mux.select(z[2], z[3], control.regDst); registerFile.setWregister(this.findRegByOpcode(resultMux)); String r2 = registerFile.rregister2.data; String signExtend = ""; if (z[3].charAt(0) == '1') { signExtend = "1111111111111111" + z[3]; } else { signExtend = "0000000000000000" + z[3]; } String resultMux2 = mux.select(r2, signExtend, control.ALUSrc); String signExtendedShiftedByTwo = Long.toBinaryString(Long .parseLong(signExtend, 2) << 2); long resultAdder2 = adder.add(pc, Long.parseLong(signExtendedShiftedByTwo, 2)); String aluRes = ""; if (in.equals("000000")) { if(z[5].equals("000000")||z[5].equals("000010")){ - aluRes = alu.performOperation(registerFile.rregister1.data, z[4], Integer.parseInt(z[5])); + aluRes = alu.performOperation(registerFile.rregister2.data, z[4], Integer.parseInt(z[5])); if (Long.parseLong(aluRes, 2) == 0) { zero = true; } } else{ aluRes = alu.performOperation(registerFile.rregister1.data, resultMux2, Integer.parseInt(z[5])); if (Long.parseLong(aluRes, 2) == 0) { zero = true; } } } if (in.equals("000100")) { aluRes = alu.performOperation(registerFile.rregister1.data, resultMux2, 100010); if (Long.parseLong(aluRes, 2) == 0) { zero = true; } } if (in.equals("001000")) { aluRes = alu.performOperation(registerFile.rregister1.data, resultMux2, 100000); } if (in.equals("001101")) { aluRes = alu.performOperation(registerFile.rregister1.data, resultMux2, 100101); } if (in.equals("001100")) { aluRes = alu.performOperation(registerFile.rregister1.data, resultMux2, 100100); } String dataRead = ""; if (control.MemRead == 1) { if (in.equals("100011")) { aluRes = alu.performOperation(registerFile.rregister1.data, resultMux2, 100000); if (Long.parseLong(aluRes, 2) == 0) { zero = true; } } if (in.equals("100001")) { aluRes = alu.performOperation(registerFile.rregister1.data, resultMux2, 100000); String part0 = aluRes; String part1 = Long.toBinaryString(Long .parseLong(aluRes, 2) + 1); dataRead = dm.readData(part0) + dm.readData(part1); } if (in.equals("001100")) { aluRes = alu.performOperation(registerFile.rregister1.data, resultMux2, 100000); dataRead = dm.readData(aluRes); } } if (control.MemWrite == 1) { if (in.equals("101011")) { aluRes = alu.performOperation(registerFile.rregister1.data, resultMux2, 100010); if (Long.parseLong(aluRes, 2) == 0) { zero = true; } } dataRead = ""; if (control.MemRead == 1) { if (in.equals("100011")) { aluRes = alu.performOperation( registerFile.rregister1.data, resultMux2, 100000); if (Long.parseLong(aluRes, 2) == 0) { zero = true; } String part0 = aluRes; String part1 = Long.toBinaryString(Long.parseLong( aluRes, 2) + 1); String part2 = Long.toBinaryString(Long.parseLong( aluRes, 2) + 2); String part3 = Long.toBinaryString(Long.parseLong( aluRes, 2) + 3); dataRead = dm.readData(part0) + dm.readData(part1) + dm.readData(part2) + dm.readData(part3); } } if (control.MemWrite == 1) { if (in.equals("101011")) { aluRes = alu.performOperation( registerFile.rregister1.data, resultMux2, 100000); if (Long.parseLong(aluRes, 2) == 0) { zero = true; } dm.writeData( Long.toBinaryString(Long.parseLong(aluRes, 2)), registerFile.rregister1.data.substring(0, 8)); dm.writeData(Long.toBinaryString(Long.parseLong(aluRes, 2) + 1), registerFile.rregister1.data .substring(8, 16)); dm.writeData(Long.toBinaryString(Long.parseLong(aluRes, 2) + 2), registerFile.rregister1.data .substring(16, 25)); dm.writeData(Long.toBinaryString(Long.parseLong(aluRes, 2) + 3), registerFile.rregister1.data .substring(25, 32)); } if (in.equals("101001")) { aluRes = alu.performOperation( registerFile.rregister1.data, resultMux2, 100000); if (Long.parseLong(aluRes, 2) == 0) { zero = true; } dm.writeData( Long.toBinaryString(Long.parseLong(aluRes, 2)), registerFile.rregister1.data.substring(8, 16)); dm.writeData(Long.toBinaryString(Long.parseLong(aluRes, 2) + 1), registerFile.rregister1.data .substring(0, 8)); } if (in.equals("101000")) { aluRes = alu.performOperation( registerFile.rregister1.data, resultMux2, 100000); if (Long.parseLong(aluRes, 2) == 0) { zero = true; } dm.writeData( Long.toBinaryString(Long.parseLong(aluRes, 2)), registerFile.rregister1.data.substring(0, 8)); } } } boolean branch = false; if (control.branch == 0) { branch = true; } else { branch = false; } int controlAdderTwo = 0; if (branch && zero) { controlAdderTwo = 1; } pc = mux.select(pc, resultAdder2, controlAdderTwo); String resultMux3 = mux.select(aluRes, dataRead, control.MemToReg); if (control.RegWrite == 1) { registerFile.setWdata(resultMux3); this.findRegByOpcode(resultMux).data = registerFile.getWdata(); System.out.println("Result of operation: " + registerFile.wregister.data); } } } public reg findRegByOpcode(String s) { if (s.equals("10001")) { return this.$s1; } else if (s.equals("10010")) { return this.$s2; } else { return this.$s3; } } public String translate(String x) { String result = ""; String[] a; a = x.split(" "); if (a[0].equals("ADD")) { result += "0000000"; } result += getRegOpcode(a[2]); result += getRegOpcode(a[3]); result += getRegOpcode(a[1]); return result; } public String getRegOpcode(String a) { if (a.equals("$s1")) { return "10001"; } else if (a.equals("$s2")) { return "10010"; } else { /* $s3 */return "10011"; } } public static void main(String[] args) { Datapath p = new Datapath(); p.$s1.set("00001000000000000000000000000110"); p.$s2.set("11010000000000000000000000000011"); p.$s3.set("10"); p.performInstruction("000000 10001 10010 10011 00000 100111"); p.performInstruction("101011 10010 10010 000000000000000001"); p.performInstruction("100011 10010 10010 000000000000000001"); p.performInstruction("001000 10001 10010 000000000001100100"); } }
true
true
public void performInstruction(String ins) { // String Instruction = im.getInstruction(pc); pc = adder.add(pc, 4); String[] z = ins.split(" "); String in = z[0]; if (z.length == 2) { control.set_controler("000010"); if (z[0].equals("000011")) { long y = pc + 4; String x = Long.toBinaryString(y); this.$ra.data = x; } String nPC = Long.toBinaryString(pc); nPC = nPC.charAt(0) + nPC.charAt(1) + nPC.charAt(2) + nPC.charAt(3) + z[1] + "00"; String w=Long.toBinaryString(pc); String q = mux.select(w, nPC, control.jump); long PC=Long.parseLong(q); pc=PC; } else { control.set_controler(in); registerFile.setRregister1(this.findRegByOpcode(z[1])); registerFile.setRregister2(this.findRegByOpcode(z[2])); String resultMux = mux.select(z[2], z[3], control.regDst); registerFile.setWregister(this.findRegByOpcode(resultMux)); String r2 = registerFile.rregister2.data; String signExtend = ""; if (z[3].charAt(0) == '1') { signExtend = "1111111111111111" + z[3]; } else { signExtend = "0000000000000000" + z[3]; } String resultMux2 = mux.select(r2, signExtend, control.ALUSrc); String signExtendedShiftedByTwo = Long.toBinaryString(Long .parseLong(signExtend, 2) << 2); long resultAdder2 = adder.add(pc, Long.parseLong(signExtendedShiftedByTwo, 2)); String aluRes = ""; if (in.equals("000000")) { if(z[5].equals("000000")||z[5].equals("000010")){ aluRes = alu.performOperation(registerFile.rregister1.data, z[4], Integer.parseInt(z[5])); if (Long.parseLong(aluRes, 2) == 0) { zero = true; } } else{ aluRes = alu.performOperation(registerFile.rregister1.data, resultMux2, Integer.parseInt(z[5])); if (Long.parseLong(aluRes, 2) == 0) { zero = true; } } } if (in.equals("000100")) { aluRes = alu.performOperation(registerFile.rregister1.data, resultMux2, 100010); if (Long.parseLong(aluRes, 2) == 0) { zero = true; } } if (in.equals("001000")) { aluRes = alu.performOperation(registerFile.rregister1.data, resultMux2, 100000); } if (in.equals("001101")) { aluRes = alu.performOperation(registerFile.rregister1.data, resultMux2, 100101); } if (in.equals("001100")) { aluRes = alu.performOperation(registerFile.rregister1.data, resultMux2, 100100); } String dataRead = ""; if (control.MemRead == 1) { if (in.equals("100011")) { aluRes = alu.performOperation(registerFile.rregister1.data, resultMux2, 100000); if (Long.parseLong(aluRes, 2) == 0) { zero = true; } } if (in.equals("100001")) { aluRes = alu.performOperation(registerFile.rregister1.data, resultMux2, 100000); String part0 = aluRes; String part1 = Long.toBinaryString(Long .parseLong(aluRes, 2) + 1); dataRead = dm.readData(part0) + dm.readData(part1); } if (in.equals("001100")) { aluRes = alu.performOperation(registerFile.rregister1.data, resultMux2, 100000); dataRead = dm.readData(aluRes); } } if (control.MemWrite == 1) { if (in.equals("101011")) { aluRes = alu.performOperation(registerFile.rregister1.data, resultMux2, 100010); if (Long.parseLong(aluRes, 2) == 0) { zero = true; } } dataRead = ""; if (control.MemRead == 1) { if (in.equals("100011")) { aluRes = alu.performOperation( registerFile.rregister1.data, resultMux2, 100000); if (Long.parseLong(aluRes, 2) == 0) { zero = true; } String part0 = aluRes; String part1 = Long.toBinaryString(Long.parseLong( aluRes, 2) + 1); String part2 = Long.toBinaryString(Long.parseLong( aluRes, 2) + 2); String part3 = Long.toBinaryString(Long.parseLong( aluRes, 2) + 3); dataRead = dm.readData(part0) + dm.readData(part1) + dm.readData(part2) + dm.readData(part3); } } if (control.MemWrite == 1) { if (in.equals("101011")) { aluRes = alu.performOperation( registerFile.rregister1.data, resultMux2, 100000); if (Long.parseLong(aluRes, 2) == 0) { zero = true; } dm.writeData( Long.toBinaryString(Long.parseLong(aluRes, 2)), registerFile.rregister1.data.substring(0, 8)); dm.writeData(Long.toBinaryString(Long.parseLong(aluRes, 2) + 1), registerFile.rregister1.data .substring(8, 16)); dm.writeData(Long.toBinaryString(Long.parseLong(aluRes, 2) + 2), registerFile.rregister1.data .substring(16, 25)); dm.writeData(Long.toBinaryString(Long.parseLong(aluRes, 2) + 3), registerFile.rregister1.data .substring(25, 32)); } if (in.equals("101001")) { aluRes = alu.performOperation( registerFile.rregister1.data, resultMux2, 100000); if (Long.parseLong(aluRes, 2) == 0) { zero = true; } dm.writeData( Long.toBinaryString(Long.parseLong(aluRes, 2)), registerFile.rregister1.data.substring(8, 16)); dm.writeData(Long.toBinaryString(Long.parseLong(aluRes, 2) + 1), registerFile.rregister1.data .substring(0, 8)); } if (in.equals("101000")) { aluRes = alu.performOperation( registerFile.rregister1.data, resultMux2, 100000); if (Long.parseLong(aluRes, 2) == 0) { zero = true; } dm.writeData( Long.toBinaryString(Long.parseLong(aluRes, 2)), registerFile.rregister1.data.substring(0, 8)); } } } boolean branch = false; if (control.branch == 0) { branch = true; } else { branch = false; } int controlAdderTwo = 0; if (branch && zero) { controlAdderTwo = 1; } pc = mux.select(pc, resultAdder2, controlAdderTwo); String resultMux3 = mux.select(aluRes, dataRead, control.MemToReg); if (control.RegWrite == 1) { registerFile.setWdata(resultMux3); this.findRegByOpcode(resultMux).data = registerFile.getWdata(); System.out.println("Result of operation: " + registerFile.wregister.data); } } }
public void performInstruction(String ins) { // String Instruction = im.getInstruction(pc); pc = adder.add(pc, 4); String[] z = ins.split(" "); String in = z[0]; if (z.length == 2) { control.set_controler("000010"); if (z[0].equals("000011")) { long y = pc + 4; String x = Long.toBinaryString(y); this.$ra.data = x; } String nPC = Long.toBinaryString(pc); nPC = nPC.charAt(0) + nPC.charAt(1) + nPC.charAt(2) + nPC.charAt(3) + z[1] + "00"; String w=Long.toBinaryString(pc); String q = mux.select(w, nPC, control.jump); long PC=Long.parseLong(q); pc=PC; } else { control.set_controler(in); registerFile.setRregister1(this.findRegByOpcode(z[1])); registerFile.setRregister2(this.findRegByOpcode(z[2])); String resultMux = mux.select(z[2], z[3], control.regDst); registerFile.setWregister(this.findRegByOpcode(resultMux)); String r2 = registerFile.rregister2.data; String signExtend = ""; if (z[3].charAt(0) == '1') { signExtend = "1111111111111111" + z[3]; } else { signExtend = "0000000000000000" + z[3]; } String resultMux2 = mux.select(r2, signExtend, control.ALUSrc); String signExtendedShiftedByTwo = Long.toBinaryString(Long .parseLong(signExtend, 2) << 2); long resultAdder2 = adder.add(pc, Long.parseLong(signExtendedShiftedByTwo, 2)); String aluRes = ""; if (in.equals("000000")) { if(z[5].equals("000000")||z[5].equals("000010")){ aluRes = alu.performOperation(registerFile.rregister2.data, z[4], Integer.parseInt(z[5])); if (Long.parseLong(aluRes, 2) == 0) { zero = true; } } else{ aluRes = alu.performOperation(registerFile.rregister1.data, resultMux2, Integer.parseInt(z[5])); if (Long.parseLong(aluRes, 2) == 0) { zero = true; } } } if (in.equals("000100")) { aluRes = alu.performOperation(registerFile.rregister1.data, resultMux2, 100010); if (Long.parseLong(aluRes, 2) == 0) { zero = true; } } if (in.equals("001000")) { aluRes = alu.performOperation(registerFile.rregister1.data, resultMux2, 100000); } if (in.equals("001101")) { aluRes = alu.performOperation(registerFile.rregister1.data, resultMux2, 100101); } if (in.equals("001100")) { aluRes = alu.performOperation(registerFile.rregister1.data, resultMux2, 100100); } String dataRead = ""; if (control.MemRead == 1) { if (in.equals("100011")) { aluRes = alu.performOperation(registerFile.rregister1.data, resultMux2, 100000); if (Long.parseLong(aluRes, 2) == 0) { zero = true; } } if (in.equals("100001")) { aluRes = alu.performOperation(registerFile.rregister1.data, resultMux2, 100000); String part0 = aluRes; String part1 = Long.toBinaryString(Long .parseLong(aluRes, 2) + 1); dataRead = dm.readData(part0) + dm.readData(part1); } if (in.equals("001100")) { aluRes = alu.performOperation(registerFile.rregister1.data, resultMux2, 100000); dataRead = dm.readData(aluRes); } } if (control.MemWrite == 1) { if (in.equals("101011")) { aluRes = alu.performOperation(registerFile.rregister1.data, resultMux2, 100010); if (Long.parseLong(aluRes, 2) == 0) { zero = true; } } dataRead = ""; if (control.MemRead == 1) { if (in.equals("100011")) { aluRes = alu.performOperation( registerFile.rregister1.data, resultMux2, 100000); if (Long.parseLong(aluRes, 2) == 0) { zero = true; } String part0 = aluRes; String part1 = Long.toBinaryString(Long.parseLong( aluRes, 2) + 1); String part2 = Long.toBinaryString(Long.parseLong( aluRes, 2) + 2); String part3 = Long.toBinaryString(Long.parseLong( aluRes, 2) + 3); dataRead = dm.readData(part0) + dm.readData(part1) + dm.readData(part2) + dm.readData(part3); } } if (control.MemWrite == 1) { if (in.equals("101011")) { aluRes = alu.performOperation( registerFile.rregister1.data, resultMux2, 100000); if (Long.parseLong(aluRes, 2) == 0) { zero = true; } dm.writeData( Long.toBinaryString(Long.parseLong(aluRes, 2)), registerFile.rregister1.data.substring(0, 8)); dm.writeData(Long.toBinaryString(Long.parseLong(aluRes, 2) + 1), registerFile.rregister1.data .substring(8, 16)); dm.writeData(Long.toBinaryString(Long.parseLong(aluRes, 2) + 2), registerFile.rregister1.data .substring(16, 25)); dm.writeData(Long.toBinaryString(Long.parseLong(aluRes, 2) + 3), registerFile.rregister1.data .substring(25, 32)); } if (in.equals("101001")) { aluRes = alu.performOperation( registerFile.rregister1.data, resultMux2, 100000); if (Long.parseLong(aluRes, 2) == 0) { zero = true; } dm.writeData( Long.toBinaryString(Long.parseLong(aluRes, 2)), registerFile.rregister1.data.substring(8, 16)); dm.writeData(Long.toBinaryString(Long.parseLong(aluRes, 2) + 1), registerFile.rregister1.data .substring(0, 8)); } if (in.equals("101000")) { aluRes = alu.performOperation( registerFile.rregister1.data, resultMux2, 100000); if (Long.parseLong(aluRes, 2) == 0) { zero = true; } dm.writeData( Long.toBinaryString(Long.parseLong(aluRes, 2)), registerFile.rregister1.data.substring(0, 8)); } } } boolean branch = false; if (control.branch == 0) { branch = true; } else { branch = false; } int controlAdderTwo = 0; if (branch && zero) { controlAdderTwo = 1; } pc = mux.select(pc, resultAdder2, controlAdderTwo); String resultMux3 = mux.select(aluRes, dataRead, control.MemToReg); if (control.RegWrite == 1) { registerFile.setWdata(resultMux3); this.findRegByOpcode(resultMux).data = registerFile.getWdata(); System.out.println("Result of operation: " + registerFile.wregister.data); } } }
diff --git a/tregmine/src/info/tregmine/Tregmine.java b/tregmine/src/info/tregmine/Tregmine.java index 80358fb..6818a6d 100644 --- a/tregmine/src/info/tregmine/Tregmine.java +++ b/tregmine/src/info/tregmine/Tregmine.java @@ -1,645 +1,645 @@ package info.tregmine; import info.tregmine.api.TregminePlayer; import info.tregmine.currency.Wallet; import info.tregmine.database.ConnectionPool; import info.tregmine.listeners.TregmineBlockListener; import info.tregmine.listeners.TregmineEntityListener; import info.tregmine.listeners.TregminePlayerListener; import info.tregmine.listeners.TregmineWeatherListener; import info.tregmine.stats.BlockStats; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.WorldCreator; import org.bukkit.World.Environment; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.BookMeta; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * @author Ein Andersson - www.tregmine.info */ public class Tregmine extends JavaPlugin { public final Logger log = Logger.getLogger("Minecraft"); public final BlockStats blockStats = new BlockStats(this); public Map<String, TregminePlayer> tregminePlayer = new HashMap<String, TregminePlayer>(); // public Map<String, Boolean> hasVoted = new HashMap<String, Boolean>(); public LinkedList <String> hasVoted = new LinkedList<String>(); public int version = 0; public int amount = 0; @Override public void onEnable() { WorldCreator citadelCreator = new WorldCreator("citadel"); citadelCreator.environment(Environment.NORMAL); citadelCreator.createWorld(); WorldCreator world = new WorldCreator("world"); world.environment(Environment.NORMAL); world.createWorld(); WorldCreator treton = new WorldCreator("treton"); treton.environment(Environment.NORMAL); treton.createWorld(); WorldCreator vanilla = new WorldCreator("elva"); vanilla.environment(Environment.NORMAL); vanilla.createWorld(); WorldCreator einhome = new WorldCreator("einhome"); einhome.environment(Environment.NORMAL); einhome.createWorld(); WorldCreator alpha = new WorldCreator("alpha"); alpha.environment(Environment.NORMAL); alpha.createWorld(); WorldCreator NETHER = new WorldCreator("world_nether"); NETHER.environment(Environment.NETHER); NETHER.createWorld(); getServer().getPluginManager().registerEvents(new info.tregmine.lookup.LookupPlayer(this), this); getServer().getPluginManager().registerEvents(new TregminePlayerListener(this), this); getServer().getPluginManager().registerEvents(new TregmineBlockListener(this), this); getServer().getPluginManager().registerEvents(new TregmineEntityListener(this), this); getServer().getPluginManager().registerEvents(new TregmineWeatherListener(this), this); getServer().getPluginManager().registerEvents(new info.tregmine.invis.InvisPlayer(this), this); getServer().getPluginManager().registerEvents(new info.tregmine.death.DeathEntity(this), this); getServer().getPluginManager().registerEvents(new info.tregmine.death.DeathPlayer(this), this); getServer().getPluginManager().registerEvents(new info.tregmine.chat.Chat(this), this); getServer().getPluginManager().registerEvents(new info.tregmine.vote.voter(this), this); getServer().getPluginManager().registerEvents(new info.tregmine.sign.Color(), this); // getServer().getPluginManager().registerEvents(new info.tregmine.vendings.Machines(this), this); } @Override public void onDisable() { //run when plugin is disabled this.getServer().getScheduler().cancelTasks(this); Player[] players = this.getServer().getOnlinePlayers(); for (Player player : players) { player.sendMessage(ChatColor.AQUA + "Tregmine successfully unloaded build: " + this.getDescription().getVersion() ); } } @Override public void onLoad() { Player[] players = this.getServer().getOnlinePlayers(); for (Player player : players) { String onlineName = player.getName(); TregminePlayer tregPlayer = new TregminePlayer(player, onlineName); tregPlayer.load(); this.tregminePlayer.put(onlineName, tregPlayer); player.sendMessage(ChatColor.GRAY + "Tregmine successfully loaded to build: " + this.getDescription().getVersion() ); // player.sendMessage(ChatColor.GRAY + "Version explanation: X.Y.Z.G"); // player.sendMessage(ChatColor.GRAY + "X new stuff added, When i make a brand new thing"); // player.sendMessage(ChatColor.GRAY + "Y new function added, when i extend what current stuff can do"); // player.sendMessage(ChatColor.GRAY + "Z bugfix that may change how function and stuff works"); // player.sendMessage(ChatColor.GRAY + "G small bugfix like spelling errors"); } this.getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() { public void run() { while(hasVoted.size() > 0) { String name = hasVoted.removeFirst(); getServer().broadcastMessage(ChatColor.YELLOW + name + " has voted and will now receive 2,000 Tregs"); getServer().broadcastMessage(ChatColor.YELLOW + name + " Read more at http://treg.co/82 what you can get"); Wallet wallet = new Wallet(name); wallet.add(2000); log.info(name + " got " + name + " Tregs for VOTING"); } } },100L,20L); } public TregminePlayer getPlayer(String name) { return tregminePlayer.get(name); } public TregminePlayer getPlayer(Player player) { return tregminePlayer.get(player.getName()); } public boolean onCommand(CommandSender sender, Command command, String commandLabel, final String[] args) { String commandName = command.getName().toLowerCase(); Player from = null; TregminePlayer player = null; if(!(sender instanceof Player)) { if(commandName.equals("say")) { StringBuffer buf = new StringBuffer(); buf.append(args[0]); for (int i = 1; i < args.length; ++i) { buf.append(" " + args[i]); } String buffMsg = buf.toString(); this.getServer().broadcastMessage("<" + ChatColor.BLUE + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); this.log.info("CONSOLE: <GOD> " + buffMsg); return true; } return false; } else { from = (Player) sender; player = this.getPlayer(from); } if("book".matches(commandName)) { if("player".matches(args[0]) && player.isOp()) { final TregminePlayer fPlayer = player; this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { public void run() { // DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); fPlayer.sendMessage(ChatColor.YELLOW + "Starting to generate book for " + args[1] ); ItemStack book = new ItemStack(Material.WRITTEN_BOOK, 1); BookMeta bookmeta = (BookMeta) book.getItemMeta(); // TregminePlayer p = getPlayer(args[1]); long placed = 0; long destroyed = 0; long total = 0; int id = 0; String joinDate = ""; bookmeta.setAuthor("Tregmine"); bookmeta.setTitle(ChatColor.GREEN + args[1] + "'s Profile"); bookmeta.addPage(ChatColor.GREEN + args[1] + "'s profile" + '\n' + "date:"+'\n'+ date.toString()); Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = ConnectionPool.getConnection(); stmt = conn.prepareStatement("SELECT count(player) as count FROM stats_blocks WHERE player=?"); stmt.setString(1, args[1]); stmt.execute(); rs = stmt.getResultSet(); if (!rs.next()) { } total = rs.getInt("count"); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) {} } if (stmt != null) { try { stmt.close(); } catch (SQLException e) {} } if (conn != null) { try { conn.close(); } catch (SQLException e) {} } } try { conn = ConnectionPool.getConnection(); stmt = conn.prepareStatement("SELECT count(player) as count FROM stats_blocks WHERE player=? AND status=1"); stmt.setString(1, args[1]); stmt.execute(); rs = stmt.getResultSet(); if (!rs.next()) { } placed = rs.getInt("count"); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) {} } if (stmt != null) { try { stmt.close(); } catch (SQLException e) {} } if (conn != null) { try { conn.close(); } catch (SQLException e) {} } } try { conn = ConnectionPool.getConnection(); stmt = conn.prepareStatement("SELECT count(player) as count FROM stats_blocks WHERE player=? AND status=0"); stmt.setString(1, args[1]); stmt.execute(); rs = stmt.getResultSet(); if (!rs.next()) { } destroyed = rs.getInt("count"); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) {} } if (stmt != null) { try { stmt.close(); } catch (SQLException e) {} } if (conn != null) { try { conn.close(); } catch (SQLException e) {} } } try { conn = ConnectionPool.getConnection(); stmt = conn.prepareStatement("SELECT * FROM user WHERE player=?"); stmt.setString(1, args[1]); stmt.execute(); rs = stmt.getResultSet(); if (!rs.next()) { } joinDate = rs.getDate("time").toString(); id = rs.getInt("uid"); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) {} } if (stmt != null) { try { stmt.close(); } catch (SQLException e) {} } if (conn != null) { try { conn.close(); } catch (SQLException e) {} } } bookmeta.addPage( ChatColor.BLUE + "ID:" +'\n' + ChatColor.BLACK + id +'\n' + ChatColor.BLUE + "JOIN-TIME (GMT):" +'\n' + ChatColor.BLACK + joinDate +'\n' + ChatColor.BLUE + "BLOCK DESTROYED:" +'\n' + ChatColor.BLACK + destroyed +'\n' + ChatColor.BLUE + "BLOCK PLACED:" +'\n' + ChatColor.BLACK + placed +'\n' + ChatColor.BLUE + "TOTAL:" +'\n' + ChatColor.BLACK + total +'\n' + "EOF"); book.setItemMeta(bookmeta); PlayerInventory inv = fPlayer.getInventory(); inv.addItem(book); } },20L); } } if("blackout".matches(commandName) && player.isAdmin()) { Player target = getServer().getPlayer(args[1]); player.sendMessage("blackout"); if ("blind".matches(args[0])) { PotionEffect ef = new PotionEffect(PotionEffectType.BLINDNESS, 60, 100); target.getPlayer().addPotionEffect(ef); player.sendMessage("Blind"); } if ("invis".matches(args[0])) { PotionEffect ef = new PotionEffect(PotionEffectType.INVISIBILITY, 1600000, 100); target.getPlayer().addPotionEffect(ef); player.sendMessage("Blind"); } if ("confuse".matches(args[0])) { PotionEffect ef = new PotionEffect(PotionEffectType.CONFUSION, 600 , 10); target.getPlayer().addPotionEffect(ef); player.sendMessage("Confuse"); } } if("te".matches(commandName) && player.isOp()) { ItemStack drop = new ItemStack(Material.MONSTER_EGG, 1, (byte)65); - List<String> lore = new ArrayList<String>(); +// List<String> lore = new ArrayList<String>(); // lore.add(ChatColor.GOLD + "EASTER EGG"); // lore.add(ChatColor.WHITE + "Found by: " + player.getChatName()); ItemMeta meta = drop.getItemMeta(); meta.setDisplayName(ChatColor.YELLOW + "EASTER EGG"); // meta.setLore(lore); -// drop.setItemMeta(meta); + drop.setItemMeta(meta); // event.getBlock().getWorld().dropItem(event.getBlock().getLocation(), drop); player.getWorld().dropItemNaturally(player.getLocation(), drop); } if ("TregDev".matches(this.getServer().getServerName())) { if("te".matches(commandName)) { ItemStack item = new ItemStack(Material.PAPER, amount, (byte) 0); // PlayerInventory inv = player.getInventory(); ItemMeta meta = item.getItemMeta(); List<String> lore = new ArrayList<String>(); lore.add(info.tregmine.api.lore.Created.PURCHASED.toColorString()); TregminePlayer p = this.getPlayer(player); lore.add(ChatColor.WHITE + "by: " + p.getName() ); lore.add(ChatColor.WHITE + "Value: 25.000" + ChatColor.WHITE + " Tregs" ); meta.setLore(lore); meta.setDisplayName(ChatColor.GREEN + "DIRT -> SPONG Coupon"); item.setItemMeta(meta); } if("op".matches(commandName)) { player.setMetaBoolean("admin", true); player.setMetaBoolean("donator", true); player.setMetaBoolean("trusted", true); player.setTemporaryChatName(ChatColor.RED + player.getName()); player.setAllowFlight(true); player.setMetaString("color", ""+ChatColor.RED); } if("donator".matches(commandName)) { player.setAllowFlight(true); player.setMetaBoolean("admin", false); player.setMetaBoolean("donator", true); player.setMetaBoolean("trusted", true); player.setTemporaryChatName(ChatColor.GOLD + player.getName()); player.setMetaString("color", ""+ChatColor.GOLD); } if("settler".matches(commandName)) { player.setAllowFlight(true); player.setMetaBoolean("admin", false); player.setMetaBoolean("donator", false); player.setMetaBoolean("trusted", true); player.setTemporaryChatName(ChatColor.GREEN + player.getName()); player.setMetaString("color", ""+ChatColor.GREEN); } } if("invis".matches(commandName) && player.isOp()) { if ("off".matches(args[0])) { for (Player p : this.getServer().getOnlinePlayers()) { p.showPlayer(player.getPlayer()); } player.setMetaBoolean("invis", false); player.sendMessage(ChatColor.YELLOW + "You can now be seen!"); } else if ("on".matches(args[0])) { for (Player p : this.getServer().getOnlinePlayers()) { if (!p.isOp()) { p.hidePlayer(player.getPlayer()); } else { p.showPlayer(player.getPlayer()); } } player.setMetaBoolean("invis", true); player.sendMessage(ChatColor.YELLOW + "*poof* no one knows where you are!"); } else { player.sendMessage("Try /invis [on|off]"); } } if(commandName.equals("text") && player.isAdmin()) { Player[] players = this.getServer().getOnlinePlayers(); // player.setTexturePack(args[0]); for (Player p : players) { p.setTexturePack(args[0]); } } if(commandName.equals("head") && player.isOp()) { ItemStack item = new ItemStack(Material.SKULL_ITEM, 1, (byte) 3); SkullMeta meta = (SkullMeta) item.getItemMeta(); meta.setOwner(args[0]); meta.setDisplayName(ChatColor.YELLOW + "Head of " + args[0]); item.setItemMeta(meta); PlayerInventory inv = player.getInventory(); inv.addItem(item); player.updateInventory(); player.sendMessage("Skull of " + args[0]); } else if(commandName.equals("head")) { player.kickPlayer(""); } if(commandName.equals("say") && player.isAdmin()) { StringBuffer buf = new StringBuffer(); buf.append(args[0]); for (int i = 1; i < args.length; ++i) { buf.append(" " + args[i]); } String buffMsg = buf.toString(); if(from.getName().matches("BlackX")) { this.getServer().broadcastMessage("<" + ChatColor.BLACK + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("mejjad")){ this.getServer().broadcastMessage("<" + ChatColor.DARK_AQUA + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("einand")){ this.getServer().broadcastMessage("<" + ChatColor.DARK_GREEN + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("LilKiw")){ this.getServer().broadcastMessage("<" + ChatColor.AQUA + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("Camrenn")){ this.getServer().broadcastMessage("<" + ChatColor.LIGHT_PURPLE + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("Mksen")){ this.getServer().broadcastMessage("<" + ChatColor.YELLOW + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("josh121297")){ this.getServer().broadcastMessage("<" + ChatColor.GREEN + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("GeorgeBombadil")){ this.getServer().broadcastMessage("<" + ChatColor.DARK_RED + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("rweiand")){ this.getServer().broadcastMessage("<" + ChatColor.GOLD + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else { this.getServer().broadcastMessage("<" + ChatColor.RED + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } this.log.info(from.getName() + ": <GOD> " + buffMsg); Player[] players = this.getServer().getOnlinePlayers(); for (Player p : players) { info.tregmine.api.TregminePlayer locTregminePlayer = this.getPlayer((p.getName())); if (locTregminePlayer.isAdmin()) { p.sendMessage(ChatColor.DARK_AQUA + "/say used by: " + player.getChatName()); } } return true; } if(commandName.equals("who") || commandName.equals("playerlist") || commandName.equals("list")){ info.tregmine.commands.Who.run(this, player, args); return true; } if(commandName.equals("tp")){ info.tregmine.commands.Tp.run(this, player, args); return true; } if(commandName.equals("channel")){ if (args.length != 1) { return false; } from.sendMessage(ChatColor.YELLOW + "You are now talking in channel " + args[0] + "."); from.sendMessage(ChatColor.YELLOW + "Write /channel global to switch to the global chat." ); player.setChatChannel(args[0]); return true; } if(commandName.equals("force") && args.length == 2 ){ player.setChatChannel(args[1]); Player to = getServer().matchPlayer(args[0]).get(0); info.tregmine.api.TregminePlayer toPlayer = this.tregminePlayer.get(to.getName()); toPlayer.setChatChannel(args[1]); to.sendMessage(ChatColor.YELLOW + player.getChatName() + " forced you into channel " + args[1].toUpperCase() + "."); to.sendMessage(ChatColor.YELLOW + "Write /channel global to switch back to the global chat." ); from.sendMessage(ChatColor.YELLOW + "You are now in a forced chat " + args[1].toUpperCase()+ " with " + to.getDisplayName() + "."); this.log.info(from.getName() + " FORCED CHAT WITH " + to.getDisplayName() + " IN CHANNEL " + args[1].toUpperCase()); return true; } if(commandName.equals("msg") || commandName.equals("m") || commandName.equals("tell")) { Player to = getServer().getPlayer(args[0]); if (to != null) { info.tregmine.api.TregminePlayer toPlayer = this.tregminePlayer.get(to.getName()); StringBuffer buf = new StringBuffer(); for (int i = 1; i < args.length; ++i) { buf.append(" " + args[i]); } String buffMsg = buf.toString(); if (!toPlayer.getMetaBoolean("invis")) { from.sendMessage(ChatColor.GREEN + "(to) " + toPlayer.getChatName() + ChatColor.GREEN + ": " + buffMsg); } to.sendMessage(ChatColor.GREEN + "(msg) " + player.getChatName() + ChatColor.GREEN + ": " + buffMsg); log.info(from.getName() + " => " + to.getName() + buffMsg); return true; } } if(commandName.equals("me") && args.length > 0 ){ StringBuffer buf = new StringBuffer(); Player[] players = getServer().getOnlinePlayers(); for (int i = 0; i < args.length; ++i) { buf.append(" " + args[i]); } for (Player tp : players) { TregminePlayer to = this.getPlayer(tp); if (player.getChatChannel().equals(to.getChatChannel())) { to.sendMessage("* " + player.getChatName() + ChatColor.WHITE + buf.toString() ); } } return true; } return false; } }
false
true
public boolean onCommand(CommandSender sender, Command command, String commandLabel, final String[] args) { String commandName = command.getName().toLowerCase(); Player from = null; TregminePlayer player = null; if(!(sender instanceof Player)) { if(commandName.equals("say")) { StringBuffer buf = new StringBuffer(); buf.append(args[0]); for (int i = 1; i < args.length; ++i) { buf.append(" " + args[i]); } String buffMsg = buf.toString(); this.getServer().broadcastMessage("<" + ChatColor.BLUE + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); this.log.info("CONSOLE: <GOD> " + buffMsg); return true; } return false; } else { from = (Player) sender; player = this.getPlayer(from); } if("book".matches(commandName)) { if("player".matches(args[0]) && player.isOp()) { final TregminePlayer fPlayer = player; this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { public void run() { // DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); fPlayer.sendMessage(ChatColor.YELLOW + "Starting to generate book for " + args[1] ); ItemStack book = new ItemStack(Material.WRITTEN_BOOK, 1); BookMeta bookmeta = (BookMeta) book.getItemMeta(); // TregminePlayer p = getPlayer(args[1]); long placed = 0; long destroyed = 0; long total = 0; int id = 0; String joinDate = ""; bookmeta.setAuthor("Tregmine"); bookmeta.setTitle(ChatColor.GREEN + args[1] + "'s Profile"); bookmeta.addPage(ChatColor.GREEN + args[1] + "'s profile" + '\n' + "date:"+'\n'+ date.toString()); Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = ConnectionPool.getConnection(); stmt = conn.prepareStatement("SELECT count(player) as count FROM stats_blocks WHERE player=?"); stmt.setString(1, args[1]); stmt.execute(); rs = stmt.getResultSet(); if (!rs.next()) { } total = rs.getInt("count"); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) {} } if (stmt != null) { try { stmt.close(); } catch (SQLException e) {} } if (conn != null) { try { conn.close(); } catch (SQLException e) {} } } try { conn = ConnectionPool.getConnection(); stmt = conn.prepareStatement("SELECT count(player) as count FROM stats_blocks WHERE player=? AND status=1"); stmt.setString(1, args[1]); stmt.execute(); rs = stmt.getResultSet(); if (!rs.next()) { } placed = rs.getInt("count"); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) {} } if (stmt != null) { try { stmt.close(); } catch (SQLException e) {} } if (conn != null) { try { conn.close(); } catch (SQLException e) {} } } try { conn = ConnectionPool.getConnection(); stmt = conn.prepareStatement("SELECT count(player) as count FROM stats_blocks WHERE player=? AND status=0"); stmt.setString(1, args[1]); stmt.execute(); rs = stmt.getResultSet(); if (!rs.next()) { } destroyed = rs.getInt("count"); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) {} } if (stmt != null) { try { stmt.close(); } catch (SQLException e) {} } if (conn != null) { try { conn.close(); } catch (SQLException e) {} } } try { conn = ConnectionPool.getConnection(); stmt = conn.prepareStatement("SELECT * FROM user WHERE player=?"); stmt.setString(1, args[1]); stmt.execute(); rs = stmt.getResultSet(); if (!rs.next()) { } joinDate = rs.getDate("time").toString(); id = rs.getInt("uid"); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) {} } if (stmt != null) { try { stmt.close(); } catch (SQLException e) {} } if (conn != null) { try { conn.close(); } catch (SQLException e) {} } } bookmeta.addPage( ChatColor.BLUE + "ID:" +'\n' + ChatColor.BLACK + id +'\n' + ChatColor.BLUE + "JOIN-TIME (GMT):" +'\n' + ChatColor.BLACK + joinDate +'\n' + ChatColor.BLUE + "BLOCK DESTROYED:" +'\n' + ChatColor.BLACK + destroyed +'\n' + ChatColor.BLUE + "BLOCK PLACED:" +'\n' + ChatColor.BLACK + placed +'\n' + ChatColor.BLUE + "TOTAL:" +'\n' + ChatColor.BLACK + total +'\n' + "EOF"); book.setItemMeta(bookmeta); PlayerInventory inv = fPlayer.getInventory(); inv.addItem(book); } },20L); } } if("blackout".matches(commandName) && player.isAdmin()) { Player target = getServer().getPlayer(args[1]); player.sendMessage("blackout"); if ("blind".matches(args[0])) { PotionEffect ef = new PotionEffect(PotionEffectType.BLINDNESS, 60, 100); target.getPlayer().addPotionEffect(ef); player.sendMessage("Blind"); } if ("invis".matches(args[0])) { PotionEffect ef = new PotionEffect(PotionEffectType.INVISIBILITY, 1600000, 100); target.getPlayer().addPotionEffect(ef); player.sendMessage("Blind"); } if ("confuse".matches(args[0])) { PotionEffect ef = new PotionEffect(PotionEffectType.CONFUSION, 600 , 10); target.getPlayer().addPotionEffect(ef); player.sendMessage("Confuse"); } } if("te".matches(commandName) && player.isOp()) { ItemStack drop = new ItemStack(Material.MONSTER_EGG, 1, (byte)65); List<String> lore = new ArrayList<String>(); // lore.add(ChatColor.GOLD + "EASTER EGG"); // lore.add(ChatColor.WHITE + "Found by: " + player.getChatName()); ItemMeta meta = drop.getItemMeta(); meta.setDisplayName(ChatColor.YELLOW + "EASTER EGG"); // meta.setLore(lore); // drop.setItemMeta(meta); // event.getBlock().getWorld().dropItem(event.getBlock().getLocation(), drop); player.getWorld().dropItemNaturally(player.getLocation(), drop); } if ("TregDev".matches(this.getServer().getServerName())) { if("te".matches(commandName)) { ItemStack item = new ItemStack(Material.PAPER, amount, (byte) 0); // PlayerInventory inv = player.getInventory(); ItemMeta meta = item.getItemMeta(); List<String> lore = new ArrayList<String>(); lore.add(info.tregmine.api.lore.Created.PURCHASED.toColorString()); TregminePlayer p = this.getPlayer(player); lore.add(ChatColor.WHITE + "by: " + p.getName() ); lore.add(ChatColor.WHITE + "Value: 25.000" + ChatColor.WHITE + " Tregs" ); meta.setLore(lore); meta.setDisplayName(ChatColor.GREEN + "DIRT -> SPONG Coupon"); item.setItemMeta(meta); } if("op".matches(commandName)) { player.setMetaBoolean("admin", true); player.setMetaBoolean("donator", true); player.setMetaBoolean("trusted", true); player.setTemporaryChatName(ChatColor.RED + player.getName()); player.setAllowFlight(true); player.setMetaString("color", ""+ChatColor.RED); } if("donator".matches(commandName)) { player.setAllowFlight(true); player.setMetaBoolean("admin", false); player.setMetaBoolean("donator", true); player.setMetaBoolean("trusted", true); player.setTemporaryChatName(ChatColor.GOLD + player.getName()); player.setMetaString("color", ""+ChatColor.GOLD); } if("settler".matches(commandName)) { player.setAllowFlight(true); player.setMetaBoolean("admin", false); player.setMetaBoolean("donator", false); player.setMetaBoolean("trusted", true); player.setTemporaryChatName(ChatColor.GREEN + player.getName()); player.setMetaString("color", ""+ChatColor.GREEN); } } if("invis".matches(commandName) && player.isOp()) { if ("off".matches(args[0])) { for (Player p : this.getServer().getOnlinePlayers()) { p.showPlayer(player.getPlayer()); } player.setMetaBoolean("invis", false); player.sendMessage(ChatColor.YELLOW + "You can now be seen!"); } else if ("on".matches(args[0])) { for (Player p : this.getServer().getOnlinePlayers()) { if (!p.isOp()) { p.hidePlayer(player.getPlayer()); } else { p.showPlayer(player.getPlayer()); } } player.setMetaBoolean("invis", true); player.sendMessage(ChatColor.YELLOW + "*poof* no one knows where you are!"); } else { player.sendMessage("Try /invis [on|off]"); } } if(commandName.equals("text") && player.isAdmin()) { Player[] players = this.getServer().getOnlinePlayers(); // player.setTexturePack(args[0]); for (Player p : players) { p.setTexturePack(args[0]); } } if(commandName.equals("head") && player.isOp()) { ItemStack item = new ItemStack(Material.SKULL_ITEM, 1, (byte) 3); SkullMeta meta = (SkullMeta) item.getItemMeta(); meta.setOwner(args[0]); meta.setDisplayName(ChatColor.YELLOW + "Head of " + args[0]); item.setItemMeta(meta); PlayerInventory inv = player.getInventory(); inv.addItem(item); player.updateInventory(); player.sendMessage("Skull of " + args[0]); } else if(commandName.equals("head")) { player.kickPlayer(""); } if(commandName.equals("say") && player.isAdmin()) { StringBuffer buf = new StringBuffer(); buf.append(args[0]); for (int i = 1; i < args.length; ++i) { buf.append(" " + args[i]); } String buffMsg = buf.toString(); if(from.getName().matches("BlackX")) { this.getServer().broadcastMessage("<" + ChatColor.BLACK + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("mejjad")){ this.getServer().broadcastMessage("<" + ChatColor.DARK_AQUA + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("einand")){ this.getServer().broadcastMessage("<" + ChatColor.DARK_GREEN + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("LilKiw")){ this.getServer().broadcastMessage("<" + ChatColor.AQUA + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("Camrenn")){ this.getServer().broadcastMessage("<" + ChatColor.LIGHT_PURPLE + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("Mksen")){ this.getServer().broadcastMessage("<" + ChatColor.YELLOW + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("josh121297")){ this.getServer().broadcastMessage("<" + ChatColor.GREEN + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("GeorgeBombadil")){ this.getServer().broadcastMessage("<" + ChatColor.DARK_RED + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("rweiand")){ this.getServer().broadcastMessage("<" + ChatColor.GOLD + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else { this.getServer().broadcastMessage("<" + ChatColor.RED + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } this.log.info(from.getName() + ": <GOD> " + buffMsg); Player[] players = this.getServer().getOnlinePlayers(); for (Player p : players) { info.tregmine.api.TregminePlayer locTregminePlayer = this.getPlayer((p.getName())); if (locTregminePlayer.isAdmin()) { p.sendMessage(ChatColor.DARK_AQUA + "/say used by: " + player.getChatName()); } } return true; } if(commandName.equals("who") || commandName.equals("playerlist") || commandName.equals("list")){ info.tregmine.commands.Who.run(this, player, args); return true; } if(commandName.equals("tp")){ info.tregmine.commands.Tp.run(this, player, args); return true; } if(commandName.equals("channel")){ if (args.length != 1) { return false; } from.sendMessage(ChatColor.YELLOW + "You are now talking in channel " + args[0] + "."); from.sendMessage(ChatColor.YELLOW + "Write /channel global to switch to the global chat." ); player.setChatChannel(args[0]); return true; } if(commandName.equals("force") && args.length == 2 ){ player.setChatChannel(args[1]); Player to = getServer().matchPlayer(args[0]).get(0); info.tregmine.api.TregminePlayer toPlayer = this.tregminePlayer.get(to.getName()); toPlayer.setChatChannel(args[1]); to.sendMessage(ChatColor.YELLOW + player.getChatName() + " forced you into channel " + args[1].toUpperCase() + "."); to.sendMessage(ChatColor.YELLOW + "Write /channel global to switch back to the global chat." ); from.sendMessage(ChatColor.YELLOW + "You are now in a forced chat " + args[1].toUpperCase()+ " with " + to.getDisplayName() + "."); this.log.info(from.getName() + " FORCED CHAT WITH " + to.getDisplayName() + " IN CHANNEL " + args[1].toUpperCase()); return true; } if(commandName.equals("msg") || commandName.equals("m") || commandName.equals("tell")) { Player to = getServer().getPlayer(args[0]); if (to != null) { info.tregmine.api.TregminePlayer toPlayer = this.tregminePlayer.get(to.getName()); StringBuffer buf = new StringBuffer(); for (int i = 1; i < args.length; ++i) { buf.append(" " + args[i]); } String buffMsg = buf.toString(); if (!toPlayer.getMetaBoolean("invis")) { from.sendMessage(ChatColor.GREEN + "(to) " + toPlayer.getChatName() + ChatColor.GREEN + ": " + buffMsg); } to.sendMessage(ChatColor.GREEN + "(msg) " + player.getChatName() + ChatColor.GREEN + ": " + buffMsg); log.info(from.getName() + " => " + to.getName() + buffMsg); return true; } } if(commandName.equals("me") && args.length > 0 ){ StringBuffer buf = new StringBuffer(); Player[] players = getServer().getOnlinePlayers(); for (int i = 0; i < args.length; ++i) { buf.append(" " + args[i]); } for (Player tp : players) { TregminePlayer to = this.getPlayer(tp); if (player.getChatChannel().equals(to.getChatChannel())) { to.sendMessage("* " + player.getChatName() + ChatColor.WHITE + buf.toString() ); } } return true; } return false; }
public boolean onCommand(CommandSender sender, Command command, String commandLabel, final String[] args) { String commandName = command.getName().toLowerCase(); Player from = null; TregminePlayer player = null; if(!(sender instanceof Player)) { if(commandName.equals("say")) { StringBuffer buf = new StringBuffer(); buf.append(args[0]); for (int i = 1; i < args.length; ++i) { buf.append(" " + args[i]); } String buffMsg = buf.toString(); this.getServer().broadcastMessage("<" + ChatColor.BLUE + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); this.log.info("CONSOLE: <GOD> " + buffMsg); return true; } return false; } else { from = (Player) sender; player = this.getPlayer(from); } if("book".matches(commandName)) { if("player".matches(args[0]) && player.isOp()) { final TregminePlayer fPlayer = player; this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { public void run() { // DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); fPlayer.sendMessage(ChatColor.YELLOW + "Starting to generate book for " + args[1] ); ItemStack book = new ItemStack(Material.WRITTEN_BOOK, 1); BookMeta bookmeta = (BookMeta) book.getItemMeta(); // TregminePlayer p = getPlayer(args[1]); long placed = 0; long destroyed = 0; long total = 0; int id = 0; String joinDate = ""; bookmeta.setAuthor("Tregmine"); bookmeta.setTitle(ChatColor.GREEN + args[1] + "'s Profile"); bookmeta.addPage(ChatColor.GREEN + args[1] + "'s profile" + '\n' + "date:"+'\n'+ date.toString()); Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = ConnectionPool.getConnection(); stmt = conn.prepareStatement("SELECT count(player) as count FROM stats_blocks WHERE player=?"); stmt.setString(1, args[1]); stmt.execute(); rs = stmt.getResultSet(); if (!rs.next()) { } total = rs.getInt("count"); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) {} } if (stmt != null) { try { stmt.close(); } catch (SQLException e) {} } if (conn != null) { try { conn.close(); } catch (SQLException e) {} } } try { conn = ConnectionPool.getConnection(); stmt = conn.prepareStatement("SELECT count(player) as count FROM stats_blocks WHERE player=? AND status=1"); stmt.setString(1, args[1]); stmt.execute(); rs = stmt.getResultSet(); if (!rs.next()) { } placed = rs.getInt("count"); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) {} } if (stmt != null) { try { stmt.close(); } catch (SQLException e) {} } if (conn != null) { try { conn.close(); } catch (SQLException e) {} } } try { conn = ConnectionPool.getConnection(); stmt = conn.prepareStatement("SELECT count(player) as count FROM stats_blocks WHERE player=? AND status=0"); stmt.setString(1, args[1]); stmt.execute(); rs = stmt.getResultSet(); if (!rs.next()) { } destroyed = rs.getInt("count"); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) {} } if (stmt != null) { try { stmt.close(); } catch (SQLException e) {} } if (conn != null) { try { conn.close(); } catch (SQLException e) {} } } try { conn = ConnectionPool.getConnection(); stmt = conn.prepareStatement("SELECT * FROM user WHERE player=?"); stmt.setString(1, args[1]); stmt.execute(); rs = stmt.getResultSet(); if (!rs.next()) { } joinDate = rs.getDate("time").toString(); id = rs.getInt("uid"); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) {} } if (stmt != null) { try { stmt.close(); } catch (SQLException e) {} } if (conn != null) { try { conn.close(); } catch (SQLException e) {} } } bookmeta.addPage( ChatColor.BLUE + "ID:" +'\n' + ChatColor.BLACK + id +'\n' + ChatColor.BLUE + "JOIN-TIME (GMT):" +'\n' + ChatColor.BLACK + joinDate +'\n' + ChatColor.BLUE + "BLOCK DESTROYED:" +'\n' + ChatColor.BLACK + destroyed +'\n' + ChatColor.BLUE + "BLOCK PLACED:" +'\n' + ChatColor.BLACK + placed +'\n' + ChatColor.BLUE + "TOTAL:" +'\n' + ChatColor.BLACK + total +'\n' + "EOF"); book.setItemMeta(bookmeta); PlayerInventory inv = fPlayer.getInventory(); inv.addItem(book); } },20L); } } if("blackout".matches(commandName) && player.isAdmin()) { Player target = getServer().getPlayer(args[1]); player.sendMessage("blackout"); if ("blind".matches(args[0])) { PotionEffect ef = new PotionEffect(PotionEffectType.BLINDNESS, 60, 100); target.getPlayer().addPotionEffect(ef); player.sendMessage("Blind"); } if ("invis".matches(args[0])) { PotionEffect ef = new PotionEffect(PotionEffectType.INVISIBILITY, 1600000, 100); target.getPlayer().addPotionEffect(ef); player.sendMessage("Blind"); } if ("confuse".matches(args[0])) { PotionEffect ef = new PotionEffect(PotionEffectType.CONFUSION, 600 , 10); target.getPlayer().addPotionEffect(ef); player.sendMessage("Confuse"); } } if("te".matches(commandName) && player.isOp()) { ItemStack drop = new ItemStack(Material.MONSTER_EGG, 1, (byte)65); // List<String> lore = new ArrayList<String>(); // lore.add(ChatColor.GOLD + "EASTER EGG"); // lore.add(ChatColor.WHITE + "Found by: " + player.getChatName()); ItemMeta meta = drop.getItemMeta(); meta.setDisplayName(ChatColor.YELLOW + "EASTER EGG"); // meta.setLore(lore); drop.setItemMeta(meta); // event.getBlock().getWorld().dropItem(event.getBlock().getLocation(), drop); player.getWorld().dropItemNaturally(player.getLocation(), drop); } if ("TregDev".matches(this.getServer().getServerName())) { if("te".matches(commandName)) { ItemStack item = new ItemStack(Material.PAPER, amount, (byte) 0); // PlayerInventory inv = player.getInventory(); ItemMeta meta = item.getItemMeta(); List<String> lore = new ArrayList<String>(); lore.add(info.tregmine.api.lore.Created.PURCHASED.toColorString()); TregminePlayer p = this.getPlayer(player); lore.add(ChatColor.WHITE + "by: " + p.getName() ); lore.add(ChatColor.WHITE + "Value: 25.000" + ChatColor.WHITE + " Tregs" ); meta.setLore(lore); meta.setDisplayName(ChatColor.GREEN + "DIRT -> SPONG Coupon"); item.setItemMeta(meta); } if("op".matches(commandName)) { player.setMetaBoolean("admin", true); player.setMetaBoolean("donator", true); player.setMetaBoolean("trusted", true); player.setTemporaryChatName(ChatColor.RED + player.getName()); player.setAllowFlight(true); player.setMetaString("color", ""+ChatColor.RED); } if("donator".matches(commandName)) { player.setAllowFlight(true); player.setMetaBoolean("admin", false); player.setMetaBoolean("donator", true); player.setMetaBoolean("trusted", true); player.setTemporaryChatName(ChatColor.GOLD + player.getName()); player.setMetaString("color", ""+ChatColor.GOLD); } if("settler".matches(commandName)) { player.setAllowFlight(true); player.setMetaBoolean("admin", false); player.setMetaBoolean("donator", false); player.setMetaBoolean("trusted", true); player.setTemporaryChatName(ChatColor.GREEN + player.getName()); player.setMetaString("color", ""+ChatColor.GREEN); } } if("invis".matches(commandName) && player.isOp()) { if ("off".matches(args[0])) { for (Player p : this.getServer().getOnlinePlayers()) { p.showPlayer(player.getPlayer()); } player.setMetaBoolean("invis", false); player.sendMessage(ChatColor.YELLOW + "You can now be seen!"); } else if ("on".matches(args[0])) { for (Player p : this.getServer().getOnlinePlayers()) { if (!p.isOp()) { p.hidePlayer(player.getPlayer()); } else { p.showPlayer(player.getPlayer()); } } player.setMetaBoolean("invis", true); player.sendMessage(ChatColor.YELLOW + "*poof* no one knows where you are!"); } else { player.sendMessage("Try /invis [on|off]"); } } if(commandName.equals("text") && player.isAdmin()) { Player[] players = this.getServer().getOnlinePlayers(); // player.setTexturePack(args[0]); for (Player p : players) { p.setTexturePack(args[0]); } } if(commandName.equals("head") && player.isOp()) { ItemStack item = new ItemStack(Material.SKULL_ITEM, 1, (byte) 3); SkullMeta meta = (SkullMeta) item.getItemMeta(); meta.setOwner(args[0]); meta.setDisplayName(ChatColor.YELLOW + "Head of " + args[0]); item.setItemMeta(meta); PlayerInventory inv = player.getInventory(); inv.addItem(item); player.updateInventory(); player.sendMessage("Skull of " + args[0]); } else if(commandName.equals("head")) { player.kickPlayer(""); } if(commandName.equals("say") && player.isAdmin()) { StringBuffer buf = new StringBuffer(); buf.append(args[0]); for (int i = 1; i < args.length; ++i) { buf.append(" " + args[i]); } String buffMsg = buf.toString(); if(from.getName().matches("BlackX")) { this.getServer().broadcastMessage("<" + ChatColor.BLACK + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("mejjad")){ this.getServer().broadcastMessage("<" + ChatColor.DARK_AQUA + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("einand")){ this.getServer().broadcastMessage("<" + ChatColor.DARK_GREEN + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("LilKiw")){ this.getServer().broadcastMessage("<" + ChatColor.AQUA + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("Camrenn")){ this.getServer().broadcastMessage("<" + ChatColor.LIGHT_PURPLE + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("Mksen")){ this.getServer().broadcastMessage("<" + ChatColor.YELLOW + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("josh121297")){ this.getServer().broadcastMessage("<" + ChatColor.GREEN + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("GeorgeBombadil")){ this.getServer().broadcastMessage("<" + ChatColor.DARK_RED + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("rweiand")){ this.getServer().broadcastMessage("<" + ChatColor.GOLD + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else { this.getServer().broadcastMessage("<" + ChatColor.RED + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } this.log.info(from.getName() + ": <GOD> " + buffMsg); Player[] players = this.getServer().getOnlinePlayers(); for (Player p : players) { info.tregmine.api.TregminePlayer locTregminePlayer = this.getPlayer((p.getName())); if (locTregminePlayer.isAdmin()) { p.sendMessage(ChatColor.DARK_AQUA + "/say used by: " + player.getChatName()); } } return true; } if(commandName.equals("who") || commandName.equals("playerlist") || commandName.equals("list")){ info.tregmine.commands.Who.run(this, player, args); return true; } if(commandName.equals("tp")){ info.tregmine.commands.Tp.run(this, player, args); return true; } if(commandName.equals("channel")){ if (args.length != 1) { return false; } from.sendMessage(ChatColor.YELLOW + "You are now talking in channel " + args[0] + "."); from.sendMessage(ChatColor.YELLOW + "Write /channel global to switch to the global chat." ); player.setChatChannel(args[0]); return true; } if(commandName.equals("force") && args.length == 2 ){ player.setChatChannel(args[1]); Player to = getServer().matchPlayer(args[0]).get(0); info.tregmine.api.TregminePlayer toPlayer = this.tregminePlayer.get(to.getName()); toPlayer.setChatChannel(args[1]); to.sendMessage(ChatColor.YELLOW + player.getChatName() + " forced you into channel " + args[1].toUpperCase() + "."); to.sendMessage(ChatColor.YELLOW + "Write /channel global to switch back to the global chat." ); from.sendMessage(ChatColor.YELLOW + "You are now in a forced chat " + args[1].toUpperCase()+ " with " + to.getDisplayName() + "."); this.log.info(from.getName() + " FORCED CHAT WITH " + to.getDisplayName() + " IN CHANNEL " + args[1].toUpperCase()); return true; } if(commandName.equals("msg") || commandName.equals("m") || commandName.equals("tell")) { Player to = getServer().getPlayer(args[0]); if (to != null) { info.tregmine.api.TregminePlayer toPlayer = this.tregminePlayer.get(to.getName()); StringBuffer buf = new StringBuffer(); for (int i = 1; i < args.length; ++i) { buf.append(" " + args[i]); } String buffMsg = buf.toString(); if (!toPlayer.getMetaBoolean("invis")) { from.sendMessage(ChatColor.GREEN + "(to) " + toPlayer.getChatName() + ChatColor.GREEN + ": " + buffMsg); } to.sendMessage(ChatColor.GREEN + "(msg) " + player.getChatName() + ChatColor.GREEN + ": " + buffMsg); log.info(from.getName() + " => " + to.getName() + buffMsg); return true; } } if(commandName.equals("me") && args.length > 0 ){ StringBuffer buf = new StringBuffer(); Player[] players = getServer().getOnlinePlayers(); for (int i = 0; i < args.length; ++i) { buf.append(" " + args[i]); } for (Player tp : players) { TregminePlayer to = this.getPlayer(tp); if (player.getChatChannel().equals(to.getChatChannel())) { to.sendMessage("* " + player.getChatName() + ChatColor.WHITE + buf.toString() ); } } return true; } return false; }
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/search/facet/terms/strings/TermsStringOrdinalsFacetCollector.java b/modules/elasticsearch/src/main/java/org/elasticsearch/search/facet/terms/strings/TermsStringOrdinalsFacetCollector.java index ba0a2ec90a0..66c23f9da28 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/search/facet/terms/strings/TermsStringOrdinalsFacetCollector.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/search/facet/terms/strings/TermsStringOrdinalsFacetCollector.java @@ -1,267 +1,271 @@ /* * Licensed to Elastic Search and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Elastic Search 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.search.facet.terms.strings; import org.apache.lucene.index.IndexReader; import org.apache.lucene.util.PriorityQueue; import org.elasticsearch.ElasticSearchIllegalArgumentException; import org.elasticsearch.common.CacheRecycler; import org.elasticsearch.common.collect.BoundedTreeSet; import org.elasticsearch.common.collect.ImmutableSet; import org.elasticsearch.index.cache.field.data.FieldDataCache; import org.elasticsearch.index.field.data.FieldData; import org.elasticsearch.index.field.data.FieldDataType; import org.elasticsearch.index.field.data.strings.StringFieldData; import org.elasticsearch.index.mapper.MapperService; import org.elasticsearch.search.facet.AbstractFacetCollector; import org.elasticsearch.search.facet.Facet; import org.elasticsearch.search.facet.terms.TermsFacet; import org.elasticsearch.search.facet.terms.support.EntryPriorityQueue; import org.elasticsearch.search.internal.SearchContext; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author kimchy (shay.banon) */ public class TermsStringOrdinalsFacetCollector extends AbstractFacetCollector { private final FieldDataCache fieldDataCache; private final String indexFieldName; private final TermsFacet.ComparatorType comparatorType; private final int size; private final int numberOfShards; private final int minCount; private final FieldDataType fieldDataType; private StringFieldData fieldData; private final List<ReaderAggregator> aggregators; private ReaderAggregator current; long missing; long total; private final ImmutableSet<String> excluded; private final Matcher matcher; public TermsStringOrdinalsFacetCollector(String facetName, String fieldName, int size, TermsFacet.ComparatorType comparatorType, boolean allTerms, SearchContext context, ImmutableSet<String> excluded, Pattern pattern) { super(facetName); this.fieldDataCache = context.fieldDataCache(); this.size = size; this.comparatorType = comparatorType; this.numberOfShards = context.numberOfShards(); MapperService.SmartNameFieldMappers smartMappers = context.smartFieldMappers(fieldName); if (smartMappers == null || !smartMappers.hasMapper()) { throw new ElasticSearchIllegalArgumentException("Field [" + fieldName + "] doesn't have a type, can't run terms long facet collector on it"); } // add type filter if there is exact doc mapper associated with it if (smartMappers.hasDocMapper() && smartMappers.explicitTypeInName()) { setFilter(context.filterCache().cache(smartMappers.docMapper().typeFilter())); } if (smartMappers.mapper().fieldDataType() != FieldDataType.DefaultTypes.STRING) { throw new ElasticSearchIllegalArgumentException("Field [" + fieldName + "] is not of string type, can't run terms string facet collector on it"); } this.indexFieldName = smartMappers.mapper().names().indexName(); this.fieldDataType = smartMappers.mapper().fieldDataType(); if (excluded == null || excluded.isEmpty()) { this.excluded = null; } else { this.excluded = excluded; } this.matcher = pattern != null ? pattern.matcher("") : null; // minCount is offset by -1 if (allTerms) { minCount = -1; } else { minCount = 0; } this.aggregators = new ArrayList<ReaderAggregator>(context.searcher().subReaders().length); } @Override protected void doSetNextReader(IndexReader reader, int docBase) throws IOException { if (current != null) { missing += current.counts[0]; total += current.total - current.counts[0]; if (current.values.length > 1) { aggregators.add(current); } } fieldData = (StringFieldData) fieldDataCache.cache(fieldDataType, reader, indexFieldName); current = new ReaderAggregator(fieldData); } @Override protected void doCollect(int doc) throws IOException { fieldData.forEachOrdinalInDoc(doc, current); } @Override public Facet facet() { if (current != null) { missing += current.counts[0]; total += current.total - current.counts[0]; // if we have values for this one, add it if (current.values.length > 1) { aggregators.add(current); } } AggregatorPriorityQueue queue = new AggregatorPriorityQueue(aggregators.size()); for (ReaderAggregator aggregator : aggregators) { if (aggregator.nextPosition()) { queue.add(aggregator); } } // YACK, we repeat the same logic, but once with an optimizer priority queue for smaller sizes if (size < EntryPriorityQueue.LIMIT) { // optimize to use priority size EntryPriorityQueue ordered = new EntryPriorityQueue(size, comparatorType.comparator()); while (queue.size() > 0) { ReaderAggregator agg = queue.top(); String value = agg.current; int count = 0; do { count += agg.counts[agg.position]; if (agg.nextPosition()) { agg = queue.updateTop(); } else { // we are done with this reader queue.pop(); agg = queue.top(); } } while (agg != null && value.equals(agg.current)); if (count > minCount) { if (excluded != null && excluded.contains(value)) { continue; } if (matcher != null && !matcher.reset(value).matches()) { continue; } InternalStringTermsFacet.StringEntry entry = new InternalStringTermsFacet.StringEntry(value, count); ordered.insertWithOverflow(entry); } } InternalStringTermsFacet.StringEntry[] list = new InternalStringTermsFacet.StringEntry[ordered.size()]; for (int i = ordered.size() - 1; i >= 0; i--) { list[i] = (InternalStringTermsFacet.StringEntry) ordered.pop(); } for (ReaderAggregator aggregator : aggregators) { CacheRecycler.pushIntArray(aggregator.counts); } return new InternalStringTermsFacet(facetName, comparatorType, size, Arrays.asList(list), missing, total); } BoundedTreeSet<InternalStringTermsFacet.StringEntry> ordered = new BoundedTreeSet<InternalStringTermsFacet.StringEntry>(comparatorType.comparator(), size); while (queue.size() > 0) { ReaderAggregator agg = queue.top(); String value = agg.current; int count = 0; do { count += agg.counts[agg.position]; if (agg.nextPosition()) { agg = queue.updateTop(); } else { // we are done with this reader queue.pop(); agg = queue.top(); } } while (agg != null && value.equals(agg.current)); if (count > minCount) { - if (excluded == null || !excluded.contains(value)) { - InternalStringTermsFacet.StringEntry entry = new InternalStringTermsFacet.StringEntry(value, count); - ordered.add(entry); + if (excluded != null && excluded.contains(value)) { + continue; + } + if (matcher != null && !matcher.reset(value).matches()) { + continue; } + InternalStringTermsFacet.StringEntry entry = new InternalStringTermsFacet.StringEntry(value, count); + ordered.add(entry); } } for (ReaderAggregator aggregator : aggregators) { CacheRecycler.pushIntArray(aggregator.counts); } return new InternalStringTermsFacet(facetName, comparatorType, size, ordered, missing, total); } public static class ReaderAggregator implements FieldData.OrdinalInDocProc { final String[] values; final int[] counts; int position = 0; String current; int total; public ReaderAggregator(StringFieldData fieldData) { this.values = fieldData.values(); this.counts = CacheRecycler.popIntArray(fieldData.values().length); } @Override public void onOrdinal(int docId, int ordinal) { counts[ordinal]++; total++; } public boolean nextPosition() { if (++position >= values.length) { return false; } current = values[position]; return true; } } public static class AggregatorPriorityQueue extends PriorityQueue<ReaderAggregator> { public AggregatorPriorityQueue(int size) { initialize(size); } @Override protected boolean lessThan(ReaderAggregator a, ReaderAggregator b) { return a.current.compareTo(b.current) < 0; } } }
false
true
@Override public Facet facet() { if (current != null) { missing += current.counts[0]; total += current.total - current.counts[0]; // if we have values for this one, add it if (current.values.length > 1) { aggregators.add(current); } } AggregatorPriorityQueue queue = new AggregatorPriorityQueue(aggregators.size()); for (ReaderAggregator aggregator : aggregators) { if (aggregator.nextPosition()) { queue.add(aggregator); } } // YACK, we repeat the same logic, but once with an optimizer priority queue for smaller sizes if (size < EntryPriorityQueue.LIMIT) { // optimize to use priority size EntryPriorityQueue ordered = new EntryPriorityQueue(size, comparatorType.comparator()); while (queue.size() > 0) { ReaderAggregator agg = queue.top(); String value = agg.current; int count = 0; do { count += agg.counts[agg.position]; if (agg.nextPosition()) { agg = queue.updateTop(); } else { // we are done with this reader queue.pop(); agg = queue.top(); } } while (agg != null && value.equals(agg.current)); if (count > minCount) { if (excluded != null && excluded.contains(value)) { continue; } if (matcher != null && !matcher.reset(value).matches()) { continue; } InternalStringTermsFacet.StringEntry entry = new InternalStringTermsFacet.StringEntry(value, count); ordered.insertWithOverflow(entry); } } InternalStringTermsFacet.StringEntry[] list = new InternalStringTermsFacet.StringEntry[ordered.size()]; for (int i = ordered.size() - 1; i >= 0; i--) { list[i] = (InternalStringTermsFacet.StringEntry) ordered.pop(); } for (ReaderAggregator aggregator : aggregators) { CacheRecycler.pushIntArray(aggregator.counts); } return new InternalStringTermsFacet(facetName, comparatorType, size, Arrays.asList(list), missing, total); } BoundedTreeSet<InternalStringTermsFacet.StringEntry> ordered = new BoundedTreeSet<InternalStringTermsFacet.StringEntry>(comparatorType.comparator(), size); while (queue.size() > 0) { ReaderAggregator agg = queue.top(); String value = agg.current; int count = 0; do { count += agg.counts[agg.position]; if (agg.nextPosition()) { agg = queue.updateTop(); } else { // we are done with this reader queue.pop(); agg = queue.top(); } } while (agg != null && value.equals(agg.current)); if (count > minCount) { if (excluded == null || !excluded.contains(value)) { InternalStringTermsFacet.StringEntry entry = new InternalStringTermsFacet.StringEntry(value, count); ordered.add(entry); } } } for (ReaderAggregator aggregator : aggregators) { CacheRecycler.pushIntArray(aggregator.counts); } return new InternalStringTermsFacet(facetName, comparatorType, size, ordered, missing, total); }
@Override public Facet facet() { if (current != null) { missing += current.counts[0]; total += current.total - current.counts[0]; // if we have values for this one, add it if (current.values.length > 1) { aggregators.add(current); } } AggregatorPriorityQueue queue = new AggregatorPriorityQueue(aggregators.size()); for (ReaderAggregator aggregator : aggregators) { if (aggregator.nextPosition()) { queue.add(aggregator); } } // YACK, we repeat the same logic, but once with an optimizer priority queue for smaller sizes if (size < EntryPriorityQueue.LIMIT) { // optimize to use priority size EntryPriorityQueue ordered = new EntryPriorityQueue(size, comparatorType.comparator()); while (queue.size() > 0) { ReaderAggregator agg = queue.top(); String value = agg.current; int count = 0; do { count += agg.counts[agg.position]; if (agg.nextPosition()) { agg = queue.updateTop(); } else { // we are done with this reader queue.pop(); agg = queue.top(); } } while (agg != null && value.equals(agg.current)); if (count > minCount) { if (excluded != null && excluded.contains(value)) { continue; } if (matcher != null && !matcher.reset(value).matches()) { continue; } InternalStringTermsFacet.StringEntry entry = new InternalStringTermsFacet.StringEntry(value, count); ordered.insertWithOverflow(entry); } } InternalStringTermsFacet.StringEntry[] list = new InternalStringTermsFacet.StringEntry[ordered.size()]; for (int i = ordered.size() - 1; i >= 0; i--) { list[i] = (InternalStringTermsFacet.StringEntry) ordered.pop(); } for (ReaderAggregator aggregator : aggregators) { CacheRecycler.pushIntArray(aggregator.counts); } return new InternalStringTermsFacet(facetName, comparatorType, size, Arrays.asList(list), missing, total); } BoundedTreeSet<InternalStringTermsFacet.StringEntry> ordered = new BoundedTreeSet<InternalStringTermsFacet.StringEntry>(comparatorType.comparator(), size); while (queue.size() > 0) { ReaderAggregator agg = queue.top(); String value = agg.current; int count = 0; do { count += agg.counts[agg.position]; if (agg.nextPosition()) { agg = queue.updateTop(); } else { // we are done with this reader queue.pop(); agg = queue.top(); } } while (agg != null && value.equals(agg.current)); if (count > minCount) { if (excluded != null && excluded.contains(value)) { continue; } if (matcher != null && !matcher.reset(value).matches()) { continue; } InternalStringTermsFacet.StringEntry entry = new InternalStringTermsFacet.StringEntry(value, count); ordered.add(entry); } } for (ReaderAggregator aggregator : aggregators) { CacheRecycler.pushIntArray(aggregator.counts); } return new InternalStringTermsFacet(facetName, comparatorType, size, ordered, missing, total); }
diff --git a/src/main/java/org/sql2o/Query.java b/src/main/java/org/sql2o/Query.java index 207d520..833deb4 100644 --- a/src/main/java/org/sql2o/Query.java +++ b/src/main/java/org/sql2o/Query.java @@ -1,505 +1,505 @@ package org.sql2o; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sql2o.converters.Convert; import org.sql2o.converters.Converter; import org.sql2o.converters.ConverterException; import org.sql2o.data.Table; import org.sql2o.data.TableFactory; import org.sql2o.reflection.Pojo; import org.sql2o.reflection.PojoMetadata; import org.sql2o.tools.NamedParameterStatement; import java.lang.reflect.Method; import java.sql.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by IntelliJ IDEA. * User: lars * Date: 5/18/11 * Time: 8:27 PM * To change this template use File | Settings | File Templates. */ public class Query { private final Logger logger = LoggerFactory.getLogger(Query.class); public Query(Connection connection, String queryText, String name) { this.connection = connection; this.name = name; try{ statement = new NamedParameterStatement(connection.getJdbcConnection(), queryText); } catch(Exception ex){ throw new RuntimeException(ex); } this.setColumnMappings(connection.getSql2o().getDefaultColumnMappings()); this.caseSensitive = connection.getSql2o().isDefaultCaseSensitive(); this.methodsMap = new HashMap<String, Method>(); } private Connection connection; private Map<String, String> caseSensitiveColumnMappings; private Map<String, String> columnMappings; private Map<String, Method> methodsMap; private NamedParameterStatement statement; private boolean caseSensitive; private final String name; public Query addParameter(String name, Object value){ try{ statement.setObject(name, value); } catch(SQLException ex){ throw new RuntimeException(ex); } return this; } public Query addParameter(String name, int value){ try{ statement.setInt(name, value); } catch (SQLException ex){ throw new Sql2oException(ex); } return this; } public Query addParameter(String name, Integer value){ try{ if (value == null){ statement.setNull(name, Types.INTEGER); }else{ statement.setInt(name, value); } } catch(SQLException ex){ throw new RuntimeException(ex); } return this; } public Query addParameter(String name, long value){ try{ statement.setLong(name, value); } catch(SQLException ex){ throw new RuntimeException(ex); } return this; } public Query addParameter(String name, Long value){ try{ if (value == null){ statement.setNull(name, Types.INTEGER); } else { statement.setLong(name, value); } } catch (SQLException ex){ throw new Sql2oException(ex); } return this; } public Query addParameter(String name, String value){ try{ if (value == null){ statement.setNull(name, Types.VARCHAR); }else{ statement.setString(name, value); } } catch(Exception ex){ throw new RuntimeException(ex); } return this; } public Query addParameter(String name, Timestamp value){ try{ if (value == null){ statement.setNull(name, Types.TIMESTAMP); } else { statement.setTimestamp(name, value); } } catch(Exception ex){ throw new RuntimeException(ex); } return this; } public Query addParameter(String name, Date value){ try{ if (value == null){ statement.setNull(name, Types.DATE); } else { statement.setDate(name, value); } } catch (Exception ex){ throw new RuntimeException(ex); } return this; } public Query addParameter(String name, java.util.Date value){ Date sqlDate = value == null ? null : new Date(value.getTime()); if (sqlDate != null && this.connection.getSql2o().quirksMode == QuirksMode.DB2){ // With the DB2 driver you can get an error if trying to put a date value into a timestamp column, // but of some reason it works if using setObject(). return addParameter(name, (Object)sqlDate); }else{ return addParameter(name, sqlDate); } } public Query addParameter(String name, Time value){ try { if (value == null){ statement.setNull(name, Types.TIME); } else { statement.setTime(name,value); } } catch (SQLException e) { throw new RuntimeException(e); } return this; } public Query addParameter(String name, DateTime value){ return addParameter(name, value.toDate()); } public boolean isCaseSensitive() { return caseSensitive; } public Query setCaseSensitive(boolean caseSensitive) { this.caseSensitive = caseSensitive; return this; } public Connection getConnection(){ return this.connection; } public String getName() { return name; } // public List[] executeAndFetchMultiple(Class ... returnTypes){ // List<List> listOfLists = new ArrayList<List>(); // // try { // boolean hasResult = statement.getStatement().execute(); // // // for (Class clazz : returnTypes){ // List objList = new ArrayList(); // PojoMetadata metadata = new PojoMetadata(clazz, this.isCaseSensitive(), this.getColumnMappings()); // // ResultSet rs = statement.getStatement().getResultSet(); // ResultSetMetaData meta = rs.getMetaData(); // // while (rs.next()){ // Pojo pojo = new Pojo(metadata, this.isCaseSensitive()); // // for (int colIdx = 1; colIdx <= meta.getColumnCount(); colIdx++){ // String colName = meta.getColumnName(colIdx); // pojo.setProperty(colName, rs.getObject(colIdx)); // } // // objList.add(pojo.getObject()); // } // // rs.close(); // // listOfLists.add(objList); // // hasResult = statement.getStatement().getMoreResults(); // } // // } catch (SQLException e) { // throw new Sql2oException("Database error", e); // } // finally { // closeConnectionIfNecessary(); // } // // return listOfLists.toArray(new ArrayList[listOfLists.size()]); // } public <T> List<T> executeAndFetch(Class returnType){ List list = new ArrayList(); PojoMetadata metadata = new PojoMetadata(returnType, this.isCaseSensitive(), this.getColumnMappings()); try{ //java.util.Date st = new java.util.Date(); long start = System.currentTimeMillis(); ResultSet rs = statement.executeQuery(); long afterExecQuery = System.currentTimeMillis(); ResultSetMetaData meta = rs.getMetaData(); while(rs.next()){ Pojo pojo = new Pojo(metadata, this.isCaseSensitive()); //Object obj = returnType.newInstance(); for(int colIdx = 1; colIdx <= meta.getColumnCount(); colIdx++){ String colName = meta.getColumnName(colIdx); pojo.setProperty(colName, rs.getObject(colIdx)); } list.add(pojo.getObject()); } rs.close(); long afterClose = System.currentTimeMillis(); logger.info("total: {} ms, execution: {} ms, reading and parsing: {} ms; executed [{}]", new Object[]{ afterClose - start, afterExecQuery-start, afterClose - afterExecQuery, this.getName() == null ? "No name" : this.getName() }); } catch(SQLException ex){ - throw new Sql2oException("Database error", ex); + throw new Sql2oException("Database error: " + ex.getMessage(), ex); } finally { closeConnectionIfNecessary(); } return list; } public <T> T executeAndFetchFirst(Class returnType){ List l = this.executeAndFetch(returnType); if (l.size() == 0){ return null; } else{ return (T)l.get(0); } } public Table executeAndFetchTable(){ ResultSet rs; long start = System.currentTimeMillis(); try { rs = statement.executeQuery(); long afterExecute = System.currentTimeMillis(); Table table = TableFactory.createTable(rs, this.isCaseSensitive()); long afterClose = System.currentTimeMillis(); logger.info("total: {} ms, execution: {} ms, reading and parsing: {} ms; executed fetch table [{}]", new Object[]{ afterClose - start, afterExecute-start, afterClose - afterExecute, this.getName() == null ? "No name" : this.getName() }); return table; } catch (SQLException e) { throw new Sql2oException("Error while executing query", e); } finally { closeConnectionIfNecessary(); } } public Connection executeUpdate(){ long start = System.currentTimeMillis(); try{ this.connection.setResult(statement.executeUpdate()); this.connection.setKeys(statement.getStatement().getGeneratedKeys()); connection.setCanGetKeys(true); } catch(SQLException ex){ this.connection.onException(); throw new Sql2oException("Error in executeUpdate, " + ex.getMessage(), ex); } finally { closeConnectionIfNecessary(); } long end = System.currentTimeMillis(); logger.info("total: {} ms; executed update [{}]", new Object[]{ end - start, this.getName() == null ? "No name" : this.getName() }); return this.connection; } public Object executeScalar(){ long start = System.currentTimeMillis(); try { ResultSet rs = this.statement.executeQuery(); if (rs.next()){ Object o = rs.getObject(1); long end = System.currentTimeMillis(); logger.info("total: {} ms; executed scalar [{}]", new Object[]{ end - start, this.getName() == null ? "No name" : this.getName() }); return o; } else{ return null; } } catch (SQLException e) { this.connection.onException(); throw new Sql2oException("Database error occurred while running executeScalar: " + e.getMessage(), e); } finally{ closeConnectionIfNecessary(); } } public <V> V executeScalar(Class returnType){ Object value = executeScalar(); Converter converter = null; try { converter = Convert.getConverter(returnType); return (V)converter.convert(value); } catch (ConverterException e) { throw new Sql2oException("Error occured while converting value from database to type " + returnType.toString(), e); } } public <T> List<T> executeScalarList(){ long start = System.currentTimeMillis(); List<T> list = new ArrayList<T>(); try{ ResultSet rs = this.statement.executeQuery(); while(rs.next()){ list.add((T)rs.getObject(1)); } long end = System.currentTimeMillis(); logger.info("total: {} ms; executed scalar list [{}]", new Object[]{ end - start, this.getName() == null ? "No name" : this.getName() }); return list; } catch(SQLException ex){ this.connection.onException(); throw new Sql2oException("Error occurred while executing scalar list: " + ex.getMessage(), ex); } finally{ closeConnectionIfNecessary(); } } /************** batch stuff *******************/ public Query addToBatch(){ try { statement.addBatch(); } catch (SQLException e) { throw new Sql2oException("Error while adding statement to batch", e); } return this; } public Connection executeBatch() throws Sql2oException { long start = System.currentTimeMillis(); try { connection.setBatchResult( statement.executeBatch() ); } catch (Throwable e) { this.connection.onException(); throw new Sql2oException("Error while executing batch operation: " + e.getMessage(), e); } finally { closeConnectionIfNecessary(); } long end = System.currentTimeMillis(); logger.info("total: {} ms; executed batch [{}]", new Object[]{ end - start, this.getName() == null ? "No name" : this.getName() }); return this.connection; } /*********** column mapping ****************/ public Map<String, String> getColumnMappings() { if (this.isCaseSensitive()){ return this.caseSensitiveColumnMappings; } else{ return this.columnMappings; } } void setColumnMappings(Map<String, String> mappings){ this.caseSensitiveColumnMappings = new HashMap<String, String>(); this.columnMappings = new HashMap<String, String>(); for (Map.Entry<String,String> entry : mappings.entrySet()){ this.caseSensitiveColumnMappings.put(entry.getKey(), entry.getValue()); this.columnMappings.put(entry.getKey().toLowerCase(), entry.getValue().toLowerCase()); } } public Query addColumnMapping(String columnName, String propertyName){ this.caseSensitiveColumnMappings.put(columnName, propertyName); this.columnMappings.put(columnName.toLowerCase(), propertyName.toLowerCase()); return this; } /************** private stuff ***************/ private void closeConnectionIfNecessary(){ try{ if (!this.connection.getJdbcConnection().isClosed() && this.connection.getJdbcConnection().getAutoCommit() && statement != null){ statement.close(); this.connection.getJdbcConnection().close(); } } catch (Exception ex){ throw new RuntimeException("Error while attempting to close connection", ex); } } // private void onErrorCleanup(){ // try { // if (this.connection.getJdbcConnection().isClosed()){ // this.connection.getJdbcConnection().close(); // } // } catch (SQLException ex) { // throw new RuntimeException("Error while attempting to close connection", ex); // } // } }
true
true
public <T> List<T> executeAndFetch(Class returnType){ List list = new ArrayList(); PojoMetadata metadata = new PojoMetadata(returnType, this.isCaseSensitive(), this.getColumnMappings()); try{ //java.util.Date st = new java.util.Date(); long start = System.currentTimeMillis(); ResultSet rs = statement.executeQuery(); long afterExecQuery = System.currentTimeMillis(); ResultSetMetaData meta = rs.getMetaData(); while(rs.next()){ Pojo pojo = new Pojo(metadata, this.isCaseSensitive()); //Object obj = returnType.newInstance(); for(int colIdx = 1; colIdx <= meta.getColumnCount(); colIdx++){ String colName = meta.getColumnName(colIdx); pojo.setProperty(colName, rs.getObject(colIdx)); } list.add(pojo.getObject()); } rs.close(); long afterClose = System.currentTimeMillis(); logger.info("total: {} ms, execution: {} ms, reading and parsing: {} ms; executed [{}]", new Object[]{ afterClose - start, afterExecQuery-start, afterClose - afterExecQuery, this.getName() == null ? "No name" : this.getName() }); } catch(SQLException ex){ throw new Sql2oException("Database error", ex); } finally { closeConnectionIfNecessary(); } return list; }
public <T> List<T> executeAndFetch(Class returnType){ List list = new ArrayList(); PojoMetadata metadata = new PojoMetadata(returnType, this.isCaseSensitive(), this.getColumnMappings()); try{ //java.util.Date st = new java.util.Date(); long start = System.currentTimeMillis(); ResultSet rs = statement.executeQuery(); long afterExecQuery = System.currentTimeMillis(); ResultSetMetaData meta = rs.getMetaData(); while(rs.next()){ Pojo pojo = new Pojo(metadata, this.isCaseSensitive()); //Object obj = returnType.newInstance(); for(int colIdx = 1; colIdx <= meta.getColumnCount(); colIdx++){ String colName = meta.getColumnName(colIdx); pojo.setProperty(colName, rs.getObject(colIdx)); } list.add(pojo.getObject()); } rs.close(); long afterClose = System.currentTimeMillis(); logger.info("total: {} ms, execution: {} ms, reading and parsing: {} ms; executed [{}]", new Object[]{ afterClose - start, afterExecQuery-start, afterClose - afterExecQuery, this.getName() == null ? "No name" : this.getName() }); } catch(SQLException ex){ throw new Sql2oException("Database error: " + ex.getMessage(), ex); } finally { closeConnectionIfNecessary(); } return list; }
diff --git a/vaadin-framework/src/main/java/pt/ist/vaadinframework/EmbeddedWindow.java b/vaadin-framework/src/main/java/pt/ist/vaadinframework/EmbeddedWindow.java index 9af87ac..d6c1913 100644 --- a/vaadin-framework/src/main/java/pt/ist/vaadinframework/EmbeddedWindow.java +++ b/vaadin-framework/src/main/java/pt/ist/vaadinframework/EmbeddedWindow.java @@ -1,109 +1,109 @@ /* * Copyright 2011 Instituto Superior Tecnico * * https://fenix-ashes.ist.utl.pt/ * * This file is part of the vaadin-framework-ant. * * The vaadin-framework-ant Infrastructure is free software: you can * redistribute it and/or modify it under the terms of the GNU Lesser General * Public License as published by the Free Software Foundation, either version * 3 of the License, or (at your option) any later version.* * * vaadin-framework-ant 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 vaadin-framework-ant. If not, see <http://www.gnu.org/licenses/>. * */ package pt.ist.vaadinframework; import java.util.Map; import java.util.Map.Entry; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import pt.ist.vaadinframework.ui.EmbeddedComponentContainer; import com.vaadin.ui.Component; import com.vaadin.ui.Label; import com.vaadin.ui.UriFragmentUtility; import com.vaadin.ui.UriFragmentUtility.FragmentChangedEvent; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.Window; /** * @author Pedro Santos ([email protected]) * */ public class EmbeddedWindow extends Window { private final UriFragmentUtility fragmentUtility = new UriFragmentUtility(); private Component current; public EmbeddedWindow(final Map<Pattern, Class<? extends EmbeddedComponentContainer>> resolver) { final VerticalLayout layout = new VerticalLayout(); layout.addComponent(fragmentUtility); fragmentUtility.addListener(new UriFragmentUtility.FragmentChangedListener() { @Override public void fragmentChanged(FragmentChangedEvent source) { String fragment = source.getUriFragmentUtility().getFragment(); for (Entry<Pattern, Class<? extends EmbeddedComponentContainer>> entry : resolver.entrySet()) { Matcher matcher = entry.getKey().matcher(fragment); - if (matcher.find()) { + if (matcher.matches()) { try { EmbeddedComponentContainer container = entry.getValue().newInstance(); Vector<String> arguments = new Vector<String>(matcher.groupCount() + 1); for (int i = 0; i <= matcher.groupCount(); i++) { arguments.add(matcher.group(i)); } container.setArguments(arguments.toArray(new String[0])); layout.replaceComponent(current, container); current = container; return; } catch (InstantiationException e) { VaadinFrameworkLogger.getLogger().error( "Embedded component resolver could not instantiate matched pattern: <" + entry.getKey().pattern() + ", " + entry.getValue().getName() + ">", e); } catch (IllegalAccessException e) { VaadinFrameworkLogger.getLogger().error( "Embedded component resolver could not instantiate matched pattern: <" + entry.getKey().pattern() + ", " + entry.getValue().getName() + ">", e); } } } Component container = new NoMatchingPatternFoundComponent(); layout.replaceComponent(current, container); current = container; } }); current = new VerticalLayout(); layout.addComponent(current); setContent(layout); } private class NoMatchingPatternFoundComponent extends VerticalLayout implements EmbeddedComponentContainer { @Override public void attach() { super.attach(); addComponent(new Label("No matching component found")); } @Override public void setArguments(String... arguments) { // Not expecting any arguments } } /** * @return the current */ public Component getCurrent() { return current; } }
true
true
public EmbeddedWindow(final Map<Pattern, Class<? extends EmbeddedComponentContainer>> resolver) { final VerticalLayout layout = new VerticalLayout(); layout.addComponent(fragmentUtility); fragmentUtility.addListener(new UriFragmentUtility.FragmentChangedListener() { @Override public void fragmentChanged(FragmentChangedEvent source) { String fragment = source.getUriFragmentUtility().getFragment(); for (Entry<Pattern, Class<? extends EmbeddedComponentContainer>> entry : resolver.entrySet()) { Matcher matcher = entry.getKey().matcher(fragment); if (matcher.find()) { try { EmbeddedComponentContainer container = entry.getValue().newInstance(); Vector<String> arguments = new Vector<String>(matcher.groupCount() + 1); for (int i = 0; i <= matcher.groupCount(); i++) { arguments.add(matcher.group(i)); } container.setArguments(arguments.toArray(new String[0])); layout.replaceComponent(current, container); current = container; return; } catch (InstantiationException e) { VaadinFrameworkLogger.getLogger().error( "Embedded component resolver could not instantiate matched pattern: <" + entry.getKey().pattern() + ", " + entry.getValue().getName() + ">", e); } catch (IllegalAccessException e) { VaadinFrameworkLogger.getLogger().error( "Embedded component resolver could not instantiate matched pattern: <" + entry.getKey().pattern() + ", " + entry.getValue().getName() + ">", e); } } } Component container = new NoMatchingPatternFoundComponent(); layout.replaceComponent(current, container); current = container; } }); current = new VerticalLayout(); layout.addComponent(current); setContent(layout); }
public EmbeddedWindow(final Map<Pattern, Class<? extends EmbeddedComponentContainer>> resolver) { final VerticalLayout layout = new VerticalLayout(); layout.addComponent(fragmentUtility); fragmentUtility.addListener(new UriFragmentUtility.FragmentChangedListener() { @Override public void fragmentChanged(FragmentChangedEvent source) { String fragment = source.getUriFragmentUtility().getFragment(); for (Entry<Pattern, Class<? extends EmbeddedComponentContainer>> entry : resolver.entrySet()) { Matcher matcher = entry.getKey().matcher(fragment); if (matcher.matches()) { try { EmbeddedComponentContainer container = entry.getValue().newInstance(); Vector<String> arguments = new Vector<String>(matcher.groupCount() + 1); for (int i = 0; i <= matcher.groupCount(); i++) { arguments.add(matcher.group(i)); } container.setArguments(arguments.toArray(new String[0])); layout.replaceComponent(current, container); current = container; return; } catch (InstantiationException e) { VaadinFrameworkLogger.getLogger().error( "Embedded component resolver could not instantiate matched pattern: <" + entry.getKey().pattern() + ", " + entry.getValue().getName() + ">", e); } catch (IllegalAccessException e) { VaadinFrameworkLogger.getLogger().error( "Embedded component resolver could not instantiate matched pattern: <" + entry.getKey().pattern() + ", " + entry.getValue().getName() + ">", e); } } } Component container = new NoMatchingPatternFoundComponent(); layout.replaceComponent(current, container); current = container; } }); current = new VerticalLayout(); layout.addComponent(current); setContent(layout); }
diff --git a/PTFrontend/src/javaworld/InstTupleRew.java b/PTFrontend/src/javaworld/InstTupleRew.java index 214154a..0ccd435 100644 --- a/PTFrontend/src/javaworld/InstTupleRew.java +++ b/PTFrontend/src/javaworld/InstTupleRew.java @@ -1,248 +1,248 @@ package javaworld; import java.util.Map; import AST.TypeDecl; import AST.ClassDecl; import AST.PTInstTuple; import AST.PTDummyRename; import AST.InterfaceDecl; import AST.PTEnumDecl; import AST.BodyDecl; import AST.ASTNode; import AST.PTMethodRename; import AST.PTMethodRenameAll; import AST.PTFieldRename; import AST.Access; import AST.MethodDecl; import AST.SimpleSet; import AST.RequiredType; import AST.FieldDeclaration; import AST.PTDecl; import java.util.Iterator; import java.util.HashMap; import java.util.LinkedHashMap; import com.google.common.collect.Maps; import com.google.common.base.Joiner; class InstTupleRew { private final PTInstTuple instantiator; public InstTupleRew(PTInstTuple dummy) { this.instantiator = dummy; } protected boolean isInterface() { return instantiator.getOriginator() instanceof AST.InterfaceDecl; } protected static TypeDecl lookupUnambiguousTypeIn( TypeDecl root, String name ) { SimpleSet matches = root.lookupType( name ); if( matches.size() != 1 ) { throw new RuntimeException( "unexpectedly unable to find supposedly unambiguous type -- " + name + "(" + matches.size() + " matches)" ); } return (TypeDecl) matches.iterator().next(); } public void createVirtualRenamingDeclarations( Map<BodyDecl, BodyDecl> virtualsToReals ) { Map<ASTNode, String> internalRenames = findInternalRenames( instantiator.getOriginator() ); PTDecl parentPTDecl = (PTDecl) instantiator.getParentClass( PTDecl.class ); TypeDecl parentType = parentPTDecl.ptLookupSpecificType( instantiator.getID() ); for( ASTNode originalNode : internalRenames.keySet() ) { String newID = internalRenames.get( originalNode ); ASTNode dummyCopy = originalNode.fullCopy(); BodyDecl dummyDecl = (BodyDecl) dummyCopy; // justified since it's a copy of == BodyDecl parentType.addBodyDecl( dummyDecl ); BodyDecl realThing = null; if( dummyCopy instanceof MethodDecl ) { MethodDecl copycopy = (MethodDecl) dummyCopy.fullCopy(); copycopy.setParent(dummyCopy.getParent()); copycopy.setID( newID ); realThing = (BodyDecl) parentType.localMethodsSignatureMap().get( copycopy.signature() ); } virtualsToReals.put( dummyDecl, realThing ); } } protected HashMap<ASTNode,String> findInternalRenames(TypeDecl target) { // XXX what about types that can only be found in the parent, are these renamed correctly? // do any such exist? is the parent always ptdecl? HashMap< ASTNode, String > rv = new LinkedHashMap< ASTNode, String >(); for( PTDummyRename ptdr : instantiator.getPTDummyRenameList() ) { String originalId = ptdr.getOrgID(); String destinationId = ptdr.getID(); if( ptdr instanceof PTFieldRename ) { // TODO } else if( ptdr instanceof PTMethodRename ) { PTMethodRename ptmr = (PTMethodRename) ptdr; AST.List<Access> args = ptmr.getAccessList(); boolean foundMethod = false; for( Object declo : target.memberMethods( originalId ) ) { MethodDecl mdecl = (MethodDecl) declo; if( mdecl.arity() != args.getNumChild() ) continue; boolean ok = true; for(int i=0;i<mdecl.arity();i++) { TypeDecl formalParamTypeDecl = mdecl.getParameter(i).type(); - TypeDecl fPTDinCopy = lookupUnambiguousTypeIn( target, formalParamTypeDecl.fullName() ); + TypeDecl fPTDinCopy = lookupUnambiguousTypeIn(target, formalParamTypeDecl.name()); Access myAcc = args.getChild(i); if( myAcc.type() != fPTDinCopy ) { ok = false; continue; } } if( ok ) { foundMethod = true; rv.put( mdecl, destinationId ); } } if( !foundMethod ) { ptmr.error( "cannot find method matching rename: " + ptmr ); } } else if( ptdr instanceof PTMethodRenameAll ) { for( Object declo : target.memberMethods( originalId ) ) { ASTNode declNode = (ASTNode) declo; rv.put( declNode, destinationId ); } } else { throw new RuntimeException( "program error -- unexpected PTDummyRename" ); } } return rv; } protected RequiredType getRenamedSourceRequiredType() { TypeDecl x = instantiator.getOriginator(); RequiredType ext = ((RequiredType)x).fullCopy(); ext.setParent(x.getParent()); ext.visitRename( instantiator.getInstDecl().getRenamedClasses() ); DefinitionsRenamer.renameDefinitions( ext, getExplicitlyRenamedDefinitions()); ext.renameTypes( instantiator.getInstDecl().getRenamedClasses() ); ext.flushCaches(); return ext; } protected InterfaceDecl getRenamedSourceInterface() { TypeDecl x = instantiator.getOriginator(); InterfaceDecl ext = ((InterfaceDecl)x).fullCopy(); ext.setParent(x.getParent()); /* HashMap<ASTNode,String> internalRenames = findInternalRenames( ext ); ext.visitRenameAccesses( internalRenames ); ext.visitRenameDeclarations( internalRenames ); */ // ext.renameMethods() // is this a wise way to do this? seems clumsy. // renameTypes should evidently NOT automatically visitRename // as well, this breaks several tests -- should investigate why ext.visitRename( instantiator.getInstDecl().getRenamedClasses() ); DefinitionsRenamer.renameDefinitions( ext, getExplicitlyRenamedDefinitions()); ext.renameTypes( instantiator.getInstDecl().getRenamedClasses() ); ext.flushCaches(); return ext; } protected PTEnumDecl getRenamedSourceEnum() { // straight rewrite of getRenamedSourceInterface, above concerns apply TypeDecl x = instantiator.getOriginator(); PTEnumDecl ext = ((PTEnumDecl)x).fullCopy(); ext.setParent(x.getParent()); ext.fixupAfterCopy(); // do we need both? ext.visitRename( instantiator.getInstDecl().getRenamedClasses() ); ext.renameTypes( instantiator.getInstDecl().getRenamedClasses() ); ext.fixupAfterCopy(); return ext; } protected ClassDeclRew getRenamedSourceClass() { TypeDecl x = instantiator.getOriginator(); ClassDecl ext = ((ClassDecl)x).fullCopy(); ext.setParent(x.getParent()); // be aware that after this, going upwards into the parent and then // (apparently) backwards into the child will NOT find the copy, but // the original child, thus it will not reflect changes. // fullCopy sanely copies down but not up, yet this can be an // unintended consequencem.. ext.getParent() does NOT simply give some // context for ext! new IntroduceExplicitCastsRewriter().mutate( ext ); ext.getParentClass( PTDecl.class ).flushCaches(); /* problem: the copy is shallow -- it contains references to types in the original. these are not == to the corresponding ones in the copy. so e.g.: class A { int getFoo(A x) { return 42; } } -> class *copy*A { int getFoo( *original*A ) { return 42; } } */ ClassDeclRew rewriteClass = new ClassDeclRew(ext, getSourceTemplateName()); HashMap<ASTNode,String> internalRenames = findInternalRenames( ext ); ext.visitRenameAccesses( internalRenames ); // ext.visitRenameDeclarations( internalRenames ); rewriteClass.renameConstructors(instantiator); rewriteClass.renameDefinitions(getExplicitlyRenamedDefinitions()); rewriteClass.renameTypes(instantiator.getInstDecl().getRenamedClasses()); return rewriteClass; } private Map<String, String> getExplicitlyRenamedDefinitions() { // TODO addsselfto... move it here!!! Map<String, String> map = Maps.newHashMap(); for (PTDummyRename entry : instantiator.getPTDummyRenameList()) { entry.addSelfTo(map); } return map; } private String getSourceTemplateName() { return instantiator.getTemplate().getID(); } }
true
true
protected HashMap<ASTNode,String> findInternalRenames(TypeDecl target) { // XXX what about types that can only be found in the parent, are these renamed correctly? // do any such exist? is the parent always ptdecl? HashMap< ASTNode, String > rv = new LinkedHashMap< ASTNode, String >(); for( PTDummyRename ptdr : instantiator.getPTDummyRenameList() ) { String originalId = ptdr.getOrgID(); String destinationId = ptdr.getID(); if( ptdr instanceof PTFieldRename ) { // TODO } else if( ptdr instanceof PTMethodRename ) { PTMethodRename ptmr = (PTMethodRename) ptdr; AST.List<Access> args = ptmr.getAccessList(); boolean foundMethod = false; for( Object declo : target.memberMethods( originalId ) ) { MethodDecl mdecl = (MethodDecl) declo; if( mdecl.arity() != args.getNumChild() ) continue; boolean ok = true; for(int i=0;i<mdecl.arity();i++) { TypeDecl formalParamTypeDecl = mdecl.getParameter(i).type(); TypeDecl fPTDinCopy = lookupUnambiguousTypeIn( target, formalParamTypeDecl.fullName() ); Access myAcc = args.getChild(i); if( myAcc.type() != fPTDinCopy ) { ok = false; continue; } } if( ok ) { foundMethod = true; rv.put( mdecl, destinationId ); } } if( !foundMethod ) { ptmr.error( "cannot find method matching rename: " + ptmr ); } } else if( ptdr instanceof PTMethodRenameAll ) { for( Object declo : target.memberMethods( originalId ) ) { ASTNode declNode = (ASTNode) declo; rv.put( declNode, destinationId ); } } else { throw new RuntimeException( "program error -- unexpected PTDummyRename" ); } } return rv; }
protected HashMap<ASTNode,String> findInternalRenames(TypeDecl target) { // XXX what about types that can only be found in the parent, are these renamed correctly? // do any such exist? is the parent always ptdecl? HashMap< ASTNode, String > rv = new LinkedHashMap< ASTNode, String >(); for( PTDummyRename ptdr : instantiator.getPTDummyRenameList() ) { String originalId = ptdr.getOrgID(); String destinationId = ptdr.getID(); if( ptdr instanceof PTFieldRename ) { // TODO } else if( ptdr instanceof PTMethodRename ) { PTMethodRename ptmr = (PTMethodRename) ptdr; AST.List<Access> args = ptmr.getAccessList(); boolean foundMethod = false; for( Object declo : target.memberMethods( originalId ) ) { MethodDecl mdecl = (MethodDecl) declo; if( mdecl.arity() != args.getNumChild() ) continue; boolean ok = true; for(int i=0;i<mdecl.arity();i++) { TypeDecl formalParamTypeDecl = mdecl.getParameter(i).type(); TypeDecl fPTDinCopy = lookupUnambiguousTypeIn(target, formalParamTypeDecl.name()); Access myAcc = args.getChild(i); if( myAcc.type() != fPTDinCopy ) { ok = false; continue; } } if( ok ) { foundMethod = true; rv.put( mdecl, destinationId ); } } if( !foundMethod ) { ptmr.error( "cannot find method matching rename: " + ptmr ); } } else if( ptdr instanceof PTMethodRenameAll ) { for( Object declo : target.memberMethods( originalId ) ) { ASTNode declNode = (ASTNode) declo; rv.put( declNode, destinationId ); } } else { throw new RuntimeException( "program error -- unexpected PTDummyRename" ); } } return rv; }
diff --git a/Slick/src/org/newdawn/slick/opengl/PNGImageData.java b/Slick/src/org/newdawn/slick/opengl/PNGImageData.java index 983db02..1ec7e41 100644 --- a/Slick/src/org/newdawn/slick/opengl/PNGImageData.java +++ b/Slick/src/org/newdawn/slick/opengl/PNGImageData.java @@ -1,787 +1,787 @@ package org.newdawn.slick.opengl; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.zip.CRC32; import java.util.zip.DataFormatException; import java.util.zip.Inflater; import org.lwjgl.BufferUtils; /** * The PNG imge data source that is pure java reading PNGs * * @author Matthias Mann (original code) */ public class PNGImageData implements LoadableImageData { /** The valid signature of a PNG */ private static final byte[] SIGNATURE = {(byte)137, 80, 78, 71, 13, 10, 26, 10}; /** The header chunk identifer */ private static final int IHDR = 0x49484452; /** The palette chunk identifer */ private static final int PLTE = 0x504C5445; /** The transparency chunk identifier */ private static final int tRNS = 0x74524E53; /** The data chunk identifier */ private static final int IDAT = 0x49444154; /** The end chunk identifier */ private static final int IEND = 0x49454E44; /** Color type for greyscale images */ private static final byte COLOR_GREYSCALE = 0; /** Color type for true colour images */ private static final byte COLOR_TRUECOLOR = 2; /** Color type for indexed palette images */ private static final byte COLOR_INDEXED = 3; /** Color type for greyscale images with alpha */ private static final byte COLOR_GREYALPHA = 4; /** Color type for true colour images with alpha */ private static final byte COLOR_TRUEALPHA = 6; /** The stream we're going to read from */ private InputStream input; /** The CRC for the current chunk */ private final CRC32 crc; /** The buffer we'll use as temporary storage */ private final byte[] buffer; /** The length of the current chunk in bytes */ private int chunkLength; /** The ID of the current chunk */ private int chunkType; /** The number of bytes remaining in the current chunk */ private int chunkRemaining; /** The width of the image read */ private int width; /** The height of the image read */ private int height; /** The type of colours in the PNG data */ private int colorType; /** The number of bytes per pixel */ private int bytesPerPixel; /** The palette data that has been read - RGB only */ private byte[] palette; /** The palette data thats be read from alpha channel */ private byte[] paletteA; /** The transparent pixel description */ private byte[] transPixel; /** The bit depth of the image */ private int bitDepth; /** The width of the texture to be generated */ private int texWidth; /** The height of the texture to be generated */ private int texHeight; /** The scratch buffer used to store the image data */ private ByteBuffer scratch; /** * Create a new PNG image data that can read image data from PNG formated files */ public PNGImageData() { this.crc = new CRC32(); this.buffer = new byte[4096]; } /** * Initialise the PNG data header fields from the input stream * * @param input The input stream to read from * @throws IOException Indicates a failure to read appropriate data from the stream */ private void init(InputStream input) throws IOException { this.input = input; int read = input.read(buffer, 0, SIGNATURE.length); if(read != SIGNATURE.length || !checkSignatur(buffer)) { throw new IOException("Not a valid PNG file"); } openChunk(IHDR); readIHDR(); closeChunk(); searchIDAT: for(;;) { openChunk(); switch (chunkType) { case IDAT: break searchIDAT; case PLTE: readPLTE(); break; case tRNS: readtRNS(); break; } closeChunk(); } } /** * @see org.newdawn.slick.opengl.ImageData#getHeight() */ public int getHeight() { return height; } /** * @see org.newdawn.slick.opengl.ImageData#getWidth() */ public int getWidth() { return width; } /** * Check if this PNG has a an alpha channel * * @return True if the PNG has an alpha channel */ public boolean hasAlpha() { return colorType == COLOR_TRUEALPHA || paletteA != null || transPixel != null; } /** * Check if the PNG is RGB formatted * * @return True if the PNG is RGB formatted */ public boolean isRGB() { return colorType == COLOR_TRUEALPHA || colorType == COLOR_TRUECOLOR || colorType == COLOR_INDEXED; } /** * Decode a PNG into a data buffer * * @param buffer The buffer to read the data into * @param stride The image stride to read (i.e. the number of bytes to skip each line) * @param flip True if the PNG should be flipped * @throws IOException Indicates a failure to read the PNG either invalid data or * not enough room in the buffer */ private void decode(ByteBuffer buffer, int stride, boolean flip) throws IOException { final int offset = buffer.position(); byte[] curLine = new byte[width*bytesPerPixel+1]; byte[] prevLine = new byte[width*bytesPerPixel+1]; final Inflater inflater = new Inflater(); try { for(int yIndex=0 ; yIndex<height ; yIndex++) { int y = yIndex; if (flip) { y = height - 1 - yIndex; } readChunkUnzip(inflater, curLine, 0, curLine.length); unfilter(curLine, prevLine); buffer.position(offset + y*stride); switch (colorType) { case COLOR_TRUECOLOR: case COLOR_TRUEALPHA: copy(buffer, curLine); break; case COLOR_INDEXED: copyExpand(buffer, curLine); break; default: throw new UnsupportedOperationException("Not yet implemented"); } byte[] tmp = curLine; curLine = prevLine; prevLine = tmp; } } finally { inflater.end(); } bitDepth = hasAlpha() ? 32 : 24; } /** * Copy some data into the given byte buffer expanding the * data based on indexing the palette * * @param buffer The buffer to write into * @param curLine The current line of data to copy */ private void copyExpand(ByteBuffer buffer, byte[] curLine) { for (int i=1;i<curLine.length;i++) { int v = curLine[i] & 255; int index = v * 3; for (int j=0;j<3;j++) { buffer.put(palette[index+j]); } if (hasAlpha()) { if (paletteA != null) { buffer.put(paletteA[v]); } else { buffer.put((byte) 255); } } } } /** * Copy the data given directly into the byte buffer (skipping * the filter byte); * * @param buffer The buffer to write into * @param curLine The current line to copy into the buffer */ private void copy(ByteBuffer buffer, byte[] curLine) { buffer.put(curLine, 1, curLine.length-1); } /** * Unfilter the data, i.e. convert it back to it's original form * * @param curLine The line of data just read * @param prevLine The line before * @throws IOException Indicates a failure to unfilter the data due to an unknown * filter type */ private void unfilter(byte[] curLine, byte[] prevLine) throws IOException { switch (curLine[0]) { case 0: // none break; case 1: unfilterSub(curLine); break; case 2: unfilterUp(curLine, prevLine); break; case 3: unfilterAverage(curLine, prevLine); break; case 4: unfilterPaeth(curLine, prevLine); break; default: throw new IOException("invalide filter type in scanline: " + curLine[0]); } } /** * Sub unfilter * {@url http://libpng.nigilist.ru/pub/png/spec/1.2/PNG-Filters.html} * * @param curLine The line of data to be unfiltered */ private void unfilterSub(byte[] curLine) { final int bpp = this.bytesPerPixel; final int lineSize = width*bpp; for(int i=bpp+1 ; i<=lineSize ; ++i) { curLine[i] += curLine[i-bpp]; } } /** * Up unfilter * {@url http://libpng.nigilist.ru/pub/png/spec/1.2/PNG-Filters.html} * * @param prevLine The line of data read before the current * @param curLine The line of data to be unfiltered */ private void unfilterUp(byte[] curLine, byte[] prevLine) { final int bpp = this.bytesPerPixel; final int lineSize = width*bpp; for(int i=1 ; i<=lineSize ; ++i) { curLine[i] += prevLine[i]; } } /** * Average unfilter * {@url http://libpng.nigilist.ru/pub/png/spec/1.2/PNG-Filters.html} * * @param prevLine The line of data read before the current * @param curLine The line of data to be unfiltered */ private void unfilterAverage(byte[] curLine, byte[] prevLine) { final int bpp = this.bytesPerPixel; final int lineSize = width*bpp; int i; for(i=1 ; i<=bpp ; ++i) { curLine[i] += (byte)((prevLine[i] & 0xFF) >>> 1); } for(; i<=lineSize ; ++i) { curLine[i] += (byte)(((prevLine[i] & 0xFF) + (curLine[i - bpp] & 0xFF)) >>> 1); } } /** * Paeth unfilter * {@url http://libpng.nigilist.ru/pub/png/spec/1.2/PNG-Filters.html} * * @param prevLine The line of data read before the current * @param curLine The line of data to be unfiltered */ private void unfilterPaeth(byte[] curLine, byte[] prevLine) { final int bpp = this.bytesPerPixel; final int lineSize = width*bpp; int i; for(i=1 ; i<=bpp ; ++i) { curLine[i] += prevLine[i]; } for(; i<=lineSize ; ++i) { int a = curLine[i - bpp] & 255; int b = prevLine[i] & 255; int c = prevLine[i - bpp] & 255; int p = a + b - c; int pa = p - a; if(pa < 0) pa = -pa; int pb = p - b; if(pb < 0) pb = -pb; int pc = p - c; if(pc < 0) pc = -pc; if(pa<=pb && pa<=pc) c = a; else if(pb<=pc) c = b; curLine[i] += (byte)c; } } /** * Read the header of the PNG * * @throws IOException Indicates a failure to read the header */ private void readIHDR() throws IOException { checkChunkLength(13); readChunk(buffer, 0, 13); width = readInt(buffer, 0); height = readInt(buffer, 4); if(buffer[8] != 8) { throw new IOException("Unsupported bit depth"); } colorType = buffer[9] & 255; switch (colorType) { case COLOR_GREYSCALE: bytesPerPixel = 1; break; case COLOR_TRUECOLOR: bytesPerPixel = 3; break; case COLOR_TRUEALPHA: bytesPerPixel = 4; break; case COLOR_INDEXED: bytesPerPixel = 1; break; default: throw new IOException("unsupported color format"); } if(buffer[10] != 0) { throw new IOException("unsupported compression method"); } if(buffer[11] != 0) { throw new IOException("unsupported filtering method"); } if(buffer[12] != 0) { throw new IOException("unsupported interlace method"); } } /** * Read the palette chunk * * @throws IOException Indicates a failure to fully read the chunk */ private void readPLTE() throws IOException { int paletteEntries = chunkLength / 3; if(paletteEntries < 1 || paletteEntries > 256 || (chunkLength % 3) != 0) { throw new IOException("PLTE chunk has wrong length"); } palette = new byte[paletteEntries*3]; readChunk(palette, 0, palette.length); } /** * Read the transparency chunk * * @throws IOException Indicates a failure to fully read the chunk */ private void readtRNS() throws IOException { switch (colorType) { case COLOR_GREYSCALE: checkChunkLength(2); transPixel = new byte[2]; readChunk(transPixel, 0, 2); break; case COLOR_TRUECOLOR: checkChunkLength(6); transPixel = new byte[6]; readChunk(transPixel, 0, 6); break; case COLOR_INDEXED: if(palette == null) { throw new IOException("tRNS chunk without PLTE chunk"); } paletteA = new byte[palette.length/3]; // initialise default palette values for (int i=0;i<paletteA.length;i++) { paletteA[i] = (byte) 255; } readChunk(paletteA, 0, paletteA.length); break; default: // just ignore it } } /** * Close the current chunk, skip the remaining data * * @throws IOException Indicates a failure to read off redundant data */ private void closeChunk() throws IOException { if(chunkRemaining > 0) { // just skip the rest and the CRC input.skip(chunkRemaining+4); } else { readFully(buffer, 0, 4); int expectedCrc = readInt(buffer, 0); int computedCrc = (int)crc.getValue(); if(computedCrc != expectedCrc) { throw new IOException("Invalid CRC"); } } chunkRemaining = 0; chunkLength = 0; chunkType = 0; } /** * Open the next chunk, determine the type and setup the internal state * * @throws IOException Indicates a failure to determine chunk information from the stream */ private void openChunk() throws IOException { readFully(buffer, 0, 8); chunkLength = readInt(buffer, 0); chunkType = readInt(buffer, 4); chunkRemaining = chunkLength; crc.reset(); crc.update(buffer, 4, 4); // only chunkType } /** * Open a chunk of an expected type * * @param expected The expected type of the next chunk * @throws IOException Indicate a failure to read data or a different chunk on the stream */ private void openChunk(int expected) throws IOException { openChunk(); if(chunkType != expected) { throw new IOException("Expected chunk: " + Integer.toHexString(expected)); } } /** * Check the current chunk has the correct size * * @param expected The expected size of the chunk * @throws IOException Indicate an invalid size */ private void checkChunkLength(int expected) throws IOException { if(chunkLength != expected) { throw new IOException("Chunk has wrong size"); } } /** * Read some data from the current chunk * * @param buffer The buffer to read into * @param offset The offset into the buffer to read into * @param length The amount of data to read * @return The number of bytes read from the chunk * @throws IOException Indicate a failure to read the appropriate data from the chunk */ private int readChunk(byte[] buffer, int offset, int length) throws IOException { if(length > chunkRemaining) { length = chunkRemaining; } readFully(buffer, offset, length); crc.update(buffer, offset, length); chunkRemaining -= length; return length; } /** * Refill the inflating stream with data from the stream * * @param inflater The inflater to fill * @throws IOException Indicates there is no more data left or invalid data has been found on * the stream. */ private void refillInflater(Inflater inflater) throws IOException { while(chunkRemaining == 0) { closeChunk(); openChunk(IDAT); } int read = readChunk(buffer, 0, buffer.length); inflater.setInput(buffer, 0, read); } /** * Read a chunk from the inflater * * @param inflater The inflater to read the data from * @param buffer The buffer to write into * @param offset The offset into the buffer at which to start writing * @param length The number of bytes to read * @throws IOException Indicates a failure to read the complete chunk */ private void readChunkUnzip(Inflater inflater, byte[] buffer, int offset, int length) throws IOException { try { do { int read = inflater.inflate(buffer, offset, length); if(read <= 0) { if(inflater.finished()) { throw new EOFException(); } if(inflater.needsInput()) { refillInflater(inflater); } else { throw new IOException("Can't inflate " + length + " bytes"); } } else { offset += read; length -= read; } } while(length > 0); } catch (DataFormatException ex) { IOException io = new IOException("inflate error"); io.initCause(ex); throw io; } } /** * Read a complete buffer of data from the input stream * * @param buffer The buffer to read into * @param offset The offset to start copying into * @param length The length of bytes to read * @throws IOException Indicates a failure to access the data */ private void readFully(byte[] buffer, int offset, int length) throws IOException { do { int read = input.read(buffer, offset, length); if(read < 0) { throw new EOFException(); } offset += read; length -= read; } while(length > 0); } /** * Read an int from a buffer * * @param buffer The buffer to read from * @param offset The offset into the buffer to read from * @return The int read interpreted in big endian */ private int readInt(byte[] buffer, int offset) { return ((buffer[offset ] ) << 24) | ((buffer[offset+1] & 255) << 16) | ((buffer[offset+2] & 255) << 8) | ((buffer[offset+3] & 255) ); } /** * Check the signature of the PNG to confirm it's a PNG * * @param buffer The buffer to read from * @return True if the PNG signature is correct */ private boolean checkSignatur(byte[] buffer) { for(int i=0 ; i<SIGNATURE.length ; i++) { if(buffer[i] != SIGNATURE[i]) { return false; } } return true; } /** * @see org.newdawn.slick.opengl.ImageData#getDepth() */ public int getDepth() { return bitDepth; } /** * @see org.newdawn.slick.opengl.ImageData#getImageBufferData() */ public ByteBuffer getImageBufferData() { return scratch; } /** * @see org.newdawn.slick.opengl.ImageData#getTexHeight() */ public int getTexHeight() { return texHeight; } /** * @see org.newdawn.slick.opengl.ImageData#getTexWidth() */ public int getTexWidth() { return texWidth; } /** * @see org.newdawn.slick.opengl.LoadableImageData#loadImage(java.io.InputStream) */ public ByteBuffer loadImage(InputStream fis) throws IOException { return loadImage(fis, false, null); } /** * @see org.newdawn.slick.opengl.LoadableImageData#loadImage(java.io.InputStream, boolean, int[]) */ public ByteBuffer loadImage(InputStream fis, boolean flipped, int[] transparent) throws IOException { return loadImage(fis, flipped, false, transparent); } /** * @see org.newdawn.slick.opengl.LoadableImageData#loadImage(java.io.InputStream, boolean, boolean, int[]) */ public ByteBuffer loadImage(InputStream fis, boolean flipped, boolean forceAlpha, int[] transparent) throws IOException { if (transparent != null) { forceAlpha = true; } init(fis); if (!isRGB()) { throw new IOException("Only RGB formatted images are supported by the PNGLoader"); } texWidth = get2Fold(width); texHeight = get2Fold(height); int perPixel = hasAlpha() ? 4 : 3; // Get a pointer to the image memory scratch = BufferUtils.createByteBuffer(texWidth * texHeight * perPixel); decode(scratch, texWidth * perPixel, flipped); if (height < texHeight-1) { int topOffset = (texHeight-1) * (texWidth*perPixel); int bottomOffset = (height-1) * (texWidth*perPixel); - for (int x=0;x<texWidth*perPixel;x++) { + for (int x=0;x<texWidth;x++) { for (int i=0;i<perPixel;i++) { scratch.put(topOffset+x+i, scratch.get(x+i)); - scratch.put(bottomOffset+(texWidth*perPixel)+x+i, scratch.get((texWidth*perPixel)+x+i)); + scratch.put(bottomOffset+(texWidth*perPixel)+x+i, scratch.get(bottomOffset+x+i)); } } } if (width < texWidth-1) { for (int y=0;y<texHeight;y++) { for (int i=0;i<perPixel;i++) { scratch.put(((y+1)*(texWidth*perPixel))-perPixel+i, scratch.get(y*(texWidth*perPixel)+i)); scratch.put((y*(texWidth*perPixel))+(width*perPixel)+i, scratch.get((y*(texWidth*perPixel))+((width-1)*perPixel)+i)); } } } if (!hasAlpha() && forceAlpha) { ByteBuffer temp = BufferUtils.createByteBuffer(texWidth * texHeight * 4); for (int x=0;x<texWidth;x++) { for (int y=0;y<texHeight;y++) { int srcOffset = (y*3)+(x*texHeight*3); int dstOffset = (y*4)+(x*texHeight*4); temp.put(dstOffset, scratch.get(srcOffset)); temp.put(dstOffset+1, scratch.get(srcOffset+1)); temp.put(dstOffset+2, scratch.get(srcOffset+2)); temp.put(dstOffset+3, (byte) 255); } } colorType = COLOR_TRUEALPHA; bitDepth = 32; scratch = temp; } if (transparent != null) { for (int i=0;i<texWidth*texHeight*4;i+=4) { boolean match = true; for (int c=0;c<3;c++) { if (toInt(scratch.get(i+c)) != transparent[c]) { match = false; } } if (match) { scratch.put(i+3, (byte) 0); } } } scratch.position(0); return scratch; } /** * Safe convert byte to int * * @param b The byte to convert * @return The converted byte */ private int toInt(byte b) { if (b < 0) { return 256+b; } return b; } /** * Get the closest greater power of 2 to the fold number * * @param fold The target number * @return The power of 2 */ private int get2Fold(int fold) { int ret = 2; while (ret < fold) { ret *= 2; } return ret; } /** * @see org.newdawn.slick.opengl.LoadableImageData#configureEdging(boolean) */ public void configureEdging(boolean edging) { } }
false
true
public ByteBuffer loadImage(InputStream fis, boolean flipped, boolean forceAlpha, int[] transparent) throws IOException { if (transparent != null) { forceAlpha = true; } init(fis); if (!isRGB()) { throw new IOException("Only RGB formatted images are supported by the PNGLoader"); } texWidth = get2Fold(width); texHeight = get2Fold(height); int perPixel = hasAlpha() ? 4 : 3; // Get a pointer to the image memory scratch = BufferUtils.createByteBuffer(texWidth * texHeight * perPixel); decode(scratch, texWidth * perPixel, flipped); if (height < texHeight-1) { int topOffset = (texHeight-1) * (texWidth*perPixel); int bottomOffset = (height-1) * (texWidth*perPixel); for (int x=0;x<texWidth*perPixel;x++) { for (int i=0;i<perPixel;i++) { scratch.put(topOffset+x+i, scratch.get(x+i)); scratch.put(bottomOffset+(texWidth*perPixel)+x+i, scratch.get((texWidth*perPixel)+x+i)); } } } if (width < texWidth-1) { for (int y=0;y<texHeight;y++) { for (int i=0;i<perPixel;i++) { scratch.put(((y+1)*(texWidth*perPixel))-perPixel+i, scratch.get(y*(texWidth*perPixel)+i)); scratch.put((y*(texWidth*perPixel))+(width*perPixel)+i, scratch.get((y*(texWidth*perPixel))+((width-1)*perPixel)+i)); } } } if (!hasAlpha() && forceAlpha) { ByteBuffer temp = BufferUtils.createByteBuffer(texWidth * texHeight * 4); for (int x=0;x<texWidth;x++) { for (int y=0;y<texHeight;y++) { int srcOffset = (y*3)+(x*texHeight*3); int dstOffset = (y*4)+(x*texHeight*4); temp.put(dstOffset, scratch.get(srcOffset)); temp.put(dstOffset+1, scratch.get(srcOffset+1)); temp.put(dstOffset+2, scratch.get(srcOffset+2)); temp.put(dstOffset+3, (byte) 255); } } colorType = COLOR_TRUEALPHA; bitDepth = 32; scratch = temp; } if (transparent != null) { for (int i=0;i<texWidth*texHeight*4;i+=4) { boolean match = true; for (int c=0;c<3;c++) { if (toInt(scratch.get(i+c)) != transparent[c]) { match = false; } } if (match) { scratch.put(i+3, (byte) 0); } } } scratch.position(0); return scratch; }
public ByteBuffer loadImage(InputStream fis, boolean flipped, boolean forceAlpha, int[] transparent) throws IOException { if (transparent != null) { forceAlpha = true; } init(fis); if (!isRGB()) { throw new IOException("Only RGB formatted images are supported by the PNGLoader"); } texWidth = get2Fold(width); texHeight = get2Fold(height); int perPixel = hasAlpha() ? 4 : 3; // Get a pointer to the image memory scratch = BufferUtils.createByteBuffer(texWidth * texHeight * perPixel); decode(scratch, texWidth * perPixel, flipped); if (height < texHeight-1) { int topOffset = (texHeight-1) * (texWidth*perPixel); int bottomOffset = (height-1) * (texWidth*perPixel); for (int x=0;x<texWidth;x++) { for (int i=0;i<perPixel;i++) { scratch.put(topOffset+x+i, scratch.get(x+i)); scratch.put(bottomOffset+(texWidth*perPixel)+x+i, scratch.get(bottomOffset+x+i)); } } } if (width < texWidth-1) { for (int y=0;y<texHeight;y++) { for (int i=0;i<perPixel;i++) { scratch.put(((y+1)*(texWidth*perPixel))-perPixel+i, scratch.get(y*(texWidth*perPixel)+i)); scratch.put((y*(texWidth*perPixel))+(width*perPixel)+i, scratch.get((y*(texWidth*perPixel))+((width-1)*perPixel)+i)); } } } if (!hasAlpha() && forceAlpha) { ByteBuffer temp = BufferUtils.createByteBuffer(texWidth * texHeight * 4); for (int x=0;x<texWidth;x++) { for (int y=0;y<texHeight;y++) { int srcOffset = (y*3)+(x*texHeight*3); int dstOffset = (y*4)+(x*texHeight*4); temp.put(dstOffset, scratch.get(srcOffset)); temp.put(dstOffset+1, scratch.get(srcOffset+1)); temp.put(dstOffset+2, scratch.get(srcOffset+2)); temp.put(dstOffset+3, (byte) 255); } } colorType = COLOR_TRUEALPHA; bitDepth = 32; scratch = temp; } if (transparent != null) { for (int i=0;i<texWidth*texHeight*4;i+=4) { boolean match = true; for (int c=0;c<3;c++) { if (toInt(scratch.get(i+c)) != transparent[c]) { match = false; } } if (match) { scratch.put(i+3, (byte) 0); } } } scratch.position(0); return scratch; }
diff --git a/src/com/android/gallery3d/app/AlbumSetPage.java b/src/com/android/gallery3d/app/AlbumSetPage.java index 6941f291..dafe3792 100644 --- a/src/com/android/gallery3d/app/AlbumSetPage.java +++ b/src/com/android/gallery3d/app/AlbumSetPage.java @@ -1,707 +1,705 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.gallery3d.app; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Rect; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.Vibrator; import android.widget.Toast; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.android.gallery3d.R; import com.android.gallery3d.common.Utils; import com.android.gallery3d.data.DataManager; import com.android.gallery3d.data.MediaDetails; import com.android.gallery3d.data.MediaObject; import com.android.gallery3d.data.MediaSet; import com.android.gallery3d.data.Path; import com.android.gallery3d.picasasource.PicasaSource; import com.android.gallery3d.settings.GallerySettings; import com.android.gallery3d.ui.ActionModeHandler; import com.android.gallery3d.ui.ActionModeHandler.ActionModeListener; import com.android.gallery3d.ui.AlbumSetSlotRenderer; import com.android.gallery3d.ui.DetailsHelper; import com.android.gallery3d.ui.DetailsHelper.CloseListener; import com.android.gallery3d.ui.FadeTexture; import com.android.gallery3d.ui.GLCanvas; import com.android.gallery3d.ui.GLRoot; import com.android.gallery3d.ui.GLView; import com.android.gallery3d.ui.PreparePageFadeoutTexture; import com.android.gallery3d.ui.SelectionManager; import com.android.gallery3d.ui.SlotView; import com.android.gallery3d.ui.SynchronizedHandler; import com.android.gallery3d.util.Future; import com.android.gallery3d.util.GalleryUtils; import com.android.gallery3d.util.HelpUtils; import java.lang.ref.WeakReference; public class AlbumSetPage extends ActivityState implements SelectionManager.SelectionListener, GalleryActionBar.ClusterRunner, EyePosition.EyePositionListener, MediaSet.SyncListener { @SuppressWarnings("unused") private static final String TAG = "AlbumSetPage"; private static final int MSG_PICK_ALBUM = 1; public static final String KEY_MEDIA_PATH = "media-path"; public static final String KEY_SET_TITLE = "set-title"; public static final String KEY_SET_SUBTITLE = "set-subtitle"; public static final String KEY_SELECTED_CLUSTER_TYPE = "selected-cluster"; private static final int DATA_CACHE_SIZE = 256; private static final int REQUEST_DO_ANIMATION = 1; private static final int BIT_LOADING_RELOAD = 1; private static final int BIT_LOADING_SYNC = 2; private boolean mIsActive = false; private SlotView mSlotView; private AlbumSetSlotRenderer mAlbumSetView; private Config.AlbumSetPage mConfig; private MediaSet mMediaSet; private String mTitle; private String mSubtitle; private boolean mShowClusterMenu; private GalleryActionBar mActionBar; private int mSelectedAction; private Vibrator mVibrator; protected SelectionManager mSelectionManager; private AlbumSetDataLoader mAlbumSetDataAdapter; private boolean mGetContent; private boolean mGetAlbum; private ActionModeHandler mActionModeHandler; private DetailsHelper mDetailsHelper; private MyDetailsSource mDetailsSource; private boolean mShowDetails; private EyePosition mEyePosition; private Handler mHandler; // The eyes' position of the user, the origin is at the center of the // device and the unit is in pixels. private float mX; private float mY; private float mZ; private Future<Integer> mSyncTask = null; private int mLoadingBits = 0; private boolean mInitialSynced = false; @Override protected int getBackgroundColorId() { return R.color.albumset_background; } private final GLView mRootPane = new GLView() { private final float mMatrix[] = new float[16]; @Override protected void renderBackground(GLCanvas view) { view.clearBuffer(getBackgroundColor()); } @Override protected void onLayout( boolean changed, int left, int top, int right, int bottom) { mEyePosition.resetPosition(); int slotViewTop = mActionBar.getHeight() + mConfig.paddingTop; int slotViewBottom = bottom - top - mConfig.paddingBottom; int slotViewRight = right - left; if (mShowDetails) { mDetailsHelper.layout(left, slotViewTop, right, bottom); } else { mAlbumSetView.setHighlightItemPath(null); } mSlotView.layout(0, slotViewTop, slotViewRight, slotViewBottom); } @Override protected void render(GLCanvas canvas) { canvas.save(GLCanvas.SAVE_FLAG_MATRIX); GalleryUtils.setViewPointMatrix(mMatrix, getWidth() / 2 + mX, getHeight() / 2 + mY, mZ); canvas.multiplyMatrix(mMatrix, 0); super.render(canvas); canvas.restore(); } }; @Override public void onEyePositionChanged(float x, float y, float z) { mRootPane.lockRendering(); mX = x; mY = y; mZ = z; mRootPane.unlockRendering(); mRootPane.invalidate(); } @Override public void onBackPressed() { if (mShowDetails) { hideDetails(); } else if (mSelectionManager.inSelectionMode()) { mSelectionManager.leaveSelectionMode(); } else { super.onBackPressed(); } } private void getSlotCenter(int slotIndex, int center[]) { Rect offset = new Rect(); mRootPane.getBoundsOf(mSlotView, offset); Rect r = mSlotView.getSlotRect(slotIndex); int scrollX = mSlotView.getScrollX(); int scrollY = mSlotView.getScrollY(); center[0] = offset.left + (r.left + r.right) / 2 - scrollX; center[1] = offset.top + (r.top + r.bottom) / 2 - scrollY; } public void onSingleTapUp(int slotIndex) { if (!mIsActive) return; if (mSelectionManager.inSelectionMode()) { MediaSet targetSet = mAlbumSetDataAdapter.getMediaSet(slotIndex); if (targetSet == null) return; // Content is dirty, we shall reload soon mSelectionManager.toggle(targetSet.getPath()); mSlotView.invalidate(); } else { // Show pressed-up animation for the single-tap. mAlbumSetView.setPressedIndex(slotIndex); mAlbumSetView.setPressedUp(); mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_PICK_ALBUM, slotIndex, 0), FadeTexture.DURATION); } } private static boolean albumShouldOpenInFilmstrip(MediaSet album) { int itemCount = album.getMediaItemCount(); return (album.isCameraRoll() && itemCount > 0) || itemCount == 1; } WeakReference<Toast> mEmptyAlbumToast = null; private void showEmptyAlbumToast(int toastLength) { Toast toast; if (mEmptyAlbumToast != null) { toast = mEmptyAlbumToast.get(); if (toast != null) { toast.show(); return; } } toast = Toast.makeText(mActivity, R.string.empty_album, toastLength); mEmptyAlbumToast = new WeakReference<Toast>(toast); toast.show(); } private void hideEmptyAlbumToast() { if (mEmptyAlbumToast != null) { Toast toast = mEmptyAlbumToast.get(); if (toast != null) toast.cancel(); } } private void pickAlbum(int slotIndex) { if (!mIsActive) return; MediaSet targetSet = mAlbumSetDataAdapter.getMediaSet(slotIndex); if (targetSet == null) return; // Content is dirty, we shall reload soon if (targetSet.getTotalMediaItemCount() == 0) { showEmptyAlbumToast(Toast.LENGTH_SHORT); return; } hideEmptyAlbumToast(); String mediaPath = targetSet.getPath().toString(); Bundle data = new Bundle(getData()); int[] center = new int[2]; getSlotCenter(slotIndex, center); data.putIntArray(AlbumPage.KEY_SET_CENTER, center); if (mGetAlbum && targetSet.isLeafAlbum()) { Activity activity = mActivity; Intent result = new Intent() .putExtra(AlbumPicker.KEY_ALBUM_PATH, targetSet.getPath().toString()); activity.setResult(Activity.RESULT_OK, result); activity.finish(); } else if (targetSet.getSubMediaSetCount() > 0) { data.putString(AlbumSetPage.KEY_MEDIA_PATH, mediaPath); mActivity.getStateManager().startStateForResult( AlbumSetPage.class, REQUEST_DO_ANIMATION, data); } else { if (!mGetContent && (targetSet.getSupportedOperations() & MediaObject.SUPPORT_IMPORT) != 0) { data.putBoolean(AlbumPage.KEY_AUTO_SELECT_ALL, true); } else if (!mGetContent && albumShouldOpenInFilmstrip(targetSet)) { - if (targetSet.getMediaItemCount() == 1) { - PreparePageFadeoutTexture.prepareFadeOutTexture(mActivity, mSlotView, mRootPane); - data.putParcelable(PhotoPage.KEY_OPEN_ANIMATION_RECT, - mSlotView.getSlotRect(slotIndex, mRootPane)); - } + PreparePageFadeoutTexture.prepareFadeOutTexture(mActivity, mSlotView, mRootPane); + data.putParcelable(PhotoPage.KEY_OPEN_ANIMATION_RECT, + mSlotView.getSlotRect(slotIndex, mRootPane)); data.putInt(PhotoPage.KEY_INDEX_HINT, 0); data.putString(PhotoPage.KEY_MEDIA_SET_PATH, mediaPath); data.putBoolean(PhotoPage.KEY_START_IN_FILMSTRIP, true); mActivity.getStateManager().startStateForResult( PhotoPage.class, AlbumPage.REQUEST_PHOTO, data); return; } data.putString(AlbumPage.KEY_MEDIA_PATH, mediaPath); // We only show cluster menu in the first AlbumPage in stack boolean inAlbum = mActivity.getStateManager().hasStateClass(AlbumPage.class); data.putBoolean(AlbumPage.KEY_SHOW_CLUSTER_MENU, !inAlbum); mActivity.getStateManager().startStateForResult( AlbumPage.class, REQUEST_DO_ANIMATION, data); } } private void onDown(int index) { mAlbumSetView.setPressedIndex(index); } private void onUp(boolean followedByLongPress) { if (followedByLongPress) { // Avoid showing press-up animations for long-press. mAlbumSetView.setPressedIndex(-1); } else { mAlbumSetView.setPressedUp(); } } public void onLongTap(int slotIndex) { if (mGetContent || mGetAlbum) return; MediaSet set = mAlbumSetDataAdapter.getMediaSet(slotIndex); if (set == null) return; mSelectionManager.setAutoLeaveSelectionMode(true); mSelectionManager.toggle(set.getPath()); mSlotView.invalidate(); } @Override public void doCluster(int clusterType) { String basePath = mMediaSet.getPath().toString(); String newPath = FilterUtils.switchClusterPath(basePath, clusterType); Bundle data = new Bundle(getData()); data.putString(AlbumSetPage.KEY_MEDIA_PATH, newPath); data.putInt(KEY_SELECTED_CLUSTER_TYPE, clusterType); mActivity.getStateManager().switchState(this, AlbumSetPage.class, data); } @Override public void onCreate(Bundle data, Bundle restoreState) { super.onCreate(data, restoreState); initializeViews(); initializeData(data); Context context = mActivity.getAndroidContext(); mGetContent = data.getBoolean(Gallery.KEY_GET_CONTENT, false); mGetAlbum = data.getBoolean(Gallery.KEY_GET_ALBUM, false); mTitle = data.getString(AlbumSetPage.KEY_SET_TITLE); mSubtitle = data.getString(AlbumSetPage.KEY_SET_SUBTITLE); mEyePosition = new EyePosition(context, this); mDetailsSource = new MyDetailsSource(); mVibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); mActionBar = mActivity.getGalleryActionBar(); mSelectedAction = data.getInt(AlbumSetPage.KEY_SELECTED_CLUSTER_TYPE, FilterUtils.CLUSTER_BY_ALBUM); mHandler = new SynchronizedHandler(mActivity.getGLRoot()) { @Override public void handleMessage(Message message) { switch (message.what) { case MSG_PICK_ALBUM: { pickAlbum(message.arg1); break; } default: throw new AssertionError(message.what); } } }; } private boolean mShowedEmptyToastForSelf = false; private void clearLoadingBit(int loadingBit) { mLoadingBits &= ~loadingBit; if (mLoadingBits == 0 && mIsActive) { if ((mAlbumSetDataAdapter.size() == 0)) { // If this is not the top of the gallery folder hierarchy, // tell the parent AlbumSetPage instance to handle displaying // the empty album toast, otherwise show it within this // instance if (mActivity.getStateManager().getStateCount() > 1) { Intent result = new Intent(); result.putExtra(AlbumPage.KEY_EMPTY_ALBUM, true); setStateResult(Activity.RESULT_OK, result); mActivity.getStateManager().finishState(this); } else { mShowedEmptyToastForSelf = true; showEmptyAlbumToast(Toast.LENGTH_LONG); } return; } } // Hide the empty album toast if we are in the root instance of // AlbumSetPage and the album is no longer empty (for instance, // after a sync is completed and web albums have been synced) if (mShowedEmptyToastForSelf) { mShowedEmptyToastForSelf = false; hideEmptyAlbumToast(); } } private void setLoadingBit(int loadingBit) { mLoadingBits |= loadingBit; } @Override public void onPause() { super.onPause(); mIsActive = false; mActionModeHandler.pause(); mAlbumSetDataAdapter.pause(); mAlbumSetView.pause(); mEyePosition.pause(); DetailsHelper.pause(); // Call disableClusterMenu to avoid receiving callback after paused. // Don't hide menu here otherwise the list menu will disappear earlier than // the action bar, which is janky and unwanted behavior. mActionBar.disableClusterMenu(false); if (mSyncTask != null) { mSyncTask.cancel(); mSyncTask = null; clearLoadingBit(BIT_LOADING_SYNC); } } @Override public void onResume() { super.onResume(); mIsActive = true; setContentPane(mRootPane); // Set the reload bit here to prevent it exit this page in clearLoadingBit(). setLoadingBit(BIT_LOADING_RELOAD); mAlbumSetDataAdapter.resume(); mAlbumSetView.resume(); mEyePosition.resume(); mActionModeHandler.resume(); if (mShowClusterMenu) { mActionBar.enableClusterMenu(mSelectedAction, this); } if (!mInitialSynced) { setLoadingBit(BIT_LOADING_SYNC); mSyncTask = mMediaSet.requestSync(AlbumSetPage.this); } } private void initializeData(Bundle data) { String mediaPath = data.getString(AlbumSetPage.KEY_MEDIA_PATH); mMediaSet = mActivity.getDataManager().getMediaSet(mediaPath); mSelectionManager.setSourceMediaSet(mMediaSet); mAlbumSetDataAdapter = new AlbumSetDataLoader( mActivity, mMediaSet, DATA_CACHE_SIZE); mAlbumSetDataAdapter.setLoadingListener(new MyLoadingListener()); mAlbumSetView.setModel(mAlbumSetDataAdapter); } private void initializeViews() { mSelectionManager = new SelectionManager(mActivity, true); mSelectionManager.setSelectionListener(this); mConfig = Config.AlbumSetPage.get(mActivity); mSlotView = new SlotView(mActivity, mConfig.slotViewSpec); mAlbumSetView = new AlbumSetSlotRenderer( mActivity, mSelectionManager, mSlotView, mConfig.labelSpec, mConfig.placeholderColor); mSlotView.setSlotRenderer(mAlbumSetView); mSlotView.setListener(new SlotView.SimpleListener() { @Override public void onDown(int index) { AlbumSetPage.this.onDown(index); } @Override public void onUp(boolean followedByLongPress) { AlbumSetPage.this.onUp(followedByLongPress); } @Override public void onSingleTapUp(int slotIndex) { AlbumSetPage.this.onSingleTapUp(slotIndex); } @Override public void onLongTap(int slotIndex) { AlbumSetPage.this.onLongTap(slotIndex); } }); mActionModeHandler = new ActionModeHandler(mActivity, mSelectionManager); mActionModeHandler.setActionModeListener(new ActionModeListener() { @Override public boolean onActionItemClicked(MenuItem item) { return onItemSelected(item); } }); mRootPane.addComponent(mSlotView); } @Override protected boolean onCreateActionBar(Menu menu) { Activity activity = mActivity; final boolean inAlbum = mActivity.getStateManager().hasStateClass(AlbumPage.class); MenuInflater inflater = getSupportMenuInflater(); if (mGetContent) { inflater.inflate(R.menu.pickup, menu); int typeBits = mData.getInt( Gallery.KEY_TYPE_BITS, DataManager.INCLUDE_IMAGE); mActionBar.setTitle(GalleryUtils.getSelectionModePrompt(typeBits)); } else if (mGetAlbum) { inflater.inflate(R.menu.pickup, menu); mActionBar.setTitle(R.string.select_album); } else { inflater.inflate(R.menu.albumset, menu); mShowClusterMenu = !inAlbum; boolean selectAlbums = !inAlbum && mActionBar.getClusterTypeAction() == FilterUtils.CLUSTER_BY_ALBUM; MenuItem selectItem = menu.findItem(R.id.action_select); selectItem.setTitle(activity.getString( selectAlbums ? R.string.select_album : R.string.select_group)); MenuItem cameraItem = menu.findItem(R.id.action_camera); cameraItem.setVisible(GalleryUtils.isCameraAvailable(activity)); FilterUtils.setupMenuItems(mActionBar, mMediaSet.getPath(), false); Intent helpIntent = HelpUtils.getHelpIntent(activity, R.string.help_url_gallery_main); MenuItem helpItem = menu.findItem(R.id.action_general_help); helpItem.setVisible(helpIntent != null); if (helpIntent != null) helpItem.setIntent(helpIntent); mActionBar.setTitle(mTitle); mActionBar.setSubtitle(mSubtitle); } return true; } @Override protected boolean onItemSelected(MenuItem item) { Activity activity = mActivity; switch (item.getItemId()) { case R.id.action_cancel: activity.setResult(Activity.RESULT_CANCELED); activity.finish(); return true; case R.id.action_select: mSelectionManager.setAutoLeaveSelectionMode(false); mSelectionManager.enterSelectionMode(); return true; case R.id.action_details: if (mAlbumSetDataAdapter.size() != 0) { if (mShowDetails) { hideDetails(); } else { showDetails(); } } else { Toast.makeText(activity, activity.getText(R.string.no_albums_alert), Toast.LENGTH_SHORT).show(); } return true; case R.id.action_camera: { GalleryUtils.startCameraActivity(activity); return true; } case R.id.action_manage_offline: { Bundle data = new Bundle(); String mediaPath = mActivity.getDataManager().getTopSetPath( DataManager.INCLUDE_ALL); data.putString(AlbumSetPage.KEY_MEDIA_PATH, mediaPath); mActivity.getStateManager().startState(ManageCachePage.class, data); return true; } case R.id.action_sync_picasa_albums: { PicasaSource.requestSync(activity); return true; } case R.id.action_settings: { activity.startActivity(new Intent(activity, GallerySettings.class)); return true; } default: return false; } } @Override protected void onStateResult(int requestCode, int resultCode, Intent data) { if (data != null && data.getBooleanExtra(AlbumPage.KEY_EMPTY_ALBUM, false)) { showEmptyAlbumToast(Toast.LENGTH_SHORT); } switch (requestCode) { case REQUEST_DO_ANIMATION: { mSlotView.startRisingAnimation(); } } } private String getSelectedString() { int count = mSelectionManager.getSelectedCount(); int action = mActionBar.getClusterTypeAction(); int string = action == FilterUtils.CLUSTER_BY_ALBUM ? R.plurals.number_of_albums_selected : R.plurals.number_of_groups_selected; String format = mActivity.getResources().getQuantityString(string, count); return String.format(format, count); } @Override public void onSelectionModeChange(int mode) { switch (mode) { case SelectionManager.ENTER_SELECTION_MODE: { mActionBar.disableClusterMenu(true); mActionModeHandler.startActionMode(); if (mHapticsEnabled) mVibrator.vibrate(100); break; } case SelectionManager.LEAVE_SELECTION_MODE: { mActionModeHandler.finishActionMode(); if (mShowClusterMenu) { mActionBar.enableClusterMenu(mSelectedAction, this); } mRootPane.invalidate(); break; } case SelectionManager.SELECT_ALL_MODE: { mActionModeHandler.updateSupportedOperation(); mRootPane.invalidate(); break; } } } @Override public void onSelectionChange(Path path, boolean selected) { mActionModeHandler.setTitle(getSelectedString()); mActionModeHandler.updateSupportedOperation(path, selected); } private void hideDetails() { mShowDetails = false; mDetailsHelper.hide(); mAlbumSetView.setHighlightItemPath(null); mSlotView.invalidate(); } private void showDetails() { mShowDetails = true; if (mDetailsHelper == null) { mDetailsHelper = new DetailsHelper(mActivity, mRootPane, mDetailsSource); mDetailsHelper.setCloseListener(new CloseListener() { @Override public void onClose() { hideDetails(); } }); } mDetailsHelper.show(); } @Override public void onSyncDone(final MediaSet mediaSet, final int resultCode) { if (resultCode == MediaSet.SYNC_RESULT_ERROR) { Log.d(TAG, "onSyncDone: " + Utils.maskDebugInfo(mediaSet.getName()) + " result=" + resultCode); } ((Activity) mActivity).runOnUiThread(new Runnable() { @Override public void run() { GLRoot root = mActivity.getGLRoot(); root.lockRenderThread(); try { if (resultCode == MediaSet.SYNC_RESULT_SUCCESS) { mInitialSynced = true; } clearLoadingBit(BIT_LOADING_SYNC); if (resultCode == MediaSet.SYNC_RESULT_ERROR && mIsActive) { Log.w(TAG, "failed to load album set"); } } finally { root.unlockRenderThread(); } } }); } private class MyLoadingListener implements LoadingListener { @Override public void onLoadingStarted() { setLoadingBit(BIT_LOADING_RELOAD); } @Override public void onLoadingFinished() { clearLoadingBit(BIT_LOADING_RELOAD); } } private class MyDetailsSource implements DetailsHelper.DetailsSource { private int mIndex; @Override public int size() { return mAlbumSetDataAdapter.size(); } @Override public int setIndex() { Path id = mSelectionManager.getSelected(false).get(0); mIndex = mAlbumSetDataAdapter.findSet(id); return mIndex; } @Override public MediaDetails getDetails() { MediaObject item = mAlbumSetDataAdapter.getMediaSet(mIndex); if (item != null) { mAlbumSetView.setHighlightItemPath(item.getPath()); return item.getDetails(); } else { return null; } } } }
true
true
private void pickAlbum(int slotIndex) { if (!mIsActive) return; MediaSet targetSet = mAlbumSetDataAdapter.getMediaSet(slotIndex); if (targetSet == null) return; // Content is dirty, we shall reload soon if (targetSet.getTotalMediaItemCount() == 0) { showEmptyAlbumToast(Toast.LENGTH_SHORT); return; } hideEmptyAlbumToast(); String mediaPath = targetSet.getPath().toString(); Bundle data = new Bundle(getData()); int[] center = new int[2]; getSlotCenter(slotIndex, center); data.putIntArray(AlbumPage.KEY_SET_CENTER, center); if (mGetAlbum && targetSet.isLeafAlbum()) { Activity activity = mActivity; Intent result = new Intent() .putExtra(AlbumPicker.KEY_ALBUM_PATH, targetSet.getPath().toString()); activity.setResult(Activity.RESULT_OK, result); activity.finish(); } else if (targetSet.getSubMediaSetCount() > 0) { data.putString(AlbumSetPage.KEY_MEDIA_PATH, mediaPath); mActivity.getStateManager().startStateForResult( AlbumSetPage.class, REQUEST_DO_ANIMATION, data); } else { if (!mGetContent && (targetSet.getSupportedOperations() & MediaObject.SUPPORT_IMPORT) != 0) { data.putBoolean(AlbumPage.KEY_AUTO_SELECT_ALL, true); } else if (!mGetContent && albumShouldOpenInFilmstrip(targetSet)) { if (targetSet.getMediaItemCount() == 1) { PreparePageFadeoutTexture.prepareFadeOutTexture(mActivity, mSlotView, mRootPane); data.putParcelable(PhotoPage.KEY_OPEN_ANIMATION_RECT, mSlotView.getSlotRect(slotIndex, mRootPane)); } data.putInt(PhotoPage.KEY_INDEX_HINT, 0); data.putString(PhotoPage.KEY_MEDIA_SET_PATH, mediaPath); data.putBoolean(PhotoPage.KEY_START_IN_FILMSTRIP, true); mActivity.getStateManager().startStateForResult( PhotoPage.class, AlbumPage.REQUEST_PHOTO, data); return; } data.putString(AlbumPage.KEY_MEDIA_PATH, mediaPath); // We only show cluster menu in the first AlbumPage in stack boolean inAlbum = mActivity.getStateManager().hasStateClass(AlbumPage.class); data.putBoolean(AlbumPage.KEY_SHOW_CLUSTER_MENU, !inAlbum); mActivity.getStateManager().startStateForResult( AlbumPage.class, REQUEST_DO_ANIMATION, data); } }
private void pickAlbum(int slotIndex) { if (!mIsActive) return; MediaSet targetSet = mAlbumSetDataAdapter.getMediaSet(slotIndex); if (targetSet == null) return; // Content is dirty, we shall reload soon if (targetSet.getTotalMediaItemCount() == 0) { showEmptyAlbumToast(Toast.LENGTH_SHORT); return; } hideEmptyAlbumToast(); String mediaPath = targetSet.getPath().toString(); Bundle data = new Bundle(getData()); int[] center = new int[2]; getSlotCenter(slotIndex, center); data.putIntArray(AlbumPage.KEY_SET_CENTER, center); if (mGetAlbum && targetSet.isLeafAlbum()) { Activity activity = mActivity; Intent result = new Intent() .putExtra(AlbumPicker.KEY_ALBUM_PATH, targetSet.getPath().toString()); activity.setResult(Activity.RESULT_OK, result); activity.finish(); } else if (targetSet.getSubMediaSetCount() > 0) { data.putString(AlbumSetPage.KEY_MEDIA_PATH, mediaPath); mActivity.getStateManager().startStateForResult( AlbumSetPage.class, REQUEST_DO_ANIMATION, data); } else { if (!mGetContent && (targetSet.getSupportedOperations() & MediaObject.SUPPORT_IMPORT) != 0) { data.putBoolean(AlbumPage.KEY_AUTO_SELECT_ALL, true); } else if (!mGetContent && albumShouldOpenInFilmstrip(targetSet)) { PreparePageFadeoutTexture.prepareFadeOutTexture(mActivity, mSlotView, mRootPane); data.putParcelable(PhotoPage.KEY_OPEN_ANIMATION_RECT, mSlotView.getSlotRect(slotIndex, mRootPane)); data.putInt(PhotoPage.KEY_INDEX_HINT, 0); data.putString(PhotoPage.KEY_MEDIA_SET_PATH, mediaPath); data.putBoolean(PhotoPage.KEY_START_IN_FILMSTRIP, true); mActivity.getStateManager().startStateForResult( PhotoPage.class, AlbumPage.REQUEST_PHOTO, data); return; } data.putString(AlbumPage.KEY_MEDIA_PATH, mediaPath); // We only show cluster menu in the first AlbumPage in stack boolean inAlbum = mActivity.getStateManager().hasStateClass(AlbumPage.class); data.putBoolean(AlbumPage.KEY_SHOW_CLUSTER_MENU, !inAlbum); mActivity.getStateManager().startStateForResult( AlbumPage.class, REQUEST_DO_ANIMATION, data); } }
diff --git a/ij/plugin/MacroInstaller.java b/ij/plugin/MacroInstaller.java index 2ac21087..32c6b306 100644 --- a/ij/plugin/MacroInstaller.java +++ b/ij/plugin/MacroInstaller.java @@ -1,409 +1,410 @@ package ij.plugin; import java.awt.*; import java.io.*; import java.awt.event.*; import ij.*; import ij.gui.*; import ij.macro.*; import ij.text.*; import ij.util.Tools; import ij.io.*; import ij.macro.MacroConstants; import ij.plugin.frame.*; import java.util.*; /** This plugin implements the Plugins/Macros/Install Macros command. It is also used by the Editor class to install macro in menus and by the ImageJ class to install macros at startup. */ public class MacroInstaller implements PlugIn, MacroConstants, ActionListener { public static final int MAX_SIZE = 28000, MAX_MACROS=100, XINC=10, YINC=18; public static final char commandPrefix = '^'; static final String commandPrefixS = "^"; private int[] macroStarts; private String[] macroNames; private MenuBar mb = new MenuBar(); private int nMacros; private Program pgm; private boolean firstEvent = true; private String shortcutsInUse; private int inUseCount; private int nShortcuts; private int toolCount; private String text; private String anonymousName; private Menu macrosMenu; private int autoRunCount, autoRunAndHideCount; private boolean openingStartupMacrosInEditor; private static String defaultDir, fileName; private static MacroInstaller instance, listener; public void run(String path) { if (path==null || path.equals("")) path = showDialog(); if (path==null) return; openingStartupMacrosInEditor = path.indexOf("StartupMacros")!=-1; String text = open(path); if (text!=null) { String functions = Interpreter.getAdditionalFunctions(); if (functions!=null) { if (!(text.endsWith("\n") || functions.startsWith("\n"))) text = text + "\n" + functions; else text = text + functions; } install(text); } } void install() { if (text!=null) { Tokenizer tok = new Tokenizer(); pgm = tok.tokenize(text); } IJ.showStatus(""); int[] code = pgm.getCode(); Symbol[] symbolTable = pgm.getSymbolTable(); int count=0, token, nextToken, address; String name; Symbol symbol; shortcutsInUse = null; inUseCount = 0; nShortcuts = 0; toolCount = 0; macroStarts = new int[MAX_MACROS]; macroNames = new String[MAX_MACROS]; int itemCount = macrosMenu.getItemCount(); int baseCount = macrosMenu==Menus.getMacrosMenu()?5:Editor.MACROS_MENU_ITEMS; if (itemCount>baseCount) { for (int i=itemCount-1; i>=baseCount; i--) macrosMenu.remove(i); } if (pgm.hasVars() && pgm.macroCount()>0 && pgm.getGlobals()==null) new Interpreter().saveGlobals(pgm); for (int i=0; i<code.length; i++) { token = code[i]&TOK_MASK; if (token==MACRO) { nextToken = code[i+1]&TOK_MASK; if (nextToken==STRING_CONSTANT) { if (count==MAX_MACROS) { if (macrosMenu==Menus.getMacrosMenu()) IJ.error("Macro Installer", "Macro sets are limited to "+MAX_MACROS+" macros."); break; } address = code[i+1]>>TOK_SHIFT; symbol = symbolTable[address]; name = symbol.str; macroStarts[count] = i + 2; macroNames[count] = name; if (name.indexOf('-')!=-1 && (name.indexOf("Tool")!=-1||name.indexOf("tool")!=-1)) { Toolbar.getInstance().addMacroTool(name, this, toolCount); toolCount++; } else if (name.startsWith("AutoRun")) { if (autoRunCount==0 && !openingStartupMacrosInEditor) { new MacroRunner(pgm, macroStarts[count], name, null); if (name.equals("AutoRunAndHide")) autoRunAndHideCount++; } autoRunCount++; count--; } else if (name.equals("Popup Menu")) installPopupMenu(name, pgm); else if (!name.endsWith("Tool Selected")){ addShortcut(name); macrosMenu.add(new MenuItem(name)); } //IJ.log(count+" "+name+" "+macroStarts[count]); count++; } } else if (token==EOF) break; } nMacros = count; if (toolCount>0) { Toolbar tb = Toolbar.getInstance(); if(Toolbar.getToolId()>=Toolbar.SPARE2) tb.setTool(Toolbar.RECTANGLE); tb.repaint(); } this.instance = this; if (shortcutsInUse!=null && text!=null) IJ.showMessage("Install Macros", (inUseCount==1?"This keyboard shortcut is":"These keyboard shortcuts are") + " already in use:"+shortcutsInUse); if (nMacros==0 && fileName!=null) { int dotIndex = fileName.lastIndexOf('.'); if (dotIndex>0) anonymousName = fileName.substring(0, dotIndex); else anonymousName =fileName; macrosMenu.add(new MenuItem(anonymousName)); + macroNames[0] = anonymousName; nMacros = 1; } String word = nMacros==1?" macro":" macros"; IJ.showStatus(nMacros + word + " installed"); } public int install(String text) { if (text==null && pgm==null) return 0; this.text = text; macrosMenu = Menus.getMacrosMenu(); if (listener!=null) macrosMenu.removeActionListener(listener); macrosMenu.addActionListener(this); listener = this; install(); return nShortcuts; } public int install(String text, Menu menu) { this.text = text; macrosMenu = menu; install(); return nShortcuts+toolCount; } public void installFile(String path) { if (path!=null) { String text = open(path); if (text!=null) install(text); } } public void installLibrary(String path) { String text = open(path); if (text!=null) Interpreter.setAdditionalFunctions(text); } /** Installs a macro set contained in ij.jar. */ public void installFromIJJar(String path) { String text = openFromIJJar(path); if (text!=null) install(text); } void installPopupMenu(String name, Program pgm) { Hashtable h = pgm.getMenus(); if (h==null) return; String[] commands = (String[])h.get(name); if (commands==null) return; PopupMenu popup = Menus.getPopupMenu(); if (popup==null) return; popup.removeAll(); for (int i=0; i<commands.length; i++) { if (commands[i].equals("-")) popup.addSeparator(); else { MenuItem mi = new MenuItem(commands[i]); mi.addActionListener(this); popup.add(mi); } } } void removeShortcuts() { Menus.getMacroShortcuts().clear(); Hashtable shortcuts = Menus.getShortcuts(); for (Enumeration en=shortcuts.keys(); en.hasMoreElements();) { Integer key = (Integer)en.nextElement(); String value = (String)shortcuts.get(key); if (value.charAt(0)==commandPrefix) shortcuts.remove(key); } } void addShortcut(String name) { int index1 = name.indexOf('['); if (index1==-1) return; int index2 = name.lastIndexOf(']'); if (index2<=(index1+1)) return; String shortcut = name.substring(index1+1, index2); int len = shortcut.length(); if (len>1) shortcut = shortcut.toUpperCase(Locale.US);; if (len>3 || (len>1&&shortcut.charAt(0)!='F'&&shortcut.charAt(0)!='N')) return; int code = Menus.convertShortcutToCode(shortcut); if (code==0) return; if (nShortcuts==0) removeShortcuts(); // One character shortcuts go in a separate hash table to // avoid conflicts with ImageJ menu shortcuts. if (len==1) { Hashtable macroShortcuts = Menus.getMacroShortcuts(); macroShortcuts.put(new Integer(code), commandPrefix+name); nShortcuts++; return; } Hashtable shortcuts = Menus.getShortcuts(); if (shortcuts.get(new Integer(code))!=null) { if (shortcutsInUse==null) shortcutsInUse = "\n \n"; shortcutsInUse += " " + name + "\n"; inUseCount++; return; } shortcuts.put(new Integer(code), commandPrefix+name); nShortcuts++; //IJ.log("addShortcut3: "+name+" "+shortcut+" "+code); } String showDialog() { if (defaultDir==null) defaultDir = Menus.getMacrosPath(); OpenDialog od = new OpenDialog("Install Macros", defaultDir, fileName); String name = od.getFileName(); if (name==null) return null; String dir = od.getDirectory(); if (!(name.endsWith(".txt")||name.endsWith(".ijm"))) { IJ.showMessage("Macro Installer", "File name must end with \".txt\" or \".ijm\" ."); return null; } fileName = name; defaultDir = dir; return dir+name; } String open(String path) { try { StringBuffer sb = new StringBuffer(5000); BufferedReader r = new BufferedReader(new FileReader(path)); while (true) { String s=r.readLine(); if (s==null) break; else sb.append(s+"\n"); } r.close(); return new String(sb); } catch (Exception e) { IJ.error(e.getMessage()); return null; } } /** Returns a text file contained in ij.jar. */ public String openFromIJJar(String path) { //ImageJ ij = IJ.getInstance(); //if (ij==null) return null; String text = null; try { InputStream is = this.getClass().getResourceAsStream(path); //IJ.log(is+" "+path); if (is==null) return null; InputStreamReader isr = new InputStreamReader(is); StringBuffer sb = new StringBuffer(); char [] b = new char [8192]; int n; while ((n = isr.read(b)) > 0) sb.append(b,0, n); text = sb.toString(); } catch (IOException e) {} return text; } //void runMacro() { // new MacroRunner(text); //} public boolean runMacroTool(String name) { for (int i=0; i<nMacros; i++) { if (macroNames[i].startsWith(name)) { new MacroRunner(pgm, macroStarts[i], name, null); return true; } } return false; } public boolean runMenuTool(String name, String command) { for (int i=0; i<nMacros; i++) { if (macroNames[i].startsWith(name)) { Recorder.recordInMacros = true; new MacroRunner(pgm, macroStarts[i], name, command); return true; } } return false; } public static boolean runMacroCommand(String name) { if (instance==null) return false; if (name.startsWith(commandPrefixS)) name = name.substring(1); for (int i=0; i<instance.nMacros; i++) { if (name.equals(instance.macroNames[i])) { new MacroRunner(instance.pgm, instance.macroStarts[i], name, null); return true; } } return false; } public static void runMacroShortcut(String name) { if (instance==null) return; if (name.startsWith(commandPrefixS)) name = name.substring(1); for (int i=0; i<instance.nMacros; i++) { if (name.equals(instance.macroNames[i])) (new MacroRunner()).runShortcut(instance.pgm, instance.macroStarts[i], name); } } public void runMacro(String name) { if (anonymousName!=null && name.equals(anonymousName)) { //IJ.log("runMacro: "+anonymousName); new MacroRunner(pgm, 0, anonymousName, null); return; } for (int i=0; i<nMacros; i++) if (name.equals(macroNames[i])) { new MacroRunner(pgm, macroStarts[i], name, null); return; } } public int getMacroCount() { return nMacros; } public Program getProgram() { return pgm; } /** Returns true if an "AutoRunAndHide" macro was run/installed. */ public boolean isAutoRunAndHide() { return autoRunAndHideCount>0; } public void setFileName(String fileName) { this.fileName = fileName; openingStartupMacrosInEditor = fileName.startsWith("StartupMacros"); } public void actionPerformed(ActionEvent evt) { String cmd = evt.getActionCommand(); MenuItem item = (MenuItem)evt.getSource(); MenuContainer parent = item.getParent(); if (parent instanceof PopupMenu) { for (int i=0; i<nMacros; i++) { if (macroNames[i].equals("Popup Menu")) { new MacroRunner(pgm, macroStarts[i], "Popup Menu", cmd); return; } } } runMacro(cmd); } }
true
true
void install() { if (text!=null) { Tokenizer tok = new Tokenizer(); pgm = tok.tokenize(text); } IJ.showStatus(""); int[] code = pgm.getCode(); Symbol[] symbolTable = pgm.getSymbolTable(); int count=0, token, nextToken, address; String name; Symbol symbol; shortcutsInUse = null; inUseCount = 0; nShortcuts = 0; toolCount = 0; macroStarts = new int[MAX_MACROS]; macroNames = new String[MAX_MACROS]; int itemCount = macrosMenu.getItemCount(); int baseCount = macrosMenu==Menus.getMacrosMenu()?5:Editor.MACROS_MENU_ITEMS; if (itemCount>baseCount) { for (int i=itemCount-1; i>=baseCount; i--) macrosMenu.remove(i); } if (pgm.hasVars() && pgm.macroCount()>0 && pgm.getGlobals()==null) new Interpreter().saveGlobals(pgm); for (int i=0; i<code.length; i++) { token = code[i]&TOK_MASK; if (token==MACRO) { nextToken = code[i+1]&TOK_MASK; if (nextToken==STRING_CONSTANT) { if (count==MAX_MACROS) { if (macrosMenu==Menus.getMacrosMenu()) IJ.error("Macro Installer", "Macro sets are limited to "+MAX_MACROS+" macros."); break; } address = code[i+1]>>TOK_SHIFT; symbol = symbolTable[address]; name = symbol.str; macroStarts[count] = i + 2; macroNames[count] = name; if (name.indexOf('-')!=-1 && (name.indexOf("Tool")!=-1||name.indexOf("tool")!=-1)) { Toolbar.getInstance().addMacroTool(name, this, toolCount); toolCount++; } else if (name.startsWith("AutoRun")) { if (autoRunCount==0 && !openingStartupMacrosInEditor) { new MacroRunner(pgm, macroStarts[count], name, null); if (name.equals("AutoRunAndHide")) autoRunAndHideCount++; } autoRunCount++; count--; } else if (name.equals("Popup Menu")) installPopupMenu(name, pgm); else if (!name.endsWith("Tool Selected")){ addShortcut(name); macrosMenu.add(new MenuItem(name)); } //IJ.log(count+" "+name+" "+macroStarts[count]); count++; } } else if (token==EOF) break; } nMacros = count; if (toolCount>0) { Toolbar tb = Toolbar.getInstance(); if(Toolbar.getToolId()>=Toolbar.SPARE2) tb.setTool(Toolbar.RECTANGLE); tb.repaint(); } this.instance = this; if (shortcutsInUse!=null && text!=null) IJ.showMessage("Install Macros", (inUseCount==1?"This keyboard shortcut is":"These keyboard shortcuts are") + " already in use:"+shortcutsInUse); if (nMacros==0 && fileName!=null) { int dotIndex = fileName.lastIndexOf('.'); if (dotIndex>0) anonymousName = fileName.substring(0, dotIndex); else anonymousName =fileName; macrosMenu.add(new MenuItem(anonymousName)); nMacros = 1; } String word = nMacros==1?" macro":" macros"; IJ.showStatus(nMacros + word + " installed"); }
void install() { if (text!=null) { Tokenizer tok = new Tokenizer(); pgm = tok.tokenize(text); } IJ.showStatus(""); int[] code = pgm.getCode(); Symbol[] symbolTable = pgm.getSymbolTable(); int count=0, token, nextToken, address; String name; Symbol symbol; shortcutsInUse = null; inUseCount = 0; nShortcuts = 0; toolCount = 0; macroStarts = new int[MAX_MACROS]; macroNames = new String[MAX_MACROS]; int itemCount = macrosMenu.getItemCount(); int baseCount = macrosMenu==Menus.getMacrosMenu()?5:Editor.MACROS_MENU_ITEMS; if (itemCount>baseCount) { for (int i=itemCount-1; i>=baseCount; i--) macrosMenu.remove(i); } if (pgm.hasVars() && pgm.macroCount()>0 && pgm.getGlobals()==null) new Interpreter().saveGlobals(pgm); for (int i=0; i<code.length; i++) { token = code[i]&TOK_MASK; if (token==MACRO) { nextToken = code[i+1]&TOK_MASK; if (nextToken==STRING_CONSTANT) { if (count==MAX_MACROS) { if (macrosMenu==Menus.getMacrosMenu()) IJ.error("Macro Installer", "Macro sets are limited to "+MAX_MACROS+" macros."); break; } address = code[i+1]>>TOK_SHIFT; symbol = symbolTable[address]; name = symbol.str; macroStarts[count] = i + 2; macroNames[count] = name; if (name.indexOf('-')!=-1 && (name.indexOf("Tool")!=-1||name.indexOf("tool")!=-1)) { Toolbar.getInstance().addMacroTool(name, this, toolCount); toolCount++; } else if (name.startsWith("AutoRun")) { if (autoRunCount==0 && !openingStartupMacrosInEditor) { new MacroRunner(pgm, macroStarts[count], name, null); if (name.equals("AutoRunAndHide")) autoRunAndHideCount++; } autoRunCount++; count--; } else if (name.equals("Popup Menu")) installPopupMenu(name, pgm); else if (!name.endsWith("Tool Selected")){ addShortcut(name); macrosMenu.add(new MenuItem(name)); } //IJ.log(count+" "+name+" "+macroStarts[count]); count++; } } else if (token==EOF) break; } nMacros = count; if (toolCount>0) { Toolbar tb = Toolbar.getInstance(); if(Toolbar.getToolId()>=Toolbar.SPARE2) tb.setTool(Toolbar.RECTANGLE); tb.repaint(); } this.instance = this; if (shortcutsInUse!=null && text!=null) IJ.showMessage("Install Macros", (inUseCount==1?"This keyboard shortcut is":"These keyboard shortcuts are") + " already in use:"+shortcutsInUse); if (nMacros==0 && fileName!=null) { int dotIndex = fileName.lastIndexOf('.'); if (dotIndex>0) anonymousName = fileName.substring(0, dotIndex); else anonymousName =fileName; macrosMenu.add(new MenuItem(anonymousName)); macroNames[0] = anonymousName; nMacros = 1; } String word = nMacros==1?" macro":" macros"; IJ.showStatus(nMacros + word + " installed"); }
diff --git a/de.xwic.etlgine/src/de/xwic/etlgine/extractor/CSVExtractor.java b/de.xwic.etlgine/src/de/xwic/etlgine/extractor/CSVExtractor.java index 7a54bdc..2c79e40 100644 --- a/de.xwic.etlgine/src/de/xwic/etlgine/extractor/CSVExtractor.java +++ b/de.xwic.etlgine/src/de/xwic/etlgine/extractor/CSVExtractor.java @@ -1,197 +1,198 @@ /* * de.xwic.etlgine.loader.CSVExtractor */ package de.xwic.etlgine.extractor; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import sun.nio.cs.StreamDecoder; import au.com.bytecode.opencsv.CSVReader; import de.xwic.etlgine.AbstractExtractor; import de.xwic.etlgine.ETLException; import de.xwic.etlgine.IColumn; import de.xwic.etlgine.IDataSet; import de.xwic.etlgine.IExtractor; import de.xwic.etlgine.IRecord; import de.xwic.etlgine.ISource; import de.xwic.etlgine.sources.FileSource; /** * Extract data from a CSV file. * @author lippisch */ public class CSVExtractor extends AbstractExtractor implements IExtractor { private CSVReader reader = null; private boolean containsHeader = true; private boolean reachedEnd = false; private char separator = ','; private char quoteChar = '"'; private int skipLines = 0; private int recordNumber = 0; private int expectedColumns = -1; private IDataSet dataSet; /* (non-Javadoc) * @see de.xwic.etlgine.ILoader#close() */ public void close() throws ETLException { if (reader != null) { try { reader.close(); } catch (IOException e) { throw new ETLException("Error closing loader: " + e, e); } } } /* (non-Javadoc) * @see de.xwic.etlgine.ILoader#getNextRecord() */ public IRecord getNextRecord() throws ETLException { if (!reachedEnd) { recordNumber++; try { IRecord record = context.newRecord(); String[] data = reader.readNext(); if (data == null) { reachedEnd = true; } else { if (containsHeader && data.length != expectedColumns) { record.markInvalid("Expected " + expectedColumns + " but record contained " + data.length + " columns. (row=" + recordNumber + ")"); } // try to load what's there int max = Math.min(expectedColumns, data.length); for (int i = 0; i < max; i++) { IColumn column = dataSet.getColumnByIndex(i); record.setData(column, data[i]); } return record; } } catch (IOException e) { throw new ETLException("Error reading record at row " + recordNumber + ": " + e, e); } } return null; } /* (non-Javadoc) * @see de.xwic.etlgine.ILoader#openSource(de.xwic.etlgine.ISource) */ public void openSource(ISource source, IDataSet dataSet) throws ETLException { this.dataSet = dataSet; if (!(source instanceof FileSource)) { throw new ETLException("Can not handle a source of this type - FileSource type required."); } FileSource fsrc = (FileSource)source; try { recordNumber = 0; reachedEnd = false; InputStream in = new FileInputStream(fsrc.getFile()); // determine encoding if (fsrc.getEncoding() == null) { String encoding = null; // java default byte[] encoding_tag = new byte[2]; // find source encoding if (in.read(encoding_tag, 0, 2) == 2 && encoding_tag[0] == -1 && encoding_tag[1] == -2) { // used by Cognos CSV reports encoding = "UTF-16LE"; } else { - in.reset(); + in.close(); + in = new FileInputStream(fsrc.getFile()); } fsrc.setEncoding(encoding); } reader = new CSVReader(new BufferedReader(StreamDecoder.forInputStreamReader(in, fsrc.getFile(), fsrc.getEncoding())), separator, quoteChar, skipLines); if (containsHeader) { String[] header = reader.readNext(); if (header == null) { // file is empty! reachedEnd = true; } else { expectedColumns = header.length; int idx = 0; for (String colName : header) { dataSet.addColumn(colName, idx++); } } } } catch (FileNotFoundException e) { throw new ETLException("Source file not found (" + source.getName() + ") : " + e, e); } catch (IOException e) { throw new ETLException("Error reading file (" + source.getName() + ") : " + e, e); } } /** * @return the containsHeader */ public boolean isContainsHeader() { return containsHeader; } /** * @param containsHeader the containsHeader to set */ public void setContainsHeader(boolean containsHeader) { this.containsHeader = containsHeader; } /** * @return the separator */ public char getSeparator() { return separator; } /** * @param separator the separator to set */ public void setSeparator(char separator) { this.separator = separator; } /** * @return the quoteChar */ public char getQuoteChar() { return quoteChar; } /** * @param quoteChar the quoteChar to set */ public void setQuoteChar(char quoteChar) { this.quoteChar = quoteChar; } /** * @return the skipLines */ public int getSkipLines() { return skipLines; } /** * @param skipLines the skipLines to set */ public void setSkipLines(int skipLines) { this.skipLines = skipLines; } }
true
true
public void openSource(ISource source, IDataSet dataSet) throws ETLException { this.dataSet = dataSet; if (!(source instanceof FileSource)) { throw new ETLException("Can not handle a source of this type - FileSource type required."); } FileSource fsrc = (FileSource)source; try { recordNumber = 0; reachedEnd = false; InputStream in = new FileInputStream(fsrc.getFile()); // determine encoding if (fsrc.getEncoding() == null) { String encoding = null; // java default byte[] encoding_tag = new byte[2]; // find source encoding if (in.read(encoding_tag, 0, 2) == 2 && encoding_tag[0] == -1 && encoding_tag[1] == -2) { // used by Cognos CSV reports encoding = "UTF-16LE"; } else { in.reset(); } fsrc.setEncoding(encoding); } reader = new CSVReader(new BufferedReader(StreamDecoder.forInputStreamReader(in, fsrc.getFile(), fsrc.getEncoding())), separator, quoteChar, skipLines); if (containsHeader) { String[] header = reader.readNext(); if (header == null) { // file is empty! reachedEnd = true; } else { expectedColumns = header.length; int idx = 0; for (String colName : header) { dataSet.addColumn(colName, idx++); } } } } catch (FileNotFoundException e) { throw new ETLException("Source file not found (" + source.getName() + ") : " + e, e); } catch (IOException e) { throw new ETLException("Error reading file (" + source.getName() + ") : " + e, e); } }
public void openSource(ISource source, IDataSet dataSet) throws ETLException { this.dataSet = dataSet; if (!(source instanceof FileSource)) { throw new ETLException("Can not handle a source of this type - FileSource type required."); } FileSource fsrc = (FileSource)source; try { recordNumber = 0; reachedEnd = false; InputStream in = new FileInputStream(fsrc.getFile()); // determine encoding if (fsrc.getEncoding() == null) { String encoding = null; // java default byte[] encoding_tag = new byte[2]; // find source encoding if (in.read(encoding_tag, 0, 2) == 2 && encoding_tag[0] == -1 && encoding_tag[1] == -2) { // used by Cognos CSV reports encoding = "UTF-16LE"; } else { in.close(); in = new FileInputStream(fsrc.getFile()); } fsrc.setEncoding(encoding); } reader = new CSVReader(new BufferedReader(StreamDecoder.forInputStreamReader(in, fsrc.getFile(), fsrc.getEncoding())), separator, quoteChar, skipLines); if (containsHeader) { String[] header = reader.readNext(); if (header == null) { // file is empty! reachedEnd = true; } else { expectedColumns = header.length; int idx = 0; for (String colName : header) { dataSet.addColumn(colName, idx++); } } } } catch (FileNotFoundException e) { throw new ETLException("Source file not found (" + source.getName() + ") : " + e, e); } catch (IOException e) { throw new ETLException("Error reading file (" + source.getName() + ") : " + e, e); } }
diff --git a/xengine_less/src/com/xengine/android/utils/XStringUtil.java b/xengine_less/src/com/xengine/android/utils/XStringUtil.java index 86b7285..cd34fd4 100644 --- a/xengine_less/src/com/xengine/android/utils/XStringUtil.java +++ b/xengine_less/src/com/xengine/android/utils/XStringUtil.java @@ -1,391 +1,393 @@ package com.xengine.android.utils; import android.text.TextUtils; import java.io.*; import java.math.BigDecimal; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Calendar; import java.util.Date; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by jasontujun. * Date: 12-3-3 * Time: 下午7:35 */ public class XStringUtil { private static final String LINE_SEPARATOR = System.getProperty("line.separator"); private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; private static final String RANDOM_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static boolean equals(String str1, String str2) { return str1 != null && str2 != null && str1.equals(str2); } public static boolean equalsIgnoreCase(String str1, String str2) { return str1 != null && str2 != null && str1.equalsIgnoreCase(str2); } public static boolean equals(String str1, String str2, boolean ignoreCase) { if (str1 != null && str2 != null) { if (ignoreCase) { return str1.equalsIgnoreCase(str2); } else { return str1.equals(str2); } } else { return str1 == null && str2 == null; } } public static String getString(String str) { return str == null ? "" : str; } /** * 返回字符串的字节个数(中文当2个字节计算) * @param s * @return */ public static int stringSize(String s) { try { String anotherString = new String(s.getBytes("GBK"), "ISO8859_1"); return anotherString.length(); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); return 0; } } public static String unquote(String s, String quote) { if (!TextUtils.isEmpty(s) && !TextUtils.isEmpty(quote)) { if (s.startsWith(quote) && s.endsWith(quote)) { return s.substring(1, s.length() - quote.length()); } } return s; } public static String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line).append(LINE_SEPARATOR); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } /** * 过滤HTML标签,取出文本内的相关数据 * * @param inputString * @return */ public static String filterHtmlTag(String inputString) { String htmlStr = inputString; // 含html标签的字符串 String textStr = ""; Pattern p_script; Matcher m_script; Pattern p_style; Matcher m_style; Pattern p_html; Matcher m_html; try { String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; // 定义script的正则表达式{�?script[^>]*?>[\\s\\S]*?<\\/script> // } String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; // 定义style的正则表达式{�?style[^>]*?>[\\s\\S]*?<\\/style> // } String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式 p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE); m_script = p_script.matcher(htmlStr); htmlStr = m_script.replaceAll(""); // 过滤script标签 p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE); m_style = p_style.matcher(htmlStr); htmlStr = m_style.replaceAll(""); // 过滤style标签 p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE); m_html = p_html.matcher(htmlStr); htmlStr = m_html.replaceAll(""); // 过滤html标签 textStr = htmlStr; } catch (Exception e) { System.err.println("Html2Text: " + e.getMessage()); } return textStr;// 返回文本字符 } /** * 验证字符串是否符合email格式 * @param email 验证的字符串 * @return 如果字符串为空或者为Null返回false * 如果不为空或Null则验证其是否符合email格式, * 符合则返回true,不符合则返回false */ public static boolean isEmail(String email) { if (TextUtils.isEmpty(email)) return false; //通过正则表达式验证Emial是否合法 return email.matches("^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@" + "([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$"); } /** * 验证字符串是否是数字(允许以0开头的数字) * 通过正则表达式验证。 * @param numStr * @return */ public static boolean isNumber(String numStr) { + if (TextUtils.isEmpty(numStr)) + return false; Pattern pattern = Pattern.compile("[0-9]*"); Matcher match = pattern.matcher(numStr); return match.matches(); } public static String date2str(long time) { return date2str(new Date(time)); } public static String date2str(Date date) { if (date == null) return null; return date2str(date.getYear() + 1900, date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes()); } public static String date2str(int year, int month, int day, int hour, int minute) { String hourStr = "" + hour; String minStr = "" + minute; if (hour < 10) { hourStr = "0" + hourStr; } if (minute < 10) { minStr = "0" +minStr; } return year + "-" + month + "-" + day + " " + hourStr + ":" + minStr; } public static String date2calendarStr(Date date) { return date2calendarStr(date.getYear() + 1900, date.getMonth() + 1, date.getDate()); } public static String date2calendarStr(int year, int month, int day) { return year+"-"+month+"-"+day; } public static String calendar2str(Calendar c) { int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH) + 1; int day = c.get(Calendar.DAY_OF_MONTH); return year + "-" + month + "-" + day; } public static Calendar str2calendar(String str) { if (TextUtils.isEmpty(str)) return null; String[] strList = str.split("-"); if (strList.length != 3 || !isNumber(strList[0]) || !isNumber(strList[1]) || !isNumber(strList[2])) return null; int year = Integer.parseInt(strList[0]); int month = Integer.parseInt(strList[1]); int day = Integer.parseInt(strList[2]); Calendar result = Calendar.getInstance(); result.set(year, month - 1, day); return result; } /** * 将字符串数组转化为用逗号连接的字符串 * @param values * @return */ public static String array2String(String[] values) { String result = ""; if (values != null) { if (values.length > 0) { for (String value : values) { result += value + ","; } result = result.substring(0, result.length() - 1); } } return result; } /** * 百分比转字符串 * @param percent * @return */ public static String percent2str(double percent) { int percentInt = (int) (percent * 100); return percentInt + "%"; } /** * 字符串转为md5编码 * @param str 源字符串 * @return md5编码后的字符串 */ public static String str2md5(String str) { try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(str.getBytes()); byte[] bytes = algorithm.digest(); StringBuilder hexString = new StringBuilder(); for (byte b : bytes) { hexString.append(HEX_DIGITS[b >> 4 & 0xf]); hexString.append(HEX_DIGITS[b & 0xf]); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } /** * 将文件大小转换(保留两位小数) * @param size 文件大小,单位:byte * @return 文件大小 */ public static String fileSize2String(long size) { return fileSize2String(size, 2); } private static final float KB = 1024; private static final float MB = 1024*1024; private static final float GB = 1024*1024*1024; /** * 将文件大小转换 * @param size 文件大小,单位:byte * @param scale 小数位数 * @return 文件大小 */ public static String fileSize2String(long size, int scale) { float result; String unit; if (size <= 0) { result = 0; unit = "B"; } else if (size < KB) { result = size; unit = "B"; } else if (size < MB) { result = size/KB; unit = "KB"; } else if (size < GB) { result = size/MB; unit = "MB"; } else { result = size/GB; unit = "GB"; } BigDecimal bg = new BigDecimal(result); float f1 = bg.setScale(scale, BigDecimal.ROUND_HALF_UP).floatValue(); return f1 + unit; } /** * 将毫秒转换为 "*日*小时*分钟*秒" * @param mss 要转换的毫秒数 * @return */ public static String formatDuring(long mss) { long days = mss / (1000 * 60 * 60 * 24); long hours = (mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60); long minutes = (mss % (1000 * 60 * 60)) / (1000 * 60); long seconds = (mss % (1000 * 60)) / 1000; if (days != 0) { if (hours > 12) { return days+"天+"; } else { return days+"天"; } } else if(hours !=0) { if (minutes >30) { return hours + "小时+"; } else { return hours + "小时"; } } else if (minutes != 0) { return minutes + "分钟"; } else { return seconds + "秒"; } } /** * 将两日期的间隔转换为 "*日*小时*分钟*秒" * @param begin 时间段的开始 * @param end 时间段的结束 * @return 输入的两个Date类型数据之间的时间间格用 * * days * hours * minutes * seconds的格式展示 */ public static String formatDuring(Date begin, Date end) { return formatDuring(end.getTime() - begin.getTime()); } /** * 处理文件名,去掉后缀 * @param srcName * @return */ public static String removeFileNameSuffix(String srcName) { int dotIndex = srcName.lastIndexOf("."); if (dotIndex == -1) return srcName; else return srcName.substring(0, dotIndex); } // 获取随即数 /** * 获取随机字符串 * @param length 字符串长度 * @return 返回随机字符串 */ public static String getRandomString(int length) { if (length <= 0) return null; StringBuffer sb = new StringBuffer(); Random r = new Random(); int range = RANDOM_CHARS.length(); for (int i = 0; i < length; i++) { sb.append(RANDOM_CHARS.charAt(r.nextInt(range))); } return sb.toString(); } }
true
true
public static String filterHtmlTag(String inputString) { String htmlStr = inputString; // 含html标签的字符串 String textStr = ""; Pattern p_script; Matcher m_script; Pattern p_style; Matcher m_style; Pattern p_html; Matcher m_html; try { String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; // 定义script的正则表达式{�?script[^>]*?>[\\s\\S]*?<\\/script> // } String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; // 定义style的正则表达式{�?style[^>]*?>[\\s\\S]*?<\\/style> // } String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式 p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE); m_script = p_script.matcher(htmlStr); htmlStr = m_script.replaceAll(""); // 过滤script标签 p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE); m_style = p_style.matcher(htmlStr); htmlStr = m_style.replaceAll(""); // 过滤style标签 p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE); m_html = p_html.matcher(htmlStr); htmlStr = m_html.replaceAll(""); // 过滤html标签 textStr = htmlStr; } catch (Exception e) { System.err.println("Html2Text: " + e.getMessage()); } return textStr;// 返回文本字符 } /** * 验证字符串是否符合email格式 * @param email 验证的字符串 * @return 如果字符串为空或者为Null返回false * 如果不为空或Null则验证其是否符合email格式, * 符合则返回true,不符合则返回false */ public static boolean isEmail(String email) { if (TextUtils.isEmpty(email)) return false; //通过正则表达式验证Emial是否合法 return email.matches("^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@" + "([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$"); } /** * 验证字符串是否是数字(允许以0开头的数字) * 通过正则表达式验证。 * @param numStr * @return */ public static boolean isNumber(String numStr) { Pattern pattern = Pattern.compile("[0-9]*"); Matcher match = pattern.matcher(numStr); return match.matches(); } public static String date2str(long time) { return date2str(new Date(time)); } public static String date2str(Date date) { if (date == null) return null; return date2str(date.getYear() + 1900, date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes()); } public static String date2str(int year, int month, int day, int hour, int minute) { String hourStr = "" + hour; String minStr = "" + minute; if (hour < 10) { hourStr = "0" + hourStr; } if (minute < 10) { minStr = "0" +minStr; } return year + "-" + month + "-" + day + " " + hourStr + ":" + minStr; } public static String date2calendarStr(Date date) { return date2calendarStr(date.getYear() + 1900, date.getMonth() + 1, date.getDate()); } public static String date2calendarStr(int year, int month, int day) { return year+"-"+month+"-"+day; } public static String calendar2str(Calendar c) { int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH) + 1; int day = c.get(Calendar.DAY_OF_MONTH); return year + "-" + month + "-" + day; } public static Calendar str2calendar(String str) { if (TextUtils.isEmpty(str)) return null; String[] strList = str.split("-"); if (strList.length != 3 || !isNumber(strList[0]) || !isNumber(strList[1]) || !isNumber(strList[2])) return null; int year = Integer.parseInt(strList[0]); int month = Integer.parseInt(strList[1]); int day = Integer.parseInt(strList[2]); Calendar result = Calendar.getInstance(); result.set(year, month - 1, day); return result; } /** * 将字符串数组转化为用逗号连接的字符串 * @param values * @return */ public static String array2String(String[] values) { String result = ""; if (values != null) { if (values.length > 0) { for (String value : values) { result += value + ","; } result = result.substring(0, result.length() - 1); } } return result; } /** * 百分比转字符串 * @param percent * @return */ public static String percent2str(double percent) { int percentInt = (int) (percent * 100); return percentInt + "%"; } /** * 字符串转为md5编码 * @param str 源字符串 * @return md5编码后的字符串 */ public static String str2md5(String str) { try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(str.getBytes()); byte[] bytes = algorithm.digest(); StringBuilder hexString = new StringBuilder(); for (byte b : bytes) { hexString.append(HEX_DIGITS[b >> 4 & 0xf]); hexString.append(HEX_DIGITS[b & 0xf]); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } /** * 将文件大小转换(保留两位小数) * @param size 文件大小,单位:byte * @return 文件大小 */ public static String fileSize2String(long size) { return fileSize2String(size, 2); } private static final float KB = 1024; private static final float MB = 1024*1024; private static final float GB = 1024*1024*1024; /** * 将文件大小转换 * @param size 文件大小,单位:byte * @param scale 小数位数 * @return 文件大小 */ public static String fileSize2String(long size, int scale) { float result; String unit; if (size <= 0) { result = 0; unit = "B"; } else if (size < KB) { result = size; unit = "B"; } else if (size < MB) { result = size/KB; unit = "KB"; } else if (size < GB) { result = size/MB; unit = "MB"; } else { result = size/GB; unit = "GB"; } BigDecimal bg = new BigDecimal(result); float f1 = bg.setScale(scale, BigDecimal.ROUND_HALF_UP).floatValue(); return f1 + unit; } /** * 将毫秒转换为 "*日*小时*分钟*秒" * @param mss 要转换的毫秒数 * @return */ public static String formatDuring(long mss) { long days = mss / (1000 * 60 * 60 * 24); long hours = (mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60); long minutes = (mss % (1000 * 60 * 60)) / (1000 * 60); long seconds = (mss % (1000 * 60)) / 1000; if (days != 0) { if (hours > 12) { return days+"天+"; } else { return days+"天"; } } else if(hours !=0) { if (minutes >30) { return hours + "小时+"; } else { return hours + "小时"; } } else if (minutes != 0) { return minutes + "分钟"; } else { return seconds + "秒"; } } /** * 将两日期的间隔转换为 "*日*小时*分钟*秒" * @param begin 时间段的开始 * @param end 时间段的结束 * @return 输入的两个Date类型数据之间的时间间格用 * * days * hours * minutes * seconds的格式展示 */ public static String formatDuring(Date begin, Date end) { return formatDuring(end.getTime() - begin.getTime()); } /** * 处理文件名,去掉后缀 * @param srcName * @return */ public static String removeFileNameSuffix(String srcName) { int dotIndex = srcName.lastIndexOf("."); if (dotIndex == -1) return srcName; else return srcName.substring(0, dotIndex); } // 获取随即数 /** * 获取随机字符串 * @param length 字符串长度 * @return 返回随机字符串 */ public static String getRandomString(int length) { if (length <= 0) return null; StringBuffer sb = new StringBuffer(); Random r = new Random(); int range = RANDOM_CHARS.length(); for (int i = 0; i < length; i++) { sb.append(RANDOM_CHARS.charAt(r.nextInt(range))); } return sb.toString(); } }
public static String filterHtmlTag(String inputString) { String htmlStr = inputString; // 含html标签的字符串 String textStr = ""; Pattern p_script; Matcher m_script; Pattern p_style; Matcher m_style; Pattern p_html; Matcher m_html; try { String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; // 定义script的正则表达式{�?script[^>]*?>[\\s\\S]*?<\\/script> // } String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; // 定义style的正则表达式{�?style[^>]*?>[\\s\\S]*?<\\/style> // } String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式 p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE); m_script = p_script.matcher(htmlStr); htmlStr = m_script.replaceAll(""); // 过滤script标签 p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE); m_style = p_style.matcher(htmlStr); htmlStr = m_style.replaceAll(""); // 过滤style标签 p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE); m_html = p_html.matcher(htmlStr); htmlStr = m_html.replaceAll(""); // 过滤html标签 textStr = htmlStr; } catch (Exception e) { System.err.println("Html2Text: " + e.getMessage()); } return textStr;// 返回文本字符 } /** * 验证字符串是否符合email格式 * @param email 验证的字符串 * @return 如果字符串为空或者为Null返回false * 如果不为空或Null则验证其是否符合email格式, * 符合则返回true,不符合则返回false */ public static boolean isEmail(String email) { if (TextUtils.isEmpty(email)) return false; //通过正则表达式验证Emial是否合法 return email.matches("^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@" + "([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$"); } /** * 验证字符串是否是数字(允许以0开头的数字) * 通过正则表达式验证。 * @param numStr * @return */ public static boolean isNumber(String numStr) { if (TextUtils.isEmpty(numStr)) return false; Pattern pattern = Pattern.compile("[0-9]*"); Matcher match = pattern.matcher(numStr); return match.matches(); } public static String date2str(long time) { return date2str(new Date(time)); } public static String date2str(Date date) { if (date == null) return null; return date2str(date.getYear() + 1900, date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes()); } public static String date2str(int year, int month, int day, int hour, int minute) { String hourStr = "" + hour; String minStr = "" + minute; if (hour < 10) { hourStr = "0" + hourStr; } if (minute < 10) { minStr = "0" +minStr; } return year + "-" + month + "-" + day + " " + hourStr + ":" + minStr; } public static String date2calendarStr(Date date) { return date2calendarStr(date.getYear() + 1900, date.getMonth() + 1, date.getDate()); } public static String date2calendarStr(int year, int month, int day) { return year+"-"+month+"-"+day; } public static String calendar2str(Calendar c) { int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH) + 1; int day = c.get(Calendar.DAY_OF_MONTH); return year + "-" + month + "-" + day; } public static Calendar str2calendar(String str) { if (TextUtils.isEmpty(str)) return null; String[] strList = str.split("-"); if (strList.length != 3 || !isNumber(strList[0]) || !isNumber(strList[1]) || !isNumber(strList[2])) return null; int year = Integer.parseInt(strList[0]); int month = Integer.parseInt(strList[1]); int day = Integer.parseInt(strList[2]); Calendar result = Calendar.getInstance(); result.set(year, month - 1, day); return result; } /** * 将字符串数组转化为用逗号连接的字符串 * @param values * @return */ public static String array2String(String[] values) { String result = ""; if (values != null) { if (values.length > 0) { for (String value : values) { result += value + ","; } result = result.substring(0, result.length() - 1); } } return result; } /** * 百分比转字符串 * @param percent * @return */ public static String percent2str(double percent) { int percentInt = (int) (percent * 100); return percentInt + "%"; } /** * 字符串转为md5编码 * @param str 源字符串 * @return md5编码后的字符串 */ public static String str2md5(String str) { try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(str.getBytes()); byte[] bytes = algorithm.digest(); StringBuilder hexString = new StringBuilder(); for (byte b : bytes) { hexString.append(HEX_DIGITS[b >> 4 & 0xf]); hexString.append(HEX_DIGITS[b & 0xf]); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } /** * 将文件大小转换(保留两位小数) * @param size 文件大小,单位:byte * @return 文件大小 */ public static String fileSize2String(long size) { return fileSize2String(size, 2); } private static final float KB = 1024; private static final float MB = 1024*1024; private static final float GB = 1024*1024*1024; /** * 将文件大小转换 * @param size 文件大小,单位:byte * @param scale 小数位数 * @return 文件大小 */ public static String fileSize2String(long size, int scale) { float result; String unit; if (size <= 0) { result = 0; unit = "B"; } else if (size < KB) { result = size; unit = "B"; } else if (size < MB) { result = size/KB; unit = "KB"; } else if (size < GB) { result = size/MB; unit = "MB"; } else { result = size/GB; unit = "GB"; } BigDecimal bg = new BigDecimal(result); float f1 = bg.setScale(scale, BigDecimal.ROUND_HALF_UP).floatValue(); return f1 + unit; } /** * 将毫秒转换为 "*日*小时*分钟*秒" * @param mss 要转换的毫秒数 * @return */ public static String formatDuring(long mss) { long days = mss / (1000 * 60 * 60 * 24); long hours = (mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60); long minutes = (mss % (1000 * 60 * 60)) / (1000 * 60); long seconds = (mss % (1000 * 60)) / 1000; if (days != 0) { if (hours > 12) { return days+"天+"; } else { return days+"天"; } } else if(hours !=0) { if (minutes >30) { return hours + "小时+"; } else { return hours + "小时"; } } else if (minutes != 0) { return minutes + "分钟"; } else { return seconds + "秒"; } } /** * 将两日期的间隔转换为 "*日*小时*分钟*秒" * @param begin 时间段的开始 * @param end 时间段的结束 * @return 输入的两个Date类型数据之间的时间间格用 * * days * hours * minutes * seconds的格式展示 */ public static String formatDuring(Date begin, Date end) { return formatDuring(end.getTime() - begin.getTime()); } /** * 处理文件名,去掉后缀 * @param srcName * @return */ public static String removeFileNameSuffix(String srcName) { int dotIndex = srcName.lastIndexOf("."); if (dotIndex == -1) return srcName; else return srcName.substring(0, dotIndex); } // 获取随即数 /** * 获取随机字符串 * @param length 字符串长度 * @return 返回随机字符串 */ public static String getRandomString(int length) { if (length <= 0) return null; StringBuffer sb = new StringBuffer(); Random r = new Random(); int range = RANDOM_CHARS.length(); for (int i = 0; i < length; i++) { sb.append(RANDOM_CHARS.charAt(r.nextInt(range))); } return sb.toString(); } }
diff --git a/rsa/src/main/java/org/rackspace/capman/tools/util/PrivKeyReader.java b/rsa/src/main/java/org/rackspace/capman/tools/util/PrivKeyReader.java index 6eeeb5c..117a0a1 100644 --- a/rsa/src/main/java/org/rackspace/capman/tools/util/PrivKeyReader.java +++ b/rsa/src/main/java/org/rackspace/capman/tools/util/PrivKeyReader.java @@ -1,113 +1,113 @@ package org.rackspace.capman.tools.util; import java.math.BigInteger; import java.security.InvalidKeyException; import java.security.KeyPair; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; import java.util.logging.Level; import java.util.logging.Logger; import org.bouncycastle.jce.provider.JCERSAPrivateCrtKey; import org.rackspace.capman.tools.ca.PemUtils; import org.rackspace.capman.tools.ca.exceptions.PemException; import org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure; import org.rackspace.capman.tools.ca.exceptions.PrivKeyDecodeException; import org.rackspace.capman.tools.ca.primitives.RsaConst; import org.rackspace.capman.tools.ca.exceptions.X509ReaderDecodeException; import org.rackspace.capman.tools.ca.primitives.bcextenders.HackedProviderAccessor; public class PrivKeyReader { static { RsaConst.init(); } private JCERSAPrivateCrtKey privKey; public PrivKeyReader(JCERSAPrivateCrtKey privKey) { this.privKey = privKey; } public BigInteger getN() { return privKey.getModulus(); } public BigInteger getP() { return privKey.getPrimeP(); } public BigInteger getQ() { return privKey.getPrimeQ(); } public BigInteger getE() { return privKey.getPublicExponent(); } public BigInteger getD() { return privKey.getPrivateExponent(); } public BigInteger getdP() { return privKey.getPrimeExponentP(); } public BigInteger getdQ() { return privKey.getPrimeExponentQ(); } public BigInteger getQinv() { return privKey.getCrtCoefficient(); } public static PrivKeyReader newPrivKeyReader(String pemString) throws PrivKeyDecodeException { JCERSAPrivateCrtKey privKey; Object obj; String msg; try { obj = PemUtils.fromPemString(pemString); } catch (PemException ex) { - throw new PrivKeyDecodeException("Error decoding Keyt", ex); + throw new PrivKeyDecodeException("Error decoding Key", ex); } if (obj instanceof KeyPair) { KeyPair kp = (KeyPair) obj; privKey = (JCERSAPrivateCrtKey) kp.getPrivate(); return new PrivKeyReader(privKey); } try { privKey = (JCERSAPrivateCrtKey) obj; } catch (ClassCastException ex) { msg = String.format("Error casting %s to %s", obj.getClass().getName(), "JCERSAPrivateCrtKey"); throw new PrivKeyDecodeException(msg, ex); } return new PrivKeyReader(privKey); } public KeyPair toKeyPair() throws InvalidKeySpecException { KeyPair kp = HackedProviderAccessor.newKeyPair(privKey); return kp; } public JCERSAPrivateCrtKey getPrivKey() { return privKey; } public void setPrivKey(JCERSAPrivateCrtKey privKey) { this.privKey = privKey; } public static String getPubKeyHash(PublicKey pubKey) { SubjectKeyIdentifierStructure skis; try { skis = new SubjectKeyIdentifierStructure(pubKey); } catch (InvalidKeyException ex) { return null; } byte[] keyIdBytes = skis.getKeyIdentifier(); if (keyIdBytes == null) { return null; } String out = StaticHelpers.bytes2hex(keyIdBytes); return out; } }
true
true
public static PrivKeyReader newPrivKeyReader(String pemString) throws PrivKeyDecodeException { JCERSAPrivateCrtKey privKey; Object obj; String msg; try { obj = PemUtils.fromPemString(pemString); } catch (PemException ex) { throw new PrivKeyDecodeException("Error decoding Keyt", ex); } if (obj instanceof KeyPair) { KeyPair kp = (KeyPair) obj; privKey = (JCERSAPrivateCrtKey) kp.getPrivate(); return new PrivKeyReader(privKey); } try { privKey = (JCERSAPrivateCrtKey) obj; } catch (ClassCastException ex) { msg = String.format("Error casting %s to %s", obj.getClass().getName(), "JCERSAPrivateCrtKey"); throw new PrivKeyDecodeException(msg, ex); } return new PrivKeyReader(privKey); }
public static PrivKeyReader newPrivKeyReader(String pemString) throws PrivKeyDecodeException { JCERSAPrivateCrtKey privKey; Object obj; String msg; try { obj = PemUtils.fromPemString(pemString); } catch (PemException ex) { throw new PrivKeyDecodeException("Error decoding Key", ex); } if (obj instanceof KeyPair) { KeyPair kp = (KeyPair) obj; privKey = (JCERSAPrivateCrtKey) kp.getPrivate(); return new PrivKeyReader(privKey); } try { privKey = (JCERSAPrivateCrtKey) obj; } catch (ClassCastException ex) { msg = String.format("Error casting %s to %s", obj.getClass().getName(), "JCERSAPrivateCrtKey"); throw new PrivKeyDecodeException(msg, ex); } return new PrivKeyReader(privKey); }
diff --git a/src/main/java/org/apache/commons/digester3/annotations/handlers/ObjectCreateHandler.java b/src/main/java/org/apache/commons/digester3/annotations/handlers/ObjectCreateHandler.java index 6c4b24a0..b6649849 100644 --- a/src/main/java/org/apache/commons/digester3/annotations/handlers/ObjectCreateHandler.java +++ b/src/main/java/org/apache/commons/digester3/annotations/handlers/ObjectCreateHandler.java @@ -1,73 +1,74 @@ package org.apache.commons.digester3.annotations.handlers; /* * 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. */ import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Constructor; import org.apache.commons.digester3.annotations.AnnotationHandler; import org.apache.commons.digester3.annotations.rules.ObjectCreate; import org.apache.commons.digester3.binder.ObjectCreateBuilder; import org.apache.commons.digester3.binder.RulesBinder; /** * {@link ObjectCreateHandler} handler. * * @since 3.0 */ public final class ObjectCreateHandler implements AnnotationHandler<ObjectCreate, AnnotatedElement> { /** * {@inheritDoc} */ public void handle( ObjectCreate annotation, AnnotatedElement element, RulesBinder rulesBinder ) { Class<?> type = null; if ( element instanceof Class<?> ) { type = (Class<?>) element; } else if ( element instanceof Constructor<?> ) { type = ( (Constructor<?>) element ).getDeclaringClass(); } else { - rulesBinder.addError( "", element ); + rulesBinder.addError( "Misplaced @ObjectCreate annotation to %s, Class and Constructor only supported", + element ); return; } ObjectCreateBuilder builder = rulesBinder .forPattern( annotation.pattern() ) .withNamespaceURI( annotation.namespaceURI() ) .createObject() .ofType( type ) .ofTypeSpecifiedByAttribute( annotation.attributeName() != null ? annotation.attributeName() : null ); if ( element instanceof Constructor<?> ) { Constructor<?> method = (Constructor<?>) element; builder.usingConstructor( method.getParameterTypes() ); } } }
true
true
public void handle( ObjectCreate annotation, AnnotatedElement element, RulesBinder rulesBinder ) { Class<?> type = null; if ( element instanceof Class<?> ) { type = (Class<?>) element; } else if ( element instanceof Constructor<?> ) { type = ( (Constructor<?>) element ).getDeclaringClass(); } else { rulesBinder.addError( "", element ); return; } ObjectCreateBuilder builder = rulesBinder .forPattern( annotation.pattern() ) .withNamespaceURI( annotation.namespaceURI() ) .createObject() .ofType( type ) .ofTypeSpecifiedByAttribute( annotation.attributeName() != null ? annotation.attributeName() : null ); if ( element instanceof Constructor<?> ) { Constructor<?> method = (Constructor<?>) element; builder.usingConstructor( method.getParameterTypes() ); } }
public void handle( ObjectCreate annotation, AnnotatedElement element, RulesBinder rulesBinder ) { Class<?> type = null; if ( element instanceof Class<?> ) { type = (Class<?>) element; } else if ( element instanceof Constructor<?> ) { type = ( (Constructor<?>) element ).getDeclaringClass(); } else { rulesBinder.addError( "Misplaced @ObjectCreate annotation to %s, Class and Constructor only supported", element ); return; } ObjectCreateBuilder builder = rulesBinder .forPattern( annotation.pattern() ) .withNamespaceURI( annotation.namespaceURI() ) .createObject() .ofType( type ) .ofTypeSpecifiedByAttribute( annotation.attributeName() != null ? annotation.attributeName() : null ); if ( element instanceof Constructor<?> ) { Constructor<?> method = (Constructor<?>) element; builder.usingConstructor( method.getParameterTypes() ); } }
diff --git a/contrib/alpha/PipesTest.java b/contrib/alpha/PipesTest.java index d01d3af..2e46794 100644 --- a/contrib/alpha/PipesTest.java +++ b/contrib/alpha/PipesTest.java @@ -1,448 +1,451 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.util.List; import java.util.regex.Pattern; import org.junit.Test; import uk.co.uwcs.choob.modules.Modules; import uk.co.uwcs.choob.support.ChoobNoSuchCallException; import uk.co.uwcs.choob.support.IRCInterface; import uk.co.uwcs.choob.support.events.Message; class Pipes { final Modules mods; private final IRCInterface irc; public Pipes(final Modules mods, final IRCInterface irc) { this.mods = mods; this.irc = irc; } static String firstToken(String s) { final int ind = s.indexOf(' '); if (ind == -1) return s; return s.substring(0, ind); } public void commandEval(final Message mes) throws Exception { String eval = eval(mods.util.getParamString(mes), new LoopbackExeculator(mes)); List<String> messes = irc.cutString(eval, mes.getNick().length() + 2 + 25); irc.sendContextReply(mes, messes.get(0) + (messes.size() > 1 ? " (" + (messes.size() - 1) + " more message" + (messes.size() == 2 ? "" : "s") + ")" : "")); } private final class LoopbackExeculator implements Execulator { // XXX mes can be NULL. D: private final Message mes; private final String nick; private final String target; LoopbackExeculator(final Message mes) { this(mes, mes.getNick(), mes.getTarget()); } LoopbackExeculator(final String nick, final String target) { this(null, nick, target); } public LoopbackExeculator(final Message mes, final String nick, final String target) { this.mes = mes; this.nick = nick; this.target = target; } @Override public String exec(String s, String stdin) throws Exception { final String[] qq = s.trim().split(" ", 2); String cmd = qq[0].trim(); String arg = qq.length > 1 ? qq[1] : ""; if ("sed".equals(cmd)) return (String)mods.plugin.callAPI("MiscUtils", "Sed", arg, stdin); if ("tr".equals(cmd)) return (String)mods.plugin.callAPI("MiscUtils", "Trans", arg, stdin); if ("pick".equals(cmd)) { // If something's been provided on stdin, we'll use it instead of the history. // This allows piping into commands that are rooted in !pick. if (!"".equals(stdin)) return stdin; // Let's just pray this won't be reached with a null mes! \o/ final List<Message> history = mods.history.getLastMessages(mes, 20); final Pattern picker = (Pattern)mods.plugin.callAPI("MiscUtils", "LinePicker", arg); for (Message m : history) if (picker.matcher(m.getMessage()).find()) return m.getMessage(); throw new IllegalArgumentException("Couldn't pick anything with " + arg); } if ("nick".equals(cmd)) return nick; if ("export".equals(cmd)) // mes return (String)mods.plugin.callAPI("Alias", "CreateAlias", mes, nick, target, "fakelias "+ arg); if ("xargs".equals(cmd)) { final String[] rr = arg.split(" ", 2); cmd = rr[0]; arg = (rr.length > 1 ? rr[1] : "") + stdin; } try { final String alcmd = cmd + " " + arg; Object res = mods.plugin.callAPI("alias", "get", cmd); if (null != res) { - cmd = (String) mods.plugin.callAPI("alias", "applyalias", res, alcmd.split(" "), arg, nick, target); + cmd = (String) mods.plugin.callAPI("alias", "applyalias", res, alcmd.split(" "), arg, + nick == null ? "" : nick, + target == null ? "" : target); arg = ""; } } catch (ChoobNoSuchCallException e) { + e.printStackTrace(); // Whatever, no alias support. } String[] alis = cmd.split(" ", 2); String[] cmds = alis[0].split("\\.", 2); if (cmds.length != 2) throw new IllegalArgumentException("Tried to exec '" + alis[0] + "', which doesn't even have a dot in it!"); // Fiddle talk.say -> talk.reply, which is pipable and does the same thing (well, close enough) if ("talk".equalsIgnoreCase(cmds[0]) && "say".equalsIgnoreCase(cmds[1])) cmds[1] = "reply"; if (alis.length > 1 && alis[1].length() > 0) arg = alis[1] + arg; if ("pipes".equalsIgnoreCase(cmds[0]) && "eval".equalsIgnoreCase(cmds[1])) if ("".equals(stdin)) return eval(arg, this); else return eval(stdin, this); return (String) mods.plugin.callGeneric(cmds[0], "command", cmds[1], arg); } } static class ParseException extends Exception { private final StringIterator pos; /** * @param pos Location the error occoured. */ public ParseException(String string, StringIterator pos) { super(string); this.pos = pos; } @Override public String toString() { return super.toString() + " before " + pos + "$$"; } } /** Keep track of the position of ourselves in a String. */ static class StringIterator { private int i; final private char[] c; StringIterator (String s) { c = s.toCharArray(); } char get() throws ParseException { if (i < c.length) return c[i++]; throw new ParseException("Unexpected end", this); } char peek() throws ParseException { if (i < c.length) return c[i]; throw new ParseException("Peek past end", this); } boolean hasMore() { return i < c.length; } @Override public String toString() { return new String(c, i, c.length - i); } public int length() { return c.length - i; } } /** @param si Positioned just after the ( in a valid $(; will terminate just after the ). * @throws Exception iff comes from Execulator. */ private static String eval(final StringIterator si, Execulator e, String stdin) throws Exception { StringBuilder sb = new StringBuilder(si.length()); boolean dquote = false, squote = false, bslash = false; while (si.hasMore()) { final char c = si.get(); if (!squote && !dquote && !bslash && '$' == c && '(' == si.peek()) { si.get(); sb.append(eval(si, e, "")); } else if (!squote && !dquote && !bslash && ')' == c) { if (bslash || dquote || squote) throw new ParseException("Unexpected end of expression", si); return e.exec(sb.toString(), stdin); } else if ('"' == c) if (squote || bslash) { sb.append(c); bslash = false; } else dquote = !dquote; else if ('\'' == c) if (bslash) { if (dquote) sb.append("\\"); sb.append(c); bslash = false; } else if (dquote) sb.append(c); else squote = !squote; else if ('\\' == c) if (bslash) { sb.append(c); bslash = false; } else if (squote) sb.append(c); else bslash = true; else if ('|' == c) { if (!squote && !dquote && !bslash) { stdin = e.exec(sb.toString(), stdin); sb.setLength(0); } else sb.append(c); } else { if (bslash) if (dquote) bslash = false; else throw new ParseException("illegal escape sequence: " + c, si); sb.append(c); } } throw new ParseException("Expected )", si); } static String eval(String s, Execulator e) throws Exception { return eval(s, e, ""); } static String eval(String s, Execulator e, String stdin) throws Exception { final StringIterator si = new StringIterator(s + ")"); final String res = eval(si, e, stdin); // XXX #testEnd if (si.hasMore() && (si.get() != ')' || si.hasMore())) throw new ParseException("Trailing characters", si); return res; } static String eval(String s) throws Exception { return eval(s, SysoExeculator); } public String apiEval(String s, String nick, String context, String stdin) throws Exception { return eval(s, new LoopbackExeculator(nick, context), stdin); } static interface Execulator { String exec(String s, String stdin) throws Exception; } private final static Execulator SysoExeculator = new Execulator() { @Override public String exec(String s, String stdin) { System.out.println(s + " with stdin of: " + stdin); return s; } }; } public class PipesTest { @Test public void testExeculator() throws Exception { assertEquals("NOOOMaNOOOM789MOOONbMOOON", Pipes.eval("a$(789)b", new Pipes.Execulator() { @Override public String exec(String s, String stdin) { return "NOOOM" + s + stdin + "MOOON"; } })); } @Test public void testTrivialDollars() throws Exception { assertEquals("6", Pipes.eval("$(6)")); assertEquals("56", Pipes.eval("5$(6)")); assertEquals("67", Pipes.eval("$(6)7")); assertEquals("567", Pipes.eval("5$(6)7")); } @Test(expected = Pipes.ParseException.class) public void testStart() throws Exception { Pipes.eval("$("); } // Fails, XXX above. @Test(expected = Pipes.ParseException.class) public void testEnd() throws Exception { Pipes.eval(")"); } private static final String DQUOTED = "\"pony\""; @Test public void testEvalQuotes() throws Exception { assertEquals("pony", Pipes.eval(DQUOTED)); assertEquals("pony pony", Pipes.eval(DQUOTED + " " + DQUOTED)); assertEquals("\"pony\"", Pipes.eval("'" + DQUOTED + "'")); assertEquals("\"pony\" \"pony\"", Pipes.eval("'" + DQUOTED + "' '" + DQUOTED + "'")); assertEquals("pony", Pipes.eval("'pony'")); assertEquals("pony pony", Pipes.eval("'pony' 'pony'")); assertEquals("pony \"pony", Pipes.eval("'pony \"pony'")); assertEquals("pony \"\"pony", Pipes.eval("'pony \"\"pony'")); } @Test public void testEvalQuotesSlash() throws Exception { assertEquals("po\\\"ny", Pipes.eval("'po\\\"ny'")); assertEquals("po\"ny", Pipes.eval("\"po\\\"ny\"")); assertEquals("'", Pipes.eval("\\'")); assertEquals("pony'pony", Pipes.eval("'pony'\\''pony'")); assertEquals("pony\\pony", Pipes.eval("\"pony\\\\pony\"")); } @Test public void testEscapes() throws Exception { assertEquals("$hi", Pipes.eval("\"\\$hi\"")); } @Test public void testEvalEnd() throws Exception { assertThrowsParse("'"); assertThrowsParse("\""); assertThrowsParse("\\"); assertThrowsParse("\\q"); } @Test public void testPipeQuotes() throws Exception { assertEquals("a|b", Pipes.eval("'a|b'")); } @Test public void testDoubleSingle() throws Exception { assertEquals("'", Pipes.eval("\"'\"")); assertEquals("'pony'", Pipes.eval("\"'pony'\"")); } @Test public void testBackSlashes() throws Exception { assertEquals("\\\'", Pipes.eval("\"\\\'\"")); assertEquals("\\", Pipes.eval("\"\\\\\"")); } @Test public void testEvalDollars() throws Exception { assertEquals("pony", Pipes.eval("$('pony')")); assertEquals("ls() qq", Pipes.eval("$('ls()' 'qq')")); assertEquals("ls() qq", Pipes.eval("$('ls()' qq)")); assertEquals("ls$() qq", Pipes.eval("$('ls$()' 'qq')")); assertEquals("ls$() qq", Pipes.eval("$('ls$()' qq)")); assertEquals("57", Pipes.eval("$(5)7")); } private static void assertThrowsParse(String string) throws Exception { try { Pipes.eval(string); fail("Didn't throw"); } catch (Pipes.ParseException e) { // expected } } }
false
true
public String exec(String s, String stdin) throws Exception { final String[] qq = s.trim().split(" ", 2); String cmd = qq[0].trim(); String arg = qq.length > 1 ? qq[1] : ""; if ("sed".equals(cmd)) return (String)mods.plugin.callAPI("MiscUtils", "Sed", arg, stdin); if ("tr".equals(cmd)) return (String)mods.plugin.callAPI("MiscUtils", "Trans", arg, stdin); if ("pick".equals(cmd)) { // If something's been provided on stdin, we'll use it instead of the history. // This allows piping into commands that are rooted in !pick. if (!"".equals(stdin)) return stdin; // Let's just pray this won't be reached with a null mes! \o/ final List<Message> history = mods.history.getLastMessages(mes, 20); final Pattern picker = (Pattern)mods.plugin.callAPI("MiscUtils", "LinePicker", arg); for (Message m : history) if (picker.matcher(m.getMessage()).find()) return m.getMessage(); throw new IllegalArgumentException("Couldn't pick anything with " + arg); } if ("nick".equals(cmd)) return nick; if ("export".equals(cmd)) // mes return (String)mods.plugin.callAPI("Alias", "CreateAlias", mes, nick, target, "fakelias "+ arg); if ("xargs".equals(cmd)) { final String[] rr = arg.split(" ", 2); cmd = rr[0]; arg = (rr.length > 1 ? rr[1] : "") + stdin; } try { final String alcmd = cmd + " " + arg; Object res = mods.plugin.callAPI("alias", "get", cmd); if (null != res) { cmd = (String) mods.plugin.callAPI("alias", "applyalias", res, alcmd.split(" "), arg, nick, target); arg = ""; } } catch (ChoobNoSuchCallException e) { // Whatever, no alias support. } String[] alis = cmd.split(" ", 2); String[] cmds = alis[0].split("\\.", 2); if (cmds.length != 2) throw new IllegalArgumentException("Tried to exec '" + alis[0] + "', which doesn't even have a dot in it!"); // Fiddle talk.say -> talk.reply, which is pipable and does the same thing (well, close enough) if ("talk".equalsIgnoreCase(cmds[0]) && "say".equalsIgnoreCase(cmds[1])) cmds[1] = "reply"; if (alis.length > 1 && alis[1].length() > 0) arg = alis[1] + arg; if ("pipes".equalsIgnoreCase(cmds[0]) && "eval".equalsIgnoreCase(cmds[1])) if ("".equals(stdin)) return eval(arg, this); else return eval(stdin, this); return (String) mods.plugin.callGeneric(cmds[0], "command", cmds[1], arg); }
public String exec(String s, String stdin) throws Exception { final String[] qq = s.trim().split(" ", 2); String cmd = qq[0].trim(); String arg = qq.length > 1 ? qq[1] : ""; if ("sed".equals(cmd)) return (String)mods.plugin.callAPI("MiscUtils", "Sed", arg, stdin); if ("tr".equals(cmd)) return (String)mods.plugin.callAPI("MiscUtils", "Trans", arg, stdin); if ("pick".equals(cmd)) { // If something's been provided on stdin, we'll use it instead of the history. // This allows piping into commands that are rooted in !pick. if (!"".equals(stdin)) return stdin; // Let's just pray this won't be reached with a null mes! \o/ final List<Message> history = mods.history.getLastMessages(mes, 20); final Pattern picker = (Pattern)mods.plugin.callAPI("MiscUtils", "LinePicker", arg); for (Message m : history) if (picker.matcher(m.getMessage()).find()) return m.getMessage(); throw new IllegalArgumentException("Couldn't pick anything with " + arg); } if ("nick".equals(cmd)) return nick; if ("export".equals(cmd)) // mes return (String)mods.plugin.callAPI("Alias", "CreateAlias", mes, nick, target, "fakelias "+ arg); if ("xargs".equals(cmd)) { final String[] rr = arg.split(" ", 2); cmd = rr[0]; arg = (rr.length > 1 ? rr[1] : "") + stdin; } try { final String alcmd = cmd + " " + arg; Object res = mods.plugin.callAPI("alias", "get", cmd); if (null != res) { cmd = (String) mods.plugin.callAPI("alias", "applyalias", res, alcmd.split(" "), arg, nick == null ? "" : nick, target == null ? "" : target); arg = ""; } } catch (ChoobNoSuchCallException e) { e.printStackTrace(); // Whatever, no alias support. } String[] alis = cmd.split(" ", 2); String[] cmds = alis[0].split("\\.", 2); if (cmds.length != 2) throw new IllegalArgumentException("Tried to exec '" + alis[0] + "', which doesn't even have a dot in it!"); // Fiddle talk.say -> talk.reply, which is pipable and does the same thing (well, close enough) if ("talk".equalsIgnoreCase(cmds[0]) && "say".equalsIgnoreCase(cmds[1])) cmds[1] = "reply"; if (alis.length > 1 && alis[1].length() > 0) arg = alis[1] + arg; if ("pipes".equalsIgnoreCase(cmds[0]) && "eval".equalsIgnoreCase(cmds[1])) if ("".equals(stdin)) return eval(arg, this); else return eval(stdin, this); return (String) mods.plugin.callGeneric(cmds[0], "command", cmds[1], arg); }
diff --git a/dspace/src/org/dspace/content/WorkspaceItem.java b/dspace/src/org/dspace/content/WorkspaceItem.java index ce353af26..3a005898d 100644 --- a/dspace/src/org/dspace/content/WorkspaceItem.java +++ b/dspace/src/org/dspace/content/WorkspaceItem.java @@ -1,600 +1,600 @@ /* * WorkspaceItem.java * * Version: $Revision$ * * Date: $Date$ * * Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts * Institute of Technology. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the Hewlett-Packard Company nor the name of the * Massachusetts Institute of Technology nor the names of their * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.dspace.content; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.eperson.EPerson; import org.dspace.eperson.Group; import org.dspace.history.HistoryManager; import org.dspace.storage.rdbms.DatabaseManager; import org.dspace.storage.rdbms.TableRow; import org.dspace.storage.rdbms.TableRowIterator; /** * Class representing an item in the process of being submitted by a user * * @author Robert Tansley * @version $Revision$ */ public class WorkspaceItem implements InProgressSubmission { /** log4j logger */ private static Logger log = Logger.getLogger(WorkspaceItem.class); /** The item this workspace object pertains to */ private Item item; /** Our context */ private Context ourContext; /** The table row corresponding to this workspace item */ private TableRow wiRow; /** The collection the item is being submitted to */ private Collection collection; /** * Construct a workspace item corresponding to the given database row * * @param context * the context this object exists in * @param row * the database row */ WorkspaceItem(Context context, TableRow row) throws SQLException { ourContext = context; wiRow = row; item = Item.find(context, wiRow.getIntColumn("item_id")); collection = Collection.find(context, wiRow .getIntColumn("collection_id")); // Cache ourselves context.cache(this, row.getIntColumn("workspace_item_id")); } /** * Get a workspace item from the database. The item, collection and * submitter are loaded into memory. * * @param context * DSpace context object * @param id * ID of the workspace item * * @return the workspace item, or null if the ID is invalid. */ public static WorkspaceItem find(Context context, int id) throws SQLException { // First check the cache WorkspaceItem fromCache = (WorkspaceItem) context.fromCache( WorkspaceItem.class, id); if (fromCache != null) { return fromCache; } TableRow row = DatabaseManager.find(context, "workspaceitem", id); if (row == null) { if (log.isDebugEnabled()) { log.debug(LogManager.getHeader(context, "find_workspace_item", "not_found,workspace_item_id=" + id)); } return null; } else { if (log.isDebugEnabled()) { log.debug(LogManager.getHeader(context, "find_workspace_item", "workspace_item_id=" + id)); } return new WorkspaceItem(context, row); } } /** * Create a new workspace item, with a new ID. An Item is also created. The * submitter is the current user in the context. * * @param c * DSpace context object * @param coll * Collection being submitted to * @param template * if <code>true</code>, the workspace item starts as a copy * of the collection's template item * * @return the newly created workspace item */ public static WorkspaceItem create(Context c, Collection coll, boolean template) throws AuthorizeException, SQLException, IOException { // Check the user has permission to ADD to the collection AuthorizeManager.authorizeAction(c, coll, Constants.ADD); // Create an item Item i = Item.create(c); i.setSubmitter(c.getCurrentUser()); // Now create the policies for the submitter and workflow // users to modify item and contents // contents = bitstreams, bundles // FIXME: icky hardcoded workflow steps Group step1group = coll.getWorkflowGroup(1); Group step2group = coll.getWorkflowGroup(2); Group step3group = coll.getWorkflowGroup(3); EPerson e = c.getCurrentUser(); // read permission AuthorizeManager.addPolicy(c, i, Constants.READ, e); if (step1group != null) { AuthorizeManager.addPolicy(c, i, Constants.READ, step1group); } if (step2group != null) { AuthorizeManager.addPolicy(c, i, Constants.READ, step2group); } if (step3group != null) { AuthorizeManager.addPolicy(c, i, Constants.READ, step3group); } // write permission AuthorizeManager.addPolicy(c, i, Constants.WRITE, e); if (step1group != null) { AuthorizeManager.addPolicy(c, i, Constants.WRITE, step1group); } if (step2group != null) { AuthorizeManager.addPolicy(c, i, Constants.WRITE, step2group); } if (step3group != null) { AuthorizeManager.addPolicy(c, i, Constants.WRITE, step3group); } // add permission AuthorizeManager.addPolicy(c, i, Constants.ADD, e); if (step1group != null) { AuthorizeManager.addPolicy(c, i, Constants.ADD, step1group); } if (step2group != null) { AuthorizeManager.addPolicy(c, i, Constants.ADD, step2group); } if (step3group != null) { AuthorizeManager.addPolicy(c, i, Constants.ADD, step3group); } // remove contents permission AuthorizeManager.addPolicy(c, i, Constants.REMOVE, e); if (step1group != null) { AuthorizeManager.addPolicy(c, i, Constants.REMOVE, step1group); } if (step2group != null) { AuthorizeManager.addPolicy(c, i, Constants.REMOVE, step2group); } if (step3group != null) { AuthorizeManager.addPolicy(c, i, Constants.REMOVE, step3group); } // Copy template if appropriate Item templateItem = coll.getTemplateItem(); if (template && (templateItem != null)) { - DCValue[] dc = templateItem.getDC(Item.ANY, Item.ANY, Item.ANY); + DCValue[] md = templateItem.getMetadata(Item.ANY, Item.ANY, Item.ANY, Item.ANY); - for (int n = 0; n < dc.length; n++) + for (int n = 0; n < md.length; n++) { - i.addDC(dc[n].element, dc[n].qualifier, dc[n].language, - dc[n].value); + i.addMetadata(md[n].schema, md[n].element, md[n].qualifier, md[n].language, + md[n].value); } } i.update(); // Create the workspace item row TableRow row = DatabaseManager.create(c, "workspaceitem"); row.setColumn("item_id", i.getID()); row.setColumn("collection_id", coll.getID()); log.info(LogManager.getHeader(c, "create_workspace_item", "workspace_item_id=" + row.getIntColumn("workspace_item_id") + "item_id=" + i.getID() + "collection_id=" + coll.getID())); DatabaseManager.update(c, row); WorkspaceItem wi = new WorkspaceItem(c, row); HistoryManager.saveHistory(c, wi, HistoryManager.CREATE, c .getCurrentUser(), c.getExtraLogInfo()); return wi; } /** * Get all workspace items for a particular e-person. These are ordered by * workspace item ID, since this should likely keep them in the order in * which they were created. * * @param context * the context object * @param ep * the eperson * * @return the corresponding workspace items */ public static WorkspaceItem[] findByEPerson(Context context, EPerson ep) throws SQLException { List wsItems = new ArrayList(); TableRowIterator tri = DatabaseManager.queryTable(context, "workspaceitem", "SELECT workspaceitem.* FROM workspaceitem, item WHERE " + "workspaceitem.item_id=item.item_id AND " + "item.submitter_id= ? " + "ORDER BY workspaceitem.workspace_item_id", ep.getID()); while (tri.hasNext()) { TableRow row = tri.next(); // Check the cache WorkspaceItem wi = (WorkspaceItem) context.fromCache( WorkspaceItem.class, row.getIntColumn("workspace_item_id")); if (wi == null) { wi = new WorkspaceItem(context, row); } wsItems.add(wi); } // close the TableRowIterator to free up resources tri.close(); WorkspaceItem[] wsArray = new WorkspaceItem[wsItems.size()]; wsArray = (WorkspaceItem[]) wsItems.toArray(wsArray); return wsArray; } /** * Get all workspace items for a particular collection. * * @param context * the context object * @param c * the collection * * @return the corresponding workspace items */ public static WorkspaceItem[] findByCollection(Context context, Collection c) throws SQLException { List wsItems = new ArrayList(); TableRowIterator tri = DatabaseManager.queryTable(context, "workspaceitem", "SELECT workspaceitem.* FROM workspaceitem WHERE " + "workspaceitem.collection_id= ? ", c.getID()); while (tri.hasNext()) { TableRow row = tri.next(); // Check the cache WorkspaceItem wi = (WorkspaceItem) context.fromCache( WorkspaceItem.class, row.getIntColumn("workspace_item_id")); // not in cache? turn row into workspaceitem if (wi == null) { wi = new WorkspaceItem(context, row); } wsItems.add(wi); } // close the TableRowIterator to free up resources tri.close(); WorkspaceItem[] wsArray = new WorkspaceItem[wsItems.size()]; wsArray = (WorkspaceItem[]) wsItems.toArray(wsArray); return wsArray; } /** * Get all workspace items in the whole system * * @param context the context object * * @return all workspace items */ public static WorkspaceItem[] findAll(Context context) throws SQLException { List wsItems = new ArrayList(); String query = "SELECT * FROM workspaceitem ORDER BY item_id"; TableRowIterator tri = DatabaseManager.queryTable(context, "workspaceitem", query); while (tri.hasNext()) { TableRow row = tri.next(); // Check the cache WorkspaceItem wi = (WorkspaceItem) context.fromCache( WorkspaceItem.class, row.getIntColumn("workspace_item_id")); // not in cache? turn row into workspaceitem if (wi == null) { wi = new WorkspaceItem(context, row); } wsItems.add(wi); } tri.close(); WorkspaceItem[] wsArray = new WorkspaceItem[wsItems.size()]; wsArray = (WorkspaceItem[]) wsItems.toArray(wsArray); return wsArray; } /** * Get the internal ID of this workspace item * * @return the internal identifier */ public int getID() { return wiRow.getIntColumn("workspace_item_id"); } /** * Get the value of the stage reached column * * @return the value of the stage reached column */ public int getStageReached() { return wiRow.getIntColumn("stage_reached"); } /** * Set the value of the stage reached column * * @param v * the value of the stage reached column */ public void setStageReached(int v) { wiRow.setColumn("stage_reached", v); } /** * Update the workspace item, including the unarchived item. */ public void update() throws SQLException, AuthorizeException, IOException { // Authorisation is checked by the item.update() method below HistoryManager.saveHistory(ourContext, this, HistoryManager.MODIFY, ourContext.getCurrentUser(), ourContext.getExtraLogInfo()); log.info(LogManager.getHeader(ourContext, "update_workspace_item", "workspace_item_id=" + getID())); // Update the item item.update(); // Update ourselves DatabaseManager.update(ourContext, wiRow); } /** * Delete the workspace item. The entry in workspaceitem, the unarchived * item and its contents are all removed (multiple inclusion * notwithstanding.) */ public void deleteAll() throws SQLException, AuthorizeException, IOException { /* * Authorisation is a special case. The submitter won't have REMOVE * permission on the collection, so our policy is this: Only the * original submitter or an administrator can delete a workspace item. */ if (!AuthorizeManager.isAdmin(ourContext) && ((ourContext.getCurrentUser() == null) || (ourContext .getCurrentUser().getID() != item.getSubmitter() .getID()))) { // Not an admit, not the submitter throw new AuthorizeException("Must be an administrator or the " + "original submitter to delete a workspace item"); } HistoryManager.saveHistory(ourContext, this, HistoryManager.REMOVE, ourContext.getCurrentUser(), ourContext.getExtraLogInfo()); log.info(LogManager.getHeader(ourContext, "delete_workspace_item", "workspace_item_id=" + getID() + "item_id=" + item.getID() + "collection_id=" + collection.getID())); //deleteSubmitPermissions(); // Remove from cache ourContext.removeCached(this, getID()); // Need to delete the epersongroup2workspaceitem row first since it refers // to workspaceitem ID deleteEpersonGroup2WorkspaceItem(); // Need to delete the workspaceitem row first since it refers // to item ID DatabaseManager.delete(ourContext, wiRow); // Delete item item.delete(); } private void deleteEpersonGroup2WorkspaceItem() throws SQLException { String removeSQL="DELETE FROM epersongroup2workspaceitem WHERE workspace_item_id = ?"; DatabaseManager.updateQuery(ourContext, removeSQL,getID()); } public void deleteWrapper() throws SQLException, AuthorizeException, IOException { // Check authorisation. We check permissions on the enclosed item. AuthorizeManager.authorizeAction(ourContext, item, Constants.WRITE); HistoryManager.saveHistory(ourContext, this, HistoryManager.REMOVE, ourContext.getCurrentUser(), ourContext.getExtraLogInfo()); log.info(LogManager.getHeader(ourContext, "delete_workspace_item", "workspace_item_id=" + getID() + "item_id=" + item.getID() + "collection_id=" + collection.getID())); // deleteSubmitPermissions(); // Remove from cache ourContext.removeCached(this, getID()); // Need to delete the workspaceitem row first since it refers // to item ID DatabaseManager.delete(ourContext, wiRow); } // InProgressSubmission methods public Item getItem() { return item; } public Collection getCollection() { return collection; } public EPerson getSubmitter() throws SQLException { return item.getSubmitter(); } public boolean hasMultipleFiles() { return wiRow.getBooleanColumn("multiple_files"); } public void setMultipleFiles(boolean b) { wiRow.setColumn("multiple_files", b); } public boolean hasMultipleTitles() { return wiRow.getBooleanColumn("multiple_titles"); } public void setMultipleTitles(boolean b) { wiRow.setColumn("multiple_titles", b); } public boolean isPublishedBefore() { return wiRow.getBooleanColumn("published_before"); } public void setPublishedBefore(boolean b) { wiRow.setColumn("published_before", b); } }
false
true
public static WorkspaceItem create(Context c, Collection coll, boolean template) throws AuthorizeException, SQLException, IOException { // Check the user has permission to ADD to the collection AuthorizeManager.authorizeAction(c, coll, Constants.ADD); // Create an item Item i = Item.create(c); i.setSubmitter(c.getCurrentUser()); // Now create the policies for the submitter and workflow // users to modify item and contents // contents = bitstreams, bundles // FIXME: icky hardcoded workflow steps Group step1group = coll.getWorkflowGroup(1); Group step2group = coll.getWorkflowGroup(2); Group step3group = coll.getWorkflowGroup(3); EPerson e = c.getCurrentUser(); // read permission AuthorizeManager.addPolicy(c, i, Constants.READ, e); if (step1group != null) { AuthorizeManager.addPolicy(c, i, Constants.READ, step1group); } if (step2group != null) { AuthorizeManager.addPolicy(c, i, Constants.READ, step2group); } if (step3group != null) { AuthorizeManager.addPolicy(c, i, Constants.READ, step3group); } // write permission AuthorizeManager.addPolicy(c, i, Constants.WRITE, e); if (step1group != null) { AuthorizeManager.addPolicy(c, i, Constants.WRITE, step1group); } if (step2group != null) { AuthorizeManager.addPolicy(c, i, Constants.WRITE, step2group); } if (step3group != null) { AuthorizeManager.addPolicy(c, i, Constants.WRITE, step3group); } // add permission AuthorizeManager.addPolicy(c, i, Constants.ADD, e); if (step1group != null) { AuthorizeManager.addPolicy(c, i, Constants.ADD, step1group); } if (step2group != null) { AuthorizeManager.addPolicy(c, i, Constants.ADD, step2group); } if (step3group != null) { AuthorizeManager.addPolicy(c, i, Constants.ADD, step3group); } // remove contents permission AuthorizeManager.addPolicy(c, i, Constants.REMOVE, e); if (step1group != null) { AuthorizeManager.addPolicy(c, i, Constants.REMOVE, step1group); } if (step2group != null) { AuthorizeManager.addPolicy(c, i, Constants.REMOVE, step2group); } if (step3group != null) { AuthorizeManager.addPolicy(c, i, Constants.REMOVE, step3group); } // Copy template if appropriate Item templateItem = coll.getTemplateItem(); if (template && (templateItem != null)) { DCValue[] dc = templateItem.getDC(Item.ANY, Item.ANY, Item.ANY); for (int n = 0; n < dc.length; n++) { i.addDC(dc[n].element, dc[n].qualifier, dc[n].language, dc[n].value); } } i.update(); // Create the workspace item row TableRow row = DatabaseManager.create(c, "workspaceitem"); row.setColumn("item_id", i.getID()); row.setColumn("collection_id", coll.getID()); log.info(LogManager.getHeader(c, "create_workspace_item", "workspace_item_id=" + row.getIntColumn("workspace_item_id") + "item_id=" + i.getID() + "collection_id=" + coll.getID())); DatabaseManager.update(c, row); WorkspaceItem wi = new WorkspaceItem(c, row); HistoryManager.saveHistory(c, wi, HistoryManager.CREATE, c .getCurrentUser(), c.getExtraLogInfo()); return wi; }
public static WorkspaceItem create(Context c, Collection coll, boolean template) throws AuthorizeException, SQLException, IOException { // Check the user has permission to ADD to the collection AuthorizeManager.authorizeAction(c, coll, Constants.ADD); // Create an item Item i = Item.create(c); i.setSubmitter(c.getCurrentUser()); // Now create the policies for the submitter and workflow // users to modify item and contents // contents = bitstreams, bundles // FIXME: icky hardcoded workflow steps Group step1group = coll.getWorkflowGroup(1); Group step2group = coll.getWorkflowGroup(2); Group step3group = coll.getWorkflowGroup(3); EPerson e = c.getCurrentUser(); // read permission AuthorizeManager.addPolicy(c, i, Constants.READ, e); if (step1group != null) { AuthorizeManager.addPolicy(c, i, Constants.READ, step1group); } if (step2group != null) { AuthorizeManager.addPolicy(c, i, Constants.READ, step2group); } if (step3group != null) { AuthorizeManager.addPolicy(c, i, Constants.READ, step3group); } // write permission AuthorizeManager.addPolicy(c, i, Constants.WRITE, e); if (step1group != null) { AuthorizeManager.addPolicy(c, i, Constants.WRITE, step1group); } if (step2group != null) { AuthorizeManager.addPolicy(c, i, Constants.WRITE, step2group); } if (step3group != null) { AuthorizeManager.addPolicy(c, i, Constants.WRITE, step3group); } // add permission AuthorizeManager.addPolicy(c, i, Constants.ADD, e); if (step1group != null) { AuthorizeManager.addPolicy(c, i, Constants.ADD, step1group); } if (step2group != null) { AuthorizeManager.addPolicy(c, i, Constants.ADD, step2group); } if (step3group != null) { AuthorizeManager.addPolicy(c, i, Constants.ADD, step3group); } // remove contents permission AuthorizeManager.addPolicy(c, i, Constants.REMOVE, e); if (step1group != null) { AuthorizeManager.addPolicy(c, i, Constants.REMOVE, step1group); } if (step2group != null) { AuthorizeManager.addPolicy(c, i, Constants.REMOVE, step2group); } if (step3group != null) { AuthorizeManager.addPolicy(c, i, Constants.REMOVE, step3group); } // Copy template if appropriate Item templateItem = coll.getTemplateItem(); if (template && (templateItem != null)) { DCValue[] md = templateItem.getMetadata(Item.ANY, Item.ANY, Item.ANY, Item.ANY); for (int n = 0; n < md.length; n++) { i.addMetadata(md[n].schema, md[n].element, md[n].qualifier, md[n].language, md[n].value); } } i.update(); // Create the workspace item row TableRow row = DatabaseManager.create(c, "workspaceitem"); row.setColumn("item_id", i.getID()); row.setColumn("collection_id", coll.getID()); log.info(LogManager.getHeader(c, "create_workspace_item", "workspace_item_id=" + row.getIntColumn("workspace_item_id") + "item_id=" + i.getID() + "collection_id=" + coll.getID())); DatabaseManager.update(c, row); WorkspaceItem wi = new WorkspaceItem(c, row); HistoryManager.saveHistory(c, wi, HistoryManager.CREATE, c .getCurrentUser(), c.getExtraLogInfo()); return wi; }
diff --git a/src/org/apache/fop/fo/flow/TableCell.java b/src/org/apache/fop/fo/flow/TableCell.java index 23643552c..eeaa99cf6 100644 --- a/src/org/apache/fop/fo/flow/TableCell.java +++ b/src/org/apache/fop/fo/flow/TableCell.java @@ -1,426 +1,432 @@ /* * -- $Id$ -- * Copyright (C) 2001 The Apache Software Foundation. All rights reserved. * For details on use and redistribution please refer to the * LICENSE file included with these sources. */ package org.apache.fop.fo.flow; // FOP import org.apache.fop.fo.*; import org.apache.fop.fo.properties.*; import org.apache.fop.layout.*; import org.apache.fop.apps.FOPException; import org.apache.fop.datatypes.*; public class TableCell extends FObj { public static class Maker extends FObj.Maker { public FObj make(FObj parent, PropertyList propertyList) throws FOPException { return new TableCell(parent, propertyList); } } public static FObj.Maker maker() { return new TableCell.Maker(); } // int spaceBefore; // int spaceAfter; ColorType backgroundColor; String id; int numColumnsSpanned; int numRowsSpanned; int iColNumber = -1; // uninitialized /** * Offset of content rectangle in inline-progression-direction, * relative to table. */ protected int startOffset; /** * Dimension of allocation rectangle in inline-progression-direction, * determined by the width of the column(s) occupied by the cell */ protected int width; /** * Offset of content rectangle, in block-progression-direction, * relative to the row. */ protected int beforeOffset = 0; /** * Offset of content rectangle, in inline-progression-direction, * relative to the column start edge. */ protected int startAdjust = 0; /** * Adjust to theoretical column width to obtain content width * relative to the column start edge. */ protected int widthAdjust = 0; /* For collapsed border style */ protected int borderHeight = 0; /** * Minimum ontent height of cell. */ protected int minCellHeight = 0; protected int height = 0; protected int top; // Ypos of cell ??? protected int verticalAlign; protected boolean bRelativeAlign = false; // boolean setup = false; boolean bSepBorders = true; /** * Border separation value in the block-progression dimension. * Used in calculating cells height. */ int m_borderSeparation = 0; AreaContainer cellArea; public TableCell(FObj parent, PropertyList propertyList) { super(parent, propertyList); this.name = "fo:table-cell"; doSetup(); // init some basic property values } // Set position relative to table (set by body?) public void setStartOffset(int offset) { startOffset = offset; } // Initially same as the column width containg this cell or the // sum of the spanned columns if numColumnsSpanned > 1 public void setWidth(int width) { this.width = width; } public int getColumnNumber() { return iColNumber; } public int getNumColumnsSpanned() { return numColumnsSpanned; } public int getNumRowsSpanned() { return numRowsSpanned; } public void doSetup() // throws FOPException { this.iColNumber = properties.get("column-number").getNumber().intValue(); if (iColNumber < 0) { iColNumber = 0; } this.numColumnsSpanned = this.properties.get("number-columns-spanned").getNumber().intValue(); if (numColumnsSpanned < 1) { numColumnsSpanned = 1; } this.numRowsSpanned = this.properties.get("number-rows-spanned").getNumber().intValue(); if (numRowsSpanned < 1) { numRowsSpanned = 1; } this.backgroundColor = this.properties.get("background-color").getColorType(); this.id = this.properties.get("id").getString(); bSepBorders = (this.properties.get("border-collapse").getEnum() == BorderCollapse.SEPARATE); calcBorders(propMgr.getBorderAndPadding()); // Vertical cell alignment verticalAlign = this.properties.get("display-align").getEnum(); if (verticalAlign == DisplayAlign.AUTO) { // Depends on all cells starting in row bRelativeAlign = true; verticalAlign = this.properties.get("relative-align").getEnum(); } else bRelativeAlign = false; // Align on a per-cell basis this.minCellHeight = this.properties.get("height").getLength().mvalue(); } public Status layout(Area area) throws FOPException { int originalAbsoluteHeight = area.getAbsoluteHeight(); if (this.marker == BREAK_AFTER) { return new Status(Status.OK); } if (this.marker == START) { // if (!setup) { // doSetup(area); // } // Calculate cell borders // calcBorders(propMgr.getBorderAndPadding()); area.getIDReferences().createID(id); this.marker = 0; } /* * if ((spaceBefore != 0) && (this.marker ==0)) { * area.increaseHeight(spaceBefore); * } */ if (marker == 0) { // configure id area.getIDReferences().configureID(id, area); } // int spaceLeft = area.spaceLeft() - m_borderSeparation/2 + borderHeight/2 ; int spaceLeft = area.spaceLeft() - m_borderSeparation; // The Area position defines the content rectangle! Borders // and padding are outside of this rectangle. this.cellArea = new AreaContainer(propMgr.getFontState(area.getFontInfo()), startOffset + startAdjust, beforeOffset, width - widthAdjust, spaceLeft, Position.RELATIVE); cellArea.foCreator = this; // G Seshadri cellArea.setPage(area.getPage()); - cellArea.setBorderAndPadding(propMgr.getBorderAndPadding()); + try { + cellArea.setBorderAndPadding((BorderAndPadding) + propMgr.getBorderAndPadding().clone()); + } catch (CloneNotSupportedException e) { + System.err.println("Can't clone BorderAndPadding: " + e) ; + cellArea.setBorderAndPadding(propMgr.getBorderAndPadding()); + } cellArea.setBackgroundColor(this.backgroundColor); cellArea.start(); cellArea.setAbsoluteHeight(area.getAbsoluteHeight()); // ??? cellArea.setIDReferences(area.getIDReferences()); // ******** CHECK THIS: we've changed startOffset (KL) cellArea.setTableCellXOffset(startOffset); int numChildren = this.children.size(); for (int i = this.marker; i < numChildren; i++) { FObj fo = (FObj)children.elementAt(i); fo.setIsInTableCell(); fo.forceWidth(width); // ??? // Overflows may cause a row to be re-layedout, // need to pass already processed content. this.marker = i; Status status; if ((status = fo.layout(cellArea)).isIncomplete()) { // this.marker = i; if ((i == 0) && (status.getCode() == Status.AREA_FULL_NONE)) { return new Status(Status.AREA_FULL_NONE); } else { // hani Elabed 11/21/2000 area.addChild(cellArea); // area.setAbsoluteHeight(cellArea.getAbsoluteHeight()); return new Status(Status.AREA_FULL_SOME); } } area.setMaxHeight(area.getMaxHeight() - spaceLeft + this.cellArea.getMaxHeight()); } cellArea.end(); area.addChild(cellArea); // Adjust for minimum cell content height if (minCellHeight > cellArea.getContentHeight()) { cellArea.setHeight(minCellHeight); } // This is the allocation height of the cell (including borders // and padding // ALSO need to include offsets if using "separate borders" height = cellArea.getHeight(); top = cellArea.getCurrentYPosition(); // CHECK THIS!!! // reset absoluteHeight to beginning of row // area.setHeight(cellArea.getHeight() + spaceBefore + spaceAfter); // I don't think we should do this here (KL) !!! // area.setHeight(cellArea.getHeight()); // area.setAbsoluteHeight(originalAbsoluteHeight); return new Status(Status.OK); } /** * Return the allocation height of the cell area. * Note: called by TableRow. * We adjust the actual allocation height of the area by the value * of border separation (for separate borders) or border height * adjustment for collapse style (because current scheme makes cell * overestimate the allocation height). */ public int getHeight() { return cellArea.getHeight() + m_borderSeparation - borderHeight; } /** * Set the final size of cell content rectangles to the actual row height * and to vertically align the actual content within the cell rectangle. * @param h Height of this row in the grid which is based on * the allocation height of all the cells in the row, including any * border separation values. */ public void setRowHeight(int h) { int delta = h - getHeight(); // cellArea.increaseHeight(h + borderHeight/2 - cellArea.getHeight()); if (bRelativeAlign) { // Must get info for all cells starting in row! // verticalAlign can be BEFORE or BASELINE // For now just treat like "before" cellArea.increaseHeight(delta); } else if (delta > 0) { BorderAndPadding cellBP = cellArea.getBorderAndPadding(); switch (verticalAlign) { case DisplayAlign.CENTER: // Increase cell padding before and after and change // "Y" position of content rectangle cellArea.shiftYPosition(delta / 2); cellBP.setPaddingLength(BorderAndPadding.TOP, cellBP.getPaddingTop(false) + delta / 2); cellBP.setPaddingLength(BorderAndPadding.BOTTOM, cellBP.getPaddingBottom(false) + delta - delta / 2); break; case DisplayAlign.AFTER: // Increase cell padding before and change // "Y" position of content rectangle cellBP.setPaddingLength(BorderAndPadding.TOP, cellBP.getPaddingTop(false) + delta); cellArea.shiftYPosition(delta); break; case DisplayAlign.BEFORE: // cellArea.increaseHeight(delta); cellBP.setPaddingLength(BorderAndPadding.BOTTOM, cellBP.getPaddingBottom(false) + delta); default: // OK break; } } } /** * Calculate cell border and padding, including offset of content * rectangle from the theoretical grid position. */ private void calcBorders(BorderAndPadding bp) { if (this.bSepBorders) { /* * Easy case. * Cell border is the property specified directly on cell. * Offset content rect by half the border-separation value, * in addition to the border and padding values. Note: * border-separate should only be specified on the table object, * but it inherits. */ int iSep = properties.get("border-separation.inline-progression-direction").getLength().mvalue(); this.startAdjust = iSep / 2 + bp.getBorderLeftWidth(false) + bp.getPaddingLeft(false); /* * int contentOffset = iSep + bp.getBorderStartWidth(false) + * bp.getPaddingStart(false); */ this.widthAdjust = startAdjust + iSep - iSep / 2 + bp.getBorderRightWidth(false) + bp.getPaddingRight(false); // bp.getBorderEndWidth(false) + bp.getPaddingEnd(false); // Offset of content rectangle in the block-progression direction m_borderSeparation = properties.get("border-separation.block-progression-direction").getLength().mvalue(); this.beforeOffset = m_borderSeparation / 2 + bp.getBorderTopWidth(false) + bp.getPaddingTop(false); // bp.getBorderBeforeWidth(false) + bp.getPaddingBefore(false); } else { // System.err.println("Collapse borders"); /* * Hard case. * Cell border is combination of other cell borders, or table * border for edge cells. Also seems to border values specified * on row and column FO in the table (if I read CR correclty.) */ // Set up before and after borders, taking into account row // and table border properties. // ??? What about table-body, header,footer /* * We can't calculate before and after because we aren't sure * whether this row will be the first or last in its area, due * to redoing break decisions (at least in the "new" architecture.) * So in the general case, we will calculate two possible values: * the first/last one and the "middle" one. * Example: border-before * 1. If the cell is in the first row in the first table body, it * will combine with the last row of the header, or with the * top (before) table border if there is no header. * 2. Otherwise there are two cases: * a. the row is first in its (non-first) Area. * The border can combine with either: * i. the last row of table-header and its cells, or * ii. the table before border (no table-header or it is * omitted on non-first Areas). * b. the row isn't first in its Area. * The border combines with the border of the previous * row and the cells which end in that row. */ /* * if-first * Calculate the effective border of the cell before-border, * it's parent row before-border, the last header row after-border, * the after border of the cell(s) which end in the last header * row. */ /* * if-not-first * Calculate the effective border of the cell before-border, * it's parent row before-border, the previous row after-border, * the after border of the cell(s) which end in the previous * row. */ /* ivan demakov */ int borderStart = bp.getBorderLeftWidth(false); int borderEnd = bp.getBorderRightWidth(false); int borderBefore = bp.getBorderTopWidth(false); int borderAfter = bp.getBorderBottomWidth(false); this.startAdjust = borderStart / 2 + bp.getPaddingLeft(false); this.widthAdjust = startAdjust + borderEnd / 2 + bp.getPaddingRight(false); this.beforeOffset = borderBefore / 2 + bp.getPaddingTop(false); // Half border height to fix overestimate of area size! this.borderHeight = (borderBefore + borderAfter) / 2; } } }
true
true
public Status layout(Area area) throws FOPException { int originalAbsoluteHeight = area.getAbsoluteHeight(); if (this.marker == BREAK_AFTER) { return new Status(Status.OK); } if (this.marker == START) { // if (!setup) { // doSetup(area); // } // Calculate cell borders // calcBorders(propMgr.getBorderAndPadding()); area.getIDReferences().createID(id); this.marker = 0; } /* * if ((spaceBefore != 0) && (this.marker ==0)) { * area.increaseHeight(spaceBefore); * } */ if (marker == 0) { // configure id area.getIDReferences().configureID(id, area); } // int spaceLeft = area.spaceLeft() - m_borderSeparation/2 + borderHeight/2 ; int spaceLeft = area.spaceLeft() - m_borderSeparation; // The Area position defines the content rectangle! Borders // and padding are outside of this rectangle. this.cellArea = new AreaContainer(propMgr.getFontState(area.getFontInfo()), startOffset + startAdjust, beforeOffset, width - widthAdjust, spaceLeft, Position.RELATIVE); cellArea.foCreator = this; // G Seshadri cellArea.setPage(area.getPage()); cellArea.setBorderAndPadding(propMgr.getBorderAndPadding()); cellArea.setBackgroundColor(this.backgroundColor); cellArea.start(); cellArea.setAbsoluteHeight(area.getAbsoluteHeight()); // ??? cellArea.setIDReferences(area.getIDReferences()); // ******** CHECK THIS: we've changed startOffset (KL) cellArea.setTableCellXOffset(startOffset); int numChildren = this.children.size(); for (int i = this.marker; i < numChildren; i++) { FObj fo = (FObj)children.elementAt(i); fo.setIsInTableCell(); fo.forceWidth(width); // ??? // Overflows may cause a row to be re-layedout, // need to pass already processed content. this.marker = i; Status status; if ((status = fo.layout(cellArea)).isIncomplete()) { // this.marker = i; if ((i == 0) && (status.getCode() == Status.AREA_FULL_NONE)) { return new Status(Status.AREA_FULL_NONE); } else { // hani Elabed 11/21/2000 area.addChild(cellArea); // area.setAbsoluteHeight(cellArea.getAbsoluteHeight()); return new Status(Status.AREA_FULL_SOME); } } area.setMaxHeight(area.getMaxHeight() - spaceLeft + this.cellArea.getMaxHeight()); } cellArea.end(); area.addChild(cellArea); // Adjust for minimum cell content height if (minCellHeight > cellArea.getContentHeight()) { cellArea.setHeight(minCellHeight); } // This is the allocation height of the cell (including borders // and padding // ALSO need to include offsets if using "separate borders" height = cellArea.getHeight(); top = cellArea.getCurrentYPosition(); // CHECK THIS!!! // reset absoluteHeight to beginning of row // area.setHeight(cellArea.getHeight() + spaceBefore + spaceAfter); // I don't think we should do this here (KL) !!! // area.setHeight(cellArea.getHeight()); // area.setAbsoluteHeight(originalAbsoluteHeight); return new Status(Status.OK); }
public Status layout(Area area) throws FOPException { int originalAbsoluteHeight = area.getAbsoluteHeight(); if (this.marker == BREAK_AFTER) { return new Status(Status.OK); } if (this.marker == START) { // if (!setup) { // doSetup(area); // } // Calculate cell borders // calcBorders(propMgr.getBorderAndPadding()); area.getIDReferences().createID(id); this.marker = 0; } /* * if ((spaceBefore != 0) && (this.marker ==0)) { * area.increaseHeight(spaceBefore); * } */ if (marker == 0) { // configure id area.getIDReferences().configureID(id, area); } // int spaceLeft = area.spaceLeft() - m_borderSeparation/2 + borderHeight/2 ; int spaceLeft = area.spaceLeft() - m_borderSeparation; // The Area position defines the content rectangle! Borders // and padding are outside of this rectangle. this.cellArea = new AreaContainer(propMgr.getFontState(area.getFontInfo()), startOffset + startAdjust, beforeOffset, width - widthAdjust, spaceLeft, Position.RELATIVE); cellArea.foCreator = this; // G Seshadri cellArea.setPage(area.getPage()); try { cellArea.setBorderAndPadding((BorderAndPadding) propMgr.getBorderAndPadding().clone()); } catch (CloneNotSupportedException e) { System.err.println("Can't clone BorderAndPadding: " + e) ; cellArea.setBorderAndPadding(propMgr.getBorderAndPadding()); } cellArea.setBackgroundColor(this.backgroundColor); cellArea.start(); cellArea.setAbsoluteHeight(area.getAbsoluteHeight()); // ??? cellArea.setIDReferences(area.getIDReferences()); // ******** CHECK THIS: we've changed startOffset (KL) cellArea.setTableCellXOffset(startOffset); int numChildren = this.children.size(); for (int i = this.marker; i < numChildren; i++) { FObj fo = (FObj)children.elementAt(i); fo.setIsInTableCell(); fo.forceWidth(width); // ??? // Overflows may cause a row to be re-layedout, // need to pass already processed content. this.marker = i; Status status; if ((status = fo.layout(cellArea)).isIncomplete()) { // this.marker = i; if ((i == 0) && (status.getCode() == Status.AREA_FULL_NONE)) { return new Status(Status.AREA_FULL_NONE); } else { // hani Elabed 11/21/2000 area.addChild(cellArea); // area.setAbsoluteHeight(cellArea.getAbsoluteHeight()); return new Status(Status.AREA_FULL_SOME); } } area.setMaxHeight(area.getMaxHeight() - spaceLeft + this.cellArea.getMaxHeight()); } cellArea.end(); area.addChild(cellArea); // Adjust for minimum cell content height if (minCellHeight > cellArea.getContentHeight()) { cellArea.setHeight(minCellHeight); } // This is the allocation height of the cell (including borders // and padding // ALSO need to include offsets if using "separate borders" height = cellArea.getHeight(); top = cellArea.getCurrentYPosition(); // CHECK THIS!!! // reset absoluteHeight to beginning of row // area.setHeight(cellArea.getHeight() + spaceBefore + spaceAfter); // I don't think we should do this here (KL) !!! // area.setHeight(cellArea.getHeight()); // area.setAbsoluteHeight(originalAbsoluteHeight); return new Status(Status.OK); }
diff --git a/src/main/java/org/iplantc/workflow/service/dto/analysis/list/AnalysisRating.java b/src/main/java/org/iplantc/workflow/service/dto/analysis/list/AnalysisRating.java index e47edd9..8de369f 100644 --- a/src/main/java/org/iplantc/workflow/service/dto/analysis/list/AnalysisRating.java +++ b/src/main/java/org/iplantc/workflow/service/dto/analysis/list/AnalysisRating.java @@ -1,98 +1,100 @@ package org.iplantc.workflow.service.dto.analysis.list; import java.util.Map; import net.sf.json.JSONObject; import org.iplantc.persistence.dto.listing.AnalysisListing; import org.iplantc.workflow.service.dto.AbstractDto; import org.iplantc.workflow.service.dto.JsonField; /** * A data transfer object representing an analysis rating. * * @author Dennis Roberts */ public class AnalysisRating extends AbstractDto { /** * The average rating for the analysis. */ @JsonField(name = "average") private double average; /** * The rating assigned to the analysis by the current user. */ @JsonField(name = "user", optional = true) private Integer user; /** * The Confluence ID of a comment on the analysis by the current user. */ @JsonField(name = "comment_id", optional = true) private Long commentId; /** * @return the average rating. */ public double getAverage() { return average; } /** * @return the rating assigned to the analysis by the user or null if the user hasn't rated the * analysis. */ public Integer getUser() { return user; } /** * @return the comment created by the user or null if the user hasn't commented on the analysis. */ public Long getCommentId() { return commentId; } /** * A package-private constructor for use with unit tests. * * @param average the average rating. * @param user the user. */ AnalysisRating(double average, Integer user) { this.average = average; this.user = user; } /** * @param json a JSON object representing the analysis rating. */ public AnalysisRating(JSONObject json) { fromJson(json); } /** * @param str a JSON string representing the analysis rating. */ public AnalysisRating(String str) { fromString(str); } public AnalysisRating(AnalysisListing analysis) { this.average = analysis.getAverageRating(); this.user = null; } /** * @param analysis the analysis that these rating values apply to. * @param userRatings the user's analysis ratings and comment IDs. */ public AnalysisRating(AnalysisListing analysis, Map<Long, UserRating> userRatings) { this.average = analysis.getAverageRating(); UserRating userRating = userRatings.get(analysis.getHid()); - this.user = userRating.userRating; - this.commentId = userRating.commentId; + if (userRating != null) { + this.user = userRating.userRating; + this.commentId = userRating.commentId; + } } }
true
true
public AnalysisRating(AnalysisListing analysis, Map<Long, UserRating> userRatings) { this.average = analysis.getAverageRating(); UserRating userRating = userRatings.get(analysis.getHid()); this.user = userRating.userRating; this.commentId = userRating.commentId; }
public AnalysisRating(AnalysisListing analysis, Map<Long, UserRating> userRatings) { this.average = analysis.getAverageRating(); UserRating userRating = userRatings.get(analysis.getHid()); if (userRating != null) { this.user = userRating.userRating; this.commentId = userRating.commentId; } }
diff --git a/src/mobi/cyann/deviltools/SettingsManager.java b/src/mobi/cyann/deviltools/SettingsManager.java index 0c63f9b..a24042c 100644 --- a/src/mobi/cyann/deviltools/SettingsManager.java +++ b/src/mobi/cyann/deviltools/SettingsManager.java @@ -1,1101 +1,1101 @@ /** * SettingsManager.java * Nov 27, 2011 11:19:28 AM */ package mobi.cyann.deviltools; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.lang.Integer; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; /** * @author arif * */ public class SettingsManager { private final static String LOG_TAG = "DevilTools.SettingsManager"; public final static int SUCCESS = 0; public final static int ERR_SET_ON_BOOT_FALSE = -1; public final static int ERR_DIFFERENT_KERNEL = -2; private static String buildCommand(Context c, SharedPreferences preferences) { StringBuilder command = new StringBuilder(); String status = null; String filepath = null; int value = -1; if(!preferences.getBoolean(c.getString(R.string.key_default_voltage), true)) { // restore voltage setting if and only if key_default_voltage is false // customvoltage // ----------------- // arm voltages value = preferences.getInt(c.getString(R.string.key_max_arm_volt), -1); if(value > -1) { String armvolts = preferences.getString(c.getString(R.string.key_arm_volt_pref), "0"); command.append("echo " + value + " > " + "/sys/class/misc/customvoltage/max_arm_volt\n"); command.append("echo " + armvolts + " > " + "/sys/class/misc/customvoltage/arm_volt\n"); }else { // uv_mv_table status = preferences.getString(c.getString(R.string.key_uvmvtable_pref), "-1"); if(!status.equals("-1")) { command.append("echo " + status + " > " + "/sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table\n"); } } // int voltages value = preferences.getInt(c.getString(R.string.key_max_int_volt), -1); if(value > -1) { String armvolts = preferences.getString(c.getString(R.string.key_int_volt_pref), "0"); command.append("echo " + value + " > " + "/sys/class/misc/customvoltage/max_int_volt\n"); command.append("echo " + armvolts + " > " + "/sys/class/misc/customvoltage/int_volt\n"); } } // Audio value = preferences.getInt(c.getString(R.string.key_speaker_tuning), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/speaker_tuning\n"); } value = preferences.getInt(c.getString(R.string.key_speaker_offset), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/speaker_offset\n"); } value = preferences.getInt(c.getString(R.string.key_headphone_amplifier_level), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/headphone_amplifier_level\n"); } value = preferences.getInt(c.getString(R.string.key_stereo_expansion), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/stereo_expansion\n"); } value = preferences.getInt(c.getString(R.string.key_stereo_expansion_gain), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/stereo_expansion_gain\n"); } value = preferences.getInt(c.getString(R.string.key_headphone_eq), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/headphone_eq\n"); } value = preferences.getInt(c.getString(R.string.key_headphone_eq_b1_gain), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/headphone_eq_b1_gain\n"); } value = preferences.getInt(c.getString(R.string.key_headphone_eq_b2_gain), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/headphone_eq_b2_gain\n"); } value = preferences.getInt(c.getString(R.string.key_headphone_eq_b3_gain), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/headphone_eq_b3_gain\n"); } value = preferences.getInt(c.getString(R.string.key_headphone_eq_b4_gain), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/headphone_eq_b4_gain\n"); } value = preferences.getInt(c.getString(R.string.key_headphone_eq_b5_gain), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/headphone_eq_b5_gain\n"); } value = preferences.getInt(c.getString(R.string.key_fll_tuning), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/fll_tuning\n"); } value = preferences.getInt(c.getString(R.string.key_dac_osr128), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/dac_osr128\n"); } value = preferences.getInt(c.getString(R.string.key_adc_osr128), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/adc_osr128\n"); } value = preferences.getInt(c.getString(R.string.key_dac_direct), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/dac_direct\n"); } value = preferences.getInt(c.getString(R.string.key_mono_downmix), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/mono_downmix\n"); } // BLD value = preferences.getInt(c.getString(R.string.key_bld_status), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/class/misc/backlightdimmer/enabled\n"); value = preferences.getInt(c.getString(R.string.key_bld_delay), -1); if(value > -1) command.append("echo " + value + " > " + "/sys/class/misc/backlightdimmer/delay\n"); } // BLN value = preferences.getInt(c.getString(R.string.key_bln_status), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/class/misc/backlightnotification/enabled\n"); value = preferences.getInt(c.getString(R.string.key_bln_blink), -1); if(value > -1) command.append("echo " + value + " > " + "/sys/class/misc/backlightnotification/in_kernel_blink\n"); value = preferences.getInt(c.getString(R.string.key_bln_blink_interval), -1); if(value > -1) command.append("echo " + value + " > " + "/sys/class/misc/backlightnotification/blink_interval\n"); value = preferences.getInt(c.getString(R.string.key_bln_blink_count), -1); if(value > -1) command.append("echo " + value + " > " + "/sys/class/misc/backlightnotification/max_blink_count\n"); } // BLX value = preferences.getInt(c.getString(R.string.key_blx_charging_limit), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/class/misc/batterylifeextender/charging_limit\n"); } //color if(!ColorTuningPreference.isVoodoo()) { //no voodoo for (String filePath : ColorTuningPreference.FILE_PATH) { value = preferences.getInt(filePath, ColorTuningPreference.MAX_VALUE); command.append("echo " + value + " > " + filePath + "\n"); } for (String filePath : ColorTuningPreference.GAMMA_FILE_PATH) { value = preferences.getInt(filePath, ColorTuningPreference.GAMMA_DEFAULT_VALUE); command.append("echo " + value + " > " + filePath + "\n"); } } else { // try voodoo for (String filePath : ColorTuningPreference.VOODOO_FILE_PATH) { value = preferences.getInt(filePath, ColorTuningPreference.MAX_VALUE); command.append("echo " + value + " > " + filePath + "\n"); } for (String filePath : ColorTuningPreference.VOODOO_GAMMA_FILE_PATH) { value = (preferences.getInt(filePath, ColorTuningPreference.GAMMA_DEFAULT_VALUE) -40); command.append("echo " + value + " > " + filePath + "\n"); } } // Mdnie filepath = Mdnie.FILE; value = Integer.parseInt(preferences.getString(filepath, "-1")); if(value > -1) { command.append("echo " + value + " > " + filepath + "\n"); } // Deepidle value = preferences.getInt(c.getString(R.string.key_deepidle_status), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/class/misc/deepidle/enabled\n"); } // Smooth Ui value = preferences.getInt(c.getString(R.string.key_smooth_ui_enabled), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/class/misc/devil_tweaks/smooth_ui_enabled\n"); } // Dyn Fsync value = preferences.getInt(c.getString(R.string.key_dyn_fsync), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/kernel/dyn_fsync/Dyn_fsync_active\n"); } // vibrator value = preferences.getInt(c.getString(R.string.key_vibration_intensity), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/class/misc/pwm_duty/pwm_duty\n"); } // Touchwake value = preferences.getInt(c.getString(R.string.key_touchwake_status), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/class/misc/touchwake/enabled\n"); value = preferences.getInt(c.getString(R.string.key_touchwake_delay), -1); if(value > -1) command.append("echo " + value + " > " + "/sys/class/misc/touchwake/delay\n"); } // TouchBoost value = preferences.getInt(c.getString(R.string.key_touch_boost_enabled), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/class/misc/touchboost/input_boost_enabled\n"); - value = preferences.getInt(c.getString(R.string.key_touch_boost_enabled), -1); + value = preferences.getInt(c.getString(R.string.key_touch_boost_freq), -1); if(value > -1) command.append("echo " + value + " > " + "/sys/class/misc/touchboost/input_boost_freq\n"); } // bigmem value = Integer.parseInt(preferences.getString(c.getString(R.string.key_bigmem), "-1")); if(value > -1) { command.append("echo " + value + " > " + "/sys/kernel/bigmem/enable\n"); } // governor status = preferences.getString(c.getString(R.string.key_governor), "-1"); if(!status.equals("-1")) { command.append("echo " + status + " > " + "/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor\n"); } // governor's parameters if(status.equals("lazy")) { // set this parameter only if active governor = lazy // lazy screenoff max freq value = preferences.getInt(c.getString(R.string.key_screenoff_maxfreq), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lazy/screenoff_maxfreq\n"); } }else if(status.equals("ondemand")) { // set this parameter only if active governor = ondemand value = preferences.getInt(c.getString(R.string.key_ondemand_sampling_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/ondemand/sampling_rate\n"); } value = preferences.getInt(c.getString(R.string.key_ondemand_up_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/ondemand/up_threshold\n"); } value = preferences.getInt(c.getString(R.string.key_ondemand_sampling_down_factor), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/ondemand/sampling_down_factor\n"); } value = preferences.getInt(c.getString(R.string.key_ondemand_powersave_bias), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/ondemand/powersave_bias\n"); } value = preferences.getInt(c.getString(R.string.key_ondemand_early_demand), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/ondemand/early_demand\n"); if (value == 1) { value = preferences.getInt(c.getString(R.string.key_ondemand_grad_up_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/ondemand/grad_up_threshold\n"); } } } value = preferences.getInt(c.getString(R.string.key_ondemand_sleep_up_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/ondemand/sleep_up_threshold\n"); } value = preferences.getInt(c.getString(R.string.key_ondemand_sleep_sampling_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/ondemand/sleep_sampling_rate\n"); } }else if(status.equals("conservative")) { // set this parameter only if active governor = conservative value = preferences.getInt(c.getString(R.string.key_conservative_sampling_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/sampling_rate\n"); } value = preferences.getInt(c.getString(R.string.key_conservative_down_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/down_threshold\n"); } value = preferences.getInt(c.getString(R.string.key_conservative_up_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/up_threshold\n"); } value = preferences.getInt(c.getString(R.string.key_conservative_sampling_down_factor), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/sampling_down_factor\n"); } value = preferences.getInt(c.getString(R.string.key_conservative_freq_step), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/freq_step\n"); } value = preferences.getInt(c.getString(R.string.key_conservative_ignore_nice_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/ignore_nice_load\n"); } value = preferences.getInt(c.getString(R.string.key_conservative_smooth_up_enabled), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/smooth_up_enabled\n"); if (value == 1) { value = preferences.getInt(c.getString(R.string.key_conservative_smooth_up), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/smooth_up\n"); } } } value = preferences.getInt(c.getString(R.string.key_conservative_sleep_up_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/sleep_up_threshold\n"); } value = preferences.getInt(c.getString(R.string.key_conservative_sleep_sampling_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/sleep_sampling_rate\n"); } }else if(status.equals("smartassV2")) { // set this parameter only if active governor = smartass2 value = preferences.getInt(c.getString(R.string.key_smartass_awake_ideal_freq), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/smartass/awake_ideal_freq\n"); } value = preferences.getInt(c.getString(R.string.key_smartass_sleep_ideal_freq), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/smartass/sleep_ideal_freq\n"); } value = preferences.getInt(c.getString(R.string.key_smartass_sleep_wakeup_freq), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/smartass/sleep_wakeup_freq\n"); } value = preferences.getInt(c.getString(R.string.key_smartass_min_cpu_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/smartass/min_cpu_load\n"); } value = preferences.getInt(c.getString(R.string.key_smartass_max_cpu_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/smartass/max_cpu_load\n"); } value = preferences.getInt(c.getString(R.string.key_smartass_ramp_down_step), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/smartass/ramp_down_step\n"); } value = preferences.getInt(c.getString(R.string.key_smartass_ramp_up_step), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/smartass/ramp_up_step\n"); } value = preferences.getInt(c.getString(R.string.key_smartass_down_rate_us), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/smartass/down_rate_us\n"); } value = preferences.getInt(c.getString(R.string.key_smartass_up_rate_us), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/smartass/up_rate_us\n"); } }else if(status.equals("interactive")) { // set this parameter only if active governor = interactive value = preferences.getInt(c.getString(R.string.key_interactive_go_hispeed_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/interactive/go_hispeed_load\n"); } value = preferences.getInt(c.getString(R.string.key_interactive_target_loads), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/interactive/target_loads\n"); } value = preferences.getInt(c.getString(R.string.key_interactive_hispeed_freq), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/interactive/hispeed_freq\n"); } value = preferences.getInt(c.getString(R.string.key_interactive_min_sample_time), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/interactive/min_sample_time\n"); } value = preferences.getInt(c.getString(R.string.key_interactive_timer_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/interactive/timer_rate\n"); } }else if(status.equals("lulzactive")) { // set this parameter only if active governor = lulzactive // lulzactive inc_cpu_load value = preferences.getInt(c.getString(R.string.key_lulzactive_inc_cpu_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactive/inc_cpu_load\n"); } // lulzactive pump_up_step value = preferences.getInt(c.getString(R.string.key_lulzactive_pump_up_step), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactive/pump_up_step\n"); } // lulzactive pump_down_step value = preferences.getInt(c.getString(R.string.key_lulzactive_pump_down_step), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactive/pump_down_step\n"); } // lulzactive screen_off_min_step value = preferences.getInt(c.getString(R.string.key_lulzactive_screen_off_min_step), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactive/screen_off_min_step\n"); } // lulzactive up_sample_time value = preferences.getInt(c.getString(R.string.key_lulzactive_up_sample_time), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactive/up_sample_time\n"); } // lulzactive down_sample_time value = preferences.getInt(c.getString(R.string.key_lulzactive_down_sample_time), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactive/down_sample_time\n"); } }else if(status.equals("lulzactiveq")) { // set this parameter only if active governor = lulzactiveq // lulzactiveq hispeed_freq value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hispeed_freq), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hispeed_freq\n"); } // lulzactiveq inc_cpu_load value = preferences.getInt(c.getString(R.string.key_lulzactiveq_inc_cpu_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/inc_cpu_load\n"); } // lulzactiveq pump_up_step value = preferences.getInt(c.getString(R.string.key_lulzactiveq_pump_up_step), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/pump_up_step\n"); } // lulzactiveq pump_down_step value = preferences.getInt(c.getString(R.string.key_lulzactiveq_pump_down_step), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/pump_down_step\n"); } // lulzactiveq screen_off_max_step value = preferences.getInt(c.getString(R.string.key_lulzactiveq_screen_off_max_step), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/screen_off_max_step\n"); } // lulzactiveq up_sample_time value = preferences.getInt(c.getString(R.string.key_lulzactiveq_up_sample_time), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/up_sample_time\n"); } // lulzactiveq down_sample_time value = preferences.getInt(c.getString(R.string.key_lulzactiveq_down_sample_time), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/down_sample_time\n"); } // lulzactiveq cpu_up_rate value = preferences.getInt(c.getString(R.string.key_lulzactiveq_cpu_up_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/cpu_up_rate\n"); } // lulzactiveq cpu_down_rate value = preferences.getInt(c.getString(R.string.key_lulzactiveq_cpu_down_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/cpu_down_rate\n"); } // lulzactiveq ignore_nice_load value = preferences.getInt(c.getString(R.string.key_lulzactiveq_ignore_nice_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/ignore_nice_load\n"); } // lulzactiveq max_cpu_lock value = preferences.getInt(c.getString(R.string.key_lulzactiveq_max_cpu_lock), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/max_cpu_lock\n"); } // lulzactiveq min_cpu_lock value = preferences.getInt(c.getString(R.string.key_lulzactiveq_min_cpu_lock), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/min_cpu_lock\n"); } // lulzactiveq hotplug_freq_1_1 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_freq_1_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_freq_1_1\n"); } // lulzactiveq hotplug_freq_2_0 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_freq_2_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_freq_2_0\n"); } // lulzactiveq hotplug_freq_2_1 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_freq_2_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_freq_2_1\n"); } // lulzactiveq hotplug_freq_3_0 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_freq_3_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_freq_3_0\n"); } // lulzactiveq hotplug_freq_3_1 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_freq_3_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_freq_3_1\n"); } // lulzactiveq hotplug_freq_4_0 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_freq_4_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_freq_4_0\n"); } // lulzactiveq hotplug_rq_1_1 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_rq_1_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_rq_1_1\n"); } // lulzactiveq hotplug_rq_2_0 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_rq_2_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_rq_2_0\n"); } // lulzactiveq hotplug_rq_2_1 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_rq_2_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_rq_2_1\n"); } // lulzactiveq hotplug_rq_3_0 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_rq_3_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_rq_3_0\n"); } // lulzactiveq hotplug_rq_3_1 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_rq_3_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_rq_3_1\n"); } // lulzactiveq hotplug_rq_4_0 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_rq_4_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_rq_4_0\n"); } // lulzactiveq hotplug_sampling_rate value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_sampling_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_sampling_rate\n"); } // lulzactiveq up_nr_cpus value = preferences.getInt(c.getString(R.string.key_lulzactiveq_up_nr_cpus), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/up_nr_cpus\n"); } // lulzactiveq hotplug_lock value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_lock), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_lock\n"); } }else if(status.equals("hotplug")) { // set this parameter only if active governor = hotplug value = preferences.getInt(c.getString(R.string.key_hotplug_up_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/hotplug/up_threshold\n"); } value = preferences.getInt(c.getString(R.string.key_hotplug_down_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/hotplug/down_threshold\n"); } value = preferences.getInt(c.getString(R.string.key_hotplug_sampling_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/hotplug/sampling_rate\n"); } value = preferences.getInt(c.getString(R.string.key_hotplug_ignore_nice_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/hotplug/ignore_nice_load\n"); } value = preferences.getInt(c.getString(R.string.key_hotplug_io_is_busy), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/hotplug/io_is_busy\n"); } value = preferences.getInt(c.getString(R.string.key_hotplug_down_differential), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/hotplug/down_differential\n"); } value = preferences.getInt(c.getString(R.string.key_hotplug_in_sampling_periods), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/hotplug/hotplug_in_sampling_periods\n"); } value = preferences.getInt(c.getString(R.string.key_hotplug_out_sampling_periods), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/hotplug/hotplug_out_sampling_periods\n"); } } else if(status.equals("devilq")) { // set this parameter only if active governor = devilq // devilq inc_cpu_load value = preferences.getInt(c.getString(R.string.key_devilq_inc_cpu_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/inc_cpu_load\n"); } value = preferences.getInt(c.getString(R.string.key_devilq_dec_cpu_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/inc_dec_load\n"); } // devilq up_sample_time value = preferences.getInt(c.getString(R.string.key_devilq_up_sample_time), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/up_sample_time\n"); } // devilq down_sample_time value = preferences.getInt(c.getString(R.string.key_devilq_down_sample_time), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/down_sample_time\n"); } // devilq cpu_up_rate value = preferences.getInt(c.getString(R.string.key_devilq_cpu_up_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/cpu_up_rate\n"); } // devilq cpu_down_rate value = preferences.getInt(c.getString(R.string.key_devilq_cpu_down_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/cpu_down_rate\n"); } value = preferences.getInt(c.getString(R.string.key_devilq_early_demand), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/early_demand\n"); if (value == 1) { value = preferences.getInt(c.getString(R.string.key_devilq_grad_up_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/grad_up_threshold\n"); } value = preferences.getInt(c.getString(R.string.key_devilq_grad_down_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/grad_down_threshold\n"); } } } // devilq ignore_nice_load value = preferences.getInt(c.getString(R.string.key_devilq_ignore_nice_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/ignore_nice_load\n"); } // devilq max_cpu_lock value = preferences.getInt(c.getString(R.string.key_devilq_max_cpu_lock), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/max_cpu_lock\n"); } // devilq min_cpu_lock value = preferences.getInt(c.getString(R.string.key_devilq_min_cpu_lock), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/min_cpu_lock\n"); } // devilq hotplug_freq_1_1 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_freq_1_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_freq_1_1\n"); } // devilq hotplug_freq_2_0 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_freq_2_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_freq_2_0\n"); } // devilq hotplug_freq_2_1 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_freq_2_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_freq_2_1\n"); } // devilq hotplug_freq_3_0 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_freq_3_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_freq_3_0\n"); } // devilq hotplug_freq_3_1 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_freq_3_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_freq_3_1\n"); } // devilq hotplug_freq_4_0 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_freq_4_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_freq_4_0\n"); } // devilq hotplug_rq_1_1 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_rq_1_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_rq_1_1\n"); } // devilq hotplug_rq_2_0 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_rq_2_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_rq_2_0\n"); } // devilq hotplug_rq_2_1 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_rq_2_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_rq_2_1\n"); } // devilq hotplug_rq_3_0 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_rq_3_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_rq_3_0\n"); } // devilq hotplug_rq_3_1 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_rq_3_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_rq_3_1\n"); } // devilq hotplug_rq_4_0 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_rq_4_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_rq_4_0\n"); } // devilq hotplug_sampling_rate value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_sampling_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_sampling_rate\n"); } // devilq up_nr_cpus value = preferences.getInt(c.getString(R.string.key_devilq_up_nr_cpus), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/up_nr_cpus\n"); } // devilq hotplug_lock value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_lock), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_lock\n"); } value = preferences.getInt(c.getString(R.string.key_devilq_suspend_max_cpu), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/suspend_max_cpu\n"); } } // battery value = preferences.getInt(c.getString(R.string.key_dcp_ac_input_curr), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/platform/samsung-battery/dcp_ac_input_curr\n"); } value = preferences.getInt(c.getString(R.string.key_dcp_ac_chrg_curr), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/platform/samsung-battery/dcp_ac_chrg_curr\n"); } value = preferences.getInt(c.getString(R.string.key_sdp_input_curr), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/platform/samsung-battery/sdp_input_curr\n"); } value = preferences.getInt(c.getString(R.string.key_sdp_chrg_curr), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/platform/samsung-battery/sdp_chrg_curr\n"); } value = preferences.getInt(c.getString(R.string.key_cdp_input_curr), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/platform/samsung-battery/cdp_input_curr\n"); } value = preferences.getInt(c.getString(R.string.key_cdp_chrg_curr), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/platform/samsung-battery/cdp_chrg_curr\n"); } value = preferences.getInt(c.getString(R.string.key_batt_chrg_soft_volt), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/platform/samsung-battery/batt_chrg_soft_volt\n"); } value = preferences.getInt(c.getString(R.string.key_ignore_stable_margin), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/platform/samsung-battery/ignore_stable_margin\n"); } value = preferences.getInt(c.getString(R.string.key_ignore_unstable_power), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/platform/samsung-battery/ignore_unstable_power\n"); } // cmled value = preferences.getInt(c.getString(R.string.key_cmled_bltimeout), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/class/misc/notification/bl_timeout\n"); } // cmled blink value = preferences.getInt(c.getString(R.string.key_cmled_blink), -1); if(value > -1) { // we must write blinktimeout before blink status // coz if we write blinktimeout it will reset blink status to enabled int timeout = preferences.getInt(c.getString(R.string.key_cmled_blinktimeout), -1); if(timeout > -1) command.append("echo " + timeout + ">" + "/sys/class/misc/notification/blinktimeout\n"); command.append("echo " + value + " > " + "/sys/class/misc/notification/blink\n"); } // gpu for (String filePath : GpuFragment.GPU_CLOCK_FILE_PATH) { status = preferences.getString(filePath, "-1"); if(!status.equals("-1")) command.append("echo " + status + " > " + filePath + "\n"); } status = preferences.getString(c.getString(R.string.key_malivolt_pref), "-1"); if(!status.equals("-1")) { command.append("echo " + status + " > " + "/sys/class/misc/mali_control/voltage_control\n"); } // io scheduler status = preferences.getString(c.getString(R.string.key_iosched), "-1"); if(!status.equals("-1")) { String[] ioscheds = c.getResources().getStringArray(R.array.iosched_interfaces); for(String i: ioscheds) { command.append("echo " + status + " > " + i + "\n"); } } // Liveoc target low int ocTargetLow = preferences.getInt(c.getString(R.string.key_liveoc_target_low), -1); if(ocTargetLow > -1) { command.append("echo " + ocTargetLow + " > " + "/sys/class/misc/liveoc/oc_target_low\n"); } // Liveoc target high int ocTargetHigh = preferences.getInt(c.getString(R.string.key_liveoc_target_high), -1); if(ocTargetHigh > -1) { command.append("echo " + ocTargetHigh + " > " + "/sys/class/misc/liveoc/oc_target_high\n"); } // Liveoc value = preferences.getInt(c.getString(R.string.key_liveoc), -1); if(value > -1 && value != 100) { // first make sure live oc at 100 then set cpu min and max freq command.append("echo 100 > " + "/sys/class/misc/liveoc/oc_value\n"); // cpu minfreq int minFreq = preferences.getInt(c.getString(R.string.key_min_cpufreq), -1); if(minFreq > -1) { if(minFreq >= ocTargetLow) { minFreq = minFreq * 100 / value; } command.append("echo " + minFreq + " > " + "/sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq\n"); } // cpu maxfreq int maxFreq = preferences.getInt(c.getString(R.string.key_max_cpufreq), -1); if(maxFreq > -1) { if(minFreq <= ocTargetHigh) { maxFreq = maxFreq * 100 / value; } command.append("echo " + maxFreq + " > " + "/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq\n"); } // now set liveoc value command.append("echo " + value + " > " + "/sys/class/misc/liveoc/oc_value\n"); }else { // make sure liveoc at 100 command.append("echo 100 > " + "/sys/class/misc/liveoc/oc_value\n"); // cpu minfreq int minFreq = preferences.getInt(c.getString(R.string.key_min_cpufreq), -1); if(minFreq > -1) { command.append("echo " + minFreq + " > " + "/sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq\n"); } // cpu maxfreq int maxFreq = preferences.getInt(c.getString(R.string.key_max_cpufreq), -1); if(maxFreq > -1) { command.append("echo " + maxFreq + " > " + "/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq\n"); } } return command.toString(); } public static void deleteSettings(Context c, String preferenceName) { File destination = new File(c.getString(R.string.SETTINGS_DIR), preferenceName); destination.delete(); } public static boolean saveSettings(Context c, String preferenceName) { boolean ret = false; File destDir = new File(c.getString(R.string.SETTINGS_DIR)); if(!destDir.exists()) destDir.mkdirs(); // create dir if not exists File destination = new File(destDir, preferenceName); if(!destination.exists()) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(c); String command = buildCommand(c, preferences); try { FileWriter fw = new FileWriter(destination); fw.write("# v" + c.getString(R.string.app_version) + "\n"); fw.write(command); fw.close(); ret = true; }catch(IOException e) { Log.e(LOG_TAG, "", e); } } return ret; } private static void checkOldSavedFile(Context c, File source) { try { FileReader fr = new FileReader(source); BufferedReader br = new BufferedReader(fr); String line = br.readLine(); String lastLine = null; String versionString = "# v" + c.getString(R.string.app_version); StringBuilder command = new StringBuilder(versionString); command.append("\n"); boolean rewrite = false; if(line != null && !line.equals(versionString)) { rewrite = true; do { if(line.contains("scaling_min_freq") && !lastLine.contains("oc_value")) { command.append("echo 100 > " + "/sys/class/misc/liveoc/oc_value\n"); } if(line != null) { command.append(line); command.append("\n"); } lastLine = line; line = br.readLine(); }while(line != null); } br.close(); fr.close(); if(rewrite) { FileWriter fw = new FileWriter(source); fw.write(command.toString()); fw.close(); } }catch(Exception ex) { Log.e(LOG_TAG, "", ex); } } /** * * @param c * @param preferenceName * @return */ public static void loadSettings(Context c, String preferenceName) { File source = new File(c.getString(R.string.SETTINGS_DIR), preferenceName); checkOldSavedFile(c, source); // check old saved file StringBuilder command = new StringBuilder(); try { FileReader fr = new FileReader(source); BufferedReader br = new BufferedReader(fr); String line = br.readLine(); while(line != null) { command.append(line); command.append("\n"); line = br.readLine(); } br.close(); fr.close(); }catch(IOException e) { Log.e(LOG_TAG, "", e); } if(command.length() > 0) { SysCommand.getInstance().suRun(command.toString()); } } /** * this method called on boot completed * * @param c * @return */ public static int loadSettingsOnBoot(Context c) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(c); // check 'set on boot' preference boolean restoreOnBoot = preferences.getBoolean(c.getString(R.string.key_restore_on_boot), true); boolean forceRestore = preferences.getBoolean(c.getString(R.string.key_force_restore_on_boot), false); if(!restoreOnBoot) { return ERR_SET_ON_BOOT_FALSE; } // now check current kernel version with saved value restoreOnBoot = false; SysCommand sysCommand = SysCommand.getInstance(); if(sysCommand.readSysfs("/proc/version") > 0) { String kernel = sysCommand.getLastResult(0); String savedKernelVersion = preferences.getString(c.getString(R.string.key_kernel_version), null); if(kernel.equals(savedKernelVersion) || forceRestore) { restoreOnBoot = true; } } if(!restoreOnBoot) { return ERR_DIFFERENT_KERNEL; } boolean restoreOnInitd = preferences.getBoolean(c.getString(R.string.key_restore_on_initd), false); if(!restoreOnInitd) { String command = buildCommand(c, preferences); SysCommand.getInstance().suRun(command); ColorTuningPreference.restore(c); Mdnie.restore(c); } return SUCCESS; } public static void saveToInitd(Context c) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(c); boolean restoreOnBoot = preferences.getBoolean(c.getString(R.string.key_restore_on_boot), true); boolean restoreOnInitd = preferences.getBoolean(c.getString(R.string.key_restore_on_initd), false); boolean forceRestore = preferences.getBoolean(c.getString(R.string.key_force_restore_on_boot), false); SysCommand sysCommand = SysCommand.getInstance(); if(restoreOnBoot && restoreOnInitd) { Log.d(LOG_TAG, "write to init.d script"); StringBuilder cmd = new StringBuilder(); cmd.append("mount -o remount,rw /dev/block/platform/s3c-sdhci.0/by-name/system /system\n"); cmd.append("echo a > " + c.getString(R.string.INITD_SCRIPT) + "\n"); cmd.append("chmod 0777 " + c.getString(R.string.INITD_SCRIPT) + "\n"); sysCommand.suRun(cmd.toString()); File destination = new File(c.getString(R.string.INITD_SCRIPT)); String command = buildCommand(c, preferences); try { FileWriter fw = new FileWriter(destination); fw.write("#!/system/bin/sh\n"); fw.write("CUR=`cat /proc/version`\n"); fw.write("SAV=\""+preferences.getString(c.getString(R.string.key_kernel_version), null)+"\"\n"); if (!forceRestore) { fw.write("if [ ! \"$CUR\" == \"$SAV\" ] ; then\n"); fw.write("exit\n"); fw.write("fi\n"); } fw.write(command); fw.close(); }catch(IOException e) { Log.e(LOG_TAG, "", e); } sysCommand.suRun("mount", "-o", "remount,ro", "/dev/block/platform/s3c-sdhci.0/by-name/system", "/system"); }else { Log.d(LOG_TAG, "remove init.d script"); StringBuilder cmd = new StringBuilder(); cmd.append("mount -o remount,rw /dev/block/platform/s3c-sdhci.0/by-name/system /system\n"); cmd.append("rm " + c.getString(R.string.INITD_SCRIPT) + "\n"); cmd.append("mount -o remount,ro /dev/block/platform/s3c-sdhci.0/by-name/system /system\n"); sysCommand.suRun(cmd.toString()); } } }
true
true
private static String buildCommand(Context c, SharedPreferences preferences) { StringBuilder command = new StringBuilder(); String status = null; String filepath = null; int value = -1; if(!preferences.getBoolean(c.getString(R.string.key_default_voltage), true)) { // restore voltage setting if and only if key_default_voltage is false // customvoltage // ----------------- // arm voltages value = preferences.getInt(c.getString(R.string.key_max_arm_volt), -1); if(value > -1) { String armvolts = preferences.getString(c.getString(R.string.key_arm_volt_pref), "0"); command.append("echo " + value + " > " + "/sys/class/misc/customvoltage/max_arm_volt\n"); command.append("echo " + armvolts + " > " + "/sys/class/misc/customvoltage/arm_volt\n"); }else { // uv_mv_table status = preferences.getString(c.getString(R.string.key_uvmvtable_pref), "-1"); if(!status.equals("-1")) { command.append("echo " + status + " > " + "/sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table\n"); } } // int voltages value = preferences.getInt(c.getString(R.string.key_max_int_volt), -1); if(value > -1) { String armvolts = preferences.getString(c.getString(R.string.key_int_volt_pref), "0"); command.append("echo " + value + " > " + "/sys/class/misc/customvoltage/max_int_volt\n"); command.append("echo " + armvolts + " > " + "/sys/class/misc/customvoltage/int_volt\n"); } } // Audio value = preferences.getInt(c.getString(R.string.key_speaker_tuning), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/speaker_tuning\n"); } value = preferences.getInt(c.getString(R.string.key_speaker_offset), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/speaker_offset\n"); } value = preferences.getInt(c.getString(R.string.key_headphone_amplifier_level), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/headphone_amplifier_level\n"); } value = preferences.getInt(c.getString(R.string.key_stereo_expansion), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/stereo_expansion\n"); } value = preferences.getInt(c.getString(R.string.key_stereo_expansion_gain), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/stereo_expansion_gain\n"); } value = preferences.getInt(c.getString(R.string.key_headphone_eq), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/headphone_eq\n"); } value = preferences.getInt(c.getString(R.string.key_headphone_eq_b1_gain), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/headphone_eq_b1_gain\n"); } value = preferences.getInt(c.getString(R.string.key_headphone_eq_b2_gain), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/headphone_eq_b2_gain\n"); } value = preferences.getInt(c.getString(R.string.key_headphone_eq_b3_gain), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/headphone_eq_b3_gain\n"); } value = preferences.getInt(c.getString(R.string.key_headphone_eq_b4_gain), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/headphone_eq_b4_gain\n"); } value = preferences.getInt(c.getString(R.string.key_headphone_eq_b5_gain), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/headphone_eq_b5_gain\n"); } value = preferences.getInt(c.getString(R.string.key_fll_tuning), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/fll_tuning\n"); } value = preferences.getInt(c.getString(R.string.key_dac_osr128), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/dac_osr128\n"); } value = preferences.getInt(c.getString(R.string.key_adc_osr128), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/adc_osr128\n"); } value = preferences.getInt(c.getString(R.string.key_dac_direct), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/dac_direct\n"); } value = preferences.getInt(c.getString(R.string.key_mono_downmix), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/mono_downmix\n"); } // BLD value = preferences.getInt(c.getString(R.string.key_bld_status), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/class/misc/backlightdimmer/enabled\n"); value = preferences.getInt(c.getString(R.string.key_bld_delay), -1); if(value > -1) command.append("echo " + value + " > " + "/sys/class/misc/backlightdimmer/delay\n"); } // BLN value = preferences.getInt(c.getString(R.string.key_bln_status), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/class/misc/backlightnotification/enabled\n"); value = preferences.getInt(c.getString(R.string.key_bln_blink), -1); if(value > -1) command.append("echo " + value + " > " + "/sys/class/misc/backlightnotification/in_kernel_blink\n"); value = preferences.getInt(c.getString(R.string.key_bln_blink_interval), -1); if(value > -1) command.append("echo " + value + " > " + "/sys/class/misc/backlightnotification/blink_interval\n"); value = preferences.getInt(c.getString(R.string.key_bln_blink_count), -1); if(value > -1) command.append("echo " + value + " > " + "/sys/class/misc/backlightnotification/max_blink_count\n"); } // BLX value = preferences.getInt(c.getString(R.string.key_blx_charging_limit), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/class/misc/batterylifeextender/charging_limit\n"); } //color if(!ColorTuningPreference.isVoodoo()) { //no voodoo for (String filePath : ColorTuningPreference.FILE_PATH) { value = preferences.getInt(filePath, ColorTuningPreference.MAX_VALUE); command.append("echo " + value + " > " + filePath + "\n"); } for (String filePath : ColorTuningPreference.GAMMA_FILE_PATH) { value = preferences.getInt(filePath, ColorTuningPreference.GAMMA_DEFAULT_VALUE); command.append("echo " + value + " > " + filePath + "\n"); } } else { // try voodoo for (String filePath : ColorTuningPreference.VOODOO_FILE_PATH) { value = preferences.getInt(filePath, ColorTuningPreference.MAX_VALUE); command.append("echo " + value + " > " + filePath + "\n"); } for (String filePath : ColorTuningPreference.VOODOO_GAMMA_FILE_PATH) { value = (preferences.getInt(filePath, ColorTuningPreference.GAMMA_DEFAULT_VALUE) -40); command.append("echo " + value + " > " + filePath + "\n"); } } // Mdnie filepath = Mdnie.FILE; value = Integer.parseInt(preferences.getString(filepath, "-1")); if(value > -1) { command.append("echo " + value + " > " + filepath + "\n"); } // Deepidle value = preferences.getInt(c.getString(R.string.key_deepidle_status), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/class/misc/deepidle/enabled\n"); } // Smooth Ui value = preferences.getInt(c.getString(R.string.key_smooth_ui_enabled), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/class/misc/devil_tweaks/smooth_ui_enabled\n"); } // Dyn Fsync value = preferences.getInt(c.getString(R.string.key_dyn_fsync), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/kernel/dyn_fsync/Dyn_fsync_active\n"); } // vibrator value = preferences.getInt(c.getString(R.string.key_vibration_intensity), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/class/misc/pwm_duty/pwm_duty\n"); } // Touchwake value = preferences.getInt(c.getString(R.string.key_touchwake_status), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/class/misc/touchwake/enabled\n"); value = preferences.getInt(c.getString(R.string.key_touchwake_delay), -1); if(value > -1) command.append("echo " + value + " > " + "/sys/class/misc/touchwake/delay\n"); } // TouchBoost value = preferences.getInt(c.getString(R.string.key_touch_boost_enabled), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/class/misc/touchboost/input_boost_enabled\n"); value = preferences.getInt(c.getString(R.string.key_touch_boost_enabled), -1); if(value > -1) command.append("echo " + value + " > " + "/sys/class/misc/touchboost/input_boost_freq\n"); } // bigmem value = Integer.parseInt(preferences.getString(c.getString(R.string.key_bigmem), "-1")); if(value > -1) { command.append("echo " + value + " > " + "/sys/kernel/bigmem/enable\n"); } // governor status = preferences.getString(c.getString(R.string.key_governor), "-1"); if(!status.equals("-1")) { command.append("echo " + status + " > " + "/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor\n"); } // governor's parameters if(status.equals("lazy")) { // set this parameter only if active governor = lazy // lazy screenoff max freq value = preferences.getInt(c.getString(R.string.key_screenoff_maxfreq), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lazy/screenoff_maxfreq\n"); } }else if(status.equals("ondemand")) { // set this parameter only if active governor = ondemand value = preferences.getInt(c.getString(R.string.key_ondemand_sampling_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/ondemand/sampling_rate\n"); } value = preferences.getInt(c.getString(R.string.key_ondemand_up_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/ondemand/up_threshold\n"); } value = preferences.getInt(c.getString(R.string.key_ondemand_sampling_down_factor), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/ondemand/sampling_down_factor\n"); } value = preferences.getInt(c.getString(R.string.key_ondemand_powersave_bias), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/ondemand/powersave_bias\n"); } value = preferences.getInt(c.getString(R.string.key_ondemand_early_demand), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/ondemand/early_demand\n"); if (value == 1) { value = preferences.getInt(c.getString(R.string.key_ondemand_grad_up_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/ondemand/grad_up_threshold\n"); } } } value = preferences.getInt(c.getString(R.string.key_ondemand_sleep_up_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/ondemand/sleep_up_threshold\n"); } value = preferences.getInt(c.getString(R.string.key_ondemand_sleep_sampling_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/ondemand/sleep_sampling_rate\n"); } }else if(status.equals("conservative")) { // set this parameter only if active governor = conservative value = preferences.getInt(c.getString(R.string.key_conservative_sampling_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/sampling_rate\n"); } value = preferences.getInt(c.getString(R.string.key_conservative_down_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/down_threshold\n"); } value = preferences.getInt(c.getString(R.string.key_conservative_up_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/up_threshold\n"); } value = preferences.getInt(c.getString(R.string.key_conservative_sampling_down_factor), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/sampling_down_factor\n"); } value = preferences.getInt(c.getString(R.string.key_conservative_freq_step), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/freq_step\n"); } value = preferences.getInt(c.getString(R.string.key_conservative_ignore_nice_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/ignore_nice_load\n"); } value = preferences.getInt(c.getString(R.string.key_conservative_smooth_up_enabled), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/smooth_up_enabled\n"); if (value == 1) { value = preferences.getInt(c.getString(R.string.key_conservative_smooth_up), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/smooth_up\n"); } } } value = preferences.getInt(c.getString(R.string.key_conservative_sleep_up_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/sleep_up_threshold\n"); } value = preferences.getInt(c.getString(R.string.key_conservative_sleep_sampling_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/sleep_sampling_rate\n"); } }else if(status.equals("smartassV2")) { // set this parameter only if active governor = smartass2 value = preferences.getInt(c.getString(R.string.key_smartass_awake_ideal_freq), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/smartass/awake_ideal_freq\n"); } value = preferences.getInt(c.getString(R.string.key_smartass_sleep_ideal_freq), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/smartass/sleep_ideal_freq\n"); } value = preferences.getInt(c.getString(R.string.key_smartass_sleep_wakeup_freq), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/smartass/sleep_wakeup_freq\n"); } value = preferences.getInt(c.getString(R.string.key_smartass_min_cpu_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/smartass/min_cpu_load\n"); } value = preferences.getInt(c.getString(R.string.key_smartass_max_cpu_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/smartass/max_cpu_load\n"); } value = preferences.getInt(c.getString(R.string.key_smartass_ramp_down_step), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/smartass/ramp_down_step\n"); } value = preferences.getInt(c.getString(R.string.key_smartass_ramp_up_step), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/smartass/ramp_up_step\n"); } value = preferences.getInt(c.getString(R.string.key_smartass_down_rate_us), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/smartass/down_rate_us\n"); } value = preferences.getInt(c.getString(R.string.key_smartass_up_rate_us), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/smartass/up_rate_us\n"); } }else if(status.equals("interactive")) { // set this parameter only if active governor = interactive value = preferences.getInt(c.getString(R.string.key_interactive_go_hispeed_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/interactive/go_hispeed_load\n"); } value = preferences.getInt(c.getString(R.string.key_interactive_target_loads), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/interactive/target_loads\n"); } value = preferences.getInt(c.getString(R.string.key_interactive_hispeed_freq), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/interactive/hispeed_freq\n"); } value = preferences.getInt(c.getString(R.string.key_interactive_min_sample_time), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/interactive/min_sample_time\n"); } value = preferences.getInt(c.getString(R.string.key_interactive_timer_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/interactive/timer_rate\n"); } }else if(status.equals("lulzactive")) { // set this parameter only if active governor = lulzactive // lulzactive inc_cpu_load value = preferences.getInt(c.getString(R.string.key_lulzactive_inc_cpu_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactive/inc_cpu_load\n"); } // lulzactive pump_up_step value = preferences.getInt(c.getString(R.string.key_lulzactive_pump_up_step), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactive/pump_up_step\n"); } // lulzactive pump_down_step value = preferences.getInt(c.getString(R.string.key_lulzactive_pump_down_step), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactive/pump_down_step\n"); } // lulzactive screen_off_min_step value = preferences.getInt(c.getString(R.string.key_lulzactive_screen_off_min_step), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactive/screen_off_min_step\n"); } // lulzactive up_sample_time value = preferences.getInt(c.getString(R.string.key_lulzactive_up_sample_time), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactive/up_sample_time\n"); } // lulzactive down_sample_time value = preferences.getInt(c.getString(R.string.key_lulzactive_down_sample_time), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactive/down_sample_time\n"); } }else if(status.equals("lulzactiveq")) { // set this parameter only if active governor = lulzactiveq // lulzactiveq hispeed_freq value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hispeed_freq), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hispeed_freq\n"); } // lulzactiveq inc_cpu_load value = preferences.getInt(c.getString(R.string.key_lulzactiveq_inc_cpu_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/inc_cpu_load\n"); } // lulzactiveq pump_up_step value = preferences.getInt(c.getString(R.string.key_lulzactiveq_pump_up_step), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/pump_up_step\n"); } // lulzactiveq pump_down_step value = preferences.getInt(c.getString(R.string.key_lulzactiveq_pump_down_step), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/pump_down_step\n"); } // lulzactiveq screen_off_max_step value = preferences.getInt(c.getString(R.string.key_lulzactiveq_screen_off_max_step), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/screen_off_max_step\n"); } // lulzactiveq up_sample_time value = preferences.getInt(c.getString(R.string.key_lulzactiveq_up_sample_time), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/up_sample_time\n"); } // lulzactiveq down_sample_time value = preferences.getInt(c.getString(R.string.key_lulzactiveq_down_sample_time), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/down_sample_time\n"); } // lulzactiveq cpu_up_rate value = preferences.getInt(c.getString(R.string.key_lulzactiveq_cpu_up_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/cpu_up_rate\n"); } // lulzactiveq cpu_down_rate value = preferences.getInt(c.getString(R.string.key_lulzactiveq_cpu_down_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/cpu_down_rate\n"); } // lulzactiveq ignore_nice_load value = preferences.getInt(c.getString(R.string.key_lulzactiveq_ignore_nice_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/ignore_nice_load\n"); } // lulzactiveq max_cpu_lock value = preferences.getInt(c.getString(R.string.key_lulzactiveq_max_cpu_lock), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/max_cpu_lock\n"); } // lulzactiveq min_cpu_lock value = preferences.getInt(c.getString(R.string.key_lulzactiveq_min_cpu_lock), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/min_cpu_lock\n"); } // lulzactiveq hotplug_freq_1_1 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_freq_1_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_freq_1_1\n"); } // lulzactiveq hotplug_freq_2_0 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_freq_2_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_freq_2_0\n"); } // lulzactiveq hotplug_freq_2_1 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_freq_2_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_freq_2_1\n"); } // lulzactiveq hotplug_freq_3_0 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_freq_3_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_freq_3_0\n"); } // lulzactiveq hotplug_freq_3_1 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_freq_3_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_freq_3_1\n"); } // lulzactiveq hotplug_freq_4_0 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_freq_4_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_freq_4_0\n"); } // lulzactiveq hotplug_rq_1_1 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_rq_1_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_rq_1_1\n"); } // lulzactiveq hotplug_rq_2_0 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_rq_2_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_rq_2_0\n"); } // lulzactiveq hotplug_rq_2_1 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_rq_2_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_rq_2_1\n"); } // lulzactiveq hotplug_rq_3_0 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_rq_3_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_rq_3_0\n"); } // lulzactiveq hotplug_rq_3_1 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_rq_3_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_rq_3_1\n"); } // lulzactiveq hotplug_rq_4_0 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_rq_4_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_rq_4_0\n"); } // lulzactiveq hotplug_sampling_rate value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_sampling_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_sampling_rate\n"); } // lulzactiveq up_nr_cpus value = preferences.getInt(c.getString(R.string.key_lulzactiveq_up_nr_cpus), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/up_nr_cpus\n"); } // lulzactiveq hotplug_lock value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_lock), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_lock\n"); } }else if(status.equals("hotplug")) { // set this parameter only if active governor = hotplug value = preferences.getInt(c.getString(R.string.key_hotplug_up_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/hotplug/up_threshold\n"); } value = preferences.getInt(c.getString(R.string.key_hotplug_down_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/hotplug/down_threshold\n"); } value = preferences.getInt(c.getString(R.string.key_hotplug_sampling_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/hotplug/sampling_rate\n"); } value = preferences.getInt(c.getString(R.string.key_hotplug_ignore_nice_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/hotplug/ignore_nice_load\n"); } value = preferences.getInt(c.getString(R.string.key_hotplug_io_is_busy), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/hotplug/io_is_busy\n"); } value = preferences.getInt(c.getString(R.string.key_hotplug_down_differential), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/hotplug/down_differential\n"); } value = preferences.getInt(c.getString(R.string.key_hotplug_in_sampling_periods), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/hotplug/hotplug_in_sampling_periods\n"); } value = preferences.getInt(c.getString(R.string.key_hotplug_out_sampling_periods), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/hotplug/hotplug_out_sampling_periods\n"); } } else if(status.equals("devilq")) { // set this parameter only if active governor = devilq // devilq inc_cpu_load value = preferences.getInt(c.getString(R.string.key_devilq_inc_cpu_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/inc_cpu_load\n"); } value = preferences.getInt(c.getString(R.string.key_devilq_dec_cpu_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/inc_dec_load\n"); } // devilq up_sample_time value = preferences.getInt(c.getString(R.string.key_devilq_up_sample_time), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/up_sample_time\n"); } // devilq down_sample_time value = preferences.getInt(c.getString(R.string.key_devilq_down_sample_time), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/down_sample_time\n"); } // devilq cpu_up_rate value = preferences.getInt(c.getString(R.string.key_devilq_cpu_up_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/cpu_up_rate\n"); } // devilq cpu_down_rate value = preferences.getInt(c.getString(R.string.key_devilq_cpu_down_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/cpu_down_rate\n"); } value = preferences.getInt(c.getString(R.string.key_devilq_early_demand), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/early_demand\n"); if (value == 1) { value = preferences.getInt(c.getString(R.string.key_devilq_grad_up_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/grad_up_threshold\n"); } value = preferences.getInt(c.getString(R.string.key_devilq_grad_down_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/grad_down_threshold\n"); } } } // devilq ignore_nice_load value = preferences.getInt(c.getString(R.string.key_devilq_ignore_nice_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/ignore_nice_load\n"); } // devilq max_cpu_lock value = preferences.getInt(c.getString(R.string.key_devilq_max_cpu_lock), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/max_cpu_lock\n"); } // devilq min_cpu_lock value = preferences.getInt(c.getString(R.string.key_devilq_min_cpu_lock), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/min_cpu_lock\n"); } // devilq hotplug_freq_1_1 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_freq_1_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_freq_1_1\n"); } // devilq hotplug_freq_2_0 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_freq_2_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_freq_2_0\n"); } // devilq hotplug_freq_2_1 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_freq_2_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_freq_2_1\n"); } // devilq hotplug_freq_3_0 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_freq_3_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_freq_3_0\n"); } // devilq hotplug_freq_3_1 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_freq_3_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_freq_3_1\n"); } // devilq hotplug_freq_4_0 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_freq_4_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_freq_4_0\n"); } // devilq hotplug_rq_1_1 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_rq_1_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_rq_1_1\n"); } // devilq hotplug_rq_2_0 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_rq_2_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_rq_2_0\n"); } // devilq hotplug_rq_2_1 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_rq_2_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_rq_2_1\n"); } // devilq hotplug_rq_3_0 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_rq_3_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_rq_3_0\n"); } // devilq hotplug_rq_3_1 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_rq_3_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_rq_3_1\n"); } // devilq hotplug_rq_4_0 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_rq_4_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_rq_4_0\n"); } // devilq hotplug_sampling_rate value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_sampling_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_sampling_rate\n"); } // devilq up_nr_cpus value = preferences.getInt(c.getString(R.string.key_devilq_up_nr_cpus), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/up_nr_cpus\n"); } // devilq hotplug_lock value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_lock), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_lock\n"); } value = preferences.getInt(c.getString(R.string.key_devilq_suspend_max_cpu), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/suspend_max_cpu\n"); } } // battery value = preferences.getInt(c.getString(R.string.key_dcp_ac_input_curr), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/platform/samsung-battery/dcp_ac_input_curr\n"); } value = preferences.getInt(c.getString(R.string.key_dcp_ac_chrg_curr), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/platform/samsung-battery/dcp_ac_chrg_curr\n"); } value = preferences.getInt(c.getString(R.string.key_sdp_input_curr), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/platform/samsung-battery/sdp_input_curr\n"); } value = preferences.getInt(c.getString(R.string.key_sdp_chrg_curr), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/platform/samsung-battery/sdp_chrg_curr\n"); } value = preferences.getInt(c.getString(R.string.key_cdp_input_curr), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/platform/samsung-battery/cdp_input_curr\n"); } value = preferences.getInt(c.getString(R.string.key_cdp_chrg_curr), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/platform/samsung-battery/cdp_chrg_curr\n"); } value = preferences.getInt(c.getString(R.string.key_batt_chrg_soft_volt), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/platform/samsung-battery/batt_chrg_soft_volt\n"); } value = preferences.getInt(c.getString(R.string.key_ignore_stable_margin), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/platform/samsung-battery/ignore_stable_margin\n"); } value = preferences.getInt(c.getString(R.string.key_ignore_unstable_power), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/platform/samsung-battery/ignore_unstable_power\n"); } // cmled value = preferences.getInt(c.getString(R.string.key_cmled_bltimeout), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/class/misc/notification/bl_timeout\n"); } // cmled blink value = preferences.getInt(c.getString(R.string.key_cmled_blink), -1); if(value > -1) { // we must write blinktimeout before blink status // coz if we write blinktimeout it will reset blink status to enabled int timeout = preferences.getInt(c.getString(R.string.key_cmled_blinktimeout), -1); if(timeout > -1) command.append("echo " + timeout + ">" + "/sys/class/misc/notification/blinktimeout\n"); command.append("echo " + value + " > " + "/sys/class/misc/notification/blink\n"); } // gpu for (String filePath : GpuFragment.GPU_CLOCK_FILE_PATH) { status = preferences.getString(filePath, "-1"); if(!status.equals("-1")) command.append("echo " + status + " > " + filePath + "\n"); } status = preferences.getString(c.getString(R.string.key_malivolt_pref), "-1"); if(!status.equals("-1")) { command.append("echo " + status + " > " + "/sys/class/misc/mali_control/voltage_control\n"); } // io scheduler status = preferences.getString(c.getString(R.string.key_iosched), "-1"); if(!status.equals("-1")) { String[] ioscheds = c.getResources().getStringArray(R.array.iosched_interfaces); for(String i: ioscheds) { command.append("echo " + status + " > " + i + "\n"); } } // Liveoc target low int ocTargetLow = preferences.getInt(c.getString(R.string.key_liveoc_target_low), -1); if(ocTargetLow > -1) { command.append("echo " + ocTargetLow + " > " + "/sys/class/misc/liveoc/oc_target_low\n"); } // Liveoc target high int ocTargetHigh = preferences.getInt(c.getString(R.string.key_liveoc_target_high), -1); if(ocTargetHigh > -1) { command.append("echo " + ocTargetHigh + " > " + "/sys/class/misc/liveoc/oc_target_high\n"); } // Liveoc value = preferences.getInt(c.getString(R.string.key_liveoc), -1); if(value > -1 && value != 100) { // first make sure live oc at 100 then set cpu min and max freq command.append("echo 100 > " + "/sys/class/misc/liveoc/oc_value\n"); // cpu minfreq int minFreq = preferences.getInt(c.getString(R.string.key_min_cpufreq), -1); if(minFreq > -1) { if(minFreq >= ocTargetLow) { minFreq = minFreq * 100 / value; } command.append("echo " + minFreq + " > " + "/sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq\n"); } // cpu maxfreq int maxFreq = preferences.getInt(c.getString(R.string.key_max_cpufreq), -1); if(maxFreq > -1) { if(minFreq <= ocTargetHigh) { maxFreq = maxFreq * 100 / value; } command.append("echo " + maxFreq + " > " + "/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq\n"); } // now set liveoc value command.append("echo " + value + " > " + "/sys/class/misc/liveoc/oc_value\n"); }else { // make sure liveoc at 100 command.append("echo 100 > " + "/sys/class/misc/liveoc/oc_value\n"); // cpu minfreq int minFreq = preferences.getInt(c.getString(R.string.key_min_cpufreq), -1); if(minFreq > -1) { command.append("echo " + minFreq + " > " + "/sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq\n"); } // cpu maxfreq int maxFreq = preferences.getInt(c.getString(R.string.key_max_cpufreq), -1); if(maxFreq > -1) { command.append("echo " + maxFreq + " > " + "/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq\n"); } } return command.toString(); }
private static String buildCommand(Context c, SharedPreferences preferences) { StringBuilder command = new StringBuilder(); String status = null; String filepath = null; int value = -1; if(!preferences.getBoolean(c.getString(R.string.key_default_voltage), true)) { // restore voltage setting if and only if key_default_voltage is false // customvoltage // ----------------- // arm voltages value = preferences.getInt(c.getString(R.string.key_max_arm_volt), -1); if(value > -1) { String armvolts = preferences.getString(c.getString(R.string.key_arm_volt_pref), "0"); command.append("echo " + value + " > " + "/sys/class/misc/customvoltage/max_arm_volt\n"); command.append("echo " + armvolts + " > " + "/sys/class/misc/customvoltage/arm_volt\n"); }else { // uv_mv_table status = preferences.getString(c.getString(R.string.key_uvmvtable_pref), "-1"); if(!status.equals("-1")) { command.append("echo " + status + " > " + "/sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table\n"); } } // int voltages value = preferences.getInt(c.getString(R.string.key_max_int_volt), -1); if(value > -1) { String armvolts = preferences.getString(c.getString(R.string.key_int_volt_pref), "0"); command.append("echo " + value + " > " + "/sys/class/misc/customvoltage/max_int_volt\n"); command.append("echo " + armvolts + " > " + "/sys/class/misc/customvoltage/int_volt\n"); } } // Audio value = preferences.getInt(c.getString(R.string.key_speaker_tuning), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/speaker_tuning\n"); } value = preferences.getInt(c.getString(R.string.key_speaker_offset), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/speaker_offset\n"); } value = preferences.getInt(c.getString(R.string.key_headphone_amplifier_level), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/headphone_amplifier_level\n"); } value = preferences.getInt(c.getString(R.string.key_stereo_expansion), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/stereo_expansion\n"); } value = preferences.getInt(c.getString(R.string.key_stereo_expansion_gain), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/stereo_expansion_gain\n"); } value = preferences.getInt(c.getString(R.string.key_headphone_eq), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/headphone_eq\n"); } value = preferences.getInt(c.getString(R.string.key_headphone_eq_b1_gain), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/headphone_eq_b1_gain\n"); } value = preferences.getInt(c.getString(R.string.key_headphone_eq_b2_gain), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/headphone_eq_b2_gain\n"); } value = preferences.getInt(c.getString(R.string.key_headphone_eq_b3_gain), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/headphone_eq_b3_gain\n"); } value = preferences.getInt(c.getString(R.string.key_headphone_eq_b4_gain), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/headphone_eq_b4_gain\n"); } value = preferences.getInt(c.getString(R.string.key_headphone_eq_b5_gain), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/headphone_eq_b5_gain\n"); } value = preferences.getInt(c.getString(R.string.key_fll_tuning), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/fll_tuning\n"); } value = preferences.getInt(c.getString(R.string.key_dac_osr128), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/dac_osr128\n"); } value = preferences.getInt(c.getString(R.string.key_adc_osr128), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/adc_osr128\n"); } value = preferences.getInt(c.getString(R.string.key_dac_direct), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/dac_direct\n"); } value = preferences.getInt(c.getString(R.string.key_mono_downmix), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/virtual/misc/scoobydoo_sound/mono_downmix\n"); } // BLD value = preferences.getInt(c.getString(R.string.key_bld_status), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/class/misc/backlightdimmer/enabled\n"); value = preferences.getInt(c.getString(R.string.key_bld_delay), -1); if(value > -1) command.append("echo " + value + " > " + "/sys/class/misc/backlightdimmer/delay\n"); } // BLN value = preferences.getInt(c.getString(R.string.key_bln_status), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/class/misc/backlightnotification/enabled\n"); value = preferences.getInt(c.getString(R.string.key_bln_blink), -1); if(value > -1) command.append("echo " + value + " > " + "/sys/class/misc/backlightnotification/in_kernel_blink\n"); value = preferences.getInt(c.getString(R.string.key_bln_blink_interval), -1); if(value > -1) command.append("echo " + value + " > " + "/sys/class/misc/backlightnotification/blink_interval\n"); value = preferences.getInt(c.getString(R.string.key_bln_blink_count), -1); if(value > -1) command.append("echo " + value + " > " + "/sys/class/misc/backlightnotification/max_blink_count\n"); } // BLX value = preferences.getInt(c.getString(R.string.key_blx_charging_limit), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/class/misc/batterylifeextender/charging_limit\n"); } //color if(!ColorTuningPreference.isVoodoo()) { //no voodoo for (String filePath : ColorTuningPreference.FILE_PATH) { value = preferences.getInt(filePath, ColorTuningPreference.MAX_VALUE); command.append("echo " + value + " > " + filePath + "\n"); } for (String filePath : ColorTuningPreference.GAMMA_FILE_PATH) { value = preferences.getInt(filePath, ColorTuningPreference.GAMMA_DEFAULT_VALUE); command.append("echo " + value + " > " + filePath + "\n"); } } else { // try voodoo for (String filePath : ColorTuningPreference.VOODOO_FILE_PATH) { value = preferences.getInt(filePath, ColorTuningPreference.MAX_VALUE); command.append("echo " + value + " > " + filePath + "\n"); } for (String filePath : ColorTuningPreference.VOODOO_GAMMA_FILE_PATH) { value = (preferences.getInt(filePath, ColorTuningPreference.GAMMA_DEFAULT_VALUE) -40); command.append("echo " + value + " > " + filePath + "\n"); } } // Mdnie filepath = Mdnie.FILE; value = Integer.parseInt(preferences.getString(filepath, "-1")); if(value > -1) { command.append("echo " + value + " > " + filepath + "\n"); } // Deepidle value = preferences.getInt(c.getString(R.string.key_deepidle_status), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/class/misc/deepidle/enabled\n"); } // Smooth Ui value = preferences.getInt(c.getString(R.string.key_smooth_ui_enabled), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/class/misc/devil_tweaks/smooth_ui_enabled\n"); } // Dyn Fsync value = preferences.getInt(c.getString(R.string.key_dyn_fsync), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/kernel/dyn_fsync/Dyn_fsync_active\n"); } // vibrator value = preferences.getInt(c.getString(R.string.key_vibration_intensity), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/class/misc/pwm_duty/pwm_duty\n"); } // Touchwake value = preferences.getInt(c.getString(R.string.key_touchwake_status), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/class/misc/touchwake/enabled\n"); value = preferences.getInt(c.getString(R.string.key_touchwake_delay), -1); if(value > -1) command.append("echo " + value + " > " + "/sys/class/misc/touchwake/delay\n"); } // TouchBoost value = preferences.getInt(c.getString(R.string.key_touch_boost_enabled), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/class/misc/touchboost/input_boost_enabled\n"); value = preferences.getInt(c.getString(R.string.key_touch_boost_freq), -1); if(value > -1) command.append("echo " + value + " > " + "/sys/class/misc/touchboost/input_boost_freq\n"); } // bigmem value = Integer.parseInt(preferences.getString(c.getString(R.string.key_bigmem), "-1")); if(value > -1) { command.append("echo " + value + " > " + "/sys/kernel/bigmem/enable\n"); } // governor status = preferences.getString(c.getString(R.string.key_governor), "-1"); if(!status.equals("-1")) { command.append("echo " + status + " > " + "/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor\n"); } // governor's parameters if(status.equals("lazy")) { // set this parameter only if active governor = lazy // lazy screenoff max freq value = preferences.getInt(c.getString(R.string.key_screenoff_maxfreq), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lazy/screenoff_maxfreq\n"); } }else if(status.equals("ondemand")) { // set this parameter only if active governor = ondemand value = preferences.getInt(c.getString(R.string.key_ondemand_sampling_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/ondemand/sampling_rate\n"); } value = preferences.getInt(c.getString(R.string.key_ondemand_up_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/ondemand/up_threshold\n"); } value = preferences.getInt(c.getString(R.string.key_ondemand_sampling_down_factor), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/ondemand/sampling_down_factor\n"); } value = preferences.getInt(c.getString(R.string.key_ondemand_powersave_bias), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/ondemand/powersave_bias\n"); } value = preferences.getInt(c.getString(R.string.key_ondemand_early_demand), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/ondemand/early_demand\n"); if (value == 1) { value = preferences.getInt(c.getString(R.string.key_ondemand_grad_up_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/ondemand/grad_up_threshold\n"); } } } value = preferences.getInt(c.getString(R.string.key_ondemand_sleep_up_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/ondemand/sleep_up_threshold\n"); } value = preferences.getInt(c.getString(R.string.key_ondemand_sleep_sampling_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/ondemand/sleep_sampling_rate\n"); } }else if(status.equals("conservative")) { // set this parameter only if active governor = conservative value = preferences.getInt(c.getString(R.string.key_conservative_sampling_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/sampling_rate\n"); } value = preferences.getInt(c.getString(R.string.key_conservative_down_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/down_threshold\n"); } value = preferences.getInt(c.getString(R.string.key_conservative_up_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/up_threshold\n"); } value = preferences.getInt(c.getString(R.string.key_conservative_sampling_down_factor), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/sampling_down_factor\n"); } value = preferences.getInt(c.getString(R.string.key_conservative_freq_step), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/freq_step\n"); } value = preferences.getInt(c.getString(R.string.key_conservative_ignore_nice_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/ignore_nice_load\n"); } value = preferences.getInt(c.getString(R.string.key_conservative_smooth_up_enabled), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/smooth_up_enabled\n"); if (value == 1) { value = preferences.getInt(c.getString(R.string.key_conservative_smooth_up), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/smooth_up\n"); } } } value = preferences.getInt(c.getString(R.string.key_conservative_sleep_up_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/sleep_up_threshold\n"); } value = preferences.getInt(c.getString(R.string.key_conservative_sleep_sampling_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/conservative/sleep_sampling_rate\n"); } }else if(status.equals("smartassV2")) { // set this parameter only if active governor = smartass2 value = preferences.getInt(c.getString(R.string.key_smartass_awake_ideal_freq), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/smartass/awake_ideal_freq\n"); } value = preferences.getInt(c.getString(R.string.key_smartass_sleep_ideal_freq), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/smartass/sleep_ideal_freq\n"); } value = preferences.getInt(c.getString(R.string.key_smartass_sleep_wakeup_freq), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/smartass/sleep_wakeup_freq\n"); } value = preferences.getInt(c.getString(R.string.key_smartass_min_cpu_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/smartass/min_cpu_load\n"); } value = preferences.getInt(c.getString(R.string.key_smartass_max_cpu_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/smartass/max_cpu_load\n"); } value = preferences.getInt(c.getString(R.string.key_smartass_ramp_down_step), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/smartass/ramp_down_step\n"); } value = preferences.getInt(c.getString(R.string.key_smartass_ramp_up_step), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/smartass/ramp_up_step\n"); } value = preferences.getInt(c.getString(R.string.key_smartass_down_rate_us), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/smartass/down_rate_us\n"); } value = preferences.getInt(c.getString(R.string.key_smartass_up_rate_us), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/smartass/up_rate_us\n"); } }else if(status.equals("interactive")) { // set this parameter only if active governor = interactive value = preferences.getInt(c.getString(R.string.key_interactive_go_hispeed_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/interactive/go_hispeed_load\n"); } value = preferences.getInt(c.getString(R.string.key_interactive_target_loads), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/interactive/target_loads\n"); } value = preferences.getInt(c.getString(R.string.key_interactive_hispeed_freq), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/interactive/hispeed_freq\n"); } value = preferences.getInt(c.getString(R.string.key_interactive_min_sample_time), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/interactive/min_sample_time\n"); } value = preferences.getInt(c.getString(R.string.key_interactive_timer_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/interactive/timer_rate\n"); } }else if(status.equals("lulzactive")) { // set this parameter only if active governor = lulzactive // lulzactive inc_cpu_load value = preferences.getInt(c.getString(R.string.key_lulzactive_inc_cpu_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactive/inc_cpu_load\n"); } // lulzactive pump_up_step value = preferences.getInt(c.getString(R.string.key_lulzactive_pump_up_step), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactive/pump_up_step\n"); } // lulzactive pump_down_step value = preferences.getInt(c.getString(R.string.key_lulzactive_pump_down_step), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactive/pump_down_step\n"); } // lulzactive screen_off_min_step value = preferences.getInt(c.getString(R.string.key_lulzactive_screen_off_min_step), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactive/screen_off_min_step\n"); } // lulzactive up_sample_time value = preferences.getInt(c.getString(R.string.key_lulzactive_up_sample_time), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactive/up_sample_time\n"); } // lulzactive down_sample_time value = preferences.getInt(c.getString(R.string.key_lulzactive_down_sample_time), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactive/down_sample_time\n"); } }else if(status.equals("lulzactiveq")) { // set this parameter only if active governor = lulzactiveq // lulzactiveq hispeed_freq value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hispeed_freq), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hispeed_freq\n"); } // lulzactiveq inc_cpu_load value = preferences.getInt(c.getString(R.string.key_lulzactiveq_inc_cpu_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/inc_cpu_load\n"); } // lulzactiveq pump_up_step value = preferences.getInt(c.getString(R.string.key_lulzactiveq_pump_up_step), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/pump_up_step\n"); } // lulzactiveq pump_down_step value = preferences.getInt(c.getString(R.string.key_lulzactiveq_pump_down_step), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/pump_down_step\n"); } // lulzactiveq screen_off_max_step value = preferences.getInt(c.getString(R.string.key_lulzactiveq_screen_off_max_step), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/screen_off_max_step\n"); } // lulzactiveq up_sample_time value = preferences.getInt(c.getString(R.string.key_lulzactiveq_up_sample_time), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/up_sample_time\n"); } // lulzactiveq down_sample_time value = preferences.getInt(c.getString(R.string.key_lulzactiveq_down_sample_time), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/down_sample_time\n"); } // lulzactiveq cpu_up_rate value = preferences.getInt(c.getString(R.string.key_lulzactiveq_cpu_up_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/cpu_up_rate\n"); } // lulzactiveq cpu_down_rate value = preferences.getInt(c.getString(R.string.key_lulzactiveq_cpu_down_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/cpu_down_rate\n"); } // lulzactiveq ignore_nice_load value = preferences.getInt(c.getString(R.string.key_lulzactiveq_ignore_nice_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/ignore_nice_load\n"); } // lulzactiveq max_cpu_lock value = preferences.getInt(c.getString(R.string.key_lulzactiveq_max_cpu_lock), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/max_cpu_lock\n"); } // lulzactiveq min_cpu_lock value = preferences.getInt(c.getString(R.string.key_lulzactiveq_min_cpu_lock), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/min_cpu_lock\n"); } // lulzactiveq hotplug_freq_1_1 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_freq_1_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_freq_1_1\n"); } // lulzactiveq hotplug_freq_2_0 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_freq_2_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_freq_2_0\n"); } // lulzactiveq hotplug_freq_2_1 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_freq_2_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_freq_2_1\n"); } // lulzactiveq hotplug_freq_3_0 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_freq_3_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_freq_3_0\n"); } // lulzactiveq hotplug_freq_3_1 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_freq_3_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_freq_3_1\n"); } // lulzactiveq hotplug_freq_4_0 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_freq_4_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_freq_4_0\n"); } // lulzactiveq hotplug_rq_1_1 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_rq_1_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_rq_1_1\n"); } // lulzactiveq hotplug_rq_2_0 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_rq_2_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_rq_2_0\n"); } // lulzactiveq hotplug_rq_2_1 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_rq_2_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_rq_2_1\n"); } // lulzactiveq hotplug_rq_3_0 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_rq_3_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_rq_3_0\n"); } // lulzactiveq hotplug_rq_3_1 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_rq_3_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_rq_3_1\n"); } // lulzactiveq hotplug_rq_4_0 value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_rq_4_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_rq_4_0\n"); } // lulzactiveq hotplug_sampling_rate value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_sampling_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_sampling_rate\n"); } // lulzactiveq up_nr_cpus value = preferences.getInt(c.getString(R.string.key_lulzactiveq_up_nr_cpus), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/up_nr_cpus\n"); } // lulzactiveq hotplug_lock value = preferences.getInt(c.getString(R.string.key_lulzactiveq_hotplug_lock), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/lulzactiveq/hotplug_lock\n"); } }else if(status.equals("hotplug")) { // set this parameter only if active governor = hotplug value = preferences.getInt(c.getString(R.string.key_hotplug_up_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/hotplug/up_threshold\n"); } value = preferences.getInt(c.getString(R.string.key_hotplug_down_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/hotplug/down_threshold\n"); } value = preferences.getInt(c.getString(R.string.key_hotplug_sampling_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/hotplug/sampling_rate\n"); } value = preferences.getInt(c.getString(R.string.key_hotplug_ignore_nice_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/hotplug/ignore_nice_load\n"); } value = preferences.getInt(c.getString(R.string.key_hotplug_io_is_busy), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/hotplug/io_is_busy\n"); } value = preferences.getInt(c.getString(R.string.key_hotplug_down_differential), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/hotplug/down_differential\n"); } value = preferences.getInt(c.getString(R.string.key_hotplug_in_sampling_periods), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/hotplug/hotplug_in_sampling_periods\n"); } value = preferences.getInt(c.getString(R.string.key_hotplug_out_sampling_periods), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/hotplug/hotplug_out_sampling_periods\n"); } } else if(status.equals("devilq")) { // set this parameter only if active governor = devilq // devilq inc_cpu_load value = preferences.getInt(c.getString(R.string.key_devilq_inc_cpu_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/inc_cpu_load\n"); } value = preferences.getInt(c.getString(R.string.key_devilq_dec_cpu_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/inc_dec_load\n"); } // devilq up_sample_time value = preferences.getInt(c.getString(R.string.key_devilq_up_sample_time), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/up_sample_time\n"); } // devilq down_sample_time value = preferences.getInt(c.getString(R.string.key_devilq_down_sample_time), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/down_sample_time\n"); } // devilq cpu_up_rate value = preferences.getInt(c.getString(R.string.key_devilq_cpu_up_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/cpu_up_rate\n"); } // devilq cpu_down_rate value = preferences.getInt(c.getString(R.string.key_devilq_cpu_down_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/cpu_down_rate\n"); } value = preferences.getInt(c.getString(R.string.key_devilq_early_demand), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/early_demand\n"); if (value == 1) { value = preferences.getInt(c.getString(R.string.key_devilq_grad_up_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/grad_up_threshold\n"); } value = preferences.getInt(c.getString(R.string.key_devilq_grad_down_threshold), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/grad_down_threshold\n"); } } } // devilq ignore_nice_load value = preferences.getInt(c.getString(R.string.key_devilq_ignore_nice_load), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/ignore_nice_load\n"); } // devilq max_cpu_lock value = preferences.getInt(c.getString(R.string.key_devilq_max_cpu_lock), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/max_cpu_lock\n"); } // devilq min_cpu_lock value = preferences.getInt(c.getString(R.string.key_devilq_min_cpu_lock), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/min_cpu_lock\n"); } // devilq hotplug_freq_1_1 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_freq_1_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_freq_1_1\n"); } // devilq hotplug_freq_2_0 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_freq_2_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_freq_2_0\n"); } // devilq hotplug_freq_2_1 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_freq_2_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_freq_2_1\n"); } // devilq hotplug_freq_3_0 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_freq_3_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_freq_3_0\n"); } // devilq hotplug_freq_3_1 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_freq_3_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_freq_3_1\n"); } // devilq hotplug_freq_4_0 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_freq_4_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_freq_4_0\n"); } // devilq hotplug_rq_1_1 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_rq_1_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_rq_1_1\n"); } // devilq hotplug_rq_2_0 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_rq_2_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_rq_2_0\n"); } // devilq hotplug_rq_2_1 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_rq_2_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_rq_2_1\n"); } // devilq hotplug_rq_3_0 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_rq_3_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_rq_3_0\n"); } // devilq hotplug_rq_3_1 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_rq_3_1), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_rq_3_1\n"); } // devilq hotplug_rq_4_0 value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_rq_4_0), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_rq_4_0\n"); } // devilq hotplug_sampling_rate value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_sampling_rate), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_sampling_rate\n"); } // devilq up_nr_cpus value = preferences.getInt(c.getString(R.string.key_devilq_up_nr_cpus), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/up_nr_cpus\n"); } // devilq hotplug_lock value = preferences.getInt(c.getString(R.string.key_devilq_hotplug_lock), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/hotplug_lock\n"); } value = preferences.getInt(c.getString(R.string.key_devilq_suspend_max_cpu), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/system/cpu/cpufreq/devilq/suspend_max_cpu\n"); } } // battery value = preferences.getInt(c.getString(R.string.key_dcp_ac_input_curr), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/platform/samsung-battery/dcp_ac_input_curr\n"); } value = preferences.getInt(c.getString(R.string.key_dcp_ac_chrg_curr), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/platform/samsung-battery/dcp_ac_chrg_curr\n"); } value = preferences.getInt(c.getString(R.string.key_sdp_input_curr), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/platform/samsung-battery/sdp_input_curr\n"); } value = preferences.getInt(c.getString(R.string.key_sdp_chrg_curr), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/platform/samsung-battery/sdp_chrg_curr\n"); } value = preferences.getInt(c.getString(R.string.key_cdp_input_curr), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/platform/samsung-battery/cdp_input_curr\n"); } value = preferences.getInt(c.getString(R.string.key_cdp_chrg_curr), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/platform/samsung-battery/cdp_chrg_curr\n"); } value = preferences.getInt(c.getString(R.string.key_batt_chrg_soft_volt), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/platform/samsung-battery/batt_chrg_soft_volt\n"); } value = preferences.getInt(c.getString(R.string.key_ignore_stable_margin), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/platform/samsung-battery/ignore_stable_margin\n"); } value = preferences.getInt(c.getString(R.string.key_ignore_unstable_power), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/devices/platform/samsung-battery/ignore_unstable_power\n"); } // cmled value = preferences.getInt(c.getString(R.string.key_cmled_bltimeout), -1); if(value > -1) { command.append("echo " + value + " > " + "/sys/class/misc/notification/bl_timeout\n"); } // cmled blink value = preferences.getInt(c.getString(R.string.key_cmled_blink), -1); if(value > -1) { // we must write blinktimeout before blink status // coz if we write blinktimeout it will reset blink status to enabled int timeout = preferences.getInt(c.getString(R.string.key_cmled_blinktimeout), -1); if(timeout > -1) command.append("echo " + timeout + ">" + "/sys/class/misc/notification/blinktimeout\n"); command.append("echo " + value + " > " + "/sys/class/misc/notification/blink\n"); } // gpu for (String filePath : GpuFragment.GPU_CLOCK_FILE_PATH) { status = preferences.getString(filePath, "-1"); if(!status.equals("-1")) command.append("echo " + status + " > " + filePath + "\n"); } status = preferences.getString(c.getString(R.string.key_malivolt_pref), "-1"); if(!status.equals("-1")) { command.append("echo " + status + " > " + "/sys/class/misc/mali_control/voltage_control\n"); } // io scheduler status = preferences.getString(c.getString(R.string.key_iosched), "-1"); if(!status.equals("-1")) { String[] ioscheds = c.getResources().getStringArray(R.array.iosched_interfaces); for(String i: ioscheds) { command.append("echo " + status + " > " + i + "\n"); } } // Liveoc target low int ocTargetLow = preferences.getInt(c.getString(R.string.key_liveoc_target_low), -1); if(ocTargetLow > -1) { command.append("echo " + ocTargetLow + " > " + "/sys/class/misc/liveoc/oc_target_low\n"); } // Liveoc target high int ocTargetHigh = preferences.getInt(c.getString(R.string.key_liveoc_target_high), -1); if(ocTargetHigh > -1) { command.append("echo " + ocTargetHigh + " > " + "/sys/class/misc/liveoc/oc_target_high\n"); } // Liveoc value = preferences.getInt(c.getString(R.string.key_liveoc), -1); if(value > -1 && value != 100) { // first make sure live oc at 100 then set cpu min and max freq command.append("echo 100 > " + "/sys/class/misc/liveoc/oc_value\n"); // cpu minfreq int minFreq = preferences.getInt(c.getString(R.string.key_min_cpufreq), -1); if(minFreq > -1) { if(minFreq >= ocTargetLow) { minFreq = minFreq * 100 / value; } command.append("echo " + minFreq + " > " + "/sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq\n"); } // cpu maxfreq int maxFreq = preferences.getInt(c.getString(R.string.key_max_cpufreq), -1); if(maxFreq > -1) { if(minFreq <= ocTargetHigh) { maxFreq = maxFreq * 100 / value; } command.append("echo " + maxFreq + " > " + "/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq\n"); } // now set liveoc value command.append("echo " + value + " > " + "/sys/class/misc/liveoc/oc_value\n"); }else { // make sure liveoc at 100 command.append("echo 100 > " + "/sys/class/misc/liveoc/oc_value\n"); // cpu minfreq int minFreq = preferences.getInt(c.getString(R.string.key_min_cpufreq), -1); if(minFreq > -1) { command.append("echo " + minFreq + " > " + "/sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq\n"); } // cpu maxfreq int maxFreq = preferences.getInt(c.getString(R.string.key_max_cpufreq), -1); if(maxFreq > -1) { command.append("echo " + maxFreq + " > " + "/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq\n"); } } return command.toString(); }
diff --git a/main/src/cgeo/geocaching/cgeoimages.java b/main/src/cgeo/geocaching/cgeoimages.java index 40adc00d5..c177bf24a 100644 --- a/main/src/cgeo/geocaching/cgeoimages.java +++ b/main/src/cgeo/geocaching/cgeoimages.java @@ -1,212 +1,212 @@ package cgeo.geocaching; import cgeo.geocaching.activity.AbstractActivity; import org.apache.commons.lang3.StringUtils; import android.app.ProgressDialog; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.text.Html; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.io.File; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; public class cgeoimages extends AbstractActivity { private static final int UNKNOWN_TYPE = 0; public static final int LOG_IMAGES = 1; public static final int SPOILER_IMAGES = 2; private String geocode = null; private LayoutInflater inflater = null; private ProgressDialog progressDialog = null; private LinearLayout imagesView = null; private int count = 0; private int countDone = 0; static private Collection<Bitmap> bitmaps = Collections.synchronizedCollection(new ArrayList<Bitmap>()); private void loadImages(final List<cgImage> images, final int progressMessage, final boolean save, final boolean offline) { count = images.size(); progressDialog = new ProgressDialog(cgeoimages.this); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setMessage(res.getString(progressMessage)); progressDialog.setCancelable(true); progressDialog.setMax(count); progressDialog.show(); LinearLayout rowView = null; for (final cgImage img : images) { rowView = (LinearLayout) inflater.inflate(R.layout.cache_image_item, null); ((TextView) rowView.findViewById(R.id.title)).setText(Html.fromHtml(img.title)); if (StringUtils.isNotBlank(img.description)) { final TextView descView = (TextView) rowView.findViewById(R.id.description); descView.setText(Html.fromHtml(img.description), TextView.BufferType.SPANNABLE); descView.setVisibility(View.VISIBLE); } new AsyncImgLoader(rowView, img, save, offline).execute(); imagesView.addView(rowView); } } private class AsyncImgLoader extends AsyncTask<Void, Void, BitmapDrawable> { final private LinearLayout view; final private cgImage img; final private boolean save; final boolean offline; public AsyncImgLoader(final LinearLayout view, final cgImage img, final boolean save, final boolean offline) { this.view = view; this.img = img; this.save = save; this.offline = offline; } @Override protected BitmapDrawable doInBackground(Void... params) { final cgHtmlImg imgGetter = new cgHtmlImg(cgeoimages.this, geocode, true, offline ? 1 : 0, false, save); return imgGetter.getDrawable(img.url); } @Override protected void onPostExecute(final BitmapDrawable image) { if (image != null) { bitmaps.add(image.getBitmap()); final ImageView image_view = (ImageView) inflater.inflate(R.layout.image_item, null); final Rect bounds = image.getBounds(); image_view.setImageResource(R.drawable.image_not_loaded); image_view.setClickable(true); image_view.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { final String directoryTarget = Environment.getExternalStorageDirectory() + "/" + cgSettings.cache + "/" + "temp.jpg"; final File file = new File(directoryTarget); try { final FileOutputStream fos = new FileOutputStream(file); image.getBitmap().compress(CompressFormat.JPEG, 100, fos); fos.close(); } catch (Exception e) { Log.e(cgSettings.tag, "cgeoimages.handleMessage.onClick: " + e.toString()); return; } Intent intent = new Intent(); intent.setAction(android.content.Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(file), "image/jpg"); startActivity(intent); if (file.exists()) file.deleteOnExit(); } }); image_view.setImageDrawable(image); image_view.setScaleType(ImageView.ScaleType.CENTER_CROP); image_view.setLayoutParams(new LayoutParams(bounds.width(), bounds.height())); view.addView(image_view); } synchronized (cgeoimages.this) { countDone++; progressDialog.setProgress(countDone); if (progressDialog.getProgress() >= count) { progressDialog.dismiss(); } } } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // get parameters Bundle extras = getIntent().getExtras(); // try to get data from extras int img_type = UNKNOWN_TYPE; if (extras != null) { geocode = extras.getString("geocode"); img_type = extras.getInt("type", 0); } if (extras == null || geocode == null) { showToast("Sorry, c:geo forgot for what cache you want to load spoiler images."); finish(); return; } if (img_type != SPOILER_IMAGES && img_type != LOG_IMAGES) { showToast("Sorry, can't load unknown image type."); finish(); return; } // init setTheme(); setContentView(R.layout.spoilers); setTitle(res.getString(img_type == SPOILER_IMAGES ? R.string.cache_spoiler_images_title : R.string.cache_log_images_title)); inflater = getLayoutInflater(); if (imagesView == null) { imagesView = (LinearLayout) findViewById(R.id.spoiler_list); } final ArrayList<cgImage> images = extras.getParcelableArrayList("images"); if (images == null || images.isEmpty()) { - showToast(res.getString(R.string.warn_load_spoiler_image)); + showToast(res.getString(R.string.warn_load_images)); finish(); return; } final int message = img_type == SPOILER_IMAGES ? R.string.cache_spoiler_images_loading : R.string.cache_log_images_loading; final boolean offline = app.isOffline(geocode, null) && (img_type == SPOILER_IMAGES || settings.storelogimages); final boolean save = img_type == SPOILER_IMAGES ? true : settings.storelogimages; loadImages(images, message, save, offline); } @Override public void onDestroy() { // Reclaim native memory faster than the finalizers would for (Bitmap b : bitmaps) { b.recycle(); } bitmaps.clear(); super.onDestroy(); } @Override public void onResume() { super.onResume(); settings.load(); } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // get parameters Bundle extras = getIntent().getExtras(); // try to get data from extras int img_type = UNKNOWN_TYPE; if (extras != null) { geocode = extras.getString("geocode"); img_type = extras.getInt("type", 0); } if (extras == null || geocode == null) { showToast("Sorry, c:geo forgot for what cache you want to load spoiler images."); finish(); return; } if (img_type != SPOILER_IMAGES && img_type != LOG_IMAGES) { showToast("Sorry, can't load unknown image type."); finish(); return; } // init setTheme(); setContentView(R.layout.spoilers); setTitle(res.getString(img_type == SPOILER_IMAGES ? R.string.cache_spoiler_images_title : R.string.cache_log_images_title)); inflater = getLayoutInflater(); if (imagesView == null) { imagesView = (LinearLayout) findViewById(R.id.spoiler_list); } final ArrayList<cgImage> images = extras.getParcelableArrayList("images"); if (images == null || images.isEmpty()) { showToast(res.getString(R.string.warn_load_spoiler_image)); finish(); return; } final int message = img_type == SPOILER_IMAGES ? R.string.cache_spoiler_images_loading : R.string.cache_log_images_loading; final boolean offline = app.isOffline(geocode, null) && (img_type == SPOILER_IMAGES || settings.storelogimages); final boolean save = img_type == SPOILER_IMAGES ? true : settings.storelogimages; loadImages(images, message, save, offline); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // get parameters Bundle extras = getIntent().getExtras(); // try to get data from extras int img_type = UNKNOWN_TYPE; if (extras != null) { geocode = extras.getString("geocode"); img_type = extras.getInt("type", 0); } if (extras == null || geocode == null) { showToast("Sorry, c:geo forgot for what cache you want to load spoiler images."); finish(); return; } if (img_type != SPOILER_IMAGES && img_type != LOG_IMAGES) { showToast("Sorry, can't load unknown image type."); finish(); return; } // init setTheme(); setContentView(R.layout.spoilers); setTitle(res.getString(img_type == SPOILER_IMAGES ? R.string.cache_spoiler_images_title : R.string.cache_log_images_title)); inflater = getLayoutInflater(); if (imagesView == null) { imagesView = (LinearLayout) findViewById(R.id.spoiler_list); } final ArrayList<cgImage> images = extras.getParcelableArrayList("images"); if (images == null || images.isEmpty()) { showToast(res.getString(R.string.warn_load_images)); finish(); return; } final int message = img_type == SPOILER_IMAGES ? R.string.cache_spoiler_images_loading : R.string.cache_log_images_loading; final boolean offline = app.isOffline(geocode, null) && (img_type == SPOILER_IMAGES || settings.storelogimages); final boolean save = img_type == SPOILER_IMAGES ? true : settings.storelogimages; loadImages(images, message, save, offline); }
diff --git a/astrid/src/com/todoroo/astrid/adapter/FilterAdapter.java b/astrid/src/com/todoroo/astrid/adapter/FilterAdapter.java index 34ba0a27e..a63fad66f 100644 --- a/astrid/src/com/todoroo/astrid/adapter/FilterAdapter.java +++ b/astrid/src/com/todoroo/astrid/adapter/FilterAdapter.java @@ -1,505 +1,505 @@ /** * See the file "LICENSE" for the full license governing this code. */ package com.todoroo.astrid.adapter; import java.util.List; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import android.app.Activity; import android.app.PendingIntent; import android.app.PendingIntent.CanceledException; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.Color; import android.os.Bundle; import android.os.Parcelable; import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import com.timsu.astrid.R; import com.todoroo.andlib.service.Autowired; import com.todoroo.andlib.service.ContextManager; import com.todoroo.andlib.service.DependencyInjectionService; import com.todoroo.astrid.activity.AstridActivity; import com.todoroo.astrid.activity.FilterListFragment; import com.todoroo.astrid.api.AstridApiConstants; import com.todoroo.astrid.api.AstridFilterExposer; import com.todoroo.astrid.api.Filter; import com.todoroo.astrid.api.FilterCategory; import com.todoroo.astrid.api.FilterCategoryWithNewButton; import com.todoroo.astrid.api.FilterListHeader; import com.todoroo.astrid.api.FilterListItem; import com.todoroo.astrid.api.FilterWithUpdate; import com.todoroo.astrid.helper.AsyncImageView; import com.todoroo.astrid.service.TaskService; import com.todoroo.astrid.tags.TagService; public class FilterAdapter extends ArrayAdapter<Filter> { // --- style constants public int filterStyle = R.style.TextAppearance_FLA_Filter; public int headerStyle = R.style.TextAppearance_FLA_Header; // --- instance variables @Autowired private TaskService taskService; /** parent activity */ protected final Activity activity; /** owner listview */ protected final ListView listView; /** display metrics for scaling icons */ private final DisplayMetrics metrics = new DisplayMetrics(); /** receiver for new filters */ private final FilterReceiver filterReceiver = new FilterReceiver(); private final BladeFilterReceiver bladeFilterReceiver = new BladeFilterReceiver(); private boolean shouldUseBladeFilter = true; /** row layout to inflate */ private final int layout; /** layout inflater */ private final LayoutInflater inflater; /** whether to skip Filters that launch intents instead of being real filters */ private final boolean skipIntentFilters; /** whether rows are selectable */ private final boolean selectable; private int mSelectedIndex; // Previous solution involved a queue of filters and a filterSizeLoadingThread. The filterSizeLoadingThread had // a few problems: how to make sure that the thread is resumed when the controlling activity is resumed, and // how to make sure that the the filterQueue does not accumulate filters without being processed. I am replacing // both the queue and a the thread with a thread pool, which will shut itself off after a second if it has // nothing to do (corePoolSize == 0, which makes it available for garbage collection), and will wake itself up // if new filters are queued (obviously it cannot be garbage collected if it is possible for new filters to // be added). private final ThreadPoolExecutor filterExecutor = new ThreadPoolExecutor(0, 1, 1, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); public FilterAdapter(Activity activity, ListView listView, int rowLayout, boolean skipIntentFilters) { this(activity, listView, rowLayout, skipIntentFilters, false); } public FilterAdapter(Activity activity, ListView listView, int rowLayout, boolean skipIntentFilters, boolean selectable) { super(activity, 0); DependencyInjectionService.getInstance().inject(this); this.activity = activity; this.listView = listView; this.layout = rowLayout; this.skipIntentFilters = skipIntentFilters; this.selectable = selectable; if (activity instanceof AstridActivity && ((AstridActivity) activity).getFragmentLayout() != AstridActivity.LAYOUT_SINGLE) filterStyle = R.style.TextAppearance_FLA_Filter_Tablet; inflater = (LayoutInflater) activity.getSystemService( Context.LAYOUT_INFLATER_SERVICE); activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); } private void offerFilter(final Filter filter) { if(selectable && selection == null) setSelection(filter); filterExecutor.submit(new Runnable() { @Override public void run() { try { if(filter.listingTitle.matches(".* \\(\\d+\\)$")) //$NON-NLS-1$ return; int size = taskService.countTasks(filter); filter.listingTitle = filter.listingTitle + (" (" + //$NON-NLS-1$ size + ")"); //$NON-NLS-1$ activity.runOnUiThread(new Runnable() { public void run() { notifyDataSetInvalidated(); } }); } catch (Exception e) { Log.e("astrid-filter-adapter", "Error loading filter size", e); //$NON-NLS-1$ //$NON-NLS-2$ } } }); } @Override public boolean hasStableIds() { return true; } @Override public void add(Filter item) { super.add(item); // load sizes offerFilter(item); } public void setLastSelected(int lastSelected) { mSelectedIndex = lastSelected; } /** * Create or reuse a view * @param convertView * @param parent * @return */ protected View newView(View convertView, ViewGroup parent) { if(convertView == null) { convertView = inflater.inflate(layout, parent, false); ViewHolder viewHolder = new ViewHolder(); viewHolder.view = convertView; viewHolder.icon = (ImageView)convertView.findViewById(R.id.icon); viewHolder.urlImage = (AsyncImageView)convertView.findViewById(R.id.url_image); viewHolder.name = (TextView)convertView.findViewById(R.id.name); viewHolder.selected = (ImageView)convertView.findViewById(R.id.selected); viewHolder.size = (TextView)convertView.findViewById(R.id.size); viewHolder.decoration = null; convertView.setTag(viewHolder); } return convertView; } public static class ViewHolder { public FilterListItem item; public ImageView icon; public AsyncImageView urlImage; public TextView name; public TextView size; public ImageView selected; public View view; public View decoration; } @Override public View getView(int position, View convertView, ViewGroup parent) { convertView = newView(convertView, parent); ViewHolder viewHolder = (ViewHolder) convertView.getTag(); viewHolder.item = (FilterListItem) getItem(position); populateView(viewHolder); if (listView.isItemChecked(position)) { convertView.setBackgroundColor(activity.getResources().getColor(R.color.tablet_list_selected)); } else { convertView.setBackgroundColor(activity.getResources().getColor(android.R.color.transparent)); } return convertView; } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { return getView(position, convertView, parent); } /* ====================================================================== * ============================================================ selection * ====================================================================== */ private FilterListItem selection = null; /** * Sets the selected item to this one * @param picked */ public void setSelection(FilterListItem picked) { selection = picked; int scroll = listView.getScrollY(); notifyDataSetInvalidated(); listView.scrollTo(0, scroll); } /** * Gets the currently selected item * @return null if no item is to be selected */ public FilterListItem getSelection() { return selection; } /* ====================================================================== * ============================================================= receiver * ====================================================================== */ /** * Receiver which receives intents to add items to the filter list * * @author Tim Su <[email protected]> * */ public class FilterReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { try { Bundle extras = intent.getExtras(); extras.setClassLoader(FilterListHeader.class.getClassLoader()); final Parcelable[] filters = extras.getParcelableArray(AstridApiConstants.EXTRAS_RESPONSE); populateFiltersToAdapter(filters); shouldUseBladeFilter = false; } catch (Exception e) { Log.e("receive-filter-" + //$NON-NLS-1$ intent.getStringExtra(AstridApiConstants.EXTRAS_ADDON), e.toString(), e); } } protected void populateFiltersToAdapter(final Parcelable[] filters) { if (filters == null) return; for (Parcelable item : filters) { FilterListItem filter = (FilterListItem) item; if(skipIntentFilters && !(filter instanceof Filter || filter instanceof FilterListHeader || filter instanceof FilterCategory)) continue; onReceiveFilter((FilterListItem)item); if (filter instanceof FilterCategory) { Filter[] children = ((FilterCategory) filter).children; for (Filter f : children) { add(f); } } else if (filter instanceof Filter){ add((Filter) filter); } } if (mSelectedIndex < getCount()) { listView.setItemChecked(mSelectedIndex, true); } notifyDataSetChanged(); } } /** * Receiver which gets called after the FilterReceiver * and checks if the filters are populated. * If they aren't (e.g. due to the bug in the ZTE Blade's Parcelable-system throwing a * ClassNotFoundExeption), the filters are fetched manually. * * @author Arne Jans <[email protected]> * */ public class BladeFilterReceiver extends FilterReceiver { private final List<ResolveInfo> filterExposerList; public BladeFilterReceiver() { // query astrids AndroidManifest.xml for all registered default-receivers to expose filters PackageManager pm = ContextManager.getContext().getPackageManager(); filterExposerList = pm.queryBroadcastReceivers( new Intent(AstridApiConstants.BROADCAST_REQUEST_FILTERS), PackageManager.MATCH_DEFAULT_ONLY); } @SuppressWarnings("nls") @Override public void onReceive(Context context, Intent intent) { if (shouldUseBladeFilter && getCount() == 0 && filterExposerList != null && filterExposerList.size()>0) { try { for (ResolveInfo filterExposerInfo : filterExposerList) { Log.d("BladeFilterReceiver", filterExposerInfo.toString()); String className = filterExposerInfo.activityInfo.name; AstridFilterExposer filterExposer = null; filterExposer = (AstridFilterExposer) Class.forName(className, true, FilterAdapter.class.getClassLoader()).newInstance(); if (filterExposer != null) { populateFiltersToAdapter(filterExposer.getFilters()); } } } catch (Exception e) { Log.e("receive-bladefilter-" + //$NON-NLS-1$ intent.getStringExtra(AstridApiConstants.EXTRAS_ADDON), e.toString(), e); } } } } /** * Broadcast a request for lists. The request is sent to every * application registered to listen for this broadcast. Each application * can then add lists to this activity */ public void getLists() { Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_REQUEST_FILTERS); // activity.sendOrderedBroadcast(broadcastIntent, AstridApiConstants.PERMISSION_READ); // the bladeFilterReceiver will be called after the usual FilterReceiver has finished (to handle the empty list) activity.sendOrderedBroadcast(broadcastIntent, AstridApiConstants.PERMISSION_READ, bladeFilterReceiver, null, Activity.RESULT_OK, null, null); } /** * Call this method from your activity's onResume() method */ public void registerRecevier() { IntentFilter regularFilter = new IntentFilter(AstridApiConstants.BROADCAST_SEND_FILTERS); regularFilter.setPriority(2); activity.registerReceiver(filterReceiver, regularFilter); IntentFilter bladeFilter = new IntentFilter(AstridApiConstants.BROADCAST_SEND_FILTERS); bladeFilter.setPriority(1); activity.registerReceiver(bladeFilterReceiver, bladeFilter); if(getCount() == 0) getLists(); } /** * Call this method from your activity's onResume() method */ public void unregisterRecevier() { activity.unregisterReceiver(filterReceiver); activity.unregisterReceiver(bladeFilterReceiver); } /** * Called when an item comes through. Override if you like * @param item */ public void onReceiveFilter(FilterListItem item) { // do nothing } /* ====================================================================== * ================================================================ views * ====================================================================== */ public void populateView(ViewHolder viewHolder) { FilterListItem filter = viewHolder.item; if(filter == null) return; viewHolder.view.setBackgroundResource(0); if(viewHolder.decoration != null) { ((ViewGroup)viewHolder.view).removeView(viewHolder.decoration); viewHolder.decoration = null; } if(viewHolder.item instanceof FilterListHeader || viewHolder.item instanceof FilterCategory) { viewHolder.name.setTextAppearance(activity, headerStyle); viewHolder.name.setShadowLayer(1, 1, 1, Color.BLACK); viewHolder.view.setPadding((int) (7 * metrics.density), 5, 0, 5); viewHolder.view.getLayoutParams().height = (int) (40 * metrics.density); } else { viewHolder.name.setTextAppearance(activity, filterStyle); viewHolder.name.setShadowLayer(0, 0, 0, 0); - viewHolder.view.setPadding((int) (7 * metrics.density), 8, 0, 8); + viewHolder.view.setPadding((int) (7 * metrics.density), 2, 0, 2); viewHolder.view.getLayoutParams().height = (int) (58 * metrics.density); } // update with filter attributes (listing icon, url, update text, size) viewHolder.urlImage.setVisibility(View.GONE); viewHolder.icon.setVisibility(View.GONE); if(filter.listingIcon != null) { viewHolder.icon.setVisibility(View.VISIBLE); viewHolder.icon.setImageBitmap(filter.listingIcon); } // title / size if(filter.listingTitle.matches(".* \\(\\d+\\)$")) { //$NON-NLS-1$ viewHolder.size.setVisibility(View.VISIBLE); viewHolder.size.setText(filter.listingTitle.substring(filter.listingTitle.lastIndexOf('(') + 1, filter.listingTitle.length() - 1)); viewHolder.name.setText(filter.listingTitle.substring(0, filter.listingTitle.lastIndexOf(' '))); } else { viewHolder.name.setText(filter.listingTitle); viewHolder.size.setVisibility(View.GONE); } viewHolder.name.getLayoutParams().height = (int) (58 * metrics.density); if(filter instanceof FilterWithUpdate) { viewHolder.urlImage.setVisibility(View.VISIBLE); viewHolder.urlImage.setDefaultImageResource(TagService.getDefaultImageIDForTag(viewHolder.name.getText().toString())); viewHolder.urlImage.setUrl(((FilterWithUpdate)filter).imageUrl); } if(filter.color != 0) viewHolder.name.setTextColor(filter.color); // selection if(selection == viewHolder.item) { viewHolder.selected.setVisibility(View.VISIBLE); viewHolder.view.setBackgroundColor(Color.rgb(128, 230, 0)); } else viewHolder.selected.setVisibility(View.GONE); if(filter instanceof FilterCategoryWithNewButton) setupCustomHeader(viewHolder, (FilterCategoryWithNewButton) filter); } private void setupCustomHeader(ViewHolder viewHolder, final FilterCategoryWithNewButton filter) { Button add = new Button(activity); add.setBackgroundResource(R.drawable.filter_btn_background); add.setCompoundDrawablesWithIntrinsicBounds(R.drawable.filter_new,0,0,0); add.setTextColor(Color.WHITE); add.setShadowLayer(1, 1, 1, Color.BLACK); add.setText(filter.label); add.setFocusable(false); RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, (int)(32 * metrics.density)); lp.rightMargin = (int) (4 * metrics.density); lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); add.setLayoutParams(lp); ((ViewGroup)viewHolder.view).addView(add); viewHolder.decoration = add; add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { filter.intent.send(FilterListFragment.REQUEST_NEW_BUTTON, new PendingIntent.OnFinished() { @Override public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode, String resultData, Bundle resultExtras) { activity.runOnUiThread(new Runnable() { public void run() { clear(); } }); } }, null); } catch (CanceledException e) { // do nothing } } }); } }
true
true
public void populateView(ViewHolder viewHolder) { FilterListItem filter = viewHolder.item; if(filter == null) return; viewHolder.view.setBackgroundResource(0); if(viewHolder.decoration != null) { ((ViewGroup)viewHolder.view).removeView(viewHolder.decoration); viewHolder.decoration = null; } if(viewHolder.item instanceof FilterListHeader || viewHolder.item instanceof FilterCategory) { viewHolder.name.setTextAppearance(activity, headerStyle); viewHolder.name.setShadowLayer(1, 1, 1, Color.BLACK); viewHolder.view.setPadding((int) (7 * metrics.density), 5, 0, 5); viewHolder.view.getLayoutParams().height = (int) (40 * metrics.density); } else { viewHolder.name.setTextAppearance(activity, filterStyle); viewHolder.name.setShadowLayer(0, 0, 0, 0); viewHolder.view.setPadding((int) (7 * metrics.density), 8, 0, 8); viewHolder.view.getLayoutParams().height = (int) (58 * metrics.density); } // update with filter attributes (listing icon, url, update text, size) viewHolder.urlImage.setVisibility(View.GONE); viewHolder.icon.setVisibility(View.GONE); if(filter.listingIcon != null) { viewHolder.icon.setVisibility(View.VISIBLE); viewHolder.icon.setImageBitmap(filter.listingIcon); } // title / size if(filter.listingTitle.matches(".* \\(\\d+\\)$")) { //$NON-NLS-1$ viewHolder.size.setVisibility(View.VISIBLE); viewHolder.size.setText(filter.listingTitle.substring(filter.listingTitle.lastIndexOf('(') + 1, filter.listingTitle.length() - 1)); viewHolder.name.setText(filter.listingTitle.substring(0, filter.listingTitle.lastIndexOf(' '))); } else { viewHolder.name.setText(filter.listingTitle); viewHolder.size.setVisibility(View.GONE); } viewHolder.name.getLayoutParams().height = (int) (58 * metrics.density); if(filter instanceof FilterWithUpdate) { viewHolder.urlImage.setVisibility(View.VISIBLE); viewHolder.urlImage.setDefaultImageResource(TagService.getDefaultImageIDForTag(viewHolder.name.getText().toString())); viewHolder.urlImage.setUrl(((FilterWithUpdate)filter).imageUrl); } if(filter.color != 0) viewHolder.name.setTextColor(filter.color); // selection if(selection == viewHolder.item) { viewHolder.selected.setVisibility(View.VISIBLE); viewHolder.view.setBackgroundColor(Color.rgb(128, 230, 0)); } else viewHolder.selected.setVisibility(View.GONE); if(filter instanceof FilterCategoryWithNewButton) setupCustomHeader(viewHolder, (FilterCategoryWithNewButton) filter); }
public void populateView(ViewHolder viewHolder) { FilterListItem filter = viewHolder.item; if(filter == null) return; viewHolder.view.setBackgroundResource(0); if(viewHolder.decoration != null) { ((ViewGroup)viewHolder.view).removeView(viewHolder.decoration); viewHolder.decoration = null; } if(viewHolder.item instanceof FilterListHeader || viewHolder.item instanceof FilterCategory) { viewHolder.name.setTextAppearance(activity, headerStyle); viewHolder.name.setShadowLayer(1, 1, 1, Color.BLACK); viewHolder.view.setPadding((int) (7 * metrics.density), 5, 0, 5); viewHolder.view.getLayoutParams().height = (int) (40 * metrics.density); } else { viewHolder.name.setTextAppearance(activity, filterStyle); viewHolder.name.setShadowLayer(0, 0, 0, 0); viewHolder.view.setPadding((int) (7 * metrics.density), 2, 0, 2); viewHolder.view.getLayoutParams().height = (int) (58 * metrics.density); } // update with filter attributes (listing icon, url, update text, size) viewHolder.urlImage.setVisibility(View.GONE); viewHolder.icon.setVisibility(View.GONE); if(filter.listingIcon != null) { viewHolder.icon.setVisibility(View.VISIBLE); viewHolder.icon.setImageBitmap(filter.listingIcon); } // title / size if(filter.listingTitle.matches(".* \\(\\d+\\)$")) { //$NON-NLS-1$ viewHolder.size.setVisibility(View.VISIBLE); viewHolder.size.setText(filter.listingTitle.substring(filter.listingTitle.lastIndexOf('(') + 1, filter.listingTitle.length() - 1)); viewHolder.name.setText(filter.listingTitle.substring(0, filter.listingTitle.lastIndexOf(' '))); } else { viewHolder.name.setText(filter.listingTitle); viewHolder.size.setVisibility(View.GONE); } viewHolder.name.getLayoutParams().height = (int) (58 * metrics.density); if(filter instanceof FilterWithUpdate) { viewHolder.urlImage.setVisibility(View.VISIBLE); viewHolder.urlImage.setDefaultImageResource(TagService.getDefaultImageIDForTag(viewHolder.name.getText().toString())); viewHolder.urlImage.setUrl(((FilterWithUpdate)filter).imageUrl); } if(filter.color != 0) viewHolder.name.setTextColor(filter.color); // selection if(selection == viewHolder.item) { viewHolder.selected.setVisibility(View.VISIBLE); viewHolder.view.setBackgroundColor(Color.rgb(128, 230, 0)); } else viewHolder.selected.setVisibility(View.GONE); if(filter instanceof FilterCategoryWithNewButton) setupCustomHeader(viewHolder, (FilterCategoryWithNewButton) filter); }
diff --git a/src/main/java/com/khs/sherpa/context/factory/ManagedBean.java b/src/main/java/com/khs/sherpa/context/factory/ManagedBean.java index 37dc3f7..7596f21 100644 --- a/src/main/java/com/khs/sherpa/context/factory/ManagedBean.java +++ b/src/main/java/com/khs/sherpa/context/factory/ManagedBean.java @@ -1,60 +1,60 @@ package com.khs.sherpa.context.factory; /* * Copyright 2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import com.khs.sherpa.exception.SherpaRuntimeException; import com.khs.sherpa.util.Util; abstract class ManagedBean { private Class<?> type; private String name; public abstract boolean isSingletone(); public abstract boolean isPrototype(); public abstract Object getInstance(); public ManagedBean(Class<?> type) { this.type = type; this.name = Util.getObjectName(type); } public Class<?> getType() { return type; } public void setType(Class<?> type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } protected Object createInstance() { try { - return type.getDeclaringClass().newInstance(); + return type.newInstance(); } catch (Exception e) { throw new SherpaRuntimeException("Unable to create Managed Bean [" + type + "]"); } } }
true
true
protected Object createInstance() { try { return type.getDeclaringClass().newInstance(); } catch (Exception e) { throw new SherpaRuntimeException("Unable to create Managed Bean [" + type + "]"); } }
protected Object createInstance() { try { return type.newInstance(); } catch (Exception e) { throw new SherpaRuntimeException("Unable to create Managed Bean [" + type + "]"); } }
diff --git a/server/src/main/java/com/metamx/druid/initialization/ServerInit.java b/server/src/main/java/com/metamx/druid/initialization/ServerInit.java index 8b38872608..bb1d0d631d 100644 --- a/server/src/main/java/com/metamx/druid/initialization/ServerInit.java +++ b/server/src/main/java/com/metamx/druid/initialization/ServerInit.java @@ -1,173 +1,173 @@ /* * Druid - a distributed column store. * Copyright (C) 2012 Metamarkets Group Inc. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package com.metamx.druid.initialization; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.metamx.common.ISE; import com.metamx.common.logger.Logger; import com.metamx.druid.DruidProcessingConfig; import com.metamx.druid.GroupByQueryEngine; import com.metamx.druid.GroupByQueryEngineConfig; import com.metamx.druid.Query; import com.metamx.druid.collect.StupidPool; import com.metamx.druid.loading.DelegatingStorageAdapterLoader; import com.metamx.druid.loading.MMappedStorageAdapterFactory; import com.metamx.druid.loading.QueryableLoaderConfig; import com.metamx.druid.loading.RealtimeSegmentGetter; import com.metamx.druid.loading.S3SegmentGetter; import com.metamx.druid.loading.S3ZippedSegmentGetter; import com.metamx.druid.loading.SingleStorageAdapterLoader; import com.metamx.druid.loading.StorageAdapterFactory; import com.metamx.druid.loading.StorageAdapterLoader; import com.metamx.druid.query.QueryRunnerFactory; import com.metamx.druid.query.group.GroupByQuery; import com.metamx.druid.query.group.GroupByQueryRunnerFactory; import com.metamx.druid.query.search.SearchQuery; import com.metamx.druid.query.search.SearchQueryRunnerFactory; import com.metamx.druid.query.timeboundary.TimeBoundaryQuery; import com.metamx.druid.query.timeboundary.TimeBoundaryQueryRunnerFactory; import com.metamx.druid.query.timeseries.TimeseriesQuery; import com.metamx.druid.query.timeseries.TimeseriesQueryRunnerFactory; import org.jets3t.service.impl.rest.httpclient.RestS3Service; import org.skife.config.ConfigurationObjectFactory; import java.lang.reflect.InvocationTargetException; import java.nio.ByteBuffer; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; /** */ public class ServerInit { private static Logger log = new Logger(ServerInit.class); public static StorageAdapterLoader makeDefaultQueryableLoader( RestS3Service s3Client, QueryableLoaderConfig config ) { DelegatingStorageAdapterLoader delegateLoader = new DelegatingStorageAdapterLoader(); final S3SegmentGetter segmentGetter = new S3SegmentGetter(s3Client, config); final S3ZippedSegmentGetter zippedGetter = new S3ZippedSegmentGetter(s3Client, config); final RealtimeSegmentGetter realtimeGetter = new RealtimeSegmentGetter(config); final StorageAdapterFactory factory; if ("mmap".equals(config.getQueryableFactoryType())) { factory = new MMappedStorageAdapterFactory(); } else { throw new ISE("Unknown queryableFactoryType[%s]", config.getQueryableFactoryType()); } delegateLoader.setLoaderTypes( ImmutableMap.<String, StorageAdapterLoader>builder() .put("s3", new SingleStorageAdapterLoader(segmentGetter, factory)) .put("s3_zip", new SingleStorageAdapterLoader(zippedGetter, factory)) .put("realtime", new SingleStorageAdapterLoader(realtimeGetter, factory)) .build() ); return delegateLoader; } public static StupidPool<ByteBuffer> makeComputeScratchPool(DruidProcessingConfig config) { try { Class<?> vmClass = Class.forName("sun.misc.VM"); Object maxDirectMemoryObj = vmClass.getMethod("maxDirectMemory").invoke(null); if (maxDirectMemoryObj == null || !(maxDirectMemoryObj instanceof Number)) { log.info("Cannot determine maxDirectMemory from[%s]", maxDirectMemoryObj); } else { long maxDirectMemory = ((Number) maxDirectMemoryObj).longValue(); final long memoryNeeded = (long) config.intermediateComputeSizeBytes() * (config.getNumThreads() + 1); if (maxDirectMemory < memoryNeeded) { throw new ISE( - "Not enough direct memory. Please adjust -XX:MaxDirectMemory or druid.computation.buffer.size: " + "Not enough direct memory. Please adjust -XX:MaxDirectMemorySize or druid.computation.buffer.size: " + "maxDirectMemory[%,d], memoryNeeded[%,d], druid.computation.buffer.size[%,d], numThreads[%,d]", maxDirectMemory, memoryNeeded, config.intermediateComputeSizeBytes(), config.getNumThreads() ); } } } catch (ClassNotFoundException e) { log.info("No VM class, cannot do memory check."); } catch (NoSuchMethodException e) { log.info("VM.maxDirectMemory doesn't exist, cannot do memory check."); } catch (InvocationTargetException e) { log.warn(e, "static method shouldn't throw this"); } catch (IllegalAccessException e) { log.warn(e, "public method, shouldn't throw this"); } return new ComputeScratchPool(config.intermediateComputeSizeBytes()); } public static Map<Class<? extends Query>, QueryRunnerFactory> initDefaultQueryTypes( ConfigurationObjectFactory configFactory, StupidPool<ByteBuffer> computationBufferPool ) { Map<Class<? extends Query>, QueryRunnerFactory> queryRunners = Maps.newLinkedHashMap(); queryRunners.put(TimeseriesQuery.class, new TimeseriesQueryRunnerFactory()); queryRunners.put( GroupByQuery.class, new GroupByQueryRunnerFactory( new GroupByQueryEngine( configFactory.build(GroupByQueryEngineConfig.class), computationBufferPool ) ) ); queryRunners.put(SearchQuery.class, new SearchQueryRunnerFactory()); queryRunners.put(TimeBoundaryQuery.class, new TimeBoundaryQueryRunnerFactory()); return queryRunners; } private static class ComputeScratchPool extends StupidPool<ByteBuffer> { private static final Logger log = new Logger(ComputeScratchPool.class); public ComputeScratchPool(final int computationBufferSize) { super( new Supplier<ByteBuffer>() { final AtomicLong count = new AtomicLong(0); @Override public ByteBuffer get() { log.info( "Allocating new computeScratchPool[%,d] of size[%,d]", count.getAndIncrement(), computationBufferSize ); return ByteBuffer.allocateDirect(computationBufferSize); } } ); } } }
true
true
public static StupidPool<ByteBuffer> makeComputeScratchPool(DruidProcessingConfig config) { try { Class<?> vmClass = Class.forName("sun.misc.VM"); Object maxDirectMemoryObj = vmClass.getMethod("maxDirectMemory").invoke(null); if (maxDirectMemoryObj == null || !(maxDirectMemoryObj instanceof Number)) { log.info("Cannot determine maxDirectMemory from[%s]", maxDirectMemoryObj); } else { long maxDirectMemory = ((Number) maxDirectMemoryObj).longValue(); final long memoryNeeded = (long) config.intermediateComputeSizeBytes() * (config.getNumThreads() + 1); if (maxDirectMemory < memoryNeeded) { throw new ISE( "Not enough direct memory. Please adjust -XX:MaxDirectMemory or druid.computation.buffer.size: " + "maxDirectMemory[%,d], memoryNeeded[%,d], druid.computation.buffer.size[%,d], numThreads[%,d]", maxDirectMemory, memoryNeeded, config.intermediateComputeSizeBytes(), config.getNumThreads() ); } } } catch (ClassNotFoundException e) { log.info("No VM class, cannot do memory check."); } catch (NoSuchMethodException e) { log.info("VM.maxDirectMemory doesn't exist, cannot do memory check."); } catch (InvocationTargetException e) { log.warn(e, "static method shouldn't throw this"); } catch (IllegalAccessException e) { log.warn(e, "public method, shouldn't throw this"); } return new ComputeScratchPool(config.intermediateComputeSizeBytes()); }
public static StupidPool<ByteBuffer> makeComputeScratchPool(DruidProcessingConfig config) { try { Class<?> vmClass = Class.forName("sun.misc.VM"); Object maxDirectMemoryObj = vmClass.getMethod("maxDirectMemory").invoke(null); if (maxDirectMemoryObj == null || !(maxDirectMemoryObj instanceof Number)) { log.info("Cannot determine maxDirectMemory from[%s]", maxDirectMemoryObj); } else { long maxDirectMemory = ((Number) maxDirectMemoryObj).longValue(); final long memoryNeeded = (long) config.intermediateComputeSizeBytes() * (config.getNumThreads() + 1); if (maxDirectMemory < memoryNeeded) { throw new ISE( "Not enough direct memory. Please adjust -XX:MaxDirectMemorySize or druid.computation.buffer.size: " + "maxDirectMemory[%,d], memoryNeeded[%,d], druid.computation.buffer.size[%,d], numThreads[%,d]", maxDirectMemory, memoryNeeded, config.intermediateComputeSizeBytes(), config.getNumThreads() ); } } } catch (ClassNotFoundException e) { log.info("No VM class, cannot do memory check."); } catch (NoSuchMethodException e) { log.info("VM.maxDirectMemory doesn't exist, cannot do memory check."); } catch (InvocationTargetException e) { log.warn(e, "static method shouldn't throw this"); } catch (IllegalAccessException e) { log.warn(e, "public method, shouldn't throw this"); } return new ComputeScratchPool(config.intermediateComputeSizeBytes()); }
diff --git a/src/java/org/jivesoftware/sparkimpl/plugin/systray/SysTrayPlugin.java b/src/java/org/jivesoftware/sparkimpl/plugin/systray/SysTrayPlugin.java index b12a529b..6778a183 100644 --- a/src/java/org/jivesoftware/sparkimpl/plugin/systray/SysTrayPlugin.java +++ b/src/java/org/jivesoftware/sparkimpl/plugin/systray/SysTrayPlugin.java @@ -1,334 +1,334 @@ package org.jivesoftware.sparkimpl.plugin.systray; import java.awt.SystemTray; import java.awt.TrayIcon; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ImageIcon; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import org.jivesoftware.Spark; import org.jivesoftware.resource.Default; import org.jivesoftware.resource.Res; import org.jivesoftware.resource.SparkRes; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smackx.MessageEventNotificationListener; import org.jivesoftware.spark.NativeHandler; import org.jivesoftware.spark.SparkManager; import org.jivesoftware.spark.plugin.Plugin; import org.jivesoftware.spark.ui.PresenceListener; import org.jivesoftware.spark.ui.status.CustomStatusItem; import org.jivesoftware.spark.ui.status.StatusBar; import org.jivesoftware.spark.ui.status.StatusItem; import org.jivesoftware.sparkimpl.settings.local.LocalPreferences; import org.jivesoftware.sparkimpl.settings.local.SettingsManager; public class SysTrayPlugin implements Plugin, NativeHandler, MessageEventNotificationListener { private JPopupMenu popupMenu = new JPopupMenu(); private final JMenuItem openMenu = new JMenuItem(Res.getString("menuitem.open")); private final JMenuItem minimizeMenu = new JMenuItem(Res.getString("menuitem.hide")); private final JMenuItem exitMenu = new JMenuItem(Res.getString("menuitem.exit")); private final JMenu statusMenu = new JMenu(Res.getString("menuitem.status")); private final JMenuItem logoutMenu = new JMenuItem(Res.getString("menuitem.logout.no.status")); private LocalPreferences pref = SettingsManager.getLocalPreferences(); private ImageIcon availableIcon; private ImageIcon dndIcon; private ImageIcon awayIcon; private ImageIcon newMessageIcon; private ImageIcon typingIcon; private TrayIcon trayIcon; public boolean canShutDown() { return true; } public void initialize() { SystemTray tray = SystemTray.getSystemTray(); SparkManager.getNativeManager().addNativeHandler(this); SparkManager.getMessageEventManager().addMessageEventNotificationListener(this); newMessageIcon = SparkRes.getImageIcon(SparkRes.MESSAGE_NEW_TRAY); typingIcon = SparkRes.getImageIcon(SparkRes.TYPING_TRAY); if (SystemTray.isSupported()) { availableIcon = Default.getImageIcon(Default.TRAY_IMAGE); if (availableIcon == null) { availableIcon = SparkRes.getImageIcon(SparkRes.TRAY_IMAGE); } awayIcon = SparkRes.getImageIcon(SparkRes.TRAY_AWAY); dndIcon = SparkRes.getImageIcon(SparkRes.TRAY_DND); popupMenu.add(openMenu); openMenu.addActionListener(new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent event) { SparkManager.getMainWindow().setVisible(true); SparkManager.getMainWindow().toFront(); } }); popupMenu.add(minimizeMenu); minimizeMenu.addActionListener(new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent event) { SparkManager.getMainWindow().setVisible(false); } }); popupMenu.addSeparator(); addStatusMessages(); popupMenu.add(statusMenu); statusMenu.addActionListener(new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent event) { } }); if (Spark.isWindows()) { popupMenu.add(logoutMenu); logoutMenu.addActionListener(new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { SparkManager.getMainWindow().logout(false); } }); } // Exit Menu exitMenu.addActionListener(new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { SparkManager.getMainWindow().shutdown(); } }); popupMenu.add(exitMenu); SparkManager.getSessionManager().addPresenceListener(new PresenceListener() { public void presenceChanged(Presence presence) { if (presence.getMode() == Presence.Mode.available) { trayIcon.setImage(availableIcon.getImage()); } else if (presence.getMode() == Presence.Mode.away) { trayIcon.setImage(awayIcon.getImage()); } else if (presence.getMode() == Presence.Mode.dnd) { trayIcon.setImage(dndIcon.getImage()); } else { trayIcon.setImage(availableIcon.getImage()); } } }); try { - trayIcon = new TrayIcon(availableIcon.getImage(), "Spark", null); + trayIcon = new TrayIcon(availableIcon.getImage(), Default.APPLICATION_NAME, null); trayIcon.setImageAutoSize(true); trayIcon.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent event) { if (event.getButton() == MouseEvent.BUTTON1 && event.getClickCount() == 1) { if (SparkManager.getMainWindow().isVisible()) { SparkManager.getMainWindow().setVisible(false); } else { SparkManager.getMainWindow().setVisible(true); SparkManager.getMainWindow().toFront(); } } else if (event.getButton() == MouseEvent.BUTTON1) { SparkManager.getMainWindow().toFront(); // SparkManager.getMainWindow().requestFocus(); } else if (event.getButton() == MouseEvent.BUTTON3) { popupMenu.setLocation(event.getX(), event.getY()); popupMenu.setInvoker(popupMenu); popupMenu.setVisible(true); } } public void mouseEntered(MouseEvent event) { } public void mouseExited(MouseEvent event) { } public void mousePressed(MouseEvent event) { } public void mouseReleased(MouseEvent event) { } }); tray.add(trayIcon); } catch (Exception e) { // Not Supported } } } public void addStatusMessages() { StatusBar statusBar = SparkManager.getWorkspace().getStatusBar(); for (Object o : statusBar.getStatusList()) { final StatusItem statusItem = (StatusItem) o; final AbstractAction action = new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { StatusBar statusBar = SparkManager.getWorkspace() .getStatusBar(); SparkManager.getSessionManager().changePresence( statusItem.getPresence()); statusBar.setStatus(statusItem.getText()); } }; action.putValue(Action.NAME, statusItem.getText()); action.putValue(Action.SMALL_ICON, statusItem.getIcon()); boolean hasChildren = false; for (Object aCustom : SparkManager.getWorkspace().getStatusBar() .getCustomStatusList()) { final CustomStatusItem cItem = (CustomStatusItem) aCustom; String type = cItem.getType(); if (type.equals(statusItem.getText())) { hasChildren = true; } } if (!hasChildren) { JMenuItem status = new JMenuItem(action); statusMenu.add(status); } else { final JMenu status = new JMenu(action); statusMenu.add(status); status.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent mouseEvent) { action.actionPerformed(null); popupMenu.setVisible(false); } }); for (Object aCustom : SparkManager.getWorkspace() .getStatusBar().getCustomStatusList()) { final CustomStatusItem customItem = (CustomStatusItem) aCustom; String type = customItem.getType(); if (type.equals(statusItem.getText())) { AbstractAction customAction = new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { StatusBar statusBar = SparkManager .getWorkspace().getStatusBar(); Presence oldPresence = statusItem.getPresence(); Presence presence = StatusBar .copyPresence(oldPresence); presence.setStatus(customItem.getStatus()); presence.setPriority(customItem.getPriority()); SparkManager.getSessionManager() .changePresence(presence); statusBar.setStatus(statusItem.getName() + " - " + customItem.getStatus()); } }; customAction.putValue(Action.NAME, customItem.getStatus()); customAction.putValue(Action.SMALL_ICON, statusItem.getIcon()); JMenuItem menuItem = new JMenuItem(customAction); status.add(menuItem); } } } } } public void shutdown() { if (SystemTray.isSupported()) { SystemTray tray = SystemTray.getSystemTray(); tray.remove(trayIcon); } } public void uninstall() { } // Info on new Messages @Override public void flashWindow(Window window) { if (pref.isSystemTrayNotificationEnabled()) { trayIcon.setImage(newMessageIcon.getImage()); } } @Override public void flashWindowStopWhenFocused(Window window) { trayIcon.setImage(availableIcon.getImage()); } @Override public boolean handleNotification() { return true; } @Override public void stopFlashing(Window window) { trayIcon.setImage(availableIcon.getImage()); } // For Typing @Override public void cancelledNotification(String from, String packetID) { trayIcon.setImage(availableIcon.getImage()); } @Override public void composingNotification(String from, String packetID) { if (pref.isTypingNotificationShown()) { trayIcon.setImage(typingIcon.getImage()); } } @Override public void deliveredNotification(String from, String packetID) { // Nothing } @Override public void displayedNotification(String from, String packetID) { // Nothing } @Override public void offlineNotification(String from, String packetID) { // Nothing } }
true
true
public void initialize() { SystemTray tray = SystemTray.getSystemTray(); SparkManager.getNativeManager().addNativeHandler(this); SparkManager.getMessageEventManager().addMessageEventNotificationListener(this); newMessageIcon = SparkRes.getImageIcon(SparkRes.MESSAGE_NEW_TRAY); typingIcon = SparkRes.getImageIcon(SparkRes.TYPING_TRAY); if (SystemTray.isSupported()) { availableIcon = Default.getImageIcon(Default.TRAY_IMAGE); if (availableIcon == null) { availableIcon = SparkRes.getImageIcon(SparkRes.TRAY_IMAGE); } awayIcon = SparkRes.getImageIcon(SparkRes.TRAY_AWAY); dndIcon = SparkRes.getImageIcon(SparkRes.TRAY_DND); popupMenu.add(openMenu); openMenu.addActionListener(new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent event) { SparkManager.getMainWindow().setVisible(true); SparkManager.getMainWindow().toFront(); } }); popupMenu.add(minimizeMenu); minimizeMenu.addActionListener(new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent event) { SparkManager.getMainWindow().setVisible(false); } }); popupMenu.addSeparator(); addStatusMessages(); popupMenu.add(statusMenu); statusMenu.addActionListener(new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent event) { } }); if (Spark.isWindows()) { popupMenu.add(logoutMenu); logoutMenu.addActionListener(new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { SparkManager.getMainWindow().logout(false); } }); } // Exit Menu exitMenu.addActionListener(new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { SparkManager.getMainWindow().shutdown(); } }); popupMenu.add(exitMenu); SparkManager.getSessionManager().addPresenceListener(new PresenceListener() { public void presenceChanged(Presence presence) { if (presence.getMode() == Presence.Mode.available) { trayIcon.setImage(availableIcon.getImage()); } else if (presence.getMode() == Presence.Mode.away) { trayIcon.setImage(awayIcon.getImage()); } else if (presence.getMode() == Presence.Mode.dnd) { trayIcon.setImage(dndIcon.getImage()); } else { trayIcon.setImage(availableIcon.getImage()); } } }); try { trayIcon = new TrayIcon(availableIcon.getImage(), "Spark", null); trayIcon.setImageAutoSize(true); trayIcon.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent event) { if (event.getButton() == MouseEvent.BUTTON1 && event.getClickCount() == 1) { if (SparkManager.getMainWindow().isVisible()) { SparkManager.getMainWindow().setVisible(false); } else { SparkManager.getMainWindow().setVisible(true); SparkManager.getMainWindow().toFront(); } } else if (event.getButton() == MouseEvent.BUTTON1) { SparkManager.getMainWindow().toFront(); // SparkManager.getMainWindow().requestFocus(); } else if (event.getButton() == MouseEvent.BUTTON3) { popupMenu.setLocation(event.getX(), event.getY()); popupMenu.setInvoker(popupMenu); popupMenu.setVisible(true); } } public void mouseEntered(MouseEvent event) { } public void mouseExited(MouseEvent event) { } public void mousePressed(MouseEvent event) { } public void mouseReleased(MouseEvent event) { } }); tray.add(trayIcon); } catch (Exception e) { // Not Supported } } }
public void initialize() { SystemTray tray = SystemTray.getSystemTray(); SparkManager.getNativeManager().addNativeHandler(this); SparkManager.getMessageEventManager().addMessageEventNotificationListener(this); newMessageIcon = SparkRes.getImageIcon(SparkRes.MESSAGE_NEW_TRAY); typingIcon = SparkRes.getImageIcon(SparkRes.TYPING_TRAY); if (SystemTray.isSupported()) { availableIcon = Default.getImageIcon(Default.TRAY_IMAGE); if (availableIcon == null) { availableIcon = SparkRes.getImageIcon(SparkRes.TRAY_IMAGE); } awayIcon = SparkRes.getImageIcon(SparkRes.TRAY_AWAY); dndIcon = SparkRes.getImageIcon(SparkRes.TRAY_DND); popupMenu.add(openMenu); openMenu.addActionListener(new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent event) { SparkManager.getMainWindow().setVisible(true); SparkManager.getMainWindow().toFront(); } }); popupMenu.add(minimizeMenu); minimizeMenu.addActionListener(new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent event) { SparkManager.getMainWindow().setVisible(false); } }); popupMenu.addSeparator(); addStatusMessages(); popupMenu.add(statusMenu); statusMenu.addActionListener(new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent event) { } }); if (Spark.isWindows()) { popupMenu.add(logoutMenu); logoutMenu.addActionListener(new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { SparkManager.getMainWindow().logout(false); } }); } // Exit Menu exitMenu.addActionListener(new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { SparkManager.getMainWindow().shutdown(); } }); popupMenu.add(exitMenu); SparkManager.getSessionManager().addPresenceListener(new PresenceListener() { public void presenceChanged(Presence presence) { if (presence.getMode() == Presence.Mode.available) { trayIcon.setImage(availableIcon.getImage()); } else if (presence.getMode() == Presence.Mode.away) { trayIcon.setImage(awayIcon.getImage()); } else if (presence.getMode() == Presence.Mode.dnd) { trayIcon.setImage(dndIcon.getImage()); } else { trayIcon.setImage(availableIcon.getImage()); } } }); try { trayIcon = new TrayIcon(availableIcon.getImage(), Default.APPLICATION_NAME, null); trayIcon.setImageAutoSize(true); trayIcon.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent event) { if (event.getButton() == MouseEvent.BUTTON1 && event.getClickCount() == 1) { if (SparkManager.getMainWindow().isVisible()) { SparkManager.getMainWindow().setVisible(false); } else { SparkManager.getMainWindow().setVisible(true); SparkManager.getMainWindow().toFront(); } } else if (event.getButton() == MouseEvent.BUTTON1) { SparkManager.getMainWindow().toFront(); // SparkManager.getMainWindow().requestFocus(); } else if (event.getButton() == MouseEvent.BUTTON3) { popupMenu.setLocation(event.getX(), event.getY()); popupMenu.setInvoker(popupMenu); popupMenu.setVisible(true); } } public void mouseEntered(MouseEvent event) { } public void mouseExited(MouseEvent event) { } public void mousePressed(MouseEvent event) { } public void mouseReleased(MouseEvent event) { } }); tray.add(trayIcon); } catch (Exception e) { // Not Supported } } }
diff --git a/src/main/gradeapp/HelperButton.java b/src/main/gradeapp/HelperButton.java index 3028938..910b8f1 100644 --- a/src/main/gradeapp/HelperButton.java +++ b/src/main/gradeapp/HelperButton.java @@ -1,233 +1,238 @@ package gradeapp; import javax.swing.JOptionPane; import javax.swing.JButton; import javax.swing.JRadioButton; import javax.swing.ButtonGroup; import javax.swing.JLabel; import javax.swing.BoxLayout; import javax.swing.BorderFactory; import javax.swing.border.Border; import javax.swing.JPanel; import javax.swing.JFrame; import java.awt.*; import java.awt.event.*; import java.util.Enumeration; import javax.swing.AbstractButton; import javax.swing.JScrollPane; import javax.swing.JTextPane; /** * * @author andrew */ public class HelperButton extends JPanel{ JLabel label; JFrame frame; String simpleDialogDesc = "Choose the topic that you need help with"; String iconDesc = "A JOptionPane has its choice of icons"; String moreDialogDesc = "Some more dialogs"; /** Creates the GUI shown inside the helperframe's content pane. */ public HelperButton(JFrame frame) { super(new BorderLayout()); this.frame = frame; //Create the components. JPanel frequentPanel = createSimpleDialogBox(); //Lay them out. Border padding = BorderFactory.createEmptyBorder(20,20,5,20); frequentPanel.setBorder(padding); add(frequentPanel, BorderLayout.CENTER); } private JPanel createSimpleDialogBox() { final ButtonGroup group = new ButtonGroup(); final String loadHelpCommand = "loadhelp"; final String graphHelpCommand = "graphhelp"; final String emailHelpCommand = "emailhelp"; final String saveHelpCommand = "savehelp"; final String printHelpCommand = "printhelp"; final String aboutCommand = "abouthelp"; JRadioButton loadhelp = new JRadioButton("Loading an Excel File."); loadhelp.setActionCommand(loadHelpCommand); group.add(loadhelp); JRadioButton graphHelp = new JRadioButton("Understanding and Modifying a Grade Tree"); graphHelp.setActionCommand(graphHelpCommand); group.add(graphHelp); JRadioButton emailHelp = new JRadioButton("Emailing a Tree"); emailHelp.setActionCommand(emailHelpCommand); group.add(emailHelp); JRadioButton saveHelp = new JRadioButton("Saving a Tree"); saveHelp.setActionCommand(saveHelpCommand); group.add(saveHelp); JRadioButton printHelp = new JRadioButton("Printing a Tree"); printHelp.setActionCommand(printHelpCommand); group.add(printHelp); JRadioButton aboutHelp = new JRadioButton("About the developers"); aboutHelp.setActionCommand(aboutCommand); group.add(aboutHelp); JButton showItButton = new JButton("Select"); showItButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String command = group.getSelection().getActionCommand(); JTextPane textPane = new JTextPane(); // creates an empty text pane textPane.setContentType("text/html"); // lets Java know it will be HTML String text = "<HTML>"; if (command.equals(loadHelpCommand)) { text += "<h1>How to load a file</h1>"; text += "<p>Begin by clicking on the 'Load *.xls' button<br />" + "which will open a window where you can browse<br />" + "your local drives for an Excel file to load. If you<br /> " + "have any issue loading a file, check the following:</p>" + "<ul><li>Are you selecting an Excel file(*.xls or *.xlsx)?</li>"+ "<li>Is the data in the selected Excel file arranged<br />"+ "in the same manner as was produced by the<br />Scantron machine?</li>"+ "</ul>"; } else if (command.equals(graphHelpCommand)) { text+= "<h1>Reading a Tree</h1><p>Once you have loaded a file a tree will be" + "shown. The tree is made up of cells and edges. Cell are the orange "+ "boxes and edges connect them. Each cell represents whether a question was" + "answered correctly or incorrectly. The main idea here is that there is no" + " extrapolation or guesswork done by the program. The results you see are" + " real.</p>"; text+="<h1>Setting what a good grade is.</h1><p>Of course, every exam is " + "different and so what constitues a good grade needs to be defined by you." + "The way that you do this is by moving the \"Good Grade\" slider to what" + "you think a good grade is.</p>"; text+="<h1>Setting the Quality</h1><p>Your first question probably is: \"What" + " is quality?\" or \"Why wouldn't I want the best Quality?\" What the quality" + " bar is really asking is \"How good a predictor does a question need to be" + " for me to show it to you?\" Basically, as the program breaks down how people" + " did on the exam (or as you traverse down the tree, however you wish to look"+ " at it.) the questions become worse and predictors. By raising the \"Quality\"" + " bar you are raising the cutoff on how good of a predictor the question needs" + " to be for it to be shown. As you increase quality you will see your tend to" + " shrink, increase and it grows. But be warned, a large graph does not necessarily " + " mean more information. Since the amount Quality wanted is dependent on the " + "exam,it needs to be tuned manually. A good rule of thumb is to increase the " + " as far as possible while still getting a <i>good</i>(This is a weasel word," + " I know) sized graph and then going down no further. </p>"; } else if (command.equals(saveHelpCommand)) { text += "<h1>Saving a Tree</h1>" + "<p><b>Note:</b> You need to have loaded an Excel file<br />" + "into the program before you will be able to save a tree.</p>" + "<br />Save a tree by clicking on the 'Save' button. This will<br />" + "open a window where you can browse to where you want to<br />" + "save a copy of the tree. You do not need to specify an<br />" + "extension (ie: .jpg, .gif, etc) the image will be automatically<br />" + "saved with a *.png extension for you.</p>"; } else if (command.equals(emailHelpCommand)) { text += "<h1>Emailing a File</h1>" + "<p>You also have to load an excel file so a graph is displayed before it can be emailed.<br>"+ "When you click on the email button you must input an email address to send the graph to.<br>" + "You do not have to select any file, the application will automaticlly select the picture of the graph.<br>"+ "After selecting a file, application will open a progress bar, which will close when the emailing process is complete.<br>"+ "You will then get a message stating whether the file was successfully sent or not.<br</p>"+ "<h2>Issues</h2>" + "<p>If not successful please must sure that you are connected to the internet.<br>"+ "Also must sure that you typed in the correct email address.<br>"+ "Please check to see if gmail server or your email server is up.<br>"; } else if (command.equals(printHelpCommand)) { text +="<h1>Printing a File</h1>" + "<p>You also have to load an excel file so a graph is displayed before it can be printed.<br>"+ "When you click on the print button a standard print window will open.<br>"+ "Please just select your printer and print the file.<br>"+ "The file will be printed zoomed out so it doesnt matter where the zoom slider is.<br>"; } else if (command.equals(aboutCommand)) { - text += "Ufaufaufa"; +text += "<h1>Team Members</h1><ul><li>Sandro Badame</li><li>Anthony DiFiore</li>" + + "<li>Christopher Eichel<li><li>Andrew Esca</li> <li>Andres Ramirez" + + "</li><li></li></ul><h2>To Learn more about this project follow us at:" + + "<a href=\"http://github.com/sbadame/desktopgradeapp/\">http://github.com/sbadame/desktopgradeapp/</a></h2>"; } text += "</HTML>"; textPane.setText(text); textPane.setEditable(false); JFrame helperframe = new JFrame(); // makes a window to put it in helperframe.getContentPane().add(new JScrollPane(textPane)); // adds the text pane to the window helperframe.pack(); // adjusts the window to the right size + helperframe.setSize(600, 500); helperframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); helperframe.addWindowListener(new WindowListener(){ public void windowClosed(WindowEvent e) { frame.pack(); frame.setVisible(true); } public void windowOpened(WindowEvent e) {} public void windowClosing(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} }); frame.setVisible(false); //Hide the help panel helperframe.setVisible(true); // makes it show up helperframe.setLocationRelativeTo(null); + textPane.setCaretPosition(0); return; } }); return createPane(simpleDialogDesc + ":", group, showItButton); } /** * Used by createSimpleDialogBox and createFeatureDialogBox * to create a pane containing a description, a single column * of radio buttons, and the Show it! button. */ private JPanel createPane(String description, ButtonGroup group, JButton showButton) { JPanel box = new JPanel(); JLabel label2 = new JLabel(description); box.setLayout(new BoxLayout(box, BoxLayout.PAGE_AXIS)); box.add(label2); Enumeration<AbstractButton> buttons = group.getElements(); while(buttons.hasMoreElements()) box.add(buttons.nextElement()); JPanel pane = new JPanel(new BorderLayout()); pane.add(box, BorderLayout.PAGE_START); pane.add(showButton, BorderLayout.PAGE_END); return pane; } /** * Create the GUI and show it. For thread safety, * this method should be invoked from the * event-dispatching thread. */ public static void createAndShowGUI() { //Create and set up the window. JFrame frame = new JFrame("Help Menu"); frame.setSize(400, 300); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setResizable(true); //Create and set up the content pane. HelperButton newContentPane = new HelperButton(frame); frame.setContentPane(newContentPane); //Display the window. frame.pack(); frame.setVisible(true); } }
false
true
private JPanel createSimpleDialogBox() { final ButtonGroup group = new ButtonGroup(); final String loadHelpCommand = "loadhelp"; final String graphHelpCommand = "graphhelp"; final String emailHelpCommand = "emailhelp"; final String saveHelpCommand = "savehelp"; final String printHelpCommand = "printhelp"; final String aboutCommand = "abouthelp"; JRadioButton loadhelp = new JRadioButton("Loading an Excel File."); loadhelp.setActionCommand(loadHelpCommand); group.add(loadhelp); JRadioButton graphHelp = new JRadioButton("Understanding and Modifying a Grade Tree"); graphHelp.setActionCommand(graphHelpCommand); group.add(graphHelp); JRadioButton emailHelp = new JRadioButton("Emailing a Tree"); emailHelp.setActionCommand(emailHelpCommand); group.add(emailHelp); JRadioButton saveHelp = new JRadioButton("Saving a Tree"); saveHelp.setActionCommand(saveHelpCommand); group.add(saveHelp); JRadioButton printHelp = new JRadioButton("Printing a Tree"); printHelp.setActionCommand(printHelpCommand); group.add(printHelp); JRadioButton aboutHelp = new JRadioButton("About the developers"); aboutHelp.setActionCommand(aboutCommand); group.add(aboutHelp); JButton showItButton = new JButton("Select"); showItButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String command = group.getSelection().getActionCommand(); JTextPane textPane = new JTextPane(); // creates an empty text pane textPane.setContentType("text/html"); // lets Java know it will be HTML String text = "<HTML>"; if (command.equals(loadHelpCommand)) { text += "<h1>How to load a file</h1>"; text += "<p>Begin by clicking on the 'Load *.xls' button<br />" + "which will open a window where you can browse<br />" + "your local drives for an Excel file to load. If you<br /> " + "have any issue loading a file, check the following:</p>" + "<ul><li>Are you selecting an Excel file(*.xls or *.xlsx)?</li>"+ "<li>Is the data in the selected Excel file arranged<br />"+ "in the same manner as was produced by the<br />Scantron machine?</li>"+ "</ul>"; } else if (command.equals(graphHelpCommand)) { text+= "<h1>Reading a Tree</h1><p>Once you have loaded a file a tree will be" + "shown. The tree is made up of cells and edges. Cell are the orange "+ "boxes and edges connect them. Each cell represents whether a question was" + "answered correctly or incorrectly. The main idea here is that there is no" + " extrapolation or guesswork done by the program. The results you see are" + " real.</p>"; text+="<h1>Setting what a good grade is.</h1><p>Of course, every exam is " + "different and so what constitues a good grade needs to be defined by you." + "The way that you do this is by moving the \"Good Grade\" slider to what" + "you think a good grade is.</p>"; text+="<h1>Setting the Quality</h1><p>Your first question probably is: \"What" + " is quality?\" or \"Why wouldn't I want the best Quality?\" What the quality" + " bar is really asking is \"How good a predictor does a question need to be" + " for me to show it to you?\" Basically, as the program breaks down how people" + " did on the exam (or as you traverse down the tree, however you wish to look"+ " at it.) the questions become worse and predictors. By raising the \"Quality\"" + " bar you are raising the cutoff on how good of a predictor the question needs" + " to be for it to be shown. As you increase quality you will see your tend to" + " shrink, increase and it grows. But be warned, a large graph does not necessarily " + " mean more information. Since the amount Quality wanted is dependent on the " + "exam,it needs to be tuned manually. A good rule of thumb is to increase the " + " as far as possible while still getting a <i>good</i>(This is a weasel word," + " I know) sized graph and then going down no further. </p>"; } else if (command.equals(saveHelpCommand)) { text += "<h1>Saving a Tree</h1>" + "<p><b>Note:</b> You need to have loaded an Excel file<br />" + "into the program before you will be able to save a tree.</p>" + "<br />Save a tree by clicking on the 'Save' button. This will<br />" + "open a window where you can browse to where you want to<br />" + "save a copy of the tree. You do not need to specify an<br />" + "extension (ie: .jpg, .gif, etc) the image will be automatically<br />" + "saved with a *.png extension for you.</p>"; } else if (command.equals(emailHelpCommand)) { text += "<h1>Emailing a File</h1>" + "<p>You also have to load an excel file so a graph is displayed before it can be emailed.<br>"+ "When you click on the email button you must input an email address to send the graph to.<br>" + "You do not have to select any file, the application will automaticlly select the picture of the graph.<br>"+ "After selecting a file, application will open a progress bar, which will close when the emailing process is complete.<br>"+ "You will then get a message stating whether the file was successfully sent or not.<br</p>"+ "<h2>Issues</h2>" + "<p>If not successful please must sure that you are connected to the internet.<br>"+ "Also must sure that you typed in the correct email address.<br>"+ "Please check to see if gmail server or your email server is up.<br>"; } else if (command.equals(printHelpCommand)) { text +="<h1>Printing a File</h1>" + "<p>You also have to load an excel file so a graph is displayed before it can be printed.<br>"+ "When you click on the print button a standard print window will open.<br>"+ "Please just select your printer and print the file.<br>"+ "The file will be printed zoomed out so it doesnt matter where the zoom slider is.<br>"; } else if (command.equals(aboutCommand)) { text += "Ufaufaufa"; } text += "</HTML>"; textPane.setText(text); textPane.setEditable(false); JFrame helperframe = new JFrame(); // makes a window to put it in helperframe.getContentPane().add(new JScrollPane(textPane)); // adds the text pane to the window helperframe.pack(); // adjusts the window to the right size helperframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); helperframe.addWindowListener(new WindowListener(){ public void windowClosed(WindowEvent e) { frame.pack(); frame.setVisible(true); } public void windowOpened(WindowEvent e) {} public void windowClosing(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} }); frame.setVisible(false); //Hide the help panel helperframe.setVisible(true); // makes it show up helperframe.setLocationRelativeTo(null); return; } }); return createPane(simpleDialogDesc + ":", group, showItButton); }
private JPanel createSimpleDialogBox() { final ButtonGroup group = new ButtonGroup(); final String loadHelpCommand = "loadhelp"; final String graphHelpCommand = "graphhelp"; final String emailHelpCommand = "emailhelp"; final String saveHelpCommand = "savehelp"; final String printHelpCommand = "printhelp"; final String aboutCommand = "abouthelp"; JRadioButton loadhelp = new JRadioButton("Loading an Excel File."); loadhelp.setActionCommand(loadHelpCommand); group.add(loadhelp); JRadioButton graphHelp = new JRadioButton("Understanding and Modifying a Grade Tree"); graphHelp.setActionCommand(graphHelpCommand); group.add(graphHelp); JRadioButton emailHelp = new JRadioButton("Emailing a Tree"); emailHelp.setActionCommand(emailHelpCommand); group.add(emailHelp); JRadioButton saveHelp = new JRadioButton("Saving a Tree"); saveHelp.setActionCommand(saveHelpCommand); group.add(saveHelp); JRadioButton printHelp = new JRadioButton("Printing a Tree"); printHelp.setActionCommand(printHelpCommand); group.add(printHelp); JRadioButton aboutHelp = new JRadioButton("About the developers"); aboutHelp.setActionCommand(aboutCommand); group.add(aboutHelp); JButton showItButton = new JButton("Select"); showItButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String command = group.getSelection().getActionCommand(); JTextPane textPane = new JTextPane(); // creates an empty text pane textPane.setContentType("text/html"); // lets Java know it will be HTML String text = "<HTML>"; if (command.equals(loadHelpCommand)) { text += "<h1>How to load a file</h1>"; text += "<p>Begin by clicking on the 'Load *.xls' button<br />" + "which will open a window where you can browse<br />" + "your local drives for an Excel file to load. If you<br /> " + "have any issue loading a file, check the following:</p>" + "<ul><li>Are you selecting an Excel file(*.xls or *.xlsx)?</li>"+ "<li>Is the data in the selected Excel file arranged<br />"+ "in the same manner as was produced by the<br />Scantron machine?</li>"+ "</ul>"; } else if (command.equals(graphHelpCommand)) { text+= "<h1>Reading a Tree</h1><p>Once you have loaded a file a tree will be" + "shown. The tree is made up of cells and edges. Cell are the orange "+ "boxes and edges connect them. Each cell represents whether a question was" + "answered correctly or incorrectly. The main idea here is that there is no" + " extrapolation or guesswork done by the program. The results you see are" + " real.</p>"; text+="<h1>Setting what a good grade is.</h1><p>Of course, every exam is " + "different and so what constitues a good grade needs to be defined by you." + "The way that you do this is by moving the \"Good Grade\" slider to what" + "you think a good grade is.</p>"; text+="<h1>Setting the Quality</h1><p>Your first question probably is: \"What" + " is quality?\" or \"Why wouldn't I want the best Quality?\" What the quality" + " bar is really asking is \"How good a predictor does a question need to be" + " for me to show it to you?\" Basically, as the program breaks down how people" + " did on the exam (or as you traverse down the tree, however you wish to look"+ " at it.) the questions become worse and predictors. By raising the \"Quality\"" + " bar you are raising the cutoff on how good of a predictor the question needs" + " to be for it to be shown. As you increase quality you will see your tend to" + " shrink, increase and it grows. But be warned, a large graph does not necessarily " + " mean more information. Since the amount Quality wanted is dependent on the " + "exam,it needs to be tuned manually. A good rule of thumb is to increase the " + " as far as possible while still getting a <i>good</i>(This is a weasel word," + " I know) sized graph and then going down no further. </p>"; } else if (command.equals(saveHelpCommand)) { text += "<h1>Saving a Tree</h1>" + "<p><b>Note:</b> You need to have loaded an Excel file<br />" + "into the program before you will be able to save a tree.</p>" + "<br />Save a tree by clicking on the 'Save' button. This will<br />" + "open a window where you can browse to where you want to<br />" + "save a copy of the tree. You do not need to specify an<br />" + "extension (ie: .jpg, .gif, etc) the image will be automatically<br />" + "saved with a *.png extension for you.</p>"; } else if (command.equals(emailHelpCommand)) { text += "<h1>Emailing a File</h1>" + "<p>You also have to load an excel file so a graph is displayed before it can be emailed.<br>"+ "When you click on the email button you must input an email address to send the graph to.<br>" + "You do not have to select any file, the application will automaticlly select the picture of the graph.<br>"+ "After selecting a file, application will open a progress bar, which will close when the emailing process is complete.<br>"+ "You will then get a message stating whether the file was successfully sent or not.<br</p>"+ "<h2>Issues</h2>" + "<p>If not successful please must sure that you are connected to the internet.<br>"+ "Also must sure that you typed in the correct email address.<br>"+ "Please check to see if gmail server or your email server is up.<br>"; } else if (command.equals(printHelpCommand)) { text +="<h1>Printing a File</h1>" + "<p>You also have to load an excel file so a graph is displayed before it can be printed.<br>"+ "When you click on the print button a standard print window will open.<br>"+ "Please just select your printer and print the file.<br>"+ "The file will be printed zoomed out so it doesnt matter where the zoom slider is.<br>"; } else if (command.equals(aboutCommand)) { text += "<h1>Team Members</h1><ul><li>Sandro Badame</li><li>Anthony DiFiore</li>" + "<li>Christopher Eichel<li><li>Andrew Esca</li> <li>Andres Ramirez" + "</li><li></li></ul><h2>To Learn more about this project follow us at:" + "<a href=\"http://github.com/sbadame/desktopgradeapp/\">http://github.com/sbadame/desktopgradeapp/</a></h2>"; } text += "</HTML>"; textPane.setText(text); textPane.setEditable(false); JFrame helperframe = new JFrame(); // makes a window to put it in helperframe.getContentPane().add(new JScrollPane(textPane)); // adds the text pane to the window helperframe.pack(); // adjusts the window to the right size helperframe.setSize(600, 500); helperframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); helperframe.addWindowListener(new WindowListener(){ public void windowClosed(WindowEvent e) { frame.pack(); frame.setVisible(true); } public void windowOpened(WindowEvent e) {} public void windowClosing(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} }); frame.setVisible(false); //Hide the help panel helperframe.setVisible(true); // makes it show up helperframe.setLocationRelativeTo(null); textPane.setCaretPosition(0); return; } }); return createPane(simpleDialogDesc + ":", group, showItButton); }