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/ini/trakem2/persistence/ProjectTiler.java b/ini/trakem2/persistence/ProjectTiler.java index 2832136d..67e06503 100644 --- a/ini/trakem2/persistence/ProjectTiler.java +++ b/ini/trakem2/persistence/ProjectTiler.java @@ -1,188 +1,188 @@ package ini.trakem2.persistence; import ij.ImagePlus; import ij.io.FileSaver; import ini.trakem2.Project; import ini.trakem2.display.DLabel; import ini.trakem2.display.Display; import ini.trakem2.display.Layer; import ini.trakem2.display.LayerSet; import ini.trakem2.display.Patch; import ini.trakem2.parallel.CountingTaskFactory; import ini.trakem2.parallel.Process; import ini.trakem2.tree.LayerThing; import ini.trakem2.tree.ProjectThing; import ini.trakem2.tree.TemplateThing; import ini.trakem2.utils.IJError; import ini.trakem2.utils.Utils; import java.io.File; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.concurrent.Callable; import mpicbg.trakem2.transform.ExportUnsignedShortLayer; import mpicbg.trakem2.transform.ExportedTile; public class ProjectTiler { /** Take a {@link Project}, a size for the image tiles, and a target directory, * and create a new copy of the current project in that folder but with the underlying * images converted to tiles with a translation-only transform. * The purpose of this newProject is to represent the given project but with much * simpler transformations for the images and a defined size for the latter, * which helps a lot regarding storage space of the XML (and parsing and saving time) * and performance when browsing layers (keep in mind that, for a 32k x 32k image, * at 100% zoom one would have to load a 32k x 32k image and render just a tiny bit * of it). * * The non-image objects of the given project are copied into the new project as well. * * @param srcProject The * @param targetDirectory The directory in which to create all the necessary data and mipmap folders for the new Project. * @param tileSide The size of the tiles to create for the data of the new project. * @param exportImageType Either {@link ImagePlus#GRAY16} or {@link ImagePlus#COLOR_RGB}, otherwise an {@link IllegalArgumentException} is thrown. * @param nExportThreads Number of layers to export in parallel. Use a small number when original images are huge (such as larger than 4096 x 4096 pixels). * * @throws Exception IllegalArgumentException When {@param exportImageType} is not {@link ImagePlus#GRAY16} or {@link ImagePlus#COLOR_RGB}, or when the directory exists and cannot be written to. */ static final public Project flatten( final Project srcProject, final String targetDirectory, final int tileSide, final int exportImageType, final boolean onlyVisibleImages, final int nExportThreads, final boolean createMipMaps) throws Exception { // Validate exportImageType switch (exportImageType) { case ImagePlus.GRAY16: case ImagePlus.COLOR_RGB: break; default: throw new IllegalArgumentException("Can only accept GRAY16 or COLOR_RGB as values for 'exportImageType'!"); } // Validate targetDirectory final File fdir = new File(targetDirectory); if (fdir.exists()) { if (!fdir.isDirectory() || !fdir.canWrite()) throw new IllegalArgumentException("Invalid directory: not a directory or cannot write to: " + targetDirectory); } else { if (!fdir.mkdirs()) { throw new IllegalArgumentException("Cannot create directory at: " + targetDirectory); } } // Create data directory final String dataDir = new StringBuilder(targetDirectory.replace('\\', '/')).append('/').append("data/").toString(); final File fDataDir = new File(dataDir); if (fDataDir.exists() && (!fDataDir.isDirectory() || !fDataDir.canWrite())) { throw new IllegalArgumentException("Cannot create data directory in the targetDirectory at: " + dataDir); } else { fDataDir.mkdir(); } // Create new Project, plain, without any automatic creation of a Layer or a Display final Project newProject = Project.newFSProject("blank", null, dataDir, false); final LayerSet newLayerSet = newProject.getRootLayerSet(); if (!createMipMaps) { Utils.log("MipMaps are DISABLED:\n --> When done, right-click and choose 'Display - Properties...' and enable mipmaps,\n and then run 'Project - Regenerate all mipmaps'\n"); newProject.getLoader().setMipMapsRegeneration(false); } // Copy the Template Tree of types newProject.getUniqueTypes(); // works by side-effect; adds all basic types. newProject.resetRootTemplateThing(srcProject.getRootTemplateThing().clone(newProject, true), null); for (final TemplateThing tt : newProject.getRootTemplateThing().getUniqueTypes(new HashMap<String,TemplateThing>()).values()) { newProject.addUniqueType(tt); } // Clone layers with the exact same IDs, so that the two projects are siblings at the layer-level: final List<Layer> srcLayers = srcProject.getRootLayerSet().getLayers(); final List<Layer> newLayers = new ArrayList<Layer>(); for (final Layer srcLayer : srcLayers) { final Layer newLayer = new Layer(newProject, srcLayer.getId(), srcLayer.getZ(), srcLayer.getThickness()); newLayer.addToDatabase(); // to update the ID generator in FSLoader newLayerSet.add(newLayer); newLayers.add(newLayer); - newProject.getRootLayerThing().addChild(new LayerThing(newProject.getTemplateThing("layer"), newProject, newLayer)); + newProject.getRootLayerThing().addChild(new LayerThing(newProject.getRootLayerThing().getChildTemplate("layer"), newProject, newLayer)); } + newProject.getLayerTree().rebuild(); // Update the LayerSet newLayerSet.setDimensions(srcProject.getRootLayerSet().getLayerWidth(), srcProject.getRootLayerSet().getLayerHeight()); - newProject.getLayerTree().rebuild(); Display.updateLayerScroller(newLayerSet); Display.update(newLayerSet); // Copy template from the src Project // (It's done after creating layers so the IDs will not collide with those of the Layers) newProject.resetRootTemplateThing(srcProject.getRootTemplateThing().clone(newProject, false), null); // Export tiles as new Patch instances, creating new PNG files in disk int i = 0; for (final Layer srcLayer : srcLayers) { Utils.log("Processing layer " + i + "/" + srcLayers.size() + " -- " + new Date()); final int layerIndex = i++; // Create subDirectory final String dir = dataDir + "/" + layerIndex + "/"; new File(dir).mkdir(); // Create a new Layer with the same Z and thickness final Layer newLayer = newLayers.get(layerIndex); // Export layer tiles final ArrayList<Patch> patches = new ArrayList<Patch>(); Process.progressive( ExportUnsignedShortLayer.exportTiles(srcLayer, tileSide, tileSide, onlyVisibleImages), new CountingTaskFactory<Callable<ExportedTile>, Patch>() { public Patch process(final Callable<ExportedTile> c, final int index) { try { // Create the tile final ExportedTile t = c.call(); // Store the file final String title = layerIndex + "-" + index; final String path = dir + title + ".png"; final ImagePlus imp = new ImagePlus(title, t.sp); if (!new FileSaver(imp).saveAsPng(path)) { throw new Exception("Could not save tile: " + path); } // Create a Patch final Patch patch = new Patch(newProject, title, t.x, t.y, imp); patch.setMinAndMax(t.min, t.max); newProject.getLoader().addedPatchFrom(path, patch); return patch; } catch (Exception e) { IJError.print(e); return null; } } }, patches, Math.max(1, Math.min(nExportThreads, Runtime.getRuntime().availableProcessors()))); // Add all Patches to the new Layer for (final Patch p : patches) { newLayer.add(p); } } // Copy all segmentations "As is" final ProjectThing source_pt = srcProject.getRootProjectThing().getChildren().get(0); final int transfer_mode = 0; // "As is" final ProjectThing landing_parent = newProject.getRootProjectThing(); srcProject.getProjectTree().rawSendToSiblingProject(source_pt, transfer_mode, newProject, landing_parent); // Copy all floating text labels i = 0; for (final Layer srcLayer : srcLayers) { for (final DLabel srcLabel : srcLayer.getAll(DLabel.class)) { newLayers.get(i++).add(srcLabel.clone(newProject, false)); } } return newProject; } }
false
true
static final public Project flatten( final Project srcProject, final String targetDirectory, final int tileSide, final int exportImageType, final boolean onlyVisibleImages, final int nExportThreads, final boolean createMipMaps) throws Exception { // Validate exportImageType switch (exportImageType) { case ImagePlus.GRAY16: case ImagePlus.COLOR_RGB: break; default: throw new IllegalArgumentException("Can only accept GRAY16 or COLOR_RGB as values for 'exportImageType'!"); } // Validate targetDirectory final File fdir = new File(targetDirectory); if (fdir.exists()) { if (!fdir.isDirectory() || !fdir.canWrite()) throw new IllegalArgumentException("Invalid directory: not a directory or cannot write to: " + targetDirectory); } else { if (!fdir.mkdirs()) { throw new IllegalArgumentException("Cannot create directory at: " + targetDirectory); } } // Create data directory final String dataDir = new StringBuilder(targetDirectory.replace('\\', '/')).append('/').append("data/").toString(); final File fDataDir = new File(dataDir); if (fDataDir.exists() && (!fDataDir.isDirectory() || !fDataDir.canWrite())) { throw new IllegalArgumentException("Cannot create data directory in the targetDirectory at: " + dataDir); } else { fDataDir.mkdir(); } // Create new Project, plain, without any automatic creation of a Layer or a Display final Project newProject = Project.newFSProject("blank", null, dataDir, false); final LayerSet newLayerSet = newProject.getRootLayerSet(); if (!createMipMaps) { Utils.log("MipMaps are DISABLED:\n --> When done, right-click and choose 'Display - Properties...' and enable mipmaps,\n and then run 'Project - Regenerate all mipmaps'\n"); newProject.getLoader().setMipMapsRegeneration(false); } // Copy the Template Tree of types newProject.getUniqueTypes(); // works by side-effect; adds all basic types. newProject.resetRootTemplateThing(srcProject.getRootTemplateThing().clone(newProject, true), null); for (final TemplateThing tt : newProject.getRootTemplateThing().getUniqueTypes(new HashMap<String,TemplateThing>()).values()) { newProject.addUniqueType(tt); } // Clone layers with the exact same IDs, so that the two projects are siblings at the layer-level: final List<Layer> srcLayers = srcProject.getRootLayerSet().getLayers(); final List<Layer> newLayers = new ArrayList<Layer>(); for (final Layer srcLayer : srcLayers) { final Layer newLayer = new Layer(newProject, srcLayer.getId(), srcLayer.getZ(), srcLayer.getThickness()); newLayer.addToDatabase(); // to update the ID generator in FSLoader newLayerSet.add(newLayer); newLayers.add(newLayer); newProject.getRootLayerThing().addChild(new LayerThing(newProject.getTemplateThing("layer"), newProject, newLayer)); } // Update the LayerSet newLayerSet.setDimensions(srcProject.getRootLayerSet().getLayerWidth(), srcProject.getRootLayerSet().getLayerHeight()); newProject.getLayerTree().rebuild(); Display.updateLayerScroller(newLayerSet); Display.update(newLayerSet); // Copy template from the src Project // (It's done after creating layers so the IDs will not collide with those of the Layers) newProject.resetRootTemplateThing(srcProject.getRootTemplateThing().clone(newProject, false), null); // Export tiles as new Patch instances, creating new PNG files in disk int i = 0; for (final Layer srcLayer : srcLayers) { Utils.log("Processing layer " + i + "/" + srcLayers.size() + " -- " + new Date()); final int layerIndex = i++; // Create subDirectory final String dir = dataDir + "/" + layerIndex + "/"; new File(dir).mkdir(); // Create a new Layer with the same Z and thickness final Layer newLayer = newLayers.get(layerIndex); // Export layer tiles final ArrayList<Patch> patches = new ArrayList<Patch>(); Process.progressive( ExportUnsignedShortLayer.exportTiles(srcLayer, tileSide, tileSide, onlyVisibleImages), new CountingTaskFactory<Callable<ExportedTile>, Patch>() { public Patch process(final Callable<ExportedTile> c, final int index) { try { // Create the tile final ExportedTile t = c.call(); // Store the file final String title = layerIndex + "-" + index; final String path = dir + title + ".png"; final ImagePlus imp = new ImagePlus(title, t.sp); if (!new FileSaver(imp).saveAsPng(path)) { throw new Exception("Could not save tile: " + path); } // Create a Patch final Patch patch = new Patch(newProject, title, t.x, t.y, imp); patch.setMinAndMax(t.min, t.max); newProject.getLoader().addedPatchFrom(path, patch); return patch; } catch (Exception e) { IJError.print(e); return null; } } }, patches, Math.max(1, Math.min(nExportThreads, Runtime.getRuntime().availableProcessors()))); // Add all Patches to the new Layer for (final Patch p : patches) { newLayer.add(p); } } // Copy all segmentations "As is" final ProjectThing source_pt = srcProject.getRootProjectThing().getChildren().get(0); final int transfer_mode = 0; // "As is" final ProjectThing landing_parent = newProject.getRootProjectThing(); srcProject.getProjectTree().rawSendToSiblingProject(source_pt, transfer_mode, newProject, landing_parent); // Copy all floating text labels i = 0; for (final Layer srcLayer : srcLayers) { for (final DLabel srcLabel : srcLayer.getAll(DLabel.class)) { newLayers.get(i++).add(srcLabel.clone(newProject, false)); } } return newProject; }
static final public Project flatten( final Project srcProject, final String targetDirectory, final int tileSide, final int exportImageType, final boolean onlyVisibleImages, final int nExportThreads, final boolean createMipMaps) throws Exception { // Validate exportImageType switch (exportImageType) { case ImagePlus.GRAY16: case ImagePlus.COLOR_RGB: break; default: throw new IllegalArgumentException("Can only accept GRAY16 or COLOR_RGB as values for 'exportImageType'!"); } // Validate targetDirectory final File fdir = new File(targetDirectory); if (fdir.exists()) { if (!fdir.isDirectory() || !fdir.canWrite()) throw new IllegalArgumentException("Invalid directory: not a directory or cannot write to: " + targetDirectory); } else { if (!fdir.mkdirs()) { throw new IllegalArgumentException("Cannot create directory at: " + targetDirectory); } } // Create data directory final String dataDir = new StringBuilder(targetDirectory.replace('\\', '/')).append('/').append("data/").toString(); final File fDataDir = new File(dataDir); if (fDataDir.exists() && (!fDataDir.isDirectory() || !fDataDir.canWrite())) { throw new IllegalArgumentException("Cannot create data directory in the targetDirectory at: " + dataDir); } else { fDataDir.mkdir(); } // Create new Project, plain, without any automatic creation of a Layer or a Display final Project newProject = Project.newFSProject("blank", null, dataDir, false); final LayerSet newLayerSet = newProject.getRootLayerSet(); if (!createMipMaps) { Utils.log("MipMaps are DISABLED:\n --> When done, right-click and choose 'Display - Properties...' and enable mipmaps,\n and then run 'Project - Regenerate all mipmaps'\n"); newProject.getLoader().setMipMapsRegeneration(false); } // Copy the Template Tree of types newProject.getUniqueTypes(); // works by side-effect; adds all basic types. newProject.resetRootTemplateThing(srcProject.getRootTemplateThing().clone(newProject, true), null); for (final TemplateThing tt : newProject.getRootTemplateThing().getUniqueTypes(new HashMap<String,TemplateThing>()).values()) { newProject.addUniqueType(tt); } // Clone layers with the exact same IDs, so that the two projects are siblings at the layer-level: final List<Layer> srcLayers = srcProject.getRootLayerSet().getLayers(); final List<Layer> newLayers = new ArrayList<Layer>(); for (final Layer srcLayer : srcLayers) { final Layer newLayer = new Layer(newProject, srcLayer.getId(), srcLayer.getZ(), srcLayer.getThickness()); newLayer.addToDatabase(); // to update the ID generator in FSLoader newLayerSet.add(newLayer); newLayers.add(newLayer); newProject.getRootLayerThing().addChild(new LayerThing(newProject.getRootLayerThing().getChildTemplate("layer"), newProject, newLayer)); } newProject.getLayerTree().rebuild(); // Update the LayerSet newLayerSet.setDimensions(srcProject.getRootLayerSet().getLayerWidth(), srcProject.getRootLayerSet().getLayerHeight()); Display.updateLayerScroller(newLayerSet); Display.update(newLayerSet); // Copy template from the src Project // (It's done after creating layers so the IDs will not collide with those of the Layers) newProject.resetRootTemplateThing(srcProject.getRootTemplateThing().clone(newProject, false), null); // Export tiles as new Patch instances, creating new PNG files in disk int i = 0; for (final Layer srcLayer : srcLayers) { Utils.log("Processing layer " + i + "/" + srcLayers.size() + " -- " + new Date()); final int layerIndex = i++; // Create subDirectory final String dir = dataDir + "/" + layerIndex + "/"; new File(dir).mkdir(); // Create a new Layer with the same Z and thickness final Layer newLayer = newLayers.get(layerIndex); // Export layer tiles final ArrayList<Patch> patches = new ArrayList<Patch>(); Process.progressive( ExportUnsignedShortLayer.exportTiles(srcLayer, tileSide, tileSide, onlyVisibleImages), new CountingTaskFactory<Callable<ExportedTile>, Patch>() { public Patch process(final Callable<ExportedTile> c, final int index) { try { // Create the tile final ExportedTile t = c.call(); // Store the file final String title = layerIndex + "-" + index; final String path = dir + title + ".png"; final ImagePlus imp = new ImagePlus(title, t.sp); if (!new FileSaver(imp).saveAsPng(path)) { throw new Exception("Could not save tile: " + path); } // Create a Patch final Patch patch = new Patch(newProject, title, t.x, t.y, imp); patch.setMinAndMax(t.min, t.max); newProject.getLoader().addedPatchFrom(path, patch); return patch; } catch (Exception e) { IJError.print(e); return null; } } }, patches, Math.max(1, Math.min(nExportThreads, Runtime.getRuntime().availableProcessors()))); // Add all Patches to the new Layer for (final Patch p : patches) { newLayer.add(p); } } // Copy all segmentations "As is" final ProjectThing source_pt = srcProject.getRootProjectThing().getChildren().get(0); final int transfer_mode = 0; // "As is" final ProjectThing landing_parent = newProject.getRootProjectThing(); srcProject.getProjectTree().rawSendToSiblingProject(source_pt, transfer_mode, newProject, landing_parent); // Copy all floating text labels i = 0; for (final Layer srcLayer : srcLayers) { for (final DLabel srcLabel : srcLayer.getAll(DLabel.class)) { newLayers.get(i++).add(srcLabel.clone(newProject, false)); } } return newProject; }
diff --git a/src/main/java/org/apache/log4j/xml/Log4jEntityResolver.java b/src/main/java/org/apache/log4j/xml/Log4jEntityResolver.java index 8ff2d610..03a801f8 100644 --- a/src/main/java/org/apache/log4j/xml/Log4jEntityResolver.java +++ b/src/main/java/org/apache/log4j/xml/Log4jEntityResolver.java @@ -1,50 +1,50 @@ /* * 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.log4j.xml; import org.apache.log4j.helpers.LogLog; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import java.io.InputStream; import java.io.ByteArrayInputStream; /** * An {@link EntityResolver} specifically designed to return * <code>log4j.dtd</code> which is embedded within the log4j jar * file. * * @author Paul Austin * */ public class Log4jEntityResolver implements EntityResolver { public InputSource resolveEntity (String publicId, String systemId) { if (systemId.endsWith("log4j.dtd")) { Class clazz = getClass(); InputStream in = clazz.getResourceAsStream("/org/apache/log4j/xml/log4j.dtd"); if (in == null) { - LogLog.error("Could not find [log4j.dtd]. Used [" + clazz.getClassLoader() - + "] class loader in the search."); + LogLog.warn("Could not find [log4j.dtd] using [" + clazz.getClassLoader() + + "] class loader, parsed without DTD."); in = new ByteArrayInputStream(new byte[0]); } return new InputSource(in); } else { return null; } } }
true
true
public InputSource resolveEntity (String publicId, String systemId) { if (systemId.endsWith("log4j.dtd")) { Class clazz = getClass(); InputStream in = clazz.getResourceAsStream("/org/apache/log4j/xml/log4j.dtd"); if (in == null) { LogLog.error("Could not find [log4j.dtd]. Used [" + clazz.getClassLoader() + "] class loader in the search."); in = new ByteArrayInputStream(new byte[0]); } return new InputSource(in); } else { return null; } }
public InputSource resolveEntity (String publicId, String systemId) { if (systemId.endsWith("log4j.dtd")) { Class clazz = getClass(); InputStream in = clazz.getResourceAsStream("/org/apache/log4j/xml/log4j.dtd"); if (in == null) { LogLog.warn("Could not find [log4j.dtd] using [" + clazz.getClassLoader() + "] class loader, parsed without DTD."); in = new ByteArrayInputStream(new byte[0]); } return new InputSource(in); } else { return null; } }
diff --git a/src/main/java/hudson/plugins/active_directory/ActiveDirectoryUnixAuthenticationProvider.java b/src/main/java/hudson/plugins/active_directory/ActiveDirectoryUnixAuthenticationProvider.java index 9a33898..87e89fe 100644 --- a/src/main/java/hudson/plugins/active_directory/ActiveDirectoryUnixAuthenticationProvider.java +++ b/src/main/java/hudson/plugins/active_directory/ActiveDirectoryUnixAuthenticationProvider.java @@ -1,124 +1,125 @@ package hudson.plugins.active_directory; import com.sun.jndi.ldap.LdapCtxFactory; import hudson.plugins.active_directory.ActiveDirectorySecurityRealm.DesciprotrImpl; import org.acegisecurity.AuthenticationException; import org.acegisecurity.BadCredentialsException; import org.acegisecurity.GrantedAuthority; import org.acegisecurity.GrantedAuthorityImpl; import org.acegisecurity.providers.AuthenticationProvider; import org.acegisecurity.providers.UsernamePasswordAuthenticationToken; import org.acegisecurity.providers.dao.AbstractUserDetailsAuthenticationProvider; import org.acegisecurity.userdetails.UserDetails; import org.acegisecurity.userdetails.UserDetailsService; import org.acegisecurity.userdetails.UsernameNotFoundException; import org.springframework.dao.DataAccessException; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; import javax.naming.directory.SearchControls; import static javax.naming.directory.SearchControls.SUBTREE_SCOPE; import javax.naming.directory.SearchResult; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * {@link AuthenticationProvider} with Active Directory, through LDAP. * * @author Kohsuke Kawaguchi */ public class ActiveDirectoryUnixAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider implements UserDetailsService { private final String domainName; public ActiveDirectoryUnixAuthenticationProvider(String domainName) { this.domainName = domainName; } /** * We'd like to implement {@link UserDetailsService} ideally, but in short of keeping the manager user/password, * we can't do so. In Active Directory authentication, we should support SPNEGO/Kerberos and * that should eliminate the need for the "remember me" service. */ public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { throw new UsernameNotFoundException("Active-directory plugin doesn't support user retrieval"); } protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { // active directory authentication is not by comparing clear text password, // so there's nothing to do here. } protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { String password = null; if(authentication!=null) password = (String) authentication.getCredentials(); // bind by using the specified username/password Hashtable props = new Hashtable(); String principalName = username + '@' + domainName; props.put(Context.SECURITY_PRINCIPAL, principalName); props.put(Context.SECURITY_CREDENTIALS,password); + props.put(Context.REFERRAL, "follow"); DirContext context; try { context = LdapCtxFactory.getLdapCtxInstance( "ldap://" + DesciprotrImpl.INSTANCE.obtainLDAPServer(domainName) + '/', props); } catch (NamingException e) { LOGGER.log(Level.WARNING,"Failed to bind to LDAP",e); throw new BadCredentialsException("Either no such user '"+principalName+"' or incorrect password",e); } try { // locate this user's record SearchControls controls = new SearchControls(); controls.setSearchScope(SUBTREE_SCOPE); NamingEnumeration<SearchResult> renum = context.search(toDC(domainName),"(& (userPrincipalName="+principalName+")(objectClass=user))", controls); if(!renum.hasMore()) throw new BadCredentialsException("Authentication was successful but cannot locate the user information for "+username); SearchResult result = renum.next(); List<GrantedAuthority> groups = new ArrayList<GrantedAuthority>(); Attribute memberOf = result.getAttributes().get("memberOf"); if(memberOf!=null) {// null if this user belongs to no group at all for(int i=0; i<memberOf.size(); i++) { Attributes atts = context.getAttributes(memberOf.get(i).toString(), new String[]{"CN"}); Attribute att = atts.get("CN"); groups.add(new GrantedAuthorityImpl(att.get().toString())); } } context.close(); return new ActiveDirectoryUserDetail( username, password, true, true, true, true, groups.toArray(new GrantedAuthority[groups.size()]) ); } catch (NamingException e) { LOGGER.log(Level.WARNING,"Failed to retrieve user information for "+username,e); throw new BadCredentialsException("Failed to retrieve user information for "+username,e); } } private static String toDC(String domainName) { StringBuilder buf = new StringBuilder(); for (String token : domainName.split("\\.")) { if(token.length()==0) continue; // defensive check if(buf.length()>0) buf.append(","); buf.append("DC=").append(token); } return buf.toString(); } private static final Logger LOGGER = Logger.getLogger(ActiveDirectoryUnixAuthenticationProvider.class.getName()); }
true
true
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { String password = null; if(authentication!=null) password = (String) authentication.getCredentials(); // bind by using the specified username/password Hashtable props = new Hashtable(); String principalName = username + '@' + domainName; props.put(Context.SECURITY_PRINCIPAL, principalName); props.put(Context.SECURITY_CREDENTIALS,password); DirContext context; try { context = LdapCtxFactory.getLdapCtxInstance( "ldap://" + DesciprotrImpl.INSTANCE.obtainLDAPServer(domainName) + '/', props); } catch (NamingException e) { LOGGER.log(Level.WARNING,"Failed to bind to LDAP",e); throw new BadCredentialsException("Either no such user '"+principalName+"' or incorrect password",e); } try { // locate this user's record SearchControls controls = new SearchControls(); controls.setSearchScope(SUBTREE_SCOPE); NamingEnumeration<SearchResult> renum = context.search(toDC(domainName),"(& (userPrincipalName="+principalName+")(objectClass=user))", controls); if(!renum.hasMore()) throw new BadCredentialsException("Authentication was successful but cannot locate the user information for "+username); SearchResult result = renum.next(); List<GrantedAuthority> groups = new ArrayList<GrantedAuthority>(); Attribute memberOf = result.getAttributes().get("memberOf"); if(memberOf!=null) {// null if this user belongs to no group at all for(int i=0; i<memberOf.size(); i++) { Attributes atts = context.getAttributes(memberOf.get(i).toString(), new String[]{"CN"}); Attribute att = atts.get("CN"); groups.add(new GrantedAuthorityImpl(att.get().toString())); } } context.close(); return new ActiveDirectoryUserDetail( username, password, true, true, true, true, groups.toArray(new GrantedAuthority[groups.size()]) ); } catch (NamingException e) { LOGGER.log(Level.WARNING,"Failed to retrieve user information for "+username,e); throw new BadCredentialsException("Failed to retrieve user information for "+username,e); } }
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { String password = null; if(authentication!=null) password = (String) authentication.getCredentials(); // bind by using the specified username/password Hashtable props = new Hashtable(); String principalName = username + '@' + domainName; props.put(Context.SECURITY_PRINCIPAL, principalName); props.put(Context.SECURITY_CREDENTIALS,password); props.put(Context.REFERRAL, "follow"); DirContext context; try { context = LdapCtxFactory.getLdapCtxInstance( "ldap://" + DesciprotrImpl.INSTANCE.obtainLDAPServer(domainName) + '/', props); } catch (NamingException e) { LOGGER.log(Level.WARNING,"Failed to bind to LDAP",e); throw new BadCredentialsException("Either no such user '"+principalName+"' or incorrect password",e); } try { // locate this user's record SearchControls controls = new SearchControls(); controls.setSearchScope(SUBTREE_SCOPE); NamingEnumeration<SearchResult> renum = context.search(toDC(domainName),"(& (userPrincipalName="+principalName+")(objectClass=user))", controls); if(!renum.hasMore()) throw new BadCredentialsException("Authentication was successful but cannot locate the user information for "+username); SearchResult result = renum.next(); List<GrantedAuthority> groups = new ArrayList<GrantedAuthority>(); Attribute memberOf = result.getAttributes().get("memberOf"); if(memberOf!=null) {// null if this user belongs to no group at all for(int i=0; i<memberOf.size(); i++) { Attributes atts = context.getAttributes(memberOf.get(i).toString(), new String[]{"CN"}); Attribute att = atts.get("CN"); groups.add(new GrantedAuthorityImpl(att.get().toString())); } } context.close(); return new ActiveDirectoryUserDetail( username, password, true, true, true, true, groups.toArray(new GrantedAuthority[groups.size()]) ); } catch (NamingException e) { LOGGER.log(Level.WARNING,"Failed to retrieve user information for "+username,e); throw new BadCredentialsException("Failed to retrieve user information for "+username,e); } }
diff --git a/src/com/redhat/ceylon/ant/CeylonAntTask.java b/src/com/redhat/ceylon/ant/CeylonAntTask.java index 99dbe19cb..6655bc1ad 100644 --- a/src/com/redhat/ceylon/ant/CeylonAntTask.java +++ b/src/com/redhat/ceylon/ant/CeylonAntTask.java @@ -1,243 +1,243 @@ /* * Copyright Red Hat Inc. and/or its affiliates and other contributors * as indicated by the authors tag. All rights reserved. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License version 2. * * This particular file is subject to the "Classpath" exception as provided in the * LICENSE file that accompanied this code. * * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License, * along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package com.redhat.ceylon.ant; import java.io.File; import java.util.Arrays; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; import org.apache.tools.ant.taskdefs.Execute; import org.apache.tools.ant.taskdefs.LogStreamHandler; import org.apache.tools.ant.types.Commandline; import com.redhat.ceylon.launcher.Launcher; /** * Baseclass for ant tasks which execute a ceylon tool in a subprocess. */ public abstract class CeylonAntTask extends Task { private final String toolName; private File executable; private ExitHandler exitHandler = new ExitHandler(); /** * @param toolName The name of the ceylon tool which this task executes. */ protected CeylonAntTask(String toolName) { this.toolName = toolName; } public String getExecutable() { return executable.getPath(); } /** Sets the location of the ceylon executable script */ public void setExecutable(String executable) { this.executable = new File(Util.getScriptName(executable)); } public boolean getFailOnError() { return exitHandler.isFailOnError(); } /** Sets whether an error in executing this task should fail the build */ public void setFailOnError(boolean failOnError) { this.exitHandler.setFailOnError(failOnError); } public String getErrorProperty() { return exitHandler.getErrorProperty(); } /** Sets name of a property to set to true in the event of an error */ public void setErrorProperty(String errorProperty) { this.exitHandler.setErrorProperty(errorProperty); } /** * Sets the Ceylon program exit code into the given property * @param resultProperty the property to set to the Ceylon program exit code */ public void setResultProperty(String resultProperty){ this.exitHandler.setResultProperty(resultProperty); } /** Executes the task */ public void execute() { Java7Checker.check(); checkParameters(); Commandline cmd = buildCommandline(); if (cmd != null) { executeCommandline(cmd); } } /** * Executes a Commandline * @param cmd The commandline */ protected void executeCommandline(Commandline cmd) { try { // Execute exe = new Execute(new LogStreamHandler(this, Project.MSG_INFO, Project.MSG_WARN)); // exe.setAntRun(getProject()); // exe.setWorkingDirectory(getProject().getBaseDir()); // exe.setCommandline(cmd.getCommandline()); // exe.execute(); // int exitValue = exe.getExitValue(); log("Command line " + Arrays.toString(cmd.getCommandline()), Project.MSG_VERBOSE); int exitValue = Launcher.run(cmd.getArguments()); if (exitValue != 0) { String message = formatFailureMessage(cmd); exitHandler.handleExit(this, exitValue, message); }else{ exitHandler.handleExit(this, exitValue, null); } } catch (Throwable e) { - throw new BuildException("Error running Ceylon compiler", e, getLocation()); + throw new BuildException("Error running Ceylon " + toolName + " tool (an exception was thrown, run ant with -v parameter to see the exception)", e, getLocation()); } } protected String formatFailureMessage(Commandline cmd) { StringBuilder sb = new StringBuilder("While executing command").append(System.lineSeparator()); for (String s : cmd.getCommandline()) { sb.append(" ").append(s).append(System.lineSeparator()); } sb.append(getFailMessage()); String message = sb.toString(); return message; } /** * Returns the message to pass to {@link ExitHandler#handleExit(Task, int, String)} */ protected abstract String getFailMessage(); /** * Builds the command line to be executed * @return the command line to be executed, * or null if there is no command to be executed */ protected Commandline buildCommandline() { Commandline cmd = new Commandline(); cmd.setExecutable(findExecutable()); cmd.createArgument().setValue(toolName); completeCommandline(cmd); return cmd; } /** * Completes the building of a partially configured Commandline * @param cmd */ protected abstract void completeCommandline(Commandline cmd); /** * Checks the parameters */ protected void checkParameters() { findExecutable(); } /** * Tries to find a ceylonc compiler either user-specified or detected */ private String findExecutable() { return Util.findCeylonScript(this.executable, getProject()); } /** * Adds a {@code --verbose} (or {@code --verbose=flags}) to the given * command line * @param cmd The command line * @param verbose The verbose flags: {@code "true"}, {@code "yes"} or * {@code "on"} just adds a plain {@code --verbose} option, * {@code "false"}, {@code "no"} or * {@code "off"} doesn't add any option, * otherwise the value is * treated as a list of flags and is passed verbatim via {@code --verbose=...}. */ protected static void appendVerboseOption(Commandline cmd, String verbose) { if (verbose != null && !"false".equals(verbose) && !"no".equals(verbose) && !"off".equals(verbose)) { if ("true".equals(verbose) || "yes".equals(verbose) || "on".equals(verbose)) { // backward compat with verbose previously being a Boolean appendOption(cmd, "--verbose"); } else { appendOptionArgument(cmd, "--verbose", verbose); } } } /** * Adds a {@code --user=user} to the given command line iff the given user * is not null. * @param cmd The command line * @param user The user */ protected static void appendUserOption(Commandline cmd, String user) { appendOptionArgument(cmd, "--user", user); } /** * Adds a {@code --pass=pass} to the given command line iff the given * password is not null. * @param cmd The command line * @param pass The password */ protected static void appendPassOption(Commandline cmd, String pass) { appendOptionArgument(cmd, "--pass", pass); } /** * Adds a long option argument to the given command line iff the given * value is not null. * @param cmd The command line * @param longOption The long option name (including the {@code --}, but * excluding the {@code =}). * @param value The option value */ protected static void appendOptionArgument(Commandline cmd, String longOption, String value) { if (value != null){ cmd.createArgument().setValue(longOption); cmd.createArgument().setValue(value); } } /** * Adds a long option (with no argument) to the given command line. * @param cmd The command line * @param longOption The long option name (including the {@code --} */ protected static void appendOption(Commandline cmd, String longOption) { cmd.createArgument().setValue(longOption); } }
true
true
protected void executeCommandline(Commandline cmd) { try { // Execute exe = new Execute(new LogStreamHandler(this, Project.MSG_INFO, Project.MSG_WARN)); // exe.setAntRun(getProject()); // exe.setWorkingDirectory(getProject().getBaseDir()); // exe.setCommandline(cmd.getCommandline()); // exe.execute(); // int exitValue = exe.getExitValue(); log("Command line " + Arrays.toString(cmd.getCommandline()), Project.MSG_VERBOSE); int exitValue = Launcher.run(cmd.getArguments()); if (exitValue != 0) { String message = formatFailureMessage(cmd); exitHandler.handleExit(this, exitValue, message); }else{ exitHandler.handleExit(this, exitValue, null); } } catch (Throwable e) { throw new BuildException("Error running Ceylon compiler", e, getLocation()); } }
protected void executeCommandline(Commandline cmd) { try { // Execute exe = new Execute(new LogStreamHandler(this, Project.MSG_INFO, Project.MSG_WARN)); // exe.setAntRun(getProject()); // exe.setWorkingDirectory(getProject().getBaseDir()); // exe.setCommandline(cmd.getCommandline()); // exe.execute(); // int exitValue = exe.getExitValue(); log("Command line " + Arrays.toString(cmd.getCommandline()), Project.MSG_VERBOSE); int exitValue = Launcher.run(cmd.getArguments()); if (exitValue != 0) { String message = formatFailureMessage(cmd); exitHandler.handleExit(this, exitValue, message); }else{ exitHandler.handleExit(this, exitValue, null); } } catch (Throwable e) { throw new BuildException("Error running Ceylon " + toolName + " tool (an exception was thrown, run ant with -v parameter to see the exception)", e, getLocation()); } }
diff --git a/src/com/djdch/bukkit/onehundredgenerator/mc100/WorldGenTaiga1.java b/src/com/djdch/bukkit/onehundredgenerator/mc100/WorldGenTaiga1.java index 47a5ddb..010f839 100644 --- a/src/com/djdch/bukkit/onehundredgenerator/mc100/WorldGenTaiga1.java +++ b/src/com/djdch/bukkit/onehundredgenerator/mc100/WorldGenTaiga1.java @@ -1,89 +1,89 @@ package com.djdch.bukkit.onehundredgenerator.mc100; import java.util.Random; import net.minecraft.server.Block; import net.minecraft.server.World; import org.bukkit.BlockChangeDelegate; public class WorldGenTaiga1 extends WorldGenerator { @Override public boolean a(World world, Random random, int i, int j, int k) { return generate((BlockChangeDelegate) world, random, i, j, k); } public boolean generate(BlockChangeDelegate world, Random random, int i, int j, int k) { int l = random.nextInt(5) + 7; int i1 = l - random.nextInt(2) - 3; int j1 = l - i1; int k1 = 1 + random.nextInt(j1 + 1); boolean flag = true; + int l1; if ((j >= 1) && (j + l + 1 <= world.getHeight())) { - for (int l1 = j; (l1 <= j + 1 + l) && (flag); l1++) { - boolean flag1 = true; - int l2; + for (l1 = j; (l1 <= j + 1 + l) && (flag); l1++) { int l2; if (l1 - j < i1) l2 = 0; else { l2 = k1; } for (int i2 = i - l2; (i2 <= i + l2) && (flag); i2++) { for (int j2 = k - l2; (j2 <= k + l2) && (flag); j2++) { if ((l1 >= 0) && (l1 < world.getHeight())) { int k2 = world.getTypeId(i2, l1, j2); if ((k2 != 0) && (k2 != Block.LEAVES.id)) flag = false; } else { flag = false; } } } } if (!flag) { return false; } l1 = world.getTypeId(i, j - 1, k); if (((l1 == Block.GRASS.id) || (l1 == Block.DIRT.id)) && (j < world.getHeight() - l - 1)) { world.setRawTypeId(i, j - 1, k, Block.DIRT.id); int l2 = 0; - for (int i2 = j + l; i2 >= j + i1; i2--) { + int i2; + for (i2 = j + l; i2 >= j + i1; i2--) { for (int j2 = i - l2; j2 <= i + l2; j2++) { int k2 = j2 - i; for (int i3 = k - l2; i3 <= k + l2; i3++) { int j3 = i3 - k; - if (((Math.abs(k2) != l2) || (Math.abs(j3) != l2) || (l2 <= 0)) && (Block.o[world.getTypeId(j2, i2, i3)] == 0)) { + if (((Math.abs(k2) != l2) || (Math.abs(j3) != l2) || (l2 <= 0)) && (Block.o[world.getTypeId(j2, i2, i3)] == false)) { world.setRawTypeIdAndData(j2, i2, i3, Block.LEAVES.id, 1); } } } if ((l2 >= 1) && (i2 == j + i1 + 1)) l2--; else if (l2 < k1) { l2++; } } for (i2 = 0; i2 < l - 1; i2++) { int j2 = world.getTypeId(i, j + i2, k); if ((j2 == 0) || (j2 == Block.LEAVES.id)) { world.setRawTypeIdAndData(i, j + i2, k, Block.LOG.id, 1); } } return true; } return false; } return false; } }
false
true
public boolean generate(BlockChangeDelegate world, Random random, int i, int j, int k) { int l = random.nextInt(5) + 7; int i1 = l - random.nextInt(2) - 3; int j1 = l - i1; int k1 = 1 + random.nextInt(j1 + 1); boolean flag = true; if ((j >= 1) && (j + l + 1 <= world.getHeight())) { for (int l1 = j; (l1 <= j + 1 + l) && (flag); l1++) { boolean flag1 = true; int l2; int l2; if (l1 - j < i1) l2 = 0; else { l2 = k1; } for (int i2 = i - l2; (i2 <= i + l2) && (flag); i2++) { for (int j2 = k - l2; (j2 <= k + l2) && (flag); j2++) { if ((l1 >= 0) && (l1 < world.getHeight())) { int k2 = world.getTypeId(i2, l1, j2); if ((k2 != 0) && (k2 != Block.LEAVES.id)) flag = false; } else { flag = false; } } } } if (!flag) { return false; } l1 = world.getTypeId(i, j - 1, k); if (((l1 == Block.GRASS.id) || (l1 == Block.DIRT.id)) && (j < world.getHeight() - l - 1)) { world.setRawTypeId(i, j - 1, k, Block.DIRT.id); int l2 = 0; for (int i2 = j + l; i2 >= j + i1; i2--) { for (int j2 = i - l2; j2 <= i + l2; j2++) { int k2 = j2 - i; for (int i3 = k - l2; i3 <= k + l2; i3++) { int j3 = i3 - k; if (((Math.abs(k2) != l2) || (Math.abs(j3) != l2) || (l2 <= 0)) && (Block.o[world.getTypeId(j2, i2, i3)] == 0)) { world.setRawTypeIdAndData(j2, i2, i3, Block.LEAVES.id, 1); } } } if ((l2 >= 1) && (i2 == j + i1 + 1)) l2--; else if (l2 < k1) { l2++; } } for (i2 = 0; i2 < l - 1; i2++) { int j2 = world.getTypeId(i, j + i2, k); if ((j2 == 0) || (j2 == Block.LEAVES.id)) { world.setRawTypeIdAndData(i, j + i2, k, Block.LOG.id, 1); } } return true; } return false; } return false; }
public boolean generate(BlockChangeDelegate world, Random random, int i, int j, int k) { int l = random.nextInt(5) + 7; int i1 = l - random.nextInt(2) - 3; int j1 = l - i1; int k1 = 1 + random.nextInt(j1 + 1); boolean flag = true; int l1; if ((j >= 1) && (j + l + 1 <= world.getHeight())) { for (l1 = j; (l1 <= j + 1 + l) && (flag); l1++) { int l2; if (l1 - j < i1) l2 = 0; else { l2 = k1; } for (int i2 = i - l2; (i2 <= i + l2) && (flag); i2++) { for (int j2 = k - l2; (j2 <= k + l2) && (flag); j2++) { if ((l1 >= 0) && (l1 < world.getHeight())) { int k2 = world.getTypeId(i2, l1, j2); if ((k2 != 0) && (k2 != Block.LEAVES.id)) flag = false; } else { flag = false; } } } } if (!flag) { return false; } l1 = world.getTypeId(i, j - 1, k); if (((l1 == Block.GRASS.id) || (l1 == Block.DIRT.id)) && (j < world.getHeight() - l - 1)) { world.setRawTypeId(i, j - 1, k, Block.DIRT.id); int l2 = 0; int i2; for (i2 = j + l; i2 >= j + i1; i2--) { for (int j2 = i - l2; j2 <= i + l2; j2++) { int k2 = j2 - i; for (int i3 = k - l2; i3 <= k + l2; i3++) { int j3 = i3 - k; if (((Math.abs(k2) != l2) || (Math.abs(j3) != l2) || (l2 <= 0)) && (Block.o[world.getTypeId(j2, i2, i3)] == false)) { world.setRawTypeIdAndData(j2, i2, i3, Block.LEAVES.id, 1); } } } if ((l2 >= 1) && (i2 == j + i1 + 1)) l2--; else if (l2 < k1) { l2++; } } for (i2 = 0; i2 < l - 1; i2++) { int j2 = world.getTypeId(i, j + i2, k); if ((j2 == 0) || (j2 == Block.LEAVES.id)) { world.setRawTypeIdAndData(i, j + i2, k, Block.LOG.id, 1); } } return true; } return false; } return false; }
diff --git a/src/java/org/infoglue/cms/applications/contenttool/actions/ContentCategoryAction.java b/src/java/org/infoglue/cms/applications/contenttool/actions/ContentCategoryAction.java index cc727327e..6b259a11f 100755 --- a/src/java/org/infoglue/cms/applications/contenttool/actions/ContentCategoryAction.java +++ b/src/java/org/infoglue/cms/applications/contenttool/actions/ContentCategoryAction.java @@ -1,43 +1,44 @@ package org.infoglue.cms.applications.contenttool.actions; import org.infoglue.cms.applications.common.actions.ModelAction; import org.infoglue.cms.entities.kernel.Persistent; import org.infoglue.cms.entities.content.ContentCategoryVO; import org.infoglue.cms.controllers.kernel.impl.simple.ContentCategoryController; import org.infoglue.cms.exception.SystemException; /** * This action will manage the category to content relations * * @author Frank Febbraro ([email protected]) */ public class ContentCategoryAction extends ModelAction { private ContentCategoryController controller = ContentCategoryController.getController(); private Integer contentId; private Integer languageId; protected Persistent createModel() { return new ContentCategoryVO(); } public ContentCategoryVO getContentCategory() { return (ContentCategoryVO)getModel(); } public Integer getContentCategoryId() { return getContentCategory().getContentCategoryId(); } public void setContentCategoryId(Integer i) { getContentCategory().setContentCategoryId(i); } public Integer getContentId() { return contentId; } public void setContentId(Integer i) { contentId = i; } public Integer getLanguageId() { return languageId; } public void setLanguageId(Integer i) { languageId = i; } public String doAdd() throws SystemException { + System.out.println("Attribute:" + getContentCategory().getAttributeName()); setModel(controller.save(getContentCategory())); return SUCCESS; } public String doDelete() throws SystemException { controller.delete(getContentCategoryId()); return SUCCESS; } }
true
true
public String doAdd() throws SystemException { setModel(controller.save(getContentCategory())); return SUCCESS; }
public String doAdd() throws SystemException { System.out.println("Attribute:" + getContentCategory().getAttributeName()); setModel(controller.save(getContentCategory())); return SUCCESS; }
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.local.core/src/org/eclipse/linuxtools/systemtap/local/core/SystemTapErrorHandler.java b/systemtap/org.eclipse.linuxtools.systemtap.local.core/src/org/eclipse/linuxtools/systemtap/local/core/SystemTapErrorHandler.java index 842f231f8..52657ad82 100644 --- a/systemtap/org.eclipse.linuxtools.systemtap.local.core/src/org/eclipse/linuxtools/systemtap/local/core/SystemTapErrorHandler.java +++ b/systemtap/org.eclipse.linuxtools.systemtap.local.core/src/org/eclipse/linuxtools/systemtap/local/core/SystemTapErrorHandler.java @@ -1,317 +1,319 @@ /******************************************************************************* * Copyright (c) 2009 Red Hat, Inc. * 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: * Red Hat - initial API and implementation *******************************************************************************/ package org.eclipse.linuxtools.systemtap.local.core; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.core.runtime.IProgressMonitor; /** * Helper class parses the given string for recognizable error messages * */ public class SystemTapErrorHandler { public static final String FILE_PROP = "errors.prop"; //$NON-NLS-1$ public static final String FILE_ERROR_LOG = "Error.log"; //$NON-NLS-1$ public static final int MAX_LOG_SIZE = 50000; private boolean errorRecognized; private String errorMessage = ""; //$NON-NLS-1$ private StringBuilder logContents; private boolean mismatchedProbePoints; ArrayList<String> functions = new ArrayList<String>(); /** * Delete the log file and create an empty one */ public static void delete(){ File log = new File(PluginConstants.DEFAULT_OUTPUT + FILE_ERROR_LOG); //$NON-NLS-1$ log.delete(); try { log.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } public SystemTapErrorHandler() { mismatchedProbePoints = false; errorRecognized = false; if (errorMessage.length() < 1) { errorMessage = Messages.getString("SystemTapErrorHandler.ErrorMessage") + //$NON-NLS-1$ Messages.getString("SystemTapErrorHandler.ErrorMessage1"); //$NON-NLS-1$ } logContents = new StringBuilder(); //$NON-NLS-1$ } /** * Search given string for recognizable error messages. Can append the contents of * the string to the error log if writeToLog() or finishHandling() are called. * A call to finishHandling() will also open a popup window with user-friendly messages * corresponding to the recognizable errors. * * @param doc */ public void handle (IProgressMonitor m, String errors){ String[] blah = errors.split("\n"); //$NON-NLS-1$ //READ FROM THE PROP FILE AND DETERMINE TYPE OF ERROR File file = new File(PluginConstants.PLUGIN_LOCATION+FILE_PROP); try { BufferedReader buff = new BufferedReader (new FileReader(file)); String line; int index; for (String message : blah) { boolean firstLine = true; //Keep the error about mismatched probe points first buff = new BufferedReader (new FileReader(file)); while ((line = buff.readLine()) != null){ if (m != null && m.isCanceled()) return; index = line.indexOf('='); String matchString = line.substring(0, index); Pattern pat = Pattern.compile(matchString, Pattern.DOTALL); Matcher matcher = pat.matcher(message); if (matcher.matches()) { if (!isErrorRecognized()) { errorMessage+=Messages.getString("SystemTapErrorHandler.ErrorMessage2"); //$NON-NLS-1$ setErrorRecognized(true); } errorMessage+=line.substring(index+1) + PluginConstants.NEW_LINE + PluginConstants.NEW_LINE; if (firstLine) { findFunctions(m, message, pat); mismatchedProbePoints = true; } break; } firstLine = false; } buff.close(); } logContents.append(errors); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void handle (IProgressMonitor m, FileReader f) throws IOException { BufferedReader br = new BufferedReader (f); String line; StringBuilder builder = new StringBuilder(); int counter = 0; while ( (line = br.readLine()) != null) { counter++; builder.append(line); builder.append("\n"); //$NON-NLS-1$ if (m != null && m.isCanceled()) return; if (counter == 300) { handle(m, builder.toString()); builder = new StringBuilder(); counter = 0; } } handle(m, builder.toString()); } /** * Run this method when there are no more error messages to handle. * Creates the error pop-up message and writes to log. * */ public void finishHandling(IProgressMonitor m, int numberOfErrors) { if (!isErrorRecognized()) { errorMessage+=Messages.getString("SystemTapErrorHandler.4") + //$NON-NLS-1$ Messages.getString("SystemTapErrorHandler.5"); //$NON-NLS-1$ } writeToLog(); if (mismatchedProbePoints){ if (numberOfErrors > 300) { errorMessage = PluginConstants.NEW_LINE + PluginConstants.NEW_LINE + Messages.getString("SystemTapErrorHandler.TooManyErrors1") + numberOfErrors +Messages.getString("SystemTapErrorHandler.TooManyErrors2") + //$NON-NLS-1$ //$NON-NLS-2$ Messages.getString("SystemTapErrorHandler.TooManyErrors3") + //$NON-NLS-1$ Messages.getString("SystemTapErrorHandler.TooManyErrors4"); //$NON-NLS-1$ + SystemTapUIErrorMessages mes = new SystemTapUIErrorMessages( + Messages.getString("SystemTapErrorHandler.ErrorMessageName"), //$NON-NLS-1$ + Messages.getString("SystemTapErrorHandler.ErrorMessageTitle"), //$NON-NLS-1$ + errorMessage); //$NON-NLS-1$ //$NON-NLS-2$ + mes.schedule(); + m.setCanceled(true); + return; } - SystemTapUIErrorMessages mes = new SystemTapUIErrorMessages( - Messages.getString("SystemTapErrorHandler.ErrorMessageName"), //$NON-NLS-1$ - Messages.getString("SystemTapErrorHandler.ErrorMessageTitle"), //$NON-NLS-1$ - errorMessage); //$NON-NLS-1$ //$NON-NLS-2$ - mes.schedule(); StringBuffer resultFileContent = new StringBuffer(); String fileLocation = PluginConstants.DEFAULT_OUTPUT + "callgraphGen.stp"; //$NON-NLS-1$ String line; boolean skip = false; File file = new File(fileLocation); try { BufferedReader buff = new BufferedReader(new FileReader(file)); while ((line = buff.readLine()) != null){ if (m != null && m.isCanceled()) return; skip = false; for (String func : functions){ if (line.contains("function(\"" + func + "\").call")){ //$NON-NLS-1$ //$NON-NLS-2$ skip = true; break; } } if (!skip && !line.equals("\n")){ //$NON-NLS-1$ resultFileContent.append(line); resultFileContent.append("\n"); //$NON-NLS-1$ } } buff.close(); BufferedWriter wbuff= new BufferedWriter(new FileWriter(file)); wbuff.write(resultFileContent.toString()); wbuff.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }else{ SystemTapUIErrorMessages mes = new SystemTapUIErrorMessages( Messages.getString("SystemTapErrorHandler.ErrorMessageName"), //$NON-NLS-1$ Messages.getString("SystemTapErrorHandler.ErrorMessageTitle"), //$NON-NLS-1$ errorMessage); //$NON-NLS-1$ //$NON-NLS-2$ mes.schedule(); } } /** * Writes the contents of logContents to the error log, along with date and time. */ public void writeToLog() { File errorLog = new File(PluginConstants.DEFAULT_OUTPUT + "Error.log"); //$NON-NLS-1$ try { //CREATE THE ERROR LOG IF IT DOES NOT EXIST //CLEAR THE ERROR LOG AFTER A FIXED SIZE(BYTES) if (!errorLog.exists() || errorLog.length() > MAX_LOG_SIZE) { errorLog.delete(); errorLog.createNewFile(); } Calendar cal = Calendar.getInstance(TimeZone.getDefault()); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); int second = cal.get(Calendar.SECOND); //APPEND THE ERROR TO THE LOG Helper .appendToFile(errorLog.getAbsolutePath(), Messages.getString("SystemTapErrorHandler.ErrorLogDashes") //$NON-NLS-1$ + PluginConstants.NEW_LINE + day + "/" + month //$NON-NLS-1$ + "/" + year + " - " + hour + ":" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + minute + ":" + second //$NON-NLS-1$ + PluginConstants.NEW_LINE + logContents + PluginConstants.NEW_LINE + PluginConstants.NEW_LINE); } catch (IOException e) { e.printStackTrace(); } logContents = new StringBuilder(); //$NON-NLS-1$ } /** * Returns true if an error matches one of the regex's in error.prop * @return */ public boolean isErrorRecognized() { return errorRecognized; } /** * Convenience method to change the error recognition value. * @param errorsRecognized */ private void setErrorRecognized(boolean errorsRecognized) { errorRecognized = errorsRecognized; } public boolean hasMismatchedProbePoints() { return mismatchedProbePoints; } public void setMismatchedProbePoints(boolean mismatchedProbePoints) { this.mismatchedProbePoints = mismatchedProbePoints; } public void findFunctions(IProgressMonitor m, String message, Pattern pat) { String[] list = message.split("\n"); //$NON-NLS-1$ String result; for (String s : list) { if (m.isCanceled()) return; if (pat.matcher(s).matches()) { int lastQuote = s.lastIndexOf('"'); int secondLastQuote = s.lastIndexOf('"', lastQuote - 1); result = s.substring(secondLastQuote+1, lastQuote); if (!functions.contains(result)) functions.add(result); } } } public ArrayList<String> getFunctions() { return functions; } }
false
true
public void finishHandling(IProgressMonitor m, int numberOfErrors) { if (!isErrorRecognized()) { errorMessage+=Messages.getString("SystemTapErrorHandler.4") + //$NON-NLS-1$ Messages.getString("SystemTapErrorHandler.5"); //$NON-NLS-1$ } writeToLog(); if (mismatchedProbePoints){ if (numberOfErrors > 300) { errorMessage = PluginConstants.NEW_LINE + PluginConstants.NEW_LINE + Messages.getString("SystemTapErrorHandler.TooManyErrors1") + numberOfErrors +Messages.getString("SystemTapErrorHandler.TooManyErrors2") + //$NON-NLS-1$ //$NON-NLS-2$ Messages.getString("SystemTapErrorHandler.TooManyErrors3") + //$NON-NLS-1$ Messages.getString("SystemTapErrorHandler.TooManyErrors4"); //$NON-NLS-1$ } SystemTapUIErrorMessages mes = new SystemTapUIErrorMessages( Messages.getString("SystemTapErrorHandler.ErrorMessageName"), //$NON-NLS-1$ Messages.getString("SystemTapErrorHandler.ErrorMessageTitle"), //$NON-NLS-1$ errorMessage); //$NON-NLS-1$ //$NON-NLS-2$ mes.schedule(); StringBuffer resultFileContent = new StringBuffer(); String fileLocation = PluginConstants.DEFAULT_OUTPUT + "callgraphGen.stp"; //$NON-NLS-1$ String line; boolean skip = false; File file = new File(fileLocation); try { BufferedReader buff = new BufferedReader(new FileReader(file)); while ((line = buff.readLine()) != null){ if (m != null && m.isCanceled()) return; skip = false; for (String func : functions){ if (line.contains("function(\"" + func + "\").call")){ //$NON-NLS-1$ //$NON-NLS-2$ skip = true; break; } } if (!skip && !line.equals("\n")){ //$NON-NLS-1$ resultFileContent.append(line); resultFileContent.append("\n"); //$NON-NLS-1$ } } buff.close(); BufferedWriter wbuff= new BufferedWriter(new FileWriter(file)); wbuff.write(resultFileContent.toString()); wbuff.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }else{ SystemTapUIErrorMessages mes = new SystemTapUIErrorMessages( Messages.getString("SystemTapErrorHandler.ErrorMessageName"), //$NON-NLS-1$ Messages.getString("SystemTapErrorHandler.ErrorMessageTitle"), //$NON-NLS-1$ errorMessage); //$NON-NLS-1$ //$NON-NLS-2$ mes.schedule(); } }
public void finishHandling(IProgressMonitor m, int numberOfErrors) { if (!isErrorRecognized()) { errorMessage+=Messages.getString("SystemTapErrorHandler.4") + //$NON-NLS-1$ Messages.getString("SystemTapErrorHandler.5"); //$NON-NLS-1$ } writeToLog(); if (mismatchedProbePoints){ if (numberOfErrors > 300) { errorMessage = PluginConstants.NEW_LINE + PluginConstants.NEW_LINE + Messages.getString("SystemTapErrorHandler.TooManyErrors1") + numberOfErrors +Messages.getString("SystemTapErrorHandler.TooManyErrors2") + //$NON-NLS-1$ //$NON-NLS-2$ Messages.getString("SystemTapErrorHandler.TooManyErrors3") + //$NON-NLS-1$ Messages.getString("SystemTapErrorHandler.TooManyErrors4"); //$NON-NLS-1$ SystemTapUIErrorMessages mes = new SystemTapUIErrorMessages( Messages.getString("SystemTapErrorHandler.ErrorMessageName"), //$NON-NLS-1$ Messages.getString("SystemTapErrorHandler.ErrorMessageTitle"), //$NON-NLS-1$ errorMessage); //$NON-NLS-1$ //$NON-NLS-2$ mes.schedule(); m.setCanceled(true); return; } StringBuffer resultFileContent = new StringBuffer(); String fileLocation = PluginConstants.DEFAULT_OUTPUT + "callgraphGen.stp"; //$NON-NLS-1$ String line; boolean skip = false; File file = new File(fileLocation); try { BufferedReader buff = new BufferedReader(new FileReader(file)); while ((line = buff.readLine()) != null){ if (m != null && m.isCanceled()) return; skip = false; for (String func : functions){ if (line.contains("function(\"" + func + "\").call")){ //$NON-NLS-1$ //$NON-NLS-2$ skip = true; break; } } if (!skip && !line.equals("\n")){ //$NON-NLS-1$ resultFileContent.append(line); resultFileContent.append("\n"); //$NON-NLS-1$ } } buff.close(); BufferedWriter wbuff= new BufferedWriter(new FileWriter(file)); wbuff.write(resultFileContent.toString()); wbuff.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }else{ SystemTapUIErrorMessages mes = new SystemTapUIErrorMessages( Messages.getString("SystemTapErrorHandler.ErrorMessageName"), //$NON-NLS-1$ Messages.getString("SystemTapErrorHandler.ErrorMessageTitle"), //$NON-NLS-1$ errorMessage); //$NON-NLS-1$ //$NON-NLS-2$ mes.schedule(); } }
diff --git a/src/com/ichi2/libanki/Models.java b/src/com/ichi2/libanki/Models.java index 539f07c4..a59cc25c 100644 --- a/src/com/ichi2/libanki/Models.java +++ b/src/com/ichi2/libanki/Models.java @@ -1,1128 +1,1128 @@ /**************************************************************************************** * Copyright (c) 2009 Daniel Svärd <[email protected]> * * Copyright (c) 2010 Rick Gruber-Riemer <[email protected]> * * Copyright (c) 2011 Norbert Nagold <[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 com.ichi2.libanki; import android.content.ContentValues; import android.database.Cursor; import android.util.Log; import com.ichi2.anki.AnkiDb; import com.ichi2.anki.AnkiDroidApp; import com.mindprod.common11.StringTools; import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class Models { private static final String defaultModel = "{'sortf': 0, " + "'did': 1, " + "'latexPre': \"" + "\\\\documentclass[12pt]{article} " + "\\\\special{papersize=3in,5in} " + "\\\\usepackage[utf8]{inputenc} " + "\\\\usepackage{amssymb,amsmath} " + "\\\\pagestyle{empty} " + "\\\\setlength{\\\\parindent}{0in} " + "\\\\begin{document} " + "\", " + "'latexPost': \"\\\\end{document}\", " + "'mod': 9, " + "'usn': 9, " + "'vers': [] }"; private static final String defaultField = "{'name': \"\", " + "'ord': None, " + "'sticky': False, " + // the following alter editing, and are used as defaults for the template wizard "'rtl': False, " + "'font': \"Arial\", " + "'size': 20, " + // reserved for future use "'media': [] }"; private static final String defaultTemplate = "{'name': \"\", " + "'ord': None, " + "'qfmt': \"\", " + "'afmt': \"\", " + "'did': None, " + "'css': \".card { " + " font-family: arial;" + " font-size: 20px;" + " text-align: center;" + " color: black;" + " background-color: white;" + " }" + "\"}"; // /** Regex pattern used in removing tags from text before diff */ // private static final Pattern sFactPattern = Pattern.compile("%\\([tT]ags\\)s"); // private static final Pattern sModelPattern = Pattern.compile("%\\(modelTags\\)s"); // private static final Pattern sTemplPattern = Pattern.compile("%\\(cardModel\\)s"); private Collection mCol; private boolean mChanged; private HashMap<Long, JSONObject> mModels; // BEGIN SQL table entries private int mId; private String mName = ""; private long mCrt = Utils.intNow(); private long mMod = Utils.intNow(); private JSONObject mConf; private String mCss = ""; private JSONArray mFields; private JSONArray mTemplates; // BEGIN SQL table entries // private Decks mDeck; // private AnkiDb mDb; // /** Map for compiled Mustache Templates */ private HashMap<Long, HashMap<Integer, Template[]>> mCmpldTemplateMap = new HashMap<Long, HashMap<Integer, Template[]>>(); // // /** Map for convenience and speed which contains FieldNames from current model */ // private TreeMap<String, Integer> mFieldMap = new TreeMap<String, Integer>(); // // /** Map for convenience and speed which contains Templates from current model */ // private TreeMap<Integer, JSONObject> mTemplateMap = new TreeMap<Integer, JSONObject>(); // // /** Map for convenience and speed which contains the CSS code related to a Template */ // private HashMap<Integer, String> mCssTemplateMap = new HashMap<Integer, String>(); // // /** // * The percentage chosen in preferences for font sizing at the time when the css for the CardModels related to this // * Model was calculated in prepareCSSForCardModels. // */ // private transient int mDisplayPercentage = 0; // private boolean mNightMode = false; /** * Saving/loading registry * *********************************************************************************************** */ public Models(Collection col) { mCol = col; } /** * Load registry from JSON. */ public void load(String json) { mChanged = false; mModels = new HashMap<Long, JSONObject>(); try { JSONObject modelarray = new JSONObject(json); JSONArray ids = modelarray.names(); for (int i = 0; i < ids.length(); i++) { String id = ids.getString(i); JSONObject o = modelarray.getJSONObject(id); mModels.put(o.getLong("id"), o); } } catch (JSONException e) { throw new RuntimeException(e); } } /** * Mark M modified if provided, and schedule registry flush. */ public void save() { save(null, false); } public void save(JSONObject m) { save(m, false); } public void save(JSONObject m, boolean templates) { if (m != null && m.has("id")) { try { m.put("mod", Utils.intNow()); m.put("usn", mCol.usn()); // TODO: fix empty id problem on _updaterequired (needed for model adding) if (m.getLong("id") != 0) { _updateRequired(m); } if (templates) { _syncTemplates(m); } } catch (JSONException e) { throw new RuntimeException(e); } } mChanged = true; } /** * Flush the registry if any models were changed. */ public void flush() { if (mChanged) { JSONObject array = new JSONObject(); try { for (Map.Entry<Long, JSONObject> o : mModels.entrySet()) { array.put(Long.toString(o.getKey()), o.getValue()); } } catch (JSONException e) { throw new RuntimeException(e); } ContentValues val = new ContentValues(); val.put("models", array.toString()); mCol.getDb().update("col", val); mChanged = false; } } /** * Retrieving and creating models * *********************************************************************************************** */ /** * Get current model. */ public JSONObject current() { JSONObject m; try { m = get(mCol.getConf().getLong("curModel")); if (m != null) { return m; } else { if (!mModels.isEmpty()) { return mModels.values().iterator().next(); } else { return null; } } } catch (JSONException e) { throw new RuntimeException(e); } } public void setCurrent(JSONObject m) { try { mCol.getConf().put("curModel", m.get("id")); } catch (JSONException e) { throw new RuntimeException(e); } mCol.setMod(); } /** get model with ID, or none. */ public JSONObject get(long id) { if (mModels.containsKey(id)) { return mModels.get(id); } else { return null; } } /** get all models */ public ArrayList<JSONObject> all() { ArrayList<JSONObject> models = new ArrayList<JSONObject>(); Iterator<JSONObject> it = mModels.values().iterator(); while(it.hasNext()) { models.add(it.next()); } return models; } /** get model with NAME. */ public JSONObject byName(String name) { for (JSONObject m : mModels.values()) { try { if (m.getString("name").equalsIgnoreCase(name)) { return m; } } catch (JSONException e) { throw new RuntimeException(e); } } return null; } /** Create a new model, save it in the registry, and return it. */ public JSONObject newModel(String name) { // caller should call save() after modifying JSONObject m; try { m = new JSONObject(defaultModel); m.put("name", name); m.put("mod", Utils.intNow()); m.put("flds", new JSONArray()); m.put("tmpls", new JSONArray()); m.put("tags", new JSONArray()); m.put("id", 0); } catch (JSONException e) { throw new RuntimeException(e); } return m; } /** Delete model, and all its cards/notes. */ public void rem(JSONObject m) { mCol.modSchema(); try { long id = m.getLong("id"); boolean current = current().getLong("id") == id; // delete notes/cards mCol.remCards(Utils.arrayList2array(mCol.getDb().queryColumn(Long.class, "SELECT id FROM cards WHERE nid IN (SELECT id FROM notes WHERE mid = " + id + ")", 0))); // then the model mModels.remove(id); save(); // GUI should ensure last model is not deleted if (current) { setCurrent(mModels.values().iterator().next()); } } catch (JSONException e) { throw new RuntimeException(e); } } public void add(JSONObject m, boolean setCurrent) { _setID(m); update(m); if (setCurrent) { setCurrent(m); } save(m); } /** Add or update an existing model. Used for syncing and merging. */ public void update(JSONObject m) { try { mModels.put(m.getLong("id"), m); } catch (JSONException e) { throw new RuntimeException(e); } // mark registry changed, but don't bump mod time save(); } private void _setID(JSONObject m) { long id = Utils.intNow(); while (mModels.containsKey(id)) { id = Utils.intNow(); } try { m.put("id", id); } catch (JSONException e) { throw new RuntimeException(e); } } public boolean have(long id) { return mModels.containsKey(id); } /** * Tools * *********************************************************************************************** */ /** Note ids for M */ public ArrayList<Long> nids(JSONObject m) { try { return mCol.getDb().queryColumn(Long.class, "SELECT id FROM notes WHERE mid = " + m.getLong("id"), 0); } catch (JSONException e) { throw new RuntimeException(e); } } // usecounts /** * Copying * *********************************************************************************************** */ // copy /** * Fields * *********************************************************************************************** */ public JSONObject newField(String name) { JSONObject f; try { f = new JSONObject(defaultField); f.put("name", name); } catch (JSONException e) { throw new RuntimeException(e); } return f; } // /** Mapping of field name --> (ord, field). */ // public TreeMap<String, Object[]> fieldMap(JSONObject m) { // JSONArray ja; // try { // ja = m.getJSONArray("flds"); // TreeMap<String, Object[]> map = new TreeMap<String, Object[]>(); // for (int i = 0; i < ja.length(); i++) { // JSONObject f = ja.getJSONObject(i); // map.put(f.getString("name"), new Object[]{f.getInt("ord"), f}); // } // return map; // } catch (JSONException e) { // throw new RuntimeException(e); // } // } public String[] orderedFields(JSONObject m) { JSONArray ja; try { ja = m.getJSONArray("flds"); TreeMap<Integer, String> map = new TreeMap<Integer, String>(); for (int i = 0; i < ja.length(); i++) { JSONObject f = ja.getJSONObject(i); map.put(f.getInt("ord"), f.getString("name")); } String[] result = new String[map.size()]; for (int i = 0; i < map.size(); i++) { result[i] = map.get(i); } return result; } catch (JSONException e) { throw new RuntimeException(e); } } public ArrayList<String> fieldNames(JSONObject m) { JSONArray ja; try { ja = m.getJSONArray("flds"); ArrayList<String> names = new ArrayList<String>(); for (int i = 0; i < ja.length(); i++) { names.add(ja.getJSONObject(i).getString("name")); } return names; } catch (JSONException e) { throw new RuntimeException(e); } } public int sortIdx(JSONObject m) { try { return m.getInt("sortf"); } catch (JSONException e) { throw new RuntimeException(e); } } // public int setSortIdx(JSONObject m, int idx) { // try { // mCol.modSchema(); // m.put("sortf", idx); // mCol.updateFieldCache(nids(m)); // save(m); // } catch (JSONException e) { // throw new RuntimeException(e); // } // } public void addField(JSONObject m, JSONObject field) { // only mod schema if model isn't new try { if (m.getLong("id") != 0) { mCol.modSchema(); } JSONArray ja = m.getJSONArray("flds"); ja.put(field); m.put("flds", ja); _updateFieldOrds(m); save(m); _transformFields(m); //, Method add); } catch (JSONException e) { throw new RuntimeException(e); } } //remfield //movefield //renamefield public void _updateFieldOrds(JSONObject m) { JSONArray ja; try { ja = m.getJSONArray("flds"); for (int i = 0; i < ja.length(); i++) { JSONObject f = ja.getJSONObject(i); f.put("ord", i); } } catch (JSONException e) { throw new RuntimeException(e); } } public void _transformFields(JSONObject m) { // Method fn) { // model hasn't been added yet? try { if (m.getLong("id") == 0) { return; } } catch (JSONException e) { throw new RuntimeException(e); } // TODO } /** * Templates * *********************************************************************************************** */ public JSONObject newTemplate(String name) { JSONObject t; try { t = new JSONObject(defaultTemplate); t.put("name", name); } catch (JSONException e) { throw new RuntimeException(e); } return t; } /** Note: should col.genCards() afterwards. */ public void addTemplate(JSONObject m, JSONObject template) { try { if (m.getLong("id") != 0) { mCol.modSchema(); } JSONArray ja = m.getJSONArray("tmpls"); ja.put(template); m.put("tmpls", ja); _updateTemplOrds(m); save(m); } catch (JSONException e) { throw new RuntimeException(e); } } //remtemplate public void _updateTemplOrds(JSONObject m) { JSONArray ja; try { ja = m.getJSONArray("tmpls"); for (int i = 0; i < ja.length(); i++) { JSONObject f = ja.getJSONObject(i); f.put("ord", i); } } catch (JSONException e) { throw new RuntimeException(e); } } //movetemplate private void _syncTemplates(JSONObject m) { ArrayList<Long> rem = mCol.genCards(Utils.arrayList2array(nids(m))); mCol.remEmptyCards(Utils.arrayList2array(rem)); } // public TreeMap<Integer, JSONObject> getTemplates() { // return mTemplateMap; // } // // // public JSONObject getTemplate(int ord) { // return mTemplateMap.get(ord); // } // not in libanki public Template[] getCmpldTemplate(long modelId, int ord) { if (!mCmpldTemplateMap.containsKey(modelId)) { mCmpldTemplateMap.put(modelId, new HashMap<Integer, Template[]>()); } if (!mCmpldTemplateMap.get(modelId).containsKey(ord)) { mCmpldTemplateMap.get(modelId).put(ord, compileTemplate(modelId, ord)); } return mCmpldTemplateMap.get(modelId).get(ord); } // not in libanki private Template[] compileTemplate(long modelId, int ord) { JSONObject model = mModels.get(modelId); JSONObject template; Template[] t = new Template[2]; try { template = model.getJSONArray("tmpls").getJSONObject(ord); - String format = template.getString("qfmt").replace("cloze", "cq:"); + String format = template.getString("qfmt").replace("cloze:", "cq:"); Log.i(AnkiDroidApp.TAG, "Compiling question template \"" + format + "\""); t[0] = Mustache.compiler().compile(format); format = template.getString("afmt").replace("cloze:", "ca:"); Log.i(AnkiDroidApp.TAG, "Compiling answer template \"" + format + "\""); t[1] = Mustache.compiler().compile(format); } catch (JSONException e) { throw new RuntimeException(e); } return t; } // /** // * This function recompiles the templates for question and answer. It should be called everytime we change mQformat // * or mAformat, so if in the future we create set(Q|A)Format setters, we should include a call to this. // */ // private void refreshTemplates(int ord) { // // Question template // StringBuffer sb = new StringBuffer(); // Matcher m = sOldStylePattern.matcher(mQformat); // while (m.find()) { // // Convert old style // m.appendReplacement(sb, "{{" + m.group(1) + "}}"); // } // m.appendTail(sb); // Log.i(AnkiDroidApp.TAG, "Compiling question template \"" + sb.toString() + "\""); // mQTemplate = Mustache.compiler().compile(sb.toString()); // // // Answer template // sb = new StringBuffer(); // m = sOldStylePattern.matcher(mAformat); // while (m.find()) { // // Convert old style // m.appendReplacement(sb, "{{" + m.group(1) + "}}"); // } // m.appendTail(sb); // Log.i(AnkiDroidApp.TAG, "Compiling answer template \"" + sb.toString() + "\""); // mATemplate = Mustache.compiler().compile(sb.toString()); // } /** * Model changing * *********************************************************************************************** */ // change //_changeNotes //_changeCards /** * Schema hash * *********************************************************************************************** */ //scmhash /** * Required field/text cache * *********************************************************************************************** */ private void _updateRequired(JSONObject m) { JSONArray req = new JSONArray(); ArrayList<String> flds = new ArrayList<String>(); JSONArray fields; try { fields = m.getJSONArray("flds"); for (int i = 0; i < fields.length(); i++) { flds.add(fields.getJSONObject(i).getString("name")); } boolean cloze = false; JSONArray templates = m.getJSONArray("tmpls"); for (int i = 0; i < templates.length(); i++) { JSONObject t = templates.getJSONObject(i); Object[] ret = _reqForTemplate(m, flds, t); if (((JSONArray)ret[2]).length() > 0) { cloze = true; } JSONArray r = new JSONArray(); r.put(t.getInt("ord")); r.put(ret[0]); r.put(ret[1]); r.put(ret[2]); req.put(r); } m.put("req", req); m.put("cloze", cloze); } catch (JSONException e) { throw new RuntimeException(e); } } private Object[] _reqForTemplate(JSONObject m, ArrayList<String> flds, JSONObject t) { try { ArrayList<String> a = new ArrayList<String> (); ArrayList<String> b = new ArrayList<String> (); String cloze = ""; JSONArray reqstrs = new JSONArray(); if (t.has("cloze")) { // need a cloze-specific filler // TODO } for (String f : flds) { a.add(cloze.length() > 0 ? cloze : "1"); b.add(""); } Object[] data; data = new Object[]{1l, 1l, m.getLong("id"), 1l, t.getInt("ord"), "", Utils.joinFields(a.toArray(new String[a.size()]))}; String full = mCol._renderQA(data).get("q"); data = new Object[]{1l, 1l, m.getLong("id"), 1l, t.getInt("ord"), "", Utils.joinFields(b.toArray(new String[b.size()]))}; String empty = mCol._renderQA(data).get("q"); // if full and empty are the same, the template is invalid and there is no way to satisfy it if (full.equals(empty)) { return new Object[] {"none", new JSONArray(), new JSONArray()}; } String type = "all"; JSONArray req = new JSONArray(); ArrayList<String> tmp = new ArrayList<String>(); for (int i = 0; i < flds.size(); i++) { tmp.clear(); tmp.addAll(a); tmp.remove(i); tmp.add(i, ""); data[6] = Utils.joinFields(tmp.toArray(new String[tmp.size()])); // if the result is same as empty, field is required if (mCol._renderQA(data).get("q").equals(empty)) { req.put(i); } } if (req.length() > 0) { return new Object[] {type, req, reqstrs}; } // if there are no required fields, switch to any mode type = "any"; req = new JSONArray(); for (int i = 0; i < flds.size(); i++) { tmp.clear(); tmp.addAll(b); tmp.remove(i); tmp.add(i, "1"); data[6] = Utils.joinFields(tmp.toArray(new String[tmp.size()])); // if not the same as empty, this field can make the card non-blank if (mCol._renderQA(data).get("q").equals(empty)) { req.put(i); } } return new Object[]{ type, req, reqstrs}; } catch (JSONException e) { throw new RuntimeException(e); } } /** Given a joined field string, return available template ordinals */ public ArrayList<Integer> availOrds(JSONObject m, String flds) { String[] fields = Utils.splitFields(flds); for (String f : fields) { f = f.trim(); } ArrayList<Integer> avail = new ArrayList<Integer>(); try { JSONArray reqArray = m.getJSONArray("req"); for (int i = 0; i < reqArray.length(); i++) { JSONArray sr = reqArray.getJSONArray(i); int ord = sr.getInt(0); String type = sr.getString(1); JSONArray req = sr.getJSONArray(2); JSONArray reqstrs = sr.getJSONArray(3); if (type.equals("none")) { // unsatisfiable template continue; } else if (type.equals("all")) { // AND requirement? boolean ok = true; for (int j = 0; j < req.length(); j++) { if (fields.length <= j || fields[j] == null || fields[j].length() == 0) { // missing and was required ok = false; break; } } if (!ok) { continue; } } else if (type.equals("any")) { // OR requirement? boolean ok = false; for (int j = 0; j < req.length(); j++) { if (fields.length <= j || fields[j] == null || fields[j].length() == 0) { // missing and was required ok = true; break; } } if (!ok) { continue; } } // extra cloze requirement? boolean ok = true; for (int j = 0; j < reqstrs.length(); j++) { if (!flds.matches(reqstrs.getString(i))) { // required cloze string was missing ok = false; break; } } if (!ok) { continue; } avail.add(ord); } } catch (JSONException e) { throw new RuntimeException(e); } return avail; } /** * Sync handling * *********************************************************************************************** */ public void beforeUpload() { try { for (JSONObject m : all()) { m.put("usn", 0); } } catch (JSONException e) { throw new RuntimeException(e); } save(); } /** * Routines from Stdmodels.py * *********************************************************************************************** */ public JSONObject addBasicModel(String name, boolean setCurrent) { JSONObject m = newModel(name); JSONObject fm = newField("Front"); addField(m, fm); fm = newField("Back"); addField(m, fm); JSONObject t = newTemplate("Forward"); try { t.put("qfmt", "{{Front}}"); t.put("afmt", t.getString("qfmt") + "\n\n<hr id=answer>\n\n{{Back}}"); } catch (JSONException e) { throw new RuntimeException(e); } addTemplate(m, t); add(m, setCurrent); return m; } // addClozeModel /** * Other stuff * NOT IN LIBANKI * *********************************************************************************************** */ public void setChanged() { mChanged = true; } /** * Css generation * *********************************************************************************************** */ /** * Returns a cached CSS for the font color and font size of a given Template taking into account the included * fields * * @param ord - number of template * @param percentage the preference factor to use for calculating the display font size from the cardmodel and * fontmodel font size * @return the html contents surrounded by a css style which contains class styles for answer/question and fields */ // public String getCSSForFontColorSize(int ord, int percentage, boolean night) { // // check whether the percentage is this the same as last time // if (mDisplayPercentage != percentage || mNightMode != night || !mCssTemplateMap.containsKey(ord)) { // mDisplayPercentage = percentage; // mNightMode = night; // mCssTemplateMap.put(ord, createCSSForFontColorSize(ord, percentage, night)); // } // return mCssTemplateMap.get(ord); // } // // // /** // * @param ord - number of template // * @param percentage the factor to apply to the font size in card model to the display size (in %) // * @param nightmode boolean // * @return the html contents surrounded by a css style which contains class styles for answer/question and fields // */ // private String createCSSForFontColorSize(int ord, int percentage, boolean night) { // StringBuffer sb = new StringBuffer(); // sb.append("<!-- ").append(percentage).append(" % display font size-->"); // sb.append("<style type=\"text/css\">\n"); // // JSONObject template = getTemplate(ord); // // try { // // fields // for (int i = 0; i < mFields.length(); i++) { // JSONObject fconf = mFields.getJSONObject(i); // sb.append(_fieldCSS(percentage, // String.format(".fm%s-%s", Utils.hexifyID(mId), Utils.hexifyID(fconf.getInt("ord"))), // fconf.getString("font"), fconf.getInt("qsize"), // invertColor(fconf.getString("qcol"), night), // fconf.getString("rtl").equals("True"), fconf.getString("pre").equals("True"))); // } // // // templates // for (int i = 0; i < mTemplates.length(); i++) { // JSONObject tmpl = mTemplates.getJSONObject(i); // sb.append(String.format(".cm%s-%s {text-align:%s;background:%s;", Utils.hexifyID(mId), Utils.hexifyID(tmpl.getInt("ord")), // align_text[template.getInt("align")], invertColor(tmpl.getString("bg"), night))); // sb.append("padding-left:5px;"); // sb.append("padding-right:5px;}\n"); // } // } catch (JSONException e) { // throw new RuntimeException(e); // } // // // finish // sb.append("</style>"); // return sb.toString(); // } // // // private static String invertColor(String color, boolean invert) { // if (invert) { // if (color.length() != 0) { // color = StringTools.toUpperCase(color); // } // final char[] items = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; // final char[] tmpItems = {'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v'}; // for (int i = 0; i < 16; i++) { // color = color.replace(items[i], tmpItems[15-i]); // } // for (int i = 0; i < 16; i++) { // color = color.replace(tmpItems[i], items[i]); // } // } // return color; // } // TODO: implement call /** * Returns a string where all colors have been inverted. * It applies to anything that is in a tag and looks like #FFFFFF * * Example: Here only #000000 will be replaced (#777777 is content) * <span style="color: #000000;">Code #777777 is the grey color</span> * * This is done with a state machine with 2 states: * - 0: within content * - 1: within a tag */ // public static String invertColors(String text, boolean invert) { // if (invert) { // int state = 0; // StringBuffer inverted = new StringBuffer(text.length()); // for(int i=0; i<text.length(); i++) { // char character = text.charAt(i); // if (state == 1 && character == '#') { // inverted.append(invertColor(text.substring(i+1, i+7), true)); // } // else { // if (character == '<') { // state = 1; // } // if (character == '>') { // state = 0; // } // inverted.append(character); // } // } // return inverted.toString(); // } // else { // return text; // } // } // // private static String _fieldCSS(int percentage, String prefix, String fontFamily, int fontSize, String fontColour, boolean rtl, boolean pre) { // StringBuffer sb = new StringBuffer(); // sb.append(prefix).append(" {"); // if (null != fontFamily && 0 < fontFamily.trim().length()) { // sb.append("font-family:\"").append(fontFamily).append("\";\n"); // } // if (0 < fontSize) { // sb.append("font-size:"); // sb.append((percentage * fontSize) / 100); // sb.append("px;\n"); // } // if (null != fontColour && 0 < fontColour.trim().length()) { // sb.append("color:").append(fontColour).append(";\n"); // } // if (rtl) { // sb.append("direction:rtl;unicode-bidi:embed;\n"); // } // if (rtl) { // sb.append("white-space:pre-wrap;\n"); // } // sb.append("}\n"); // return sb.toString(); // } // /** // * Prepares the Background Colors for all CardModels in this Model // */ // private void prepareColorForCardModels(boolean invertedColors) { // CardModel myCardModel = null; // String color = null; // for (Map.Entry<Long, CardModel> entry : mCardModelsMap.entrySet()) { // myCardModel = entry.getValue(); // color = invertColor(myCardModel.getLastFontColour(), invertedColors); // mColorCardModelMap.put(myCardModel.getId(), color); // } // } // // protected final String getBackgroundColor(long myCardModelId, boolean invertedColors) { // if (mColorCardModelMap.size() == 0) { // prepareColorForCardModels(invertedColors); // } // String color = mColorCardModelMap.get(myCardModelId); // if (color != null) { // return color; // } else { // return "#FFFFFF"; // } // } /** * *********************************************************************************************** */ // // public static HashMap<Long, Model> getModels(Deck deck) { // Model mModel; // HashMap<Long, Model> mModels = new HashMap<Long, Model>(); // // Cursor mCursor = null; // try { // mCursor = deck.getDB().getDatabase().rawQuery("SELECT id FROM models", null); // if (!mCursor.moveToFirst()) { // return mModels; // } // do { // Long id = mCursor.getLong(0); // mModel = getModel(deck, id, true); // mModels.put(id, mModel); // // } while (mCursor.moveToNext()); // // } finally { // if (mCursor != null) { // mCursor.close(); // } // } // return mModels; // } // // // // private static String replaceField(String replaceFrom, Fact fact, int replaceAt, boolean isQuestion) { // int endIndex = replaceFrom.indexOf(")", replaceAt); // String fieldName = replaceFrom.substring(replaceAt + 2, endIndex); // char fieldType = replaceFrom.charAt(endIndex + 1); // if (isQuestion) { // String replace = "%(" + fieldName + ")" + fieldType; // String with = "<span class=\"fm" + Long.toHexString(fact.getFieldModelId(fieldName)) + "\">" // + fact.getFieldValue(fieldName) + "</span>"; // replaceFrom = replaceFrom.replace(replace, with); // } else { // replaceFrom.replace("%(" + fieldName + ")" + fieldType, "<span class=\"fma" // + Long.toHexString(fact.getFieldModelId(fieldName)) + "\">" + fact.getFieldValue(fieldName) // + "</span"); // } // return replaceFrom; // } // // // private static String replaceHtmlField(String replaceFrom, Fact fact, int replaceAt) { // int endIndex = replaceFrom.indexOf(")", replaceAt); // String fieldName = replaceFrom.substring(replaceAt + 7, endIndex); // char fieldType = replaceFrom.charAt(endIndex + 1); // String replace = "%(text:" + fieldName + ")" + fieldType; // String with = fact.getFieldValue(fieldName); // replaceFrom = replaceFrom.replace(replace, with); // return replaceFrom; // } /** * @return the ID */ public int getId() { return mId; } /** * @return the name */ public String getName() { return mName; } }
true
true
public void _transformFields(JSONObject m) { // Method fn) { // model hasn't been added yet? try { if (m.getLong("id") == 0) { return; } } catch (JSONException e) { throw new RuntimeException(e); } // TODO } /** * Templates * *********************************************************************************************** */ public JSONObject newTemplate(String name) { JSONObject t; try { t = new JSONObject(defaultTemplate); t.put("name", name); } catch (JSONException e) { throw new RuntimeException(e); } return t; } /** Note: should col.genCards() afterwards. */ public void addTemplate(JSONObject m, JSONObject template) { try { if (m.getLong("id") != 0) { mCol.modSchema(); } JSONArray ja = m.getJSONArray("tmpls"); ja.put(template); m.put("tmpls", ja); _updateTemplOrds(m); save(m); } catch (JSONException e) { throw new RuntimeException(e); } } //remtemplate public void _updateTemplOrds(JSONObject m) { JSONArray ja; try { ja = m.getJSONArray("tmpls"); for (int i = 0; i < ja.length(); i++) { JSONObject f = ja.getJSONObject(i); f.put("ord", i); } } catch (JSONException e) { throw new RuntimeException(e); } } //movetemplate private void _syncTemplates(JSONObject m) { ArrayList<Long> rem = mCol.genCards(Utils.arrayList2array(nids(m))); mCol.remEmptyCards(Utils.arrayList2array(rem)); } // public TreeMap<Integer, JSONObject> getTemplates() { // return mTemplateMap; // } // // // public JSONObject getTemplate(int ord) { // return mTemplateMap.get(ord); // } // not in libanki public Template[] getCmpldTemplate(long modelId, int ord) { if (!mCmpldTemplateMap.containsKey(modelId)) { mCmpldTemplateMap.put(modelId, new HashMap<Integer, Template[]>()); } if (!mCmpldTemplateMap.get(modelId).containsKey(ord)) { mCmpldTemplateMap.get(modelId).put(ord, compileTemplate(modelId, ord)); } return mCmpldTemplateMap.get(modelId).get(ord); } // not in libanki private Template[] compileTemplate(long modelId, int ord) { JSONObject model = mModels.get(modelId); JSONObject template; Template[] t = new Template[2]; try { template = model.getJSONArray("tmpls").getJSONObject(ord); String format = template.getString("qfmt").replace("cloze", "cq:"); Log.i(AnkiDroidApp.TAG, "Compiling question template \"" + format + "\""); t[0] = Mustache.compiler().compile(format); format = template.getString("afmt").replace("cloze:", "ca:"); Log.i(AnkiDroidApp.TAG, "Compiling answer template \"" + format + "\""); t[1] = Mustache.compiler().compile(format); } catch (JSONException e) { throw new RuntimeException(e); } return t; } // /** // * This function recompiles the templates for question and answer. It should be called everytime we change mQformat // * or mAformat, so if in the future we create set(Q|A)Format setters, we should include a call to this. // */ // private void refreshTemplates(int ord) { // // Question template // StringBuffer sb = new StringBuffer(); // Matcher m = sOldStylePattern.matcher(mQformat); // while (m.find()) { // // Convert old style // m.appendReplacement(sb, "{{" + m.group(1) + "}}"); // } // m.appendTail(sb); // Log.i(AnkiDroidApp.TAG, "Compiling question template \"" + sb.toString() + "\""); // mQTemplate = Mustache.compiler().compile(sb.toString()); // // // Answer template // sb = new StringBuffer(); // m = sOldStylePattern.matcher(mAformat); // while (m.find()) { // // Convert old style // m.appendReplacement(sb, "{{" + m.group(1) + "}}"); // } // m.appendTail(sb); // Log.i(AnkiDroidApp.TAG, "Compiling answer template \"" + sb.toString() + "\""); // mATemplate = Mustache.compiler().compile(sb.toString()); // } /** * Model changing * *********************************************************************************************** */ // change //_changeNotes //_changeCards /** * Schema hash * *********************************************************************************************** */ //scmhash /** * Required field/text cache * *********************************************************************************************** */ private void _updateRequired(JSONObject m) { JSONArray req = new JSONArray(); ArrayList<String> flds = new ArrayList<String>(); JSONArray fields; try { fields = m.getJSONArray("flds"); for (int i = 0; i < fields.length(); i++) { flds.add(fields.getJSONObject(i).getString("name")); } boolean cloze = false; JSONArray templates = m.getJSONArray("tmpls"); for (int i = 0; i < templates.length(); i++) { JSONObject t = templates.getJSONObject(i); Object[] ret = _reqForTemplate(m, flds, t); if (((JSONArray)ret[2]).length() > 0) { cloze = true; } JSONArray r = new JSONArray(); r.put(t.getInt("ord")); r.put(ret[0]); r.put(ret[1]); r.put(ret[2]); req.put(r); } m.put("req", req); m.put("cloze", cloze); } catch (JSONException e) { throw new RuntimeException(e); } } private Object[] _reqForTemplate(JSONObject m, ArrayList<String> flds, JSONObject t) { try { ArrayList<String> a = new ArrayList<String> (); ArrayList<String> b = new ArrayList<String> (); String cloze = ""; JSONArray reqstrs = new JSONArray(); if (t.has("cloze")) { // need a cloze-specific filler // TODO } for (String f : flds) { a.add(cloze.length() > 0 ? cloze : "1"); b.add(""); } Object[] data; data = new Object[]{1l, 1l, m.getLong("id"), 1l, t.getInt("ord"), "", Utils.joinFields(a.toArray(new String[a.size()]))}; String full = mCol._renderQA(data).get("q"); data = new Object[]{1l, 1l, m.getLong("id"), 1l, t.getInt("ord"), "", Utils.joinFields(b.toArray(new String[b.size()]))}; String empty = mCol._renderQA(data).get("q"); // if full and empty are the same, the template is invalid and there is no way to satisfy it if (full.equals(empty)) { return new Object[] {"none", new JSONArray(), new JSONArray()}; } String type = "all"; JSONArray req = new JSONArray(); ArrayList<String> tmp = new ArrayList<String>(); for (int i = 0; i < flds.size(); i++) { tmp.clear(); tmp.addAll(a); tmp.remove(i); tmp.add(i, ""); data[6] = Utils.joinFields(tmp.toArray(new String[tmp.size()])); // if the result is same as empty, field is required if (mCol._renderQA(data).get("q").equals(empty)) { req.put(i); } } if (req.length() > 0) { return new Object[] {type, req, reqstrs}; } // if there are no required fields, switch to any mode type = "any"; req = new JSONArray(); for (int i = 0; i < flds.size(); i++) { tmp.clear(); tmp.addAll(b); tmp.remove(i); tmp.add(i, "1"); data[6] = Utils.joinFields(tmp.toArray(new String[tmp.size()])); // if not the same as empty, this field can make the card non-blank if (mCol._renderQA(data).get("q").equals(empty)) { req.put(i); } } return new Object[]{ type, req, reqstrs}; } catch (JSONException e) { throw new RuntimeException(e); } } /** Given a joined field string, return available template ordinals */ public ArrayList<Integer> availOrds(JSONObject m, String flds) { String[] fields = Utils.splitFields(flds); for (String f : fields) { f = f.trim(); } ArrayList<Integer> avail = new ArrayList<Integer>(); try { JSONArray reqArray = m.getJSONArray("req"); for (int i = 0; i < reqArray.length(); i++) { JSONArray sr = reqArray.getJSONArray(i); int ord = sr.getInt(0); String type = sr.getString(1); JSONArray req = sr.getJSONArray(2); JSONArray reqstrs = sr.getJSONArray(3); if (type.equals("none")) { // unsatisfiable template continue; } else if (type.equals("all")) { // AND requirement? boolean ok = true; for (int j = 0; j < req.length(); j++) { if (fields.length <= j || fields[j] == null || fields[j].length() == 0) { // missing and was required ok = false; break; } } if (!ok) { continue; } } else if (type.equals("any")) { // OR requirement? boolean ok = false; for (int j = 0; j < req.length(); j++) { if (fields.length <= j || fields[j] == null || fields[j].length() == 0) { // missing and was required ok = true; break; } } if (!ok) { continue; } } // extra cloze requirement? boolean ok = true; for (int j = 0; j < reqstrs.length(); j++) { if (!flds.matches(reqstrs.getString(i))) { // required cloze string was missing ok = false; break; } } if (!ok) { continue; } avail.add(ord); } } catch (JSONException e) { throw new RuntimeException(e); } return avail; } /** * Sync handling * *********************************************************************************************** */ public void beforeUpload() { try { for (JSONObject m : all()) { m.put("usn", 0); } } catch (JSONException e) { throw new RuntimeException(e); } save(); } /** * Routines from Stdmodels.py * *********************************************************************************************** */ public JSONObject addBasicModel(String name, boolean setCurrent) { JSONObject m = newModel(name); JSONObject fm = newField("Front"); addField(m, fm); fm = newField("Back"); addField(m, fm); JSONObject t = newTemplate("Forward"); try { t.put("qfmt", "{{Front}}"); t.put("afmt", t.getString("qfmt") + "\n\n<hr id=answer>\n\n{{Back}}"); } catch (JSONException e) { throw new RuntimeException(e); } addTemplate(m, t); add(m, setCurrent); return m; } // addClozeModel /** * Other stuff * NOT IN LIBANKI * *********************************************************************************************** */ public void setChanged() { mChanged = true; } /** * Css generation * *********************************************************************************************** */ /** * Returns a cached CSS for the font color and font size of a given Template taking into account the included * fields * * @param ord - number of template * @param percentage the preference factor to use for calculating the display font size from the cardmodel and * fontmodel font size * @return the html contents surrounded by a css style which contains class styles for answer/question and fields */ // public String getCSSForFontColorSize(int ord, int percentage, boolean night) { // // check whether the percentage is this the same as last time // if (mDisplayPercentage != percentage || mNightMode != night || !mCssTemplateMap.containsKey(ord)) { // mDisplayPercentage = percentage; // mNightMode = night; // mCssTemplateMap.put(ord, createCSSForFontColorSize(ord, percentage, night)); // } // return mCssTemplateMap.get(ord); // } // // // /** // * @param ord - number of template // * @param percentage the factor to apply to the font size in card model to the display size (in %) // * @param nightmode boolean // * @return the html contents surrounded by a css style which contains class styles for answer/question and fields // */ // private String createCSSForFontColorSize(int ord, int percentage, boolean night) { // StringBuffer sb = new StringBuffer(); // sb.append("<!-- ").append(percentage).append(" % display font size-->"); // sb.append("<style type=\"text/css\">\n"); // // JSONObject template = getTemplate(ord); // // try { // // fields // for (int i = 0; i < mFields.length(); i++) { // JSONObject fconf = mFields.getJSONObject(i); // sb.append(_fieldCSS(percentage, // String.format(".fm%s-%s", Utils.hexifyID(mId), Utils.hexifyID(fconf.getInt("ord"))), // fconf.getString("font"), fconf.getInt("qsize"), // invertColor(fconf.getString("qcol"), night), // fconf.getString("rtl").equals("True"), fconf.getString("pre").equals("True"))); // } // // // templates // for (int i = 0; i < mTemplates.length(); i++) { // JSONObject tmpl = mTemplates.getJSONObject(i); // sb.append(String.format(".cm%s-%s {text-align:%s;background:%s;", Utils.hexifyID(mId), Utils.hexifyID(tmpl.getInt("ord")), // align_text[template.getInt("align")], invertColor(tmpl.getString("bg"), night))); // sb.append("padding-left:5px;"); // sb.append("padding-right:5px;}\n"); // } // } catch (JSONException e) { // throw new RuntimeException(e); // } // // // finish // sb.append("</style>"); // return sb.toString(); // } // // // private static String invertColor(String color, boolean invert) { // if (invert) { // if (color.length() != 0) { // color = StringTools.toUpperCase(color); // } // final char[] items = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; // final char[] tmpItems = {'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v'}; // for (int i = 0; i < 16; i++) { // color = color.replace(items[i], tmpItems[15-i]); // } // for (int i = 0; i < 16; i++) { // color = color.replace(tmpItems[i], items[i]); // } // } // return color; // } // TODO: implement call /** * Returns a string where all colors have been inverted. * It applies to anything that is in a tag and looks like #FFFFFF * * Example: Here only #000000 will be replaced (#777777 is content) * <span style="color: #000000;">Code #777777 is the grey color</span> * * This is done with a state machine with 2 states: * - 0: within content * - 1: within a tag */ // public static String invertColors(String text, boolean invert) { // if (invert) { // int state = 0; // StringBuffer inverted = new StringBuffer(text.length()); // for(int i=0; i<text.length(); i++) { // char character = text.charAt(i); // if (state == 1 && character == '#') { // inverted.append(invertColor(text.substring(i+1, i+7), true)); // } // else { // if (character == '<') { // state = 1; // } // if (character == '>') { // state = 0; // } // inverted.append(character); // } // } // return inverted.toString(); // } // else { // return text; // } // } // // private static String _fieldCSS(int percentage, String prefix, String fontFamily, int fontSize, String fontColour, boolean rtl, boolean pre) { // StringBuffer sb = new StringBuffer(); // sb.append(prefix).append(" {"); // if (null != fontFamily && 0 < fontFamily.trim().length()) { // sb.append("font-family:\"").append(fontFamily).append("\";\n"); // } // if (0 < fontSize) { // sb.append("font-size:"); // sb.append((percentage * fontSize) / 100); // sb.append("px;\n"); // } // if (null != fontColour && 0 < fontColour.trim().length()) { // sb.append("color:").append(fontColour).append(";\n"); // } // if (rtl) { // sb.append("direction:rtl;unicode-bidi:embed;\n"); // } // if (rtl) { // sb.append("white-space:pre-wrap;\n"); // } // sb.append("}\n"); // return sb.toString(); // } // /** // * Prepares the Background Colors for all CardModels in this Model // */ // private void prepareColorForCardModels(boolean invertedColors) { // CardModel myCardModel = null; // String color = null; // for (Map.Entry<Long, CardModel> entry : mCardModelsMap.entrySet()) { // myCardModel = entry.getValue(); // color = invertColor(myCardModel.getLastFontColour(), invertedColors); // mColorCardModelMap.put(myCardModel.getId(), color); // } // } // // protected final String getBackgroundColor(long myCardModelId, boolean invertedColors) { // if (mColorCardModelMap.size() == 0) { // prepareColorForCardModels(invertedColors); // } // String color = mColorCardModelMap.get(myCardModelId); // if (color != null) { // return color; // } else { // return "#FFFFFF"; // } // } /** * *********************************************************************************************** */ // // public static HashMap<Long, Model> getModels(Deck deck) { // Model mModel; // HashMap<Long, Model> mModels = new HashMap<Long, Model>(); // // Cursor mCursor = null; // try { // mCursor = deck.getDB().getDatabase().rawQuery("SELECT id FROM models", null); // if (!mCursor.moveToFirst()) { // return mModels; // } // do { // Long id = mCursor.getLong(0); // mModel = getModel(deck, id, true); // mModels.put(id, mModel); // // } while (mCursor.moveToNext()); // // } finally { // if (mCursor != null) { // mCursor.close(); // } // } // return mModels; // } // // // // private static String replaceField(String replaceFrom, Fact fact, int replaceAt, boolean isQuestion) { // int endIndex = replaceFrom.indexOf(")", replaceAt); // String fieldName = replaceFrom.substring(replaceAt + 2, endIndex); // char fieldType = replaceFrom.charAt(endIndex + 1); // if (isQuestion) { // String replace = "%(" + fieldName + ")" + fieldType; // String with = "<span class=\"fm" + Long.toHexString(fact.getFieldModelId(fieldName)) + "\">" // + fact.getFieldValue(fieldName) + "</span>"; // replaceFrom = replaceFrom.replace(replace, with); // } else { // replaceFrom.replace("%(" + fieldName + ")" + fieldType, "<span class=\"fma" // + Long.toHexString(fact.getFieldModelId(fieldName)) + "\">" + fact.getFieldValue(fieldName) // + "</span"); // } // return replaceFrom; // } // // // private static String replaceHtmlField(String replaceFrom, Fact fact, int replaceAt) { // int endIndex = replaceFrom.indexOf(")", replaceAt); // String fieldName = replaceFrom.substring(replaceAt + 7, endIndex); // char fieldType = replaceFrom.charAt(endIndex + 1); // String replace = "%(text:" + fieldName + ")" + fieldType; // String with = fact.getFieldValue(fieldName); // replaceFrom = replaceFrom.replace(replace, with); // return replaceFrom; // } /** * @return the ID */ public int getId() { return mId; } /** * @return the name */ public String getName() { return mName; } }
public void _transformFields(JSONObject m) { // Method fn) { // model hasn't been added yet? try { if (m.getLong("id") == 0) { return; } } catch (JSONException e) { throw new RuntimeException(e); } // TODO } /** * Templates * *********************************************************************************************** */ public JSONObject newTemplate(String name) { JSONObject t; try { t = new JSONObject(defaultTemplate); t.put("name", name); } catch (JSONException e) { throw new RuntimeException(e); } return t; } /** Note: should col.genCards() afterwards. */ public void addTemplate(JSONObject m, JSONObject template) { try { if (m.getLong("id") != 0) { mCol.modSchema(); } JSONArray ja = m.getJSONArray("tmpls"); ja.put(template); m.put("tmpls", ja); _updateTemplOrds(m); save(m); } catch (JSONException e) { throw new RuntimeException(e); } } //remtemplate public void _updateTemplOrds(JSONObject m) { JSONArray ja; try { ja = m.getJSONArray("tmpls"); for (int i = 0; i < ja.length(); i++) { JSONObject f = ja.getJSONObject(i); f.put("ord", i); } } catch (JSONException e) { throw new RuntimeException(e); } } //movetemplate private void _syncTemplates(JSONObject m) { ArrayList<Long> rem = mCol.genCards(Utils.arrayList2array(nids(m))); mCol.remEmptyCards(Utils.arrayList2array(rem)); } // public TreeMap<Integer, JSONObject> getTemplates() { // return mTemplateMap; // } // // // public JSONObject getTemplate(int ord) { // return mTemplateMap.get(ord); // } // not in libanki public Template[] getCmpldTemplate(long modelId, int ord) { if (!mCmpldTemplateMap.containsKey(modelId)) { mCmpldTemplateMap.put(modelId, new HashMap<Integer, Template[]>()); } if (!mCmpldTemplateMap.get(modelId).containsKey(ord)) { mCmpldTemplateMap.get(modelId).put(ord, compileTemplate(modelId, ord)); } return mCmpldTemplateMap.get(modelId).get(ord); } // not in libanki private Template[] compileTemplate(long modelId, int ord) { JSONObject model = mModels.get(modelId); JSONObject template; Template[] t = new Template[2]; try { template = model.getJSONArray("tmpls").getJSONObject(ord); String format = template.getString("qfmt").replace("cloze:", "cq:"); Log.i(AnkiDroidApp.TAG, "Compiling question template \"" + format + "\""); t[0] = Mustache.compiler().compile(format); format = template.getString("afmt").replace("cloze:", "ca:"); Log.i(AnkiDroidApp.TAG, "Compiling answer template \"" + format + "\""); t[1] = Mustache.compiler().compile(format); } catch (JSONException e) { throw new RuntimeException(e); } return t; } // /** // * This function recompiles the templates for question and answer. It should be called everytime we change mQformat // * or mAformat, so if in the future we create set(Q|A)Format setters, we should include a call to this. // */ // private void refreshTemplates(int ord) { // // Question template // StringBuffer sb = new StringBuffer(); // Matcher m = sOldStylePattern.matcher(mQformat); // while (m.find()) { // // Convert old style // m.appendReplacement(sb, "{{" + m.group(1) + "}}"); // } // m.appendTail(sb); // Log.i(AnkiDroidApp.TAG, "Compiling question template \"" + sb.toString() + "\""); // mQTemplate = Mustache.compiler().compile(sb.toString()); // // // Answer template // sb = new StringBuffer(); // m = sOldStylePattern.matcher(mAformat); // while (m.find()) { // // Convert old style // m.appendReplacement(sb, "{{" + m.group(1) + "}}"); // } // m.appendTail(sb); // Log.i(AnkiDroidApp.TAG, "Compiling answer template \"" + sb.toString() + "\""); // mATemplate = Mustache.compiler().compile(sb.toString()); // } /** * Model changing * *********************************************************************************************** */ // change //_changeNotes //_changeCards /** * Schema hash * *********************************************************************************************** */ //scmhash /** * Required field/text cache * *********************************************************************************************** */ private void _updateRequired(JSONObject m) { JSONArray req = new JSONArray(); ArrayList<String> flds = new ArrayList<String>(); JSONArray fields; try { fields = m.getJSONArray("flds"); for (int i = 0; i < fields.length(); i++) { flds.add(fields.getJSONObject(i).getString("name")); } boolean cloze = false; JSONArray templates = m.getJSONArray("tmpls"); for (int i = 0; i < templates.length(); i++) { JSONObject t = templates.getJSONObject(i); Object[] ret = _reqForTemplate(m, flds, t); if (((JSONArray)ret[2]).length() > 0) { cloze = true; } JSONArray r = new JSONArray(); r.put(t.getInt("ord")); r.put(ret[0]); r.put(ret[1]); r.put(ret[2]); req.put(r); } m.put("req", req); m.put("cloze", cloze); } catch (JSONException e) { throw new RuntimeException(e); } } private Object[] _reqForTemplate(JSONObject m, ArrayList<String> flds, JSONObject t) { try { ArrayList<String> a = new ArrayList<String> (); ArrayList<String> b = new ArrayList<String> (); String cloze = ""; JSONArray reqstrs = new JSONArray(); if (t.has("cloze")) { // need a cloze-specific filler // TODO } for (String f : flds) { a.add(cloze.length() > 0 ? cloze : "1"); b.add(""); } Object[] data; data = new Object[]{1l, 1l, m.getLong("id"), 1l, t.getInt("ord"), "", Utils.joinFields(a.toArray(new String[a.size()]))}; String full = mCol._renderQA(data).get("q"); data = new Object[]{1l, 1l, m.getLong("id"), 1l, t.getInt("ord"), "", Utils.joinFields(b.toArray(new String[b.size()]))}; String empty = mCol._renderQA(data).get("q"); // if full and empty are the same, the template is invalid and there is no way to satisfy it if (full.equals(empty)) { return new Object[] {"none", new JSONArray(), new JSONArray()}; } String type = "all"; JSONArray req = new JSONArray(); ArrayList<String> tmp = new ArrayList<String>(); for (int i = 0; i < flds.size(); i++) { tmp.clear(); tmp.addAll(a); tmp.remove(i); tmp.add(i, ""); data[6] = Utils.joinFields(tmp.toArray(new String[tmp.size()])); // if the result is same as empty, field is required if (mCol._renderQA(data).get("q").equals(empty)) { req.put(i); } } if (req.length() > 0) { return new Object[] {type, req, reqstrs}; } // if there are no required fields, switch to any mode type = "any"; req = new JSONArray(); for (int i = 0; i < flds.size(); i++) { tmp.clear(); tmp.addAll(b); tmp.remove(i); tmp.add(i, "1"); data[6] = Utils.joinFields(tmp.toArray(new String[tmp.size()])); // if not the same as empty, this field can make the card non-blank if (mCol._renderQA(data).get("q").equals(empty)) { req.put(i); } } return new Object[]{ type, req, reqstrs}; } catch (JSONException e) { throw new RuntimeException(e); } } /** Given a joined field string, return available template ordinals */ public ArrayList<Integer> availOrds(JSONObject m, String flds) { String[] fields = Utils.splitFields(flds); for (String f : fields) { f = f.trim(); } ArrayList<Integer> avail = new ArrayList<Integer>(); try { JSONArray reqArray = m.getJSONArray("req"); for (int i = 0; i < reqArray.length(); i++) { JSONArray sr = reqArray.getJSONArray(i); int ord = sr.getInt(0); String type = sr.getString(1); JSONArray req = sr.getJSONArray(2); JSONArray reqstrs = sr.getJSONArray(3); if (type.equals("none")) { // unsatisfiable template continue; } else if (type.equals("all")) { // AND requirement? boolean ok = true; for (int j = 0; j < req.length(); j++) { if (fields.length <= j || fields[j] == null || fields[j].length() == 0) { // missing and was required ok = false; break; } } if (!ok) { continue; } } else if (type.equals("any")) { // OR requirement? boolean ok = false; for (int j = 0; j < req.length(); j++) { if (fields.length <= j || fields[j] == null || fields[j].length() == 0) { // missing and was required ok = true; break; } } if (!ok) { continue; } } // extra cloze requirement? boolean ok = true; for (int j = 0; j < reqstrs.length(); j++) { if (!flds.matches(reqstrs.getString(i))) { // required cloze string was missing ok = false; break; } } if (!ok) { continue; } avail.add(ord); } } catch (JSONException e) { throw new RuntimeException(e); } return avail; } /** * Sync handling * *********************************************************************************************** */ public void beforeUpload() { try { for (JSONObject m : all()) { m.put("usn", 0); } } catch (JSONException e) { throw new RuntimeException(e); } save(); } /** * Routines from Stdmodels.py * *********************************************************************************************** */ public JSONObject addBasicModel(String name, boolean setCurrent) { JSONObject m = newModel(name); JSONObject fm = newField("Front"); addField(m, fm); fm = newField("Back"); addField(m, fm); JSONObject t = newTemplate("Forward"); try { t.put("qfmt", "{{Front}}"); t.put("afmt", t.getString("qfmt") + "\n\n<hr id=answer>\n\n{{Back}}"); } catch (JSONException e) { throw new RuntimeException(e); } addTemplate(m, t); add(m, setCurrent); return m; } // addClozeModel /** * Other stuff * NOT IN LIBANKI * *********************************************************************************************** */ public void setChanged() { mChanged = true; } /** * Css generation * *********************************************************************************************** */ /** * Returns a cached CSS for the font color and font size of a given Template taking into account the included * fields * * @param ord - number of template * @param percentage the preference factor to use for calculating the display font size from the cardmodel and * fontmodel font size * @return the html contents surrounded by a css style which contains class styles for answer/question and fields */ // public String getCSSForFontColorSize(int ord, int percentage, boolean night) { // // check whether the percentage is this the same as last time // if (mDisplayPercentage != percentage || mNightMode != night || !mCssTemplateMap.containsKey(ord)) { // mDisplayPercentage = percentage; // mNightMode = night; // mCssTemplateMap.put(ord, createCSSForFontColorSize(ord, percentage, night)); // } // return mCssTemplateMap.get(ord); // } // // // /** // * @param ord - number of template // * @param percentage the factor to apply to the font size in card model to the display size (in %) // * @param nightmode boolean // * @return the html contents surrounded by a css style which contains class styles for answer/question and fields // */ // private String createCSSForFontColorSize(int ord, int percentage, boolean night) { // StringBuffer sb = new StringBuffer(); // sb.append("<!-- ").append(percentage).append(" % display font size-->"); // sb.append("<style type=\"text/css\">\n"); // // JSONObject template = getTemplate(ord); // // try { // // fields // for (int i = 0; i < mFields.length(); i++) { // JSONObject fconf = mFields.getJSONObject(i); // sb.append(_fieldCSS(percentage, // String.format(".fm%s-%s", Utils.hexifyID(mId), Utils.hexifyID(fconf.getInt("ord"))), // fconf.getString("font"), fconf.getInt("qsize"), // invertColor(fconf.getString("qcol"), night), // fconf.getString("rtl").equals("True"), fconf.getString("pre").equals("True"))); // } // // // templates // for (int i = 0; i < mTemplates.length(); i++) { // JSONObject tmpl = mTemplates.getJSONObject(i); // sb.append(String.format(".cm%s-%s {text-align:%s;background:%s;", Utils.hexifyID(mId), Utils.hexifyID(tmpl.getInt("ord")), // align_text[template.getInt("align")], invertColor(tmpl.getString("bg"), night))); // sb.append("padding-left:5px;"); // sb.append("padding-right:5px;}\n"); // } // } catch (JSONException e) { // throw new RuntimeException(e); // } // // // finish // sb.append("</style>"); // return sb.toString(); // } // // // private static String invertColor(String color, boolean invert) { // if (invert) { // if (color.length() != 0) { // color = StringTools.toUpperCase(color); // } // final char[] items = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; // final char[] tmpItems = {'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v'}; // for (int i = 0; i < 16; i++) { // color = color.replace(items[i], tmpItems[15-i]); // } // for (int i = 0; i < 16; i++) { // color = color.replace(tmpItems[i], items[i]); // } // } // return color; // } // TODO: implement call /** * Returns a string where all colors have been inverted. * It applies to anything that is in a tag and looks like #FFFFFF * * Example: Here only #000000 will be replaced (#777777 is content) * <span style="color: #000000;">Code #777777 is the grey color</span> * * This is done with a state machine with 2 states: * - 0: within content * - 1: within a tag */ // public static String invertColors(String text, boolean invert) { // if (invert) { // int state = 0; // StringBuffer inverted = new StringBuffer(text.length()); // for(int i=0; i<text.length(); i++) { // char character = text.charAt(i); // if (state == 1 && character == '#') { // inverted.append(invertColor(text.substring(i+1, i+7), true)); // } // else { // if (character == '<') { // state = 1; // } // if (character == '>') { // state = 0; // } // inverted.append(character); // } // } // return inverted.toString(); // } // else { // return text; // } // } // // private static String _fieldCSS(int percentage, String prefix, String fontFamily, int fontSize, String fontColour, boolean rtl, boolean pre) { // StringBuffer sb = new StringBuffer(); // sb.append(prefix).append(" {"); // if (null != fontFamily && 0 < fontFamily.trim().length()) { // sb.append("font-family:\"").append(fontFamily).append("\";\n"); // } // if (0 < fontSize) { // sb.append("font-size:"); // sb.append((percentage * fontSize) / 100); // sb.append("px;\n"); // } // if (null != fontColour && 0 < fontColour.trim().length()) { // sb.append("color:").append(fontColour).append(";\n"); // } // if (rtl) { // sb.append("direction:rtl;unicode-bidi:embed;\n"); // } // if (rtl) { // sb.append("white-space:pre-wrap;\n"); // } // sb.append("}\n"); // return sb.toString(); // } // /** // * Prepares the Background Colors for all CardModels in this Model // */ // private void prepareColorForCardModels(boolean invertedColors) { // CardModel myCardModel = null; // String color = null; // for (Map.Entry<Long, CardModel> entry : mCardModelsMap.entrySet()) { // myCardModel = entry.getValue(); // color = invertColor(myCardModel.getLastFontColour(), invertedColors); // mColorCardModelMap.put(myCardModel.getId(), color); // } // } // // protected final String getBackgroundColor(long myCardModelId, boolean invertedColors) { // if (mColorCardModelMap.size() == 0) { // prepareColorForCardModels(invertedColors); // } // String color = mColorCardModelMap.get(myCardModelId); // if (color != null) { // return color; // } else { // return "#FFFFFF"; // } // } /** * *********************************************************************************************** */ // // public static HashMap<Long, Model> getModels(Deck deck) { // Model mModel; // HashMap<Long, Model> mModels = new HashMap<Long, Model>(); // // Cursor mCursor = null; // try { // mCursor = deck.getDB().getDatabase().rawQuery("SELECT id FROM models", null); // if (!mCursor.moveToFirst()) { // return mModels; // } // do { // Long id = mCursor.getLong(0); // mModel = getModel(deck, id, true); // mModels.put(id, mModel); // // } while (mCursor.moveToNext()); // // } finally { // if (mCursor != null) { // mCursor.close(); // } // } // return mModels; // } // // // // private static String replaceField(String replaceFrom, Fact fact, int replaceAt, boolean isQuestion) { // int endIndex = replaceFrom.indexOf(")", replaceAt); // String fieldName = replaceFrom.substring(replaceAt + 2, endIndex); // char fieldType = replaceFrom.charAt(endIndex + 1); // if (isQuestion) { // String replace = "%(" + fieldName + ")" + fieldType; // String with = "<span class=\"fm" + Long.toHexString(fact.getFieldModelId(fieldName)) + "\">" // + fact.getFieldValue(fieldName) + "</span>"; // replaceFrom = replaceFrom.replace(replace, with); // } else { // replaceFrom.replace("%(" + fieldName + ")" + fieldType, "<span class=\"fma" // + Long.toHexString(fact.getFieldModelId(fieldName)) + "\">" + fact.getFieldValue(fieldName) // + "</span"); // } // return replaceFrom; // } // // // private static String replaceHtmlField(String replaceFrom, Fact fact, int replaceAt) { // int endIndex = replaceFrom.indexOf(")", replaceAt); // String fieldName = replaceFrom.substring(replaceAt + 7, endIndex); // char fieldType = replaceFrom.charAt(endIndex + 1); // String replace = "%(text:" + fieldName + ")" + fieldType; // String with = fact.getFieldValue(fieldName); // replaceFrom = replaceFrom.replace(replace, with); // return replaceFrom; // } /** * @return the ID */ public int getId() { return mId; } /** * @return the name */ public String getName() { return mName; } }
diff --git a/src/main/java/hudson/scm/IntegrityCheckoutTask.java b/src/main/java/hudson/scm/IntegrityCheckoutTask.java index a5b770d..0188cfa 100644 --- a/src/main/java/hudson/scm/IntegrityCheckoutTask.java +++ b/src/main/java/hudson/scm/IntegrityCheckoutTask.java @@ -1,312 +1,312 @@ package hudson.scm; import java.io.File; import java.io.IOException; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import com.mks.api.response.APIException; import com.mks.api.util.Base64; import hudson.FilePath; import hudson.FilePath.FileCallable; import hudson.model.BuildListener; import hudson.remoting.VirtualChannel; public class IntegrityCheckoutTask implements FileCallable<Boolean> { private static final long serialVersionUID = 1240357991626897900L; private static final int CHECKOUT_TRESHOLD = 500; private final List<Hashtable<CM_PROJECT, Object>> projectMembersList; private final List<String> dirList; private final String lineTerminator; private final boolean restoreTimestamp; private final boolean cleanCopy; private final String alternateWorkspaceDir; private final boolean fetchChangedWorkspaceFiles; private final BuildListener listener; // API connection information private String ipHostName; private String hostName; private int ipPort = 0; private int port; private boolean secure; private String userName; private String password; // Checksum Hash private Hashtable<String, String> checksumHash; // Counts private int addCount; private int updateCount; private int dropCount; private int fetchCount; /** * Hudson supports building on distributed machines, and the SCM plugin must * be able to be executed on other machines than the master. * @param projectMembersList A list of all the members that are in this Integrity SCM project * @param dirList A list of all the unique directories in this Integrity SCM project * @param alternateWorkspaceDir Specifies an alternate location for checkout other than the default workspace * @param lineTerminator The line termination setting for this checkout operation * @param restoreTimestamp Toggles whether to use the current date/time or the original date/time for the member * @param cleanCopy Indicates whether or not the workspace needs to be cleaned up prior to checking out files * @param fetchChangedWorkspaceFiles Toggles whether or not to calculate checksums, so if changed then it will be overwritten * @param listener The Hudson build listener */ public IntegrityCheckoutTask(List<Hashtable<CM_PROJECT, Object>> projectMembersList, List<String> dirList, String alternateWorkspaceDir, String lineTerminator, boolean restoreTimestamp, boolean cleanCopy, boolean fetchChangedWorkspaceFiles, BuildListener listener) { this.projectMembersList = projectMembersList; this.dirList = dirList; this.alternateWorkspaceDir = alternateWorkspaceDir; this.lineTerminator = lineTerminator; this.restoreTimestamp = restoreTimestamp; this.cleanCopy = cleanCopy; this.fetchChangedWorkspaceFiles = fetchChangedWorkspaceFiles; this.listener = listener; this.ipHostName = ""; this.ipPort = 0; this.hostName = ""; this.port = 7001; this.secure = false; this.userName = ""; this.password = ""; this.addCount = 0; this.updateCount = 0; this.dropCount = 0; this.fetchCount = 0; this.checksumHash = new Hashtable<String, String>(); Logger.debug("Integrity Checkout Task Created!"); } /** * Helper function to initialize all the variables needed to establish an APISession * @param ipHostName Integration Point Hostname * @param ipPort Integration Point Port * @param hostName Integrity Server Hostname * @param port Integrity Server Port * @param secure Toggles whether Integrity Server is SSL enabled * @param userName Username to connect to the Integrity Server * @param password Password for the Username connection to the Integrity Server */ public void initAPIVariables(String ipHostName, int ipPort, String hostName, int port, boolean secure, String userName, String password) { this.ipHostName = ipHostName; this.ipPort = ipPort; this.hostName = hostName; this.port = port; this.secure = secure; this.userName = userName; this.password = password; } /** * Creates an authenticated API Session against the Integrity Server * @return An authenticated API Session */ public APISession createAPISession() { // Attempt to open a connection to the Integrity Server try { Logger.debug("Creating Integrity API Session..."); return new APISession(ipHostName, ipPort, hostName, port, userName, Base64.decode(password), secure); } catch(APIException aex) { Logger.error("API Exception caught..."); ExceptionHandler eh = new ExceptionHandler(aex); Logger.error(eh.getMessage()); Logger.debug(eh.getCommand() + " returned exit code " + eh.getExitCode()); Logger.fatal(aex); return null; } } /** * Creates the folder structure for the project's contents allowing empty folders to be created * @param workspace */ private void createFolderStructure(FilePath workspace) { Iterator<String> folders = dirList.iterator(); while( folders.hasNext() ) { File dir = new File(workspace + folders.next()); if( ! dir.isDirectory() ) { Logger.debug("Creating folder: " + dir.getAbsolutePath()); dir.mkdirs(); } } } /** * Returns all the changes to the checksums that were performed * @return */ public Hashtable<String, String> getChecksumUpdates() { return checksumHash; } /** * This task wraps around the code necessary to checkout Integrity CM Members on remote machines */ public Boolean invoke(File workspaceFile, VirtualChannel channel) throws IOException { // Figure out where we should be checking out this project File checkOutDir = (null != alternateWorkspaceDir && alternateWorkspaceDir.length() > 0) ? new File(alternateWorkspaceDir) : workspaceFile; // Convert the file object to a hudson FilePath (helps us with workspace.deleteContents()) FilePath workspace = new FilePath(checkOutDir.isAbsolute() ? checkOutDir : new File(workspaceFile.getAbsolutePath() + IntegritySCM.FS + checkOutDir.getPath())); listener.getLogger().println("Checkout directory is " + workspace); // Create a fresh API Session as we may/will be executing from another server APISession api = createAPISession(); // Ensure we've successfully created an API Session if( null == api ) { listener.getLogger().println("Failed to establish an API connection to the Integrity Server!"); return false; } // If we got here, then APISession was created successfully! try { // Keep count of the open file handles generated on the server int openFileHandles = 0; if( cleanCopy ) { listener.getLogger().println("A clean copy is requested; deleting contents of " + workspace); Logger.debug("Deleting contents of workspace " + workspace); workspace.deleteContents(); listener.getLogger().println("Populating clean workspace..."); } // Create an empty folder structure first createFolderStructure(workspace); // Perform a synchronize of each file in the member list... for( Iterator<Hashtable<CM_PROJECT, Object>> it = projectMembersList.iterator(); it.hasNext(); ) { openFileHandles++; Hashtable<CM_PROJECT, Object> memberInfo = it.next(); short deltaFlag = (null == memberInfo.get(CM_PROJECT.DELTA) ? -1 : Short.valueOf(memberInfo.get(CM_PROJECT.DELTA).toString())); File targetFile = new File(workspace + memberInfo.get(CM_PROJECT.RELATIVE_FILE).toString()); String memberName = memberInfo.get(CM_PROJECT.NAME).toString(); String memberID = memberInfo.get(CM_PROJECT.MEMBER_ID).toString(); String memberRev = memberInfo.get(CM_PROJECT.REVISION).toString(); String configPath = memberInfo.get(CM_PROJECT.CONFIG_PATH).toString(); String checksum = (null == memberInfo.get(CM_PROJECT.CHECKSUM) ? "" : memberInfo.get(CM_PROJECT.CHECKSUM).toString()); - if( cleanCopy || deltaFlag == -1 ) + if( cleanCopy && deltaFlag != 3 ) { Logger.debug("Attempting to checkout file: " + targetFile.getAbsolutePath() + " at revision " + memberRev); IntegrityCMMember.checkout(api, configPath, memberID, memberRev, targetFile, restoreTimestamp, lineTerminator); // Calculate the checksum for this file, so we'll know if its changed on the filesystem if( fetchChangedWorkspaceFiles ) { checksumHash.put(memberName, IntegrityCMMember.getMD5Checksum(targetFile)); } } else if( deltaFlag == 0 && fetchChangedWorkspaceFiles && checksum.length() > 0 ) { if( ! checksum.equals(IntegrityCMMember.getMD5Checksum(targetFile)) ) { Logger.debug("Attempting to restore changed workspace file: " + targetFile.getAbsolutePath() + " to revision " + memberRev); IntegrityCMMember.checkout(api, configPath, memberID, memberRev, targetFile, restoreTimestamp, lineTerminator); fetchCount++; } } else if( deltaFlag == 1 ) { Logger.debug("Attempting to get new file: " + targetFile.getAbsolutePath() + " at revision " + memberRev); IntegrityCMMember.checkout(api, configPath, memberID, memberRev, targetFile, restoreTimestamp, lineTerminator); addCount++; // Calculate the checksum for this file, so we'll know if its changed on the filesystem if( fetchChangedWorkspaceFiles ) { checksumHash.put(memberName, IntegrityCMMember.getMD5Checksum(targetFile)); } } else if( deltaFlag == 2 ) { Logger.debug("Attempting to update file: " + targetFile.getAbsolutePath() + " to revision " + memberRev); IntegrityCMMember.checkout(api, configPath, memberID, memberRev, targetFile, restoreTimestamp, lineTerminator); updateCount++; // Calculate the checksum for this file, so we'll know if its changed on the filesystem if( fetchChangedWorkspaceFiles ) { checksumHash.put(memberName, IntegrityCMMember.getMD5Checksum(targetFile)); } } else if( deltaFlag == 3 ) { Logger.debug("Attempting to drop file: " + targetFile.getAbsolutePath() + " was at revision " + memberRev); dropCount++; if( targetFile.exists() && !targetFile.delete() ) { listener.getLogger().println("Failed to clean up workspace file " + targetFile.getAbsolutePath() + "!"); return false; } } // Check to see if we need to release the APISession to clear some file handles if( openFileHandles % CHECKOUT_TRESHOLD == 0 ) { api.Terminate(); api = createAPISession(); } } // Lets advice the user that we've checked out all the members if( cleanCopy ) { listener.getLogger().println("Successfully checked out " + projectMembersList.size() + " files!"); } else { // Lets advice the user that we've performed the updates to the workspace listener.getLogger().println("Successfully updated workspace with " + (addCount+updateCount) + " updates and cleaned up " + dropCount + " files!"); if( fetchChangedWorkspaceFiles && fetchCount > 0 ) { listener.getLogger().println("Additionally, a total of " + fetchCount + " files were restored to their original repository state!"); } } } catch( APIException aex ) { Logger.error("API Exception caught..."); listener.getLogger().println("An API Exception was caught!"); ExceptionHandler eh = new ExceptionHandler(aex); Logger.error(eh.getMessage()); listener.getLogger().println(eh.getMessage()); Logger.debug(eh.getCommand() + " returned exit code " + eh.getExitCode()); listener.getLogger().println(eh.getCommand() + " returned exit code " + eh.getExitCode()); Logger.fatal(aex); return false; } catch( InterruptedException iex ) { Logger.error("Interrupted Exception caught..."); listener.getLogger().println("An Interrupted Exception was caught!"); Logger.error(iex.getMessage()); listener.getLogger().println(iex.getMessage()); listener.getLogger().println("Failed to clean up workspace (" + workspace + ") contents!"); return false; } finally { // Close out the API Session created on this slave. api.Terminate(); } //If we got here, everything is good on the checkout... return true; } }
true
true
public Boolean invoke(File workspaceFile, VirtualChannel channel) throws IOException { // Figure out where we should be checking out this project File checkOutDir = (null != alternateWorkspaceDir && alternateWorkspaceDir.length() > 0) ? new File(alternateWorkspaceDir) : workspaceFile; // Convert the file object to a hudson FilePath (helps us with workspace.deleteContents()) FilePath workspace = new FilePath(checkOutDir.isAbsolute() ? checkOutDir : new File(workspaceFile.getAbsolutePath() + IntegritySCM.FS + checkOutDir.getPath())); listener.getLogger().println("Checkout directory is " + workspace); // Create a fresh API Session as we may/will be executing from another server APISession api = createAPISession(); // Ensure we've successfully created an API Session if( null == api ) { listener.getLogger().println("Failed to establish an API connection to the Integrity Server!"); return false; } // If we got here, then APISession was created successfully! try { // Keep count of the open file handles generated on the server int openFileHandles = 0; if( cleanCopy ) { listener.getLogger().println("A clean copy is requested; deleting contents of " + workspace); Logger.debug("Deleting contents of workspace " + workspace); workspace.deleteContents(); listener.getLogger().println("Populating clean workspace..."); } // Create an empty folder structure first createFolderStructure(workspace); // Perform a synchronize of each file in the member list... for( Iterator<Hashtable<CM_PROJECT, Object>> it = projectMembersList.iterator(); it.hasNext(); ) { openFileHandles++; Hashtable<CM_PROJECT, Object> memberInfo = it.next(); short deltaFlag = (null == memberInfo.get(CM_PROJECT.DELTA) ? -1 : Short.valueOf(memberInfo.get(CM_PROJECT.DELTA).toString())); File targetFile = new File(workspace + memberInfo.get(CM_PROJECT.RELATIVE_FILE).toString()); String memberName = memberInfo.get(CM_PROJECT.NAME).toString(); String memberID = memberInfo.get(CM_PROJECT.MEMBER_ID).toString(); String memberRev = memberInfo.get(CM_PROJECT.REVISION).toString(); String configPath = memberInfo.get(CM_PROJECT.CONFIG_PATH).toString(); String checksum = (null == memberInfo.get(CM_PROJECT.CHECKSUM) ? "" : memberInfo.get(CM_PROJECT.CHECKSUM).toString()); if( cleanCopy || deltaFlag == -1 ) { Logger.debug("Attempting to checkout file: " + targetFile.getAbsolutePath() + " at revision " + memberRev); IntegrityCMMember.checkout(api, configPath, memberID, memberRev, targetFile, restoreTimestamp, lineTerminator); // Calculate the checksum for this file, so we'll know if its changed on the filesystem if( fetchChangedWorkspaceFiles ) { checksumHash.put(memberName, IntegrityCMMember.getMD5Checksum(targetFile)); } } else if( deltaFlag == 0 && fetchChangedWorkspaceFiles && checksum.length() > 0 ) { if( ! checksum.equals(IntegrityCMMember.getMD5Checksum(targetFile)) ) { Logger.debug("Attempting to restore changed workspace file: " + targetFile.getAbsolutePath() + " to revision " + memberRev); IntegrityCMMember.checkout(api, configPath, memberID, memberRev, targetFile, restoreTimestamp, lineTerminator); fetchCount++; } } else if( deltaFlag == 1 ) { Logger.debug("Attempting to get new file: " + targetFile.getAbsolutePath() + " at revision " + memberRev); IntegrityCMMember.checkout(api, configPath, memberID, memberRev, targetFile, restoreTimestamp, lineTerminator); addCount++; // Calculate the checksum for this file, so we'll know if its changed on the filesystem if( fetchChangedWorkspaceFiles ) { checksumHash.put(memberName, IntegrityCMMember.getMD5Checksum(targetFile)); } } else if( deltaFlag == 2 ) { Logger.debug("Attempting to update file: " + targetFile.getAbsolutePath() + " to revision " + memberRev); IntegrityCMMember.checkout(api, configPath, memberID, memberRev, targetFile, restoreTimestamp, lineTerminator); updateCount++; // Calculate the checksum for this file, so we'll know if its changed on the filesystem if( fetchChangedWorkspaceFiles ) { checksumHash.put(memberName, IntegrityCMMember.getMD5Checksum(targetFile)); } } else if( deltaFlag == 3 ) { Logger.debug("Attempting to drop file: " + targetFile.getAbsolutePath() + " was at revision " + memberRev); dropCount++; if( targetFile.exists() && !targetFile.delete() ) { listener.getLogger().println("Failed to clean up workspace file " + targetFile.getAbsolutePath() + "!"); return false; } } // Check to see if we need to release the APISession to clear some file handles if( openFileHandles % CHECKOUT_TRESHOLD == 0 ) { api.Terminate(); api = createAPISession(); } } // Lets advice the user that we've checked out all the members if( cleanCopy ) { listener.getLogger().println("Successfully checked out " + projectMembersList.size() + " files!"); } else { // Lets advice the user that we've performed the updates to the workspace listener.getLogger().println("Successfully updated workspace with " + (addCount+updateCount) + " updates and cleaned up " + dropCount + " files!"); if( fetchChangedWorkspaceFiles && fetchCount > 0 ) { listener.getLogger().println("Additionally, a total of " + fetchCount + " files were restored to their original repository state!"); } } } catch( APIException aex ) { Logger.error("API Exception caught..."); listener.getLogger().println("An API Exception was caught!"); ExceptionHandler eh = new ExceptionHandler(aex); Logger.error(eh.getMessage()); listener.getLogger().println(eh.getMessage()); Logger.debug(eh.getCommand() + " returned exit code " + eh.getExitCode()); listener.getLogger().println(eh.getCommand() + " returned exit code " + eh.getExitCode()); Logger.fatal(aex); return false; } catch( InterruptedException iex ) { Logger.error("Interrupted Exception caught..."); listener.getLogger().println("An Interrupted Exception was caught!"); Logger.error(iex.getMessage()); listener.getLogger().println(iex.getMessage()); listener.getLogger().println("Failed to clean up workspace (" + workspace + ") contents!"); return false; } finally { // Close out the API Session created on this slave. api.Terminate(); } //If we got here, everything is good on the checkout... return true; }
public Boolean invoke(File workspaceFile, VirtualChannel channel) throws IOException { // Figure out where we should be checking out this project File checkOutDir = (null != alternateWorkspaceDir && alternateWorkspaceDir.length() > 0) ? new File(alternateWorkspaceDir) : workspaceFile; // Convert the file object to a hudson FilePath (helps us with workspace.deleteContents()) FilePath workspace = new FilePath(checkOutDir.isAbsolute() ? checkOutDir : new File(workspaceFile.getAbsolutePath() + IntegritySCM.FS + checkOutDir.getPath())); listener.getLogger().println("Checkout directory is " + workspace); // Create a fresh API Session as we may/will be executing from another server APISession api = createAPISession(); // Ensure we've successfully created an API Session if( null == api ) { listener.getLogger().println("Failed to establish an API connection to the Integrity Server!"); return false; } // If we got here, then APISession was created successfully! try { // Keep count of the open file handles generated on the server int openFileHandles = 0; if( cleanCopy ) { listener.getLogger().println("A clean copy is requested; deleting contents of " + workspace); Logger.debug("Deleting contents of workspace " + workspace); workspace.deleteContents(); listener.getLogger().println("Populating clean workspace..."); } // Create an empty folder structure first createFolderStructure(workspace); // Perform a synchronize of each file in the member list... for( Iterator<Hashtable<CM_PROJECT, Object>> it = projectMembersList.iterator(); it.hasNext(); ) { openFileHandles++; Hashtable<CM_PROJECT, Object> memberInfo = it.next(); short deltaFlag = (null == memberInfo.get(CM_PROJECT.DELTA) ? -1 : Short.valueOf(memberInfo.get(CM_PROJECT.DELTA).toString())); File targetFile = new File(workspace + memberInfo.get(CM_PROJECT.RELATIVE_FILE).toString()); String memberName = memberInfo.get(CM_PROJECT.NAME).toString(); String memberID = memberInfo.get(CM_PROJECT.MEMBER_ID).toString(); String memberRev = memberInfo.get(CM_PROJECT.REVISION).toString(); String configPath = memberInfo.get(CM_PROJECT.CONFIG_PATH).toString(); String checksum = (null == memberInfo.get(CM_PROJECT.CHECKSUM) ? "" : memberInfo.get(CM_PROJECT.CHECKSUM).toString()); if( cleanCopy && deltaFlag != 3 ) { Logger.debug("Attempting to checkout file: " + targetFile.getAbsolutePath() + " at revision " + memberRev); IntegrityCMMember.checkout(api, configPath, memberID, memberRev, targetFile, restoreTimestamp, lineTerminator); // Calculate the checksum for this file, so we'll know if its changed on the filesystem if( fetchChangedWorkspaceFiles ) { checksumHash.put(memberName, IntegrityCMMember.getMD5Checksum(targetFile)); } } else if( deltaFlag == 0 && fetchChangedWorkspaceFiles && checksum.length() > 0 ) { if( ! checksum.equals(IntegrityCMMember.getMD5Checksum(targetFile)) ) { Logger.debug("Attempting to restore changed workspace file: " + targetFile.getAbsolutePath() + " to revision " + memberRev); IntegrityCMMember.checkout(api, configPath, memberID, memberRev, targetFile, restoreTimestamp, lineTerminator); fetchCount++; } } else if( deltaFlag == 1 ) { Logger.debug("Attempting to get new file: " + targetFile.getAbsolutePath() + " at revision " + memberRev); IntegrityCMMember.checkout(api, configPath, memberID, memberRev, targetFile, restoreTimestamp, lineTerminator); addCount++; // Calculate the checksum for this file, so we'll know if its changed on the filesystem if( fetchChangedWorkspaceFiles ) { checksumHash.put(memberName, IntegrityCMMember.getMD5Checksum(targetFile)); } } else if( deltaFlag == 2 ) { Logger.debug("Attempting to update file: " + targetFile.getAbsolutePath() + " to revision " + memberRev); IntegrityCMMember.checkout(api, configPath, memberID, memberRev, targetFile, restoreTimestamp, lineTerminator); updateCount++; // Calculate the checksum for this file, so we'll know if its changed on the filesystem if( fetchChangedWorkspaceFiles ) { checksumHash.put(memberName, IntegrityCMMember.getMD5Checksum(targetFile)); } } else if( deltaFlag == 3 ) { Logger.debug("Attempting to drop file: " + targetFile.getAbsolutePath() + " was at revision " + memberRev); dropCount++; if( targetFile.exists() && !targetFile.delete() ) { listener.getLogger().println("Failed to clean up workspace file " + targetFile.getAbsolutePath() + "!"); return false; } } // Check to see if we need to release the APISession to clear some file handles if( openFileHandles % CHECKOUT_TRESHOLD == 0 ) { api.Terminate(); api = createAPISession(); } } // Lets advice the user that we've checked out all the members if( cleanCopy ) { listener.getLogger().println("Successfully checked out " + projectMembersList.size() + " files!"); } else { // Lets advice the user that we've performed the updates to the workspace listener.getLogger().println("Successfully updated workspace with " + (addCount+updateCount) + " updates and cleaned up " + dropCount + " files!"); if( fetchChangedWorkspaceFiles && fetchCount > 0 ) { listener.getLogger().println("Additionally, a total of " + fetchCount + " files were restored to their original repository state!"); } } } catch( APIException aex ) { Logger.error("API Exception caught..."); listener.getLogger().println("An API Exception was caught!"); ExceptionHandler eh = new ExceptionHandler(aex); Logger.error(eh.getMessage()); listener.getLogger().println(eh.getMessage()); Logger.debug(eh.getCommand() + " returned exit code " + eh.getExitCode()); listener.getLogger().println(eh.getCommand() + " returned exit code " + eh.getExitCode()); Logger.fatal(aex); return false; } catch( InterruptedException iex ) { Logger.error("Interrupted Exception caught..."); listener.getLogger().println("An Interrupted Exception was caught!"); Logger.error(iex.getMessage()); listener.getLogger().println(iex.getMessage()); listener.getLogger().println("Failed to clean up workspace (" + workspace + ") contents!"); return false; } finally { // Close out the API Session created on this slave. api.Terminate(); } //If we got here, everything is good on the checkout... return true; }
diff --git a/src/org/apache/xerces/dom/DeferredAttrImpl.java b/src/org/apache/xerces/dom/DeferredAttrImpl.java index b9a03bf8..d7f8fb35 100644 --- a/src/org/apache/xerces/dom/DeferredAttrImpl.java +++ b/src/org/apache/xerces/dom/DeferredAttrImpl.java @@ -1,180 +1,180 @@ /* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.apache.org. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * WARNING: because java doesn't support multi-inheritance some code is * duplicated. If you're changing this file you probably want to change * DeferredAttrNSImpl.java at the same time. */ package org.apache.xerces.dom; /** * Attribute represents an XML-style attribute of an * Element. Typically, the allowable values are controlled by its * declaration in the Document Type Definition (DTD) governing this * kind of document. * <P> * If the attribute has not been explicitly assigned a value, but has * been declared in the DTD, it will exist and have that default. Only * if neither the document nor the DTD specifies a value will the * Attribute really be considered absent and have no value; in that * case, querying the attribute will return null. * <P> * Attributes may have multiple children that contain their data. (XML * allows attributes to contain entity references, and tokenized * attribute types such as NMTOKENS may have a child for each token.) * For convenience, the Attribute object's getValue() method returns * the string version of the attribute's value. * <P> * Attributes are not children of the Elements they belong to, in the * usual sense, and have no valid Parent reference. However, the spec * says they _do_ belong to a specific Element, and an INUSE exception * is to be thrown if the user attempts to explicitly share them * between elements. * <P> * Note that Elements do not permit attributes to appear to be shared * (see the INUSE exception), so this object's mutability is * officially not an issue. * <P> * DeferredAttrImpl inherits from AttrImpl which does not support * Namespaces. DeferredAttrNSImpl, which inherits from AttrNSImpl, does. * @see DeferredAttrNSImpl * * * @author Andy Clark, IBM * @author Arnaud Le Hors, IBM * @version $Id$ * @since PR-DOM-Level-1-19980818. */ public final class DeferredAttrImpl extends AttrImpl implements DeferredNode { // // Constants // /** Serialization version. */ static final long serialVersionUID = 6903232312469148636L; // // Data // /** Node index. */ protected transient int fNodeIndex; // // Constructors // /** * This is the deferred constructor. Only the fNodeIndex is given here. * All other data, can be requested from the ownerDocument via the index. */ DeferredAttrImpl(DeferredDocumentImpl ownerDocument, int nodeIndex) { super(ownerDocument, null); fNodeIndex = nodeIndex; needsSyncData(true); needsSyncChildren(true); } // <init>(DeferredDocumentImpl,int) // // DeferredNode methods // /** Returns the node index. */ public int getNodeIndex() { return fNodeIndex; } // // Protected methods // /** Synchronizes the data (name and value) for fast nodes. */ protected void synchronizeData() { // no need to sync in the future needsSyncData(false); // fluff data DeferredDocumentImpl ownerDocument = (DeferredDocumentImpl) ownerDocument(); name = ownerDocument.getNodeName(fNodeIndex); int extra = ownerDocument.getNodeExtra(fNodeIndex); - isSpecified((extra & SPECIFIED) == 1); - isIdAttribute((extra & IDATTRIBUTE) == 1); + isSpecified((extra & SPECIFIED) != 0); + isIdAttribute((extra & IDATTRIBUTE) != 0); } // synchronizeData() /** * Synchronizes the node's children with the internal structure. * Fluffing the children at once solves a lot of work to keep * the two structures in sync. The problem gets worse when * editing the tree -- this makes it a lot easier. */ protected void synchronizeChildren() { DeferredDocumentImpl ownerDocument = (DeferredDocumentImpl) ownerDocument(); ownerDocument.synchronizeChildren(this, fNodeIndex); } // synchronizeChildren() } // class DeferredAttrImpl
true
true
protected void synchronizeData() { // no need to sync in the future needsSyncData(false); // fluff data DeferredDocumentImpl ownerDocument = (DeferredDocumentImpl) ownerDocument(); name = ownerDocument.getNodeName(fNodeIndex); int extra = ownerDocument.getNodeExtra(fNodeIndex); isSpecified((extra & SPECIFIED) == 1); isIdAttribute((extra & IDATTRIBUTE) == 1); } // synchronizeData()
protected void synchronizeData() { // no need to sync in the future needsSyncData(false); // fluff data DeferredDocumentImpl ownerDocument = (DeferredDocumentImpl) ownerDocument(); name = ownerDocument.getNodeName(fNodeIndex); int extra = ownerDocument.getNodeExtra(fNodeIndex); isSpecified((extra & SPECIFIED) != 0); isIdAttribute((extra & IDATTRIBUTE) != 0); } // synchronizeData()
diff --git a/main/src/cgeo/geocaching/cgData.java b/main/src/cgeo/geocaching/cgData.java index ff2653bae..5220f203e 100644 --- a/main/src/cgeo/geocaching/cgData.java +++ b/main/src/cgeo/geocaching/cgData.java @@ -1,2971 +1,2971 @@ package cgeo.geocaching; import cgeo.geocaching.enumerations.CacheSize; import cgeo.geocaching.enumerations.CacheType; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.enumerations.LoadFlags.LoadFlag; import cgeo.geocaching.enumerations.LoadFlags.RemoveFlag; import cgeo.geocaching.enumerations.LoadFlags.SaveFlag; import cgeo.geocaching.enumerations.LogType; import cgeo.geocaching.enumerations.WaypointType; import cgeo.geocaching.files.LocalStorage; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.geopoint.Viewport; import cgeo.geocaching.utils.Log; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import android.content.ContentValues; import android.content.Context; import android.content.ContextWrapper; import android.content.res.Resources; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.DatabaseUtils.InsertHelper; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteDoneException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteStatement; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Pattern; public class cgData { public enum StorageLocation { HEAP, CACHE, DATABASE, } /** The list of fields needed for mapping. */ private static final String[] CACHE_COLUMNS = new String[] { "_id", "updated", "reason", "detailed", "detailedupdate", "visiteddate", "geocode", "cacheid", "guid", "type", "name", "own", "owner", "owner_real", "hidden", "hint", "size", "difficulty", "distance", "direction", "terrain", "latlon", "location", "latitude", "longitude", "elevation", "shortdesc", "favourite_cnt", "rating", "votes", "myvote", "disabled", "archived", "members", "found", "favourite", "inventorycoins", "inventorytags", "inventoryunknown", "onWatchlist", "personal_note", "reliable_latlon", "coordsChanged", "finalDefined" // reason is replaced by listId in cgCache }; /** The list of fields needed for mapping. */ private static final String[] WAYPOINT_COLUMNS = new String[] { "_id", "geocode", "updated", "type", "prefix", "lookup", "name", "latlon", "latitude", "longitude", "note", "own" }; /** Number of days (as ms) after temporarily saved caches are deleted */ private final static long DAYS_AFTER_CACHE_IS_DELETED = 3 * 24 * 60 * 60 * 1000; /** * holds the column indexes of the cache table to avoid lookups */ private static int[] cacheColumnIndex; private CacheCache cacheCache = new CacheCache(); private SQLiteDatabase database = null; private static final int dbVersion = 64; public static final int customListIdOffset = 10; private static final String dbName = "data"; private static final String dbTableCaches = "cg_caches"; private static final String dbTableLists = "cg_lists"; private static final String dbTableAttributes = "cg_attributes"; private static final String dbTableWaypoints = "cg_waypoints"; private static final String dbTableSpoilers = "cg_spoilers"; private static final String dbTableLogs = "cg_logs"; private static final String dbTableLogCount = "cg_logCount"; private static final String dbTableLogImages = "cg_logImages"; private static final String dbTableLogsOffline = "cg_logs_offline"; private static final String dbTableTrackables = "cg_trackables"; private static final String dbTableSearchDestionationHistory = "cg_search_destination_history"; private static final String dbCreateCaches = "" + "create table " + dbTableCaches + " (" + "_id integer primary key autoincrement, " + "updated long not null, " + "detailed integer not null default 0, " + "detailedupdate long, " + "visiteddate long, " + "geocode text unique not null, " + "reason integer not null default 0, " // cached, favourite... + "cacheid text, " + "guid text, " + "type text, " + "name text, " + "own integer not null default 0, " + "owner text, " + "owner_real text, " + "hidden long, " + "hint text, " + "size text, " + "difficulty float, " + "terrain float, " + "latlon text, " + "location text, " + "direction double, " + "distance double, " + "latitude double, " + "longitude double, " + "reliable_latlon integer, " + "elevation double, " + "personal_note text, " + "shortdesc text, " + "description text, " + "favourite_cnt integer, " + "rating float, " + "votes integer, " + "myvote float, " + "disabled integer not null default 0, " + "archived integer not null default 0, " + "members integer not null default 0, " + "found integer not null default 0, " + "favourite integer not null default 0, " + "inventorycoins integer default 0, " + "inventorytags integer default 0, " + "inventoryunknown integer default 0, " + "onWatchlist integer default 0, " + "coordsChanged integer default 0, " + "finalDefined integer default 0" + "); "; private static final String dbCreateLists = "" + "create table " + dbTableLists + " (" + "_id integer primary key autoincrement, " + "title text not null, " + "updated long not null, " + "latitude double, " + "longitude double " + "); "; private static final String dbCreateAttributes = "" + "create table " + dbTableAttributes + " (" + "_id integer primary key autoincrement, " + "geocode text not null, " + "updated long not null, " // date of save + "attribute text " + "); "; private final static int ATTRIBUTES_GEOCODE = 2; private final static int ATTRIBUTES_UPDATED = 3; private final static int ATTRIBUTES_ATTRIBUTE = 4; private static final String dbCreateWaypoints = "" + "create table " + dbTableWaypoints + " (" + "_id integer primary key autoincrement, " + "geocode text not null, " + "updated long not null, " // date of save + "type text not null default 'waypoint', " + "prefix text, " + "lookup text, " + "name text, " + "latlon text, " + "latitude double, " + "longitude double, " + "note text, " + "own integer default 0" + "); "; private static final String dbCreateSpoilers = "" + "create table " + dbTableSpoilers + " (" + "_id integer primary key autoincrement, " + "geocode text not null, " + "updated long not null, " // date of save + "url text, " + "title text, " + "description text " + "); "; private static final String dbCreateLogs = "" + "create table " + dbTableLogs + " (" + "_id integer primary key autoincrement, " + "geocode text not null, " + "updated long not null, " // date of save + "type integer not null default 4, " + "author text, " + "log text, " + "date long, " + "found integer not null default 0, " + "friend integer " + "); "; private final static int LOGS_GEOCODE = 2; private final static int LOGS_UPDATED = 3; private final static int LOGS_TYPE = 4; private final static int LOGS_AUTHOR = 5; private final static int LOGS_LOG = 6; private final static int LOGS_DATE = 7; private final static int LOGS_FOUND = 8; private final static int LOGS_FRIEND = 9; private static final String dbCreateLogCount = "" + "create table " + dbTableLogCount + " (" + "_id integer primary key autoincrement, " + "geocode text not null, " + "updated long not null, " // date of save + "type integer not null default 4, " + "count integer not null default 0 " + "); "; private static final String dbCreateLogImages = "" + "create table " + dbTableLogImages + " (" + "_id integer primary key autoincrement, " + "log_id integer not null, " + "title text not null, " + "url text not null" + "); "; private static final String dbCreateLogsOffline = "" + "create table " + dbTableLogsOffline + " (" + "_id integer primary key autoincrement, " + "geocode text not null, " + "updated long not null, " // date of save + "type integer not null default 4, " + "log text, " + "date long " + "); "; private static final String dbCreateTrackables = "" + "create table " + dbTableTrackables + " (" + "_id integer primary key autoincrement, " + "updated long not null, " // date of save + "tbcode text not null, " + "guid text, " + "title text, " + "owner text, " + "released long, " + "goal text, " + "description text, " + "geocode text " + "); "; private static final String dbCreateSearchDestinationHistory = "" + "create table " + dbTableSearchDestionationHistory + " (" + "_id integer primary key autoincrement, " + "date long not null, " + "latitude double, " + "longitude double " + "); "; private HashMap<String, SQLiteStatement> statements = new HashMap<String, SQLiteStatement>(); private static boolean newlyCreatedDatabase = false; public synchronized void init() { if (database != null) { return; } try { final DbHelper dbHelper = new DbHelper(new DBContext(cgeoapplication.getInstance())); database = dbHelper.getWritableDatabase(); } catch (Exception e) { Log.e("cgData.init: unable to open database for R/W", e); } } public void closeDb() { if (database == null) { return; } cacheCache.removeAllFromCache(); clearPreparedStatements(); database.close(); database = null; } private void clearPreparedStatements() { for (SQLiteStatement statement : statements.values()) { statement.close(); } statements.clear(); } private static File backupFile() { return new File(LocalStorage.getStorage(), "cgeo.sqlite"); } public String backupDatabase() { if (!LocalStorage.isExternalStorageAvailable()) { Log.w("Database wasn't backed up: no external memory"); return null; } final File target = backupFile(); closeDb(); final boolean backupDone = LocalStorage.copy(databasePath(), target); init(); if (!backupDone) { Log.e("Database could not be copied to " + target); return null; } Log.i("Database was copied to " + target); return target.getPath(); } public boolean moveDatabase() { if (!LocalStorage.isExternalStorageAvailable()) { Log.w("Database was not moved: external memory not available"); return false; } closeDb(); final File source = databasePath(); final File target = databaseAlternatePath(); if (!LocalStorage.copy(source, target)) { Log.e("Database could not be moved to " + target); init(); return false; } source.delete(); Settings.setDbOnSDCard(!Settings.isDbOnSDCard()); Log.i("Database was moved to " + target); init(); return true; } private static File databasePath(final boolean internal) { return new File(internal ? LocalStorage.getInternalDbDirectory() : LocalStorage.getExternalDbDirectory(), dbName); } private static File databasePath() { return databasePath(!Settings.isDbOnSDCard()); } private static File databaseAlternatePath() { return databasePath(Settings.isDbOnSDCard()); } public static File isRestoreFile() { final File fileSourceFile = backupFile(); return fileSourceFile.exists() ? fileSourceFile : null; } public boolean restoreDatabase() { if (!LocalStorage.isExternalStorageAvailable()) { Log.w("Database wasn't restored: no external memory"); return false; } final File sourceFile = backupFile(); closeDb(); final boolean restoreDone = LocalStorage.copy(sourceFile, databasePath()); init(); if (restoreDone) { Log.i("Database succesfully restored from " + sourceFile.getPath()); } else { Log.e("Could not restore database from " + sourceFile.getPath()); } return restoreDone; } private static class DBContext extends ContextWrapper { public DBContext(Context base) { super(base); } /** * We override the default open/create as it doesn't work on OS 1.6 and * causes issues on other devices too. */ @Override public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory) { final File file = new File(name); file.getParentFile().mkdirs(); return SQLiteDatabase.openOrCreateDatabase(file, factory); } } private static class DbHelper extends SQLiteOpenHelper { DbHelper(Context context) { super(context, databasePath().getPath(), null, dbVersion); } @Override public void onCreate(SQLiteDatabase db) { newlyCreatedDatabase = true; db.execSQL(dbCreateCaches); db.execSQL(dbCreateLists); db.execSQL(dbCreateAttributes); db.execSQL(dbCreateWaypoints); db.execSQL(dbCreateSpoilers); db.execSQL(dbCreateLogs); db.execSQL(dbCreateLogCount); db.execSQL(dbCreateLogImages); db.execSQL(dbCreateLogsOffline); db.execSQL(dbCreateTrackables); db.execSQL(dbCreateSearchDestinationHistory); createIndices(db); } static private void createIndices(final SQLiteDatabase db) { db.execSQL("create index if not exists in_caches_geo on " + dbTableCaches + " (geocode)"); db.execSQL("create index if not exists in_caches_guid on " + dbTableCaches + " (guid)"); db.execSQL("create index if not exists in_caches_lat on " + dbTableCaches + " (latitude)"); db.execSQL("create index if not exists in_caches_lon on " + dbTableCaches + " (longitude)"); db.execSQL("create index if not exists in_caches_reason on " + dbTableCaches + " (reason)"); db.execSQL("create index if not exists in_caches_detailed on " + dbTableCaches + " (detailed)"); db.execSQL("create index if not exists in_caches_type on " + dbTableCaches + " (type)"); db.execSQL("create index if not exists in_caches_visit_detail on " + dbTableCaches + " (visiteddate, detailedupdate)"); db.execSQL("create index if not exists in_attr_geo on " + dbTableAttributes + " (geocode)"); db.execSQL("create index if not exists in_wpts_geo on " + dbTableWaypoints + " (geocode)"); db.execSQL("create index if not exists in_wpts_geo_type on " + dbTableWaypoints + " (geocode, type)"); db.execSQL("create index if not exists in_spoil_geo on " + dbTableSpoilers + " (geocode)"); db.execSQL("create index if not exists in_logs_geo on " + dbTableLogs + " (geocode)"); db.execSQL("create index if not exists in_logcount_geo on " + dbTableLogCount + " (geocode)"); db.execSQL("create index if not exists in_logsoff_geo on " + dbTableLogsOffline + " (geocode)"); db.execSQL("create index if not exists in_trck_geo on " + dbTableTrackables + " (geocode)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.i("Upgrade database from ver. " + oldVersion + " to ver. " + newVersion + ": start"); try { if (db.isReadOnly()) { return; } db.beginTransaction(); if (oldVersion <= 0) { // new table dropDatabase(db); onCreate(db); Log.i("Database structure created."); } if (oldVersion > 0) { db.execSQL("delete from " + dbTableCaches + " where reason = 0"); if (oldVersion < 52) { // upgrade to 52 try { db.execSQL(dbCreateSearchDestinationHistory); Log.i("Added table " + dbTableSearchDestionationHistory + "."); } catch (Exception e) { Log.e("Failed to upgrade to ver. 52", e); } } if (oldVersion < 53) { // upgrade to 53 try { db.execSQL("alter table " + dbTableCaches + " add column onWatchlist integer"); Log.i("Column onWatchlist added to " + dbTableCaches + "."); } catch (Exception e) { Log.e("Failed to upgrade to ver. 53", e); } } if (oldVersion < 54) { // update to 54 try { db.execSQL(dbCreateLogImages); } catch (Exception e) { Log.e("Failed to upgrade to ver. 54: " + e.toString()); } } if (oldVersion < 55) { // update to 55 try { db.execSQL("alter table " + dbTableCaches + " add column personal_note text"); } catch (Exception e) { Log.e("Failed to upgrade to ver. 55: " + e.toString()); } } // make all internal attribute names lowercase // @see issue #299 if (oldVersion < 56) { // update to 56 try { db.execSQL("update " + dbTableAttributes + " set attribute = " + "lower(attribute) where attribute like \"%_yes\" " + "or attribute like \"%_no\""); } catch (Exception e) { Log.e("Failed to upgrade to ver. 56: " + e.toString()); } } // Create missing indices. See issue #435 if (oldVersion < 57) { // update to 57 try { db.execSQL("drop index in_a"); db.execSQL("drop index in_b"); db.execSQL("drop index in_c"); db.execSQL("drop index in_d"); db.execSQL("drop index in_e"); db.execSQL("drop index in_f"); createIndices(db); } catch (Exception e) { Log.e("Failed to upgrade to ver. 57: " + e.toString()); } } if (oldVersion < 58) { // upgrade to 58 try { db.beginTransaction(); final String dbTableCachesTemp = dbTableCaches + "_temp"; final String dbCreateCachesTemp = "" + "create table " + dbTableCachesTemp + " (" + "_id integer primary key autoincrement, " + "updated long not null, " + "detailed integer not null default 0, " + "detailedupdate long, " + "visiteddate long, " + "geocode text unique not null, " + "reason integer not null default 0, " + "cacheid text, " + "guid text, " + "type text, " + "name text, " + "own integer not null default 0, " + "owner text, " + "owner_real text, " + "hidden long, " + "hint text, " + "size text, " + "difficulty float, " + "terrain float, " + "latlon text, " + "location text, " + "direction double, " + "distance double, " + "latitude double, " + "longitude double, " + "reliable_latlon integer, " + "elevation double, " + "personal_note text, " + "shortdesc text, " + "description text, " + "favourite_cnt integer, " + "rating float, " + "votes integer, " + "myvote float, " + "disabled integer not null default 0, " + "archived integer not null default 0, " + "members integer not null default 0, " + "found integer not null default 0, " + "favourite integer not null default 0, " + "inventorycoins integer default 0, " + "inventorytags integer default 0, " + "inventoryunknown integer default 0, " + "onWatchlist integer default 0 " + "); "; db.execSQL(dbCreateCachesTemp); db.execSQL("insert into " + dbTableCachesTemp + " select _id,updated,detailed,detailedupdate,visiteddate,geocode,reason,cacheid,guid,type,name,own,owner,owner_real," + - "hidden,hint,size,difficulty,terrain,latlon,location,direction,distance,latitude,longitude,reliable_latlon,elevation," + + "hidden,hint,size,difficulty,terrain,latlon,location,direction,distance,latitude,longitude, 0,elevation," + "personal_note,shortdesc,description,favourite_cnt,rating,votes,myvote,disabled,archived,members,found,favourite,inventorycoins," + "inventorytags,inventoryunknown,onWatchlist from " + dbTableCaches); db.execSQL("drop table " + dbTableCaches); db.execSQL("alter table " + dbTableCachesTemp + " rename to " + dbTableCaches); final String dbTableWaypointsTemp = dbTableWaypoints + "_temp"; final String dbCreateWaypointsTemp = "" + "create table " + dbTableWaypointsTemp + " (" + "_id integer primary key autoincrement, " + "geocode text not null, " + "updated long not null, " // date of save + "type text not null default 'waypoint', " + "prefix text, " + "lookup text, " + "name text, " + "latlon text, " + "latitude double, " + "longitude double, " + "note text " + "); "; db.execSQL(dbCreateWaypointsTemp); db.execSQL("insert into " + dbTableWaypointsTemp + " select _id, geocode, updated, type, prefix, lookup, name, latlon, latitude, longitude, note from " + dbTableWaypoints); db.execSQL("drop table " + dbTableWaypoints); db.execSQL("alter table " + dbTableWaypointsTemp + " rename to " + dbTableWaypoints); createIndices(db); db.setTransactionSuccessful(); Log.i("Removed latitude_string and longitude_string columns"); } catch (Exception e) { Log.e("Failed to upgrade to ver. 58", e); } finally { db.endTransaction(); } } if (oldVersion < 59) { try { // Add new indices and remove obsolete cache files createIndices(db); removeObsoleteCacheDirectories(db); } catch (Exception e) { Log.e("Failed to upgrade to ver. 59", e); } } if (oldVersion < 60) { try { removeSecEmptyDirs(); } catch (Exception e) { Log.e("Failed to upgrade to ver. 60", e); } } if (oldVersion < 61) { try { db.execSQL("alter table " + dbTableLogs + " add column friend integer"); db.execSQL("alter table " + dbTableCaches + " add column coordsChanged integer default 0"); } catch (Exception e) { Log.e("Failed to upgrade to ver. 61: " + e.toString()); } } // Introduces finalDefined on caches and own on waypoints if (oldVersion < 62) { try { db.execSQL("alter table " + dbTableCaches + " add column finalDefined integer default 0"); db.execSQL("alter table " + dbTableWaypoints + " add column own integer default 0"); db.execSQL("update " + dbTableWaypoints + " set own = 1 where type = 'own'"); } catch (Exception e) { Log.e("Failed to upgrade to ver. 62: " + e.toString()); } } if (oldVersion < 63) { try { removeDoubleUnderscoreMapFiles(); } catch (Exception e) { Log.e("Failed to upgrade to ver. 63: " + e.toString()); } } if (oldVersion < 64) { try { // No cache should ever be stored into the ALL_CACHES list. Here we use hardcoded list ids // rather than symbolic ones because the fix must be applied with the values at the time // of the problem. The problem was introduced in release 2012.06.01. db.execSQL("update " + dbTableCaches + " set reason=1 where reason=2"); } catch (Exception e) { Log.e("Failed to upgrade to ver. 64", e); } } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } Log.i("Upgrade database from ver. " + oldVersion + " to ver. " + newVersion + ": completed"); } /** * Method to remove static map files with double underscore due to issue#1670 * introduced with release on 2012-05-24. */ private static void removeDoubleUnderscoreMapFiles() { File[] geocodeDirs = LocalStorage.getStorage().listFiles(); final FilenameFilter filter = new FilenameFilter() { @Override public boolean accept(File dir, String filename) { return (filename.startsWith("map_") && filename.contains("__")); } }; for (File dir : geocodeDirs) { File[] wrongFiles = dir.listFiles(filter); for (File wrongFile : wrongFiles) { wrongFile.delete(); } } } } /** * Remove obsolete cache directories in c:geo private storage. * * @param db * the read-write database to use */ private static void removeObsoleteCacheDirectories(final SQLiteDatabase db) { final Pattern oldFilePattern = Pattern.compile("^[GC|TB|O][A-Z0-9]{4,7}$"); final SQLiteStatement select = db.compileStatement("select count(*) from " + dbTableCaches + " where geocode = ?"); final File[] files = LocalStorage.getStorage().listFiles(); final ArrayList<File> toRemove = new ArrayList<File>(files.length); for (final File file : files) { if (file.isDirectory()) { final String geocode = file.getName(); if (oldFilePattern.matcher(geocode).find()) { select.bindString(1, geocode); if (select.simpleQueryForLong() == 0) { toRemove.add(file); } } } } // Use a background thread for the real removal to avoid keeping the database locked // if we are called from within a transaction. new Thread(new Runnable() { @Override public void run() { for (final File dir : toRemove) { Log.i("Removing obsolete cache directory for " + dir.getName()); LocalStorage.deleteDirectory(dir); } } }).start(); } /* * Remove empty directories created in the secondary storage area. */ private static void removeSecEmptyDirs() { for (final File file : LocalStorage.getStorageSec().listFiles()) { if (file.isDirectory()) { // This will silently fail if the directory is not empty. file.delete(); } } } private static void dropDatabase(SQLiteDatabase db) { db.execSQL("drop table if exists " + dbTableCaches); db.execSQL("drop table if exists " + dbTableAttributes); db.execSQL("drop table if exists " + dbTableWaypoints); db.execSQL("drop table if exists " + dbTableSpoilers); db.execSQL("drop table if exists " + dbTableLogs); db.execSQL("drop table if exists " + dbTableLogCount); db.execSQL("drop table if exists " + dbTableLogsOffline); db.execSQL("drop table if exists " + dbTableTrackables); } public String[] allDetailedThere() { init(); Cursor cursor = null; List<String> list = new ArrayList<String>(); try { long timestamp = System.currentTimeMillis() - DAYS_AFTER_CACHE_IS_DELETED; cursor = database.query( dbTableCaches, new String[]{"geocode"}, "(detailed = 1 and detailedupdate > ?) or reason > 0", new String[]{Long.toString(timestamp)}, null, null, "detailedupdate desc", "100"); if (cursor != null) { int index; if (cursor.getCount() > 0) { cursor.moveToFirst(); index = cursor.getColumnIndex("geocode"); do { list.add(cursor.getString(index)); } while (cursor.moveToNext()); } else { cursor.close(); return null; } } } catch (Exception e) { Log.e("cgData.allDetailedThere: " + e.toString()); } if (cursor != null) { cursor.close(); } return list.toArray(new String[list.size()]); } public boolean isThere(String geocode, String guid, boolean detailed, boolean checkTime) { init(); Cursor cursor = null; int cnt = 0; long dataUpdated = 0; long dataDetailedUpdate = 0; int dataDetailed = 0; try { if (StringUtils.isNotBlank(geocode)) { cursor = database.query( dbTableCaches, new String[]{"detailed", "detailedupdate", "updated"}, "geocode = ?", new String[]{geocode}, null, null, null, "1"); } else if (StringUtils.isNotBlank(guid)) { cursor = database.query( dbTableCaches, new String[]{"detailed", "detailedupdate", "updated"}, "guid = ?", new String[]{guid}, null, null, null, "1"); } else { return false; } if (cursor != null) { int index; cnt = cursor.getCount(); if (cnt > 0) { cursor.moveToFirst(); index = cursor.getColumnIndex("updated"); dataUpdated = cursor.getLong(index); index = cursor.getColumnIndex("detailedupdate"); dataDetailedUpdate = cursor.getLong(index); index = cursor.getColumnIndex("detailed"); dataDetailed = cursor.getInt(index); } } } catch (Exception e) { Log.e("cgData.isThere: " + e.toString()); } if (cursor != null) { cursor.close(); } if (cnt > 0) { if (detailed && dataDetailed == 0) { // we want details, but these are not stored return false; } if (checkTime && detailed && dataDetailedUpdate < (System.currentTimeMillis() - DAYS_AFTER_CACHE_IS_DELETED)) { // we want to check time for detailed cache, but data are older than 3 hours return false; } if (checkTime && !detailed && dataUpdated < (System.currentTimeMillis() - DAYS_AFTER_CACHE_IS_DELETED)) { // we want to check time for short cache, but data are older than 3 hours return false; } // we have some cache return true; } // we have no such cache stored in cache return false; } /** is cache stored in one of the lists (not only temporary) */ public boolean isOffline(String geocode, String guid) { if (StringUtils.isBlank(geocode) && StringUtils.isBlank(guid)) { return false; } init(); try { final SQLiteStatement listId; final String value; if (StringUtils.isNotBlank(geocode)) { listId = getStatementListIdFromGeocode(); value = geocode; } else { listId = getStatementListIdFromGuid(); value = guid; } synchronized (listId) { listId.bindString(1, value); return listId.simpleQueryForLong() != StoredList.TEMPORARY_LIST_ID; } } catch (SQLiteDoneException e) { // Do nothing, it only means we have no information on the cache } catch (Exception e) { Log.e("cgData.isOffline", e); } return false; } public String getGeocodeForGuid(String guid) { if (StringUtils.isBlank(guid)) { return null; } init(); try { final SQLiteStatement description = getStatementGeocode(); synchronized (description) { description.bindString(1, guid); return description.simpleQueryForString(); } } catch (SQLiteDoneException e) { // Do nothing, it only means we have no information on the cache } catch (Exception e) { Log.e("cgData.getGeocodeForGuid", e); } return null; } public String getCacheidForGeocode(String geocode) { if (StringUtils.isBlank(geocode)) { return null; } init(); try { final SQLiteStatement description = getStatementCacheId(); synchronized (description) { description.bindString(1, geocode); return description.simpleQueryForString(); } } catch (SQLiteDoneException e) { // Do nothing, it only means we have no information on the cache } catch (Exception e) { Log.e("cgData.getCacheidForGeocode", e); } return null; } /** * Save/store a cache to the CacheCache * * @param cache * the Cache to save in the CacheCache/DB * @param saveFlags * * @return true = cache saved successfully to the CacheCache/DB */ public boolean saveCache(cgCache cache, EnumSet<LoadFlags.SaveFlag> saveFlags) { if (cache == null) { throw new IllegalArgumentException("cache must not be null"); } // merge always with data already stored in the CacheCache or DB if (saveFlags.contains(SaveFlag.SAVE_CACHE)) { cache.gatherMissingFrom(cacheCache.getCacheFromCache(cache.getGeocode())); cacheCache.putCacheInCache(cache); } if (!saveFlags.contains(SaveFlag.SAVE_DB)) { return true; } boolean updateRequired = !cache.gatherMissingFrom(loadCache(cache.getGeocode(), LoadFlags.LOAD_ALL_DB_ONLY)); // only save a cache to the database if // - the cache is detailed // - there are changes // - the cache is only stored in the CacheCache so far if ((!updateRequired || !cache.isDetailed()) && cache.getStorageLocation().contains(StorageLocation.DATABASE)) { return false; } cache.addStorageLocation(StorageLocation.DATABASE); cacheCache.putCacheInCache(cache); Log.d("Saving " + cache.toString() + " (" + cache.getListId() + ") to DB"); ContentValues values = new ContentValues(); if (cache.getUpdated() == 0) { values.put("updated", System.currentTimeMillis()); } else { values.put("updated", cache.getUpdated()); } values.put("reason", cache.getListId()); values.put("detailed", cache.isDetailed() ? 1 : 0); values.put("detailedupdate", cache.getDetailedUpdate()); values.put("visiteddate", cache.getVisitedDate()); values.put("geocode", cache.getGeocode()); values.put("cacheid", cache.getCacheId()); values.put("guid", cache.getGuid()); values.put("type", cache.getType().id); values.put("name", cache.getName()); values.put("own", cache.isOwn() ? 1 : 0); values.put("owner", cache.getOwnerDisplayName()); values.put("owner_real", cache.getOwnerUserId()); if (cache.getHiddenDate() == null) { values.put("hidden", 0); } else { values.put("hidden", cache.getHiddenDate().getTime()); } values.put("hint", cache.getHint()); values.put("size", cache.getSize() == null ? "" : cache.getSize().id); values.put("difficulty", cache.getDifficulty()); values.put("terrain", cache.getTerrain()); values.put("latlon", cache.getLatlon()); values.put("location", cache.getLocation()); values.put("distance", cache.getDistance()); values.put("direction", cache.getDirection()); putCoords(values, cache.getCoords()); values.put("reliable_latlon", cache.isReliableLatLon() ? 1 : 0); values.put("elevation", cache.getElevation()); values.put("shortdesc", cache.getShortdesc()); values.put("personal_note", cache.getPersonalNote()); values.put("description", cache.getDescription()); values.put("favourite_cnt", cache.getFavoritePoints()); values.put("rating", cache.getRating()); values.put("votes", cache.getVotes()); values.put("myvote", cache.getMyVote()); values.put("disabled", cache.isDisabled() ? 1 : 0); values.put("archived", cache.isArchived() ? 1 : 0); values.put("members", cache.isPremiumMembersOnly() ? 1 : 0); values.put("found", cache.isFound() ? 1 : 0); values.put("favourite", cache.isFavorite() ? 1 : 0); values.put("inventoryunknown", cache.getInventoryItems()); values.put("onWatchlist", cache.isOnWatchlist() ? 1 : 0); values.put("coordsChanged", cache.hasUserModifiedCoords() ? 1 : 0); values.put("finalDefined", cache.hasFinalDefined() ? 1 : 0); boolean result = false; init(); //try to update record else insert fresh.. database.beginTransaction(); try { saveAttributesWithoutTransaction(cache); saveOriginalWaypointsWithoutTransaction(cache); saveSpoilersWithoutTransaction(cache); saveLogsWithoutTransaction(cache.getGeocode(), cache.getLogs()); saveLogCountsWithoutTransaction(cache); saveInventoryWithoutTransaction(cache.getGeocode(), cache.getInventory()); int rows = database.update(dbTableCaches, values, "geocode = ?", new String[] { cache.getGeocode() }); if (rows == 0) { // cache is not in the DB, insert it /* long id = */ database.insert(dbTableCaches, null, values); } database.setTransactionSuccessful(); result = true; } catch (Exception e) { // nothing } finally { database.endTransaction(); } return result; } private void saveAttributesWithoutTransaction(final cgCache cache) { String geocode = cache.getGeocode(); database.delete(dbTableAttributes, "geocode = ?", new String[]{geocode}); final List<String> attributes = cache.getAttributes(); if (CollectionUtils.isNotEmpty(attributes)) { InsertHelper helper = new InsertHelper(database, dbTableAttributes); long timeStamp = System.currentTimeMillis(); for (String attribute : attributes) { helper.prepareForInsert(); helper.bind(ATTRIBUTES_GEOCODE, geocode); helper.bind(ATTRIBUTES_UPDATED, timeStamp); helper.bind(ATTRIBUTES_ATTRIBUTE, attribute); helper.execute(); } helper.close(); } } /** * Persists the given <code>destination</code> into the database. * * @param destination * a destination to save */ public void saveSearchedDestination(final Destination destination) { init(); database.beginTransaction(); try { ContentValues values = new ContentValues(); values.put("date", destination.getDate()); putCoords(values, destination.getCoords()); database.insert(dbTableSearchDestionationHistory, null, values); database.setTransactionSuccessful(); } catch (Exception e) { Log.e("Updating searchedDestinations db failed", e); } finally { database.endTransaction(); } } public boolean saveWaypoints(final cgCache cache) { boolean result = false; init(); database.beginTransaction(); try { saveOriginalWaypointsWithoutTransaction(cache); database.setTransactionSuccessful(); result = true; } catch (Exception e) { Log.e("saveWaypoints", e); } finally { database.endTransaction(); } return result; } private void saveOriginalWaypointsWithoutTransaction(final cgCache cache) { String geocode = cache.getGeocode(); database.delete(dbTableWaypoints, "geocode = ? and type <> ? and own = 0", new String[]{geocode, "own"}); List<cgWaypoint> waypoints = cache.getWaypoints(); if (CollectionUtils.isNotEmpty(waypoints)) { ContentValues values = new ContentValues(); long timeStamp = System.currentTimeMillis(); for (cgWaypoint oneWaypoint : waypoints) { if (oneWaypoint.isUserDefined()) { continue; } values.clear(); values.put("geocode", geocode); values.put("updated", timeStamp); values.put("type", oneWaypoint.getWaypointType() != null ? oneWaypoint.getWaypointType().id : null); values.put("prefix", oneWaypoint.getPrefix()); values.put("lookup", oneWaypoint.getLookup()); values.put("name", oneWaypoint.getName()); values.put("latlon", oneWaypoint.getLatlon()); putCoords(values, oneWaypoint.getCoords()); values.put("note", oneWaypoint.getNote()); values.put("own", oneWaypoint.isUserDefined() ? 1 : 0); final long rowId = database.insert(dbTableWaypoints, null, values); oneWaypoint.setId((int) rowId); } } } /** * Save coordinates into a ContentValues * * @param values * a ContentValues to save coordinates in * @param oneWaypoint * coordinates to save, or null to save empty coordinates */ private static void putCoords(final ContentValues values, final Geopoint coords) { values.put("latitude", coords == null ? null : coords.getLatitude()); values.put("longitude", coords == null ? null : coords.getLongitude()); } /** * Retrieve coordinates from a Cursor * * @param cursor * a Cursor representing a row in the database * @param indexLat * index of the latitude column * @param indexLon * index of the longitude column * @return the coordinates, or null if latitude or longitude is null or the coordinates are invalid */ private static Geopoint getCoords(final Cursor cursor, final int indexLat, final int indexLon) { if (cursor.isNull(indexLat) || cursor.isNull(indexLon)) { return null; } return new Geopoint(cursor.getDouble(indexLat), cursor.getDouble(indexLon)); } public boolean saveWaypoint(int id, String geocode, cgWaypoint waypoint) { if ((StringUtils.isBlank(geocode) && id <= 0) || waypoint == null) { return false; } init(); boolean ok = false; database.beginTransaction(); try { ContentValues values = new ContentValues(); values.put("geocode", geocode); values.put("updated", System.currentTimeMillis()); values.put("type", waypoint.getWaypointType() != null ? waypoint.getWaypointType().id : null); values.put("prefix", waypoint.getPrefix()); values.put("lookup", waypoint.getLookup()); values.put("name", waypoint.getName()); values.put("latlon", waypoint.getLatlon()); putCoords(values, waypoint.getCoords()); values.put("note", waypoint.getNote()); values.put("own", waypoint.isUserDefined() ? 1 : 0); if (id <= 0) { final long rowId = database.insert(dbTableWaypoints, null, values); waypoint.setId((int) rowId); ok = true; } else { final int rows = database.update(dbTableWaypoints, values, "_id = " + id, null); ok = rows > 0; } database.setTransactionSuccessful(); } finally { database.endTransaction(); } return ok; } public boolean deleteWaypoint(int id) { if (id == 0) { return false; } init(); return database.delete(dbTableWaypoints, "_id = " + id, null) > 0; } private void saveSpoilersWithoutTransaction(final cgCache cache) { String geocode = cache.getGeocode(); database.delete(dbTableSpoilers, "geocode = ?", new String[]{geocode}); List<cgImage> spoilers = cache.getSpoilers(); if (CollectionUtils.isNotEmpty(spoilers)) { ContentValues values = new ContentValues(); long timeStamp = System.currentTimeMillis(); for (cgImage spoiler : spoilers) { values.clear(); values.put("geocode", geocode); values.put("updated", timeStamp); values.put("url", spoiler.getUrl()); values.put("title", spoiler.getTitle()); values.put("description", spoiler.getDescription()); database.insert(dbTableSpoilers, null, values); } } } private void saveLogsWithoutTransaction(final String geocode, final List<LogEntry> logs) { // TODO delete logimages referring these logs database.delete(dbTableLogs, "geocode = ?", new String[]{geocode}); if (CollectionUtils.isNotEmpty(logs)) { InsertHelper helper = new InsertHelper(database, dbTableLogs); long timeStamp = System.currentTimeMillis(); for (LogEntry log : logs) { helper.prepareForInsert(); helper.bind(LOGS_GEOCODE, geocode); helper.bind(LOGS_UPDATED, timeStamp); helper.bind(LOGS_TYPE, log.type.id); helper.bind(LOGS_AUTHOR, log.author); helper.bind(LOGS_LOG, log.log); helper.bind(LOGS_DATE, log.date); helper.bind(LOGS_FOUND, log.found); helper.bind(LOGS_FRIEND, log.friend); long log_id = helper.execute(); if (log.hasLogImages()) { ContentValues values = new ContentValues(); for (cgImage img : log.getLogImages()) { values.clear(); values.put("log_id", log_id); values.put("title", img.getTitle()); values.put("url", img.getUrl()); database.insert(dbTableLogImages, null, values); } } } helper.close(); } } private void saveLogCountsWithoutTransaction(final cgCache cache) { String geocode = cache.getGeocode(); database.delete(dbTableLogCount, "geocode = ?", new String[]{geocode}); Map<LogType, Integer> logCounts = cache.getLogCounts(); if (MapUtils.isNotEmpty(logCounts)) { ContentValues values = new ContentValues(); Set<Entry<LogType, Integer>> logCountsItems = logCounts.entrySet(); long timeStamp = System.currentTimeMillis(); for (Entry<LogType, Integer> pair : logCountsItems) { values.clear(); values.put("geocode", geocode); values.put("updated", timeStamp); values.put("type", pair.getKey().id); values.put("count", pair.getValue()); database.insert(dbTableLogCount, null, values); } } } public boolean saveTrackable(final cgTrackable trackable) { init(); database.beginTransaction(); try { saveInventoryWithoutTransaction(null, Collections.singletonList(trackable)); database.setTransactionSuccessful(); } finally { database.endTransaction(); } return true; } private void saveInventoryWithoutTransaction(final String geocode, final List<cgTrackable> trackables) { if (geocode != null) { database.delete(dbTableTrackables, "geocode = ?", new String[]{geocode}); } if (CollectionUtils.isNotEmpty(trackables)) { ContentValues values = new ContentValues(); long timeStamp = System.currentTimeMillis(); for (cgTrackable trackable : trackables) { values.clear(); if (geocode != null) { values.put("geocode", geocode); } values.put("updated", timeStamp); values.put("tbcode", trackable.getGeocode()); values.put("guid", trackable.getGuid()); values.put("title", trackable.getName()); values.put("owner", trackable.getOwner()); if (trackable.getReleased() != null) { values.put("released", trackable.getReleased().getTime()); } else { values.put("released", 0L); } values.put("goal", trackable.getGoal()); values.put("description", trackable.getDetails()); database.insert(dbTableTrackables, null, values); saveLogsWithoutTransaction(trackable.getGeocode(), trackable.getLogs()); } } } public Viewport getBounds(final Set<String> geocodes) { if (CollectionUtils.isEmpty(geocodes)) { return null; } final Set<cgCache> caches = loadCaches(geocodes, LoadFlags.LOAD_CACHE_OR_DB); return Viewport.containing(caches); } /** * Load a single Cache. * * @param geocode * The Geocode GCXXXX * @return the loaded cache (if found). Can be null */ public cgCache loadCache(final String geocode, final EnumSet<LoadFlag> loadFlags) { if (StringUtils.isBlank(geocode)) { throw new IllegalArgumentException("geocode must not be empty"); } final Set<cgCache> caches = loadCaches(Collections.singleton(geocode), loadFlags); return caches.isEmpty() ? null : caches.iterator().next(); } /** * Load caches. * * @param geocodes * @return Set of loaded caches. Never null. */ public Set<cgCache> loadCaches(final Set<String> geocodes, final EnumSet<LoadFlag> loadFlags) { if (CollectionUtils.isEmpty(geocodes)) { return new HashSet<cgCache>(); } Set<cgCache> result = new HashSet<cgCache>(); Set<String> remaining = new HashSet<String>(geocodes); if (loadFlags.contains(LoadFlag.LOAD_CACHE_BEFORE)) { for (String geocode : new HashSet<String>(remaining)) { cgCache cache = cacheCache.getCacheFromCache(geocode); if (cache != null) { result.add(cache); remaining.remove(cache.getGeocode()); } } } if (loadFlags.contains(LoadFlag.LOAD_DB_MINIMAL) || loadFlags.contains(LoadFlag.LOAD_ATTRIBUTES) || loadFlags.contains(LoadFlag.LOAD_WAYPOINTS) || loadFlags.contains(LoadFlag.LOAD_SPOILERS) || loadFlags.contains(LoadFlag.LOAD_LOGS) || loadFlags.contains(LoadFlag.LOAD_INVENTORY) || loadFlags.contains(LoadFlag.LOAD_OFFLINE_LOG)) { final Set<cgCache> cachesFromDB = loadCachesFromGeocodes(remaining, loadFlags); result.addAll(cachesFromDB); for (final cgCache cache : cachesFromDB) { remaining.remove(cache.getGeocode()); } } if (loadFlags.contains(LoadFlag.LOAD_CACHE_AFTER)) { for (String geocode : new HashSet<String>(remaining)) { cgCache cache = cacheCache.getCacheFromCache(geocode); if (cache != null) { result.add(cache); remaining.remove(cache.getGeocode()); } } } if (remaining.size() >= 1) { Log.e("cgData.loadCaches(" + remaining.toString() + ") failed"); } return result; } /** * Load caches. * * @param geocodes * @param loadFlags * @return Set of loaded caches. Never null. */ private Set<cgCache> loadCachesFromGeocodes(final Set<String> geocodes, final EnumSet<LoadFlag> loadFlags) { if (CollectionUtils.isEmpty(geocodes)) { return Collections.emptySet(); } Log.d("cgData.loadCachesFromGeocodes(" + geocodes.toString() + ") from DB"); init(); final StringBuilder query = new StringBuilder("SELECT "); for (int i = 0; i < CACHE_COLUMNS.length; i++) { query.append(i > 0 ? ", " : "").append(dbTableCaches).append('.').append(CACHE_COLUMNS[i]).append(' '); } if (loadFlags.contains(LoadFlag.LOAD_OFFLINE_LOG)) { query.append(',').append(dbTableLogsOffline).append(".log"); } query.append(" FROM ").append(dbTableCaches); if (loadFlags.contains(LoadFlag.LOAD_OFFLINE_LOG)) { query.append(" LEFT OUTER JOIN ").append(dbTableLogsOffline).append(" ON ( ").append(dbTableCaches).append(".geocode == ").append(dbTableLogsOffline).append(".geocode) "); } query.append(" WHERE ").append(dbTableCaches).append('.'); query.append(cgData.whereGeocodeIn(geocodes)); Cursor cursor = database.rawQuery(query.toString(), null); try { if (!cursor.moveToFirst()) { return Collections.emptySet(); } final Set<cgCache> caches = new HashSet<cgCache>(); int logIndex = -1; do { //Extracted Method = LOADDBMINIMAL cgCache cache = cgData.createCacheFromDatabaseContent(cursor); if (loadFlags.contains(LoadFlag.LOAD_ATTRIBUTES)) { cache.setAttributes(loadAttributes(cache.getGeocode())); } if (loadFlags.contains(LoadFlag.LOAD_WAYPOINTS)) { final List<cgWaypoint> waypoints = loadWaypoints(cache.getGeocode()); if (CollectionUtils.isNotEmpty(waypoints)) { cache.setWaypoints(waypoints, false); } } if (loadFlags.contains(LoadFlag.LOAD_SPOILERS)) { final List<cgImage> spoilers = loadSpoilers(cache.getGeocode()); if (CollectionUtils.isNotEmpty(spoilers)) { if (cache.getSpoilers() == null) { cache.setSpoilers(new ArrayList<cgImage>()); } else { cache.getSpoilers().clear(); } cache.getSpoilers().addAll(spoilers); } } if (loadFlags.contains(LoadFlag.LOAD_LOGS)) { cache.setLogs(loadLogs(cache.getGeocode())); final Map<LogType, Integer> logCounts = loadLogCounts(cache.getGeocode()); if (MapUtils.isNotEmpty(logCounts)) { cache.getLogCounts().clear(); cache.getLogCounts().putAll(logCounts); } } if (loadFlags.contains(LoadFlag.LOAD_INVENTORY)) { final List<cgTrackable> inventory = loadInventory(cache.getGeocode()); if (CollectionUtils.isNotEmpty(inventory)) { if (cache.getInventory() == null) { cache.setInventory(new ArrayList<cgTrackable>()); } else { cache.getInventory().clear(); } cache.getInventory().addAll(inventory); } } if (loadFlags.contains(LoadFlag.LOAD_OFFLINE_LOG)) { if (logIndex < 0) { logIndex = cursor.getColumnIndex("log"); } cache.setLogOffline(!cursor.isNull(logIndex)); } cache.addStorageLocation(StorageLocation.DATABASE); cacheCache.putCacheInCache(cache); caches.add(cache); } while (cursor.moveToNext()); return caches; } finally { cursor.close(); } } /** * Builds a where for a viewport with the size enhanced by 50%. * * @param dbTable * @param viewport * @return */ private static String buildCoordinateWhere(final String dbTable, final Viewport viewport) { return viewport.resize(1.5).sqlWhere(dbTable); } /** * creates a Cache from the cursor. Doesn't next. * * @param cursor * @return Cache from DB */ private static cgCache createCacheFromDatabaseContent(Cursor cursor) { int index; cgCache cache = new cgCache(); if (cacheColumnIndex == null) { int[] local_cci = new int[41]; // use a local variable to avoid having the not yet fully initialized array be visible to other threads local_cci[0] = cursor.getColumnIndex("updated"); local_cci[1] = cursor.getColumnIndex("reason"); local_cci[2] = cursor.getColumnIndex("detailed"); local_cci[3] = cursor.getColumnIndex("detailedupdate"); local_cci[4] = cursor.getColumnIndex("visiteddate"); local_cci[5] = cursor.getColumnIndex("geocode"); local_cci[6] = cursor.getColumnIndex("cacheid"); local_cci[7] = cursor.getColumnIndex("guid"); local_cci[8] = cursor.getColumnIndex("type"); local_cci[9] = cursor.getColumnIndex("name"); local_cci[10] = cursor.getColumnIndex("own"); local_cci[11] = cursor.getColumnIndex("owner"); local_cci[12] = cursor.getColumnIndex("owner_real"); local_cci[13] = cursor.getColumnIndex("hidden"); local_cci[14] = cursor.getColumnIndex("hint"); local_cci[15] = cursor.getColumnIndex("size"); local_cci[16] = cursor.getColumnIndex("difficulty"); local_cci[17] = cursor.getColumnIndex("direction"); local_cci[18] = cursor.getColumnIndex("distance"); local_cci[19] = cursor.getColumnIndex("terrain"); local_cci[20] = cursor.getColumnIndex("latlon"); local_cci[21] = cursor.getColumnIndex("location"); local_cci[22] = cursor.getColumnIndex("elevation"); local_cci[23] = cursor.getColumnIndex("personal_note"); local_cci[24] = cursor.getColumnIndex("shortdesc"); local_cci[25] = cursor.getColumnIndex("favourite_cnt"); local_cci[26] = cursor.getColumnIndex("rating"); local_cci[27] = cursor.getColumnIndex("votes"); local_cci[28] = cursor.getColumnIndex("myvote"); local_cci[29] = cursor.getColumnIndex("disabled"); local_cci[30] = cursor.getColumnIndex("archived"); local_cci[31] = cursor.getColumnIndex("members"); local_cci[32] = cursor.getColumnIndex("found"); local_cci[33] = cursor.getColumnIndex("favourite"); local_cci[34] = cursor.getColumnIndex("inventoryunknown"); local_cci[35] = cursor.getColumnIndex("onWatchlist"); local_cci[36] = cursor.getColumnIndex("reliable_latlon"); local_cci[37] = cursor.getColumnIndex("coordsChanged"); local_cci[38] = cursor.getColumnIndex("latitude"); local_cci[39] = cursor.getColumnIndex("longitude"); local_cci[40] = cursor.getColumnIndex("finalDefined"); cacheColumnIndex = local_cci; } cache.setUpdated(cursor.getLong(cacheColumnIndex[0])); cache.setListId(cursor.getInt(cacheColumnIndex[1])); cache.setDetailed(cursor.getInt(cacheColumnIndex[2]) == 1); cache.setDetailedUpdate(cursor.getLong(cacheColumnIndex[3])); cache.setVisitedDate(cursor.getLong(cacheColumnIndex[4])); cache.setGeocode(cursor.getString(cacheColumnIndex[5])); cache.setCacheId(cursor.getString(cacheColumnIndex[6])); cache.setGuid(cursor.getString(cacheColumnIndex[7])); cache.setType(CacheType.getById(cursor.getString(cacheColumnIndex[8]))); cache.setName(cursor.getString(cacheColumnIndex[9])); cache.setOwn(cursor.getInt(cacheColumnIndex[10]) == 1); cache.setOwnerDisplayName(cursor.getString(cacheColumnIndex[11])); cache.setOwnerUserId(cursor.getString(cacheColumnIndex[12])); long dateValue = cursor.getLong(cacheColumnIndex[13]); if (dateValue != 0) { cache.setHidden(new Date(dateValue)); } cache.setHint(cursor.getString(cacheColumnIndex[14])); cache.setSize(CacheSize.getById(cursor.getString(cacheColumnIndex[15]))); cache.setDifficulty(cursor.getFloat(cacheColumnIndex[16])); index = cacheColumnIndex[17]; if (cursor.isNull(index)) { cache.setDirection(null); } else { cache.setDirection(cursor.getFloat(index)); } index = cacheColumnIndex[18]; if (cursor.isNull(index)) { cache.setDistance(null); } else { cache.setDistance(cursor.getFloat(index)); } cache.setTerrain(cursor.getFloat(cacheColumnIndex[19])); cache.setLatlon(cursor.getString(cacheColumnIndex[20])); cache.setLocation(cursor.getString(cacheColumnIndex[21])); cache.setCoords(getCoords(cursor, cacheColumnIndex[38], cacheColumnIndex[39])); index = cacheColumnIndex[22]; if (cursor.isNull(index)) { cache.setElevation(null); } else { cache.setElevation(cursor.getDouble(index)); } cache.setPersonalNote(cursor.getString(cacheColumnIndex[23])); cache.setShortdesc(cursor.getString(cacheColumnIndex[24])); // do not set cache.description ! cache.setFavoritePoints(cursor.getInt(cacheColumnIndex[25])); cache.setRating(cursor.getFloat(cacheColumnIndex[26])); cache.setVotes(cursor.getInt(cacheColumnIndex[27])); cache.setMyVote(cursor.getFloat(cacheColumnIndex[28])); cache.setDisabled(cursor.getInt(cacheColumnIndex[29]) == 1); cache.setArchived(cursor.getInt(cacheColumnIndex[30]) == 1); cache.setPremiumMembersOnly(cursor.getInt(cacheColumnIndex[31]) == 1); cache.setFound(cursor.getInt(cacheColumnIndex[32]) == 1); cache.setFavorite(cursor.getInt(cacheColumnIndex[33]) == 1); cache.setInventoryItems(cursor.getInt(cacheColumnIndex[34])); cache.setOnWatchlist(cursor.getInt(cacheColumnIndex[35]) == 1); cache.setReliableLatLon(cursor.getInt(cacheColumnIndex[36]) > 0); cache.setUserModifiedCoords(cursor.getInt(cacheColumnIndex[37]) > 0); cache.setFinalDefined(cursor.getInt(cacheColumnIndex[40]) > 0); Log.d("Loading " + cache.toString() + " (" + cache.getListId() + ") from DB"); return cache; } public List<String> loadAttributes(String geocode) { if (StringUtils.isBlank(geocode)) { return null; } init(); ArrayList<String> attributes = new ArrayList<String>(); Cursor cursor = database.query( dbTableAttributes, new String[]{"attribute"}, "geocode = ?", new String[]{geocode}, null, null, null, "100"); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); int index = cursor.getColumnIndex("attribute"); do { attributes.add(cursor.getString(index)); } while (cursor.moveToNext()); } if (cursor != null) { cursor.close(); } return attributes; } public cgWaypoint loadWaypoint(int id) { if (id == 0) { return null; } init(); cgWaypoint waypoint = null; Cursor cursor = database.query( dbTableWaypoints, WAYPOINT_COLUMNS, "_id = ?", new String[]{Integer.toString(id)}, null, null, null, "1"); Log.d("cgData.loadWaypoint(" + id + ")"); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); waypoint = createWaypointFromDatabaseContent(cursor); } if (cursor != null) { cursor.close(); } return waypoint; } public List<cgWaypoint> loadWaypoints(final String geocode) { if (StringUtils.isBlank(geocode)) { return null; } init(); List<cgWaypoint> waypoints = new ArrayList<cgWaypoint>(); Cursor cursor = database.query( dbTableWaypoints, WAYPOINT_COLUMNS, "geocode = ?", new String[]{geocode}, null, null, "_id", "100"); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); do { cgWaypoint waypoint = createWaypointFromDatabaseContent(cursor); waypoints.add(waypoint); } while (cursor.moveToNext()); } if (cursor != null) { cursor.close(); } return waypoints; } private static cgWaypoint createWaypointFromDatabaseContent(Cursor cursor) { String name = cursor.getString(cursor.getColumnIndex("name")); WaypointType type = WaypointType.findById(cursor.getString(cursor.getColumnIndex("type"))); boolean own = cursor.getInt(cursor.getColumnIndex("own")) != 0; cgWaypoint waypoint = new cgWaypoint(name, type, own); waypoint.setId(cursor.getInt(cursor.getColumnIndex("_id"))); waypoint.setGeocode(cursor.getString(cursor.getColumnIndex("geocode"))); waypoint.setPrefix(cursor.getString(cursor.getColumnIndex("prefix"))); waypoint.setLookup(cursor.getString(cursor.getColumnIndex("lookup"))); waypoint.setLatlon(cursor.getString(cursor.getColumnIndex("latlon"))); waypoint.setCoords(getCoords(cursor, cursor.getColumnIndex("latitude"), cursor.getColumnIndex("longitude"))); waypoint.setNote(cursor.getString(cursor.getColumnIndex("note"))); return waypoint; } private List<cgImage> loadSpoilers(String geocode) { if (StringUtils.isBlank(geocode)) { return null; } init(); List<cgImage> spoilers = new ArrayList<cgImage>(); Cursor cursor = database.query( dbTableSpoilers, new String[]{"url", "title", "description"}, "geocode = ?", new String[]{geocode}, null, null, null, "100"); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); int indexUrl = cursor.getColumnIndex("url"); int indexTitle = cursor.getColumnIndex("title"); int indexDescription = cursor.getColumnIndex("description"); do { cgImage spoiler = new cgImage(cursor.getString(indexUrl), cursor.getString(indexTitle), cursor.getString(indexDescription)); spoilers.add(spoiler); } while (cursor.moveToNext()); } if (cursor != null) { cursor.close(); } return spoilers; } /** * Loads the history of previously entered destinations from * the database. If no destinations exist, an {@link Collections#emptyList()} will be returned. * * @return A list of previously entered destinations or an empty list. */ public List<Destination> loadHistoryOfSearchedLocations() { init(); Cursor cursor = database.query(dbTableSearchDestionationHistory, new String[]{"_id", "date", "latitude", "longitude"}, null, null, null, null, "date desc", "100"); final List<Destination> destinations = new LinkedList<Destination>(); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); int indexId = cursor.getColumnIndex("_id"); int indexDate = cursor.getColumnIndex("date"); int indexLatitude = cursor.getColumnIndex("latitude"); int indexLongitude = cursor.getColumnIndex("longitude"); do { final Destination dest = new Destination(cursor.getLong(indexId), cursor.getLong(indexDate), getCoords(cursor, indexLatitude, indexLongitude)); // If coordinates are non-existent or invalid, do not consider // this point. if (dest.getCoords() != null) { destinations.add(dest); } } while (cursor.moveToNext()); } if (cursor != null) { cursor.close(); } return destinations; } public boolean clearSearchedDestinations() { boolean success = true; init(); database.beginTransaction(); try { database.delete(dbTableSearchDestionationHistory, null, null); database.setTransactionSuccessful(); } catch (Exception e) { success = false; Log.e("Unable to clear searched destinations", e); } finally { database.endTransaction(); } return success; } public List<LogEntry> loadLogs(String geocode) { if (StringUtils.isBlank(geocode)) { return null; } init(); List<LogEntry> logs = new ArrayList<LogEntry>(); Cursor cursor = database.rawQuery( "SELECT cg_logs._id as cg_logs_id, type, author, log, date, found, friend, " + dbTableLogImages + "._id as cg_logImages_id, log_id, title, url FROM " + dbTableLogs + " LEFT OUTER JOIN " + dbTableLogImages + " ON ( cg_logs._id = log_id ) WHERE geocode = ? ORDER BY date desc, cg_logs._id asc", new String[]{geocode}); if (cursor != null && cursor.getCount() > 0) { LogEntry log = null; int indexLogsId = cursor.getColumnIndex("cg_logs_id"); int indexType = cursor.getColumnIndex("type"); int indexAuthor = cursor.getColumnIndex("author"); int indexLog = cursor.getColumnIndex("log"); int indexDate = cursor.getColumnIndex("date"); int indexFound = cursor.getColumnIndex("found"); int indexFriend = cursor.getColumnIndex("friend"); int indexLogImagesId = cursor.getColumnIndex("cg_logImages_id"); int indexTitle = cursor.getColumnIndex("title"); int indexUrl = cursor.getColumnIndex("url"); while (cursor.moveToNext() && logs.size() < 100) { if (log == null || log.id != cursor.getInt(indexLogsId)) { log = new LogEntry( cursor.getString(indexAuthor), cursor.getLong(indexDate), LogType.getById(cursor.getInt(indexType)), cursor.getString(indexLog)); log.id = cursor.getInt(indexLogsId); log.found = cursor.getInt(indexFound); log.friend = cursor.getInt(indexFriend) == 1; logs.add(log); } if (!cursor.isNull(indexLogImagesId)) { String title = cursor.getString(indexTitle); String url = cursor.getString(indexUrl); log.addLogImage(new cgImage(url, title)); } } } if (cursor != null) { cursor.close(); } return logs; } public Map<LogType, Integer> loadLogCounts(String geocode) { if (StringUtils.isBlank(geocode)) { return null; } init(); Map<LogType, Integer> logCounts = new HashMap<LogType, Integer>(); Cursor cursor = database.query( dbTableLogCount, new String[]{"type", "count"}, "geocode = ?", new String[]{geocode}, null, null, null, "100"); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); int indexType = cursor.getColumnIndex("type"); int indexCount = cursor.getColumnIndex("count"); do { LogType type = LogType.getById(cursor.getInt(indexType)); Integer count = cursor.getInt(indexCount); logCounts.put(type, count); } while (cursor.moveToNext()); } if (cursor != null) { cursor.close(); } return logCounts; } private List<cgTrackable> loadInventory(String geocode) { if (StringUtils.isBlank(geocode)) { return null; } init(); List<cgTrackable> trackables = new ArrayList<cgTrackable>(); Cursor cursor = database.query( dbTableTrackables, new String[]{"_id", "updated", "tbcode", "guid", "title", "owner", "released", "goal", "description"}, "geocode = ?", new String[]{geocode}, null, null, "title COLLATE NOCASE ASC", "100"); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); do { cgTrackable trackable = createTrackableFromDatabaseContent(cursor); trackables.add(trackable); } while (cursor.moveToNext()); } if (cursor != null) { cursor.close(); } return trackables; } public cgTrackable loadTrackable(String geocode) { if (StringUtils.isBlank(geocode)) { return null; } init(); cgTrackable trackable = new cgTrackable(); Cursor cursor = database.query( dbTableTrackables, new String[]{"updated", "tbcode", "guid", "title", "owner", "released", "goal", "description"}, "tbcode = ?", new String[]{geocode}, null, null, null, "1"); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); trackable = createTrackableFromDatabaseContent(cursor); } if (cursor != null) { cursor.close(); } return trackable; } private cgTrackable createTrackableFromDatabaseContent(Cursor cursor) { cgTrackable trackable = new cgTrackable(); trackable.setGeocode(cursor.getString(cursor.getColumnIndex("tbcode"))); trackable.setGuid(cursor.getString(cursor.getColumnIndex("guid"))); trackable.setName(cursor.getString(cursor.getColumnIndex("title"))); trackable.setOwner(cursor.getString(cursor.getColumnIndex("owner"))); String released = cursor.getString(cursor.getColumnIndex("released")); if (released != null) { try { long releaseMilliSeconds = Long.parseLong(released); trackable.setReleased(new Date(releaseMilliSeconds)); } catch (NumberFormatException e) { Log.e("createTrackableFromDatabaseContent", e); } } trackable.setGoal(cursor.getString(cursor.getColumnIndex("goal"))); trackable.setDetails(cursor.getString(cursor.getColumnIndex("description"))); trackable.setLogs(loadLogs(trackable.getGeocode())); return trackable; } /** * Number of caches stored. The number is shown on the starting activity of c:geo * * @param detailedOnly * @param cacheType * @param list * @return */ public int getAllStoredCachesCount(final boolean detailedOnly, final CacheType cacheType, final int list) { if (cacheType == null) { throw new IllegalArgumentException("cacheType must not be null"); } init(); String listSql; String listSqlW; if (list == 0) { listSql = " where reason >= 1"; listSqlW = " and reason >= 1"; } else if (list >= 1) { listSql = " where reason = " + list; listSqlW = " and reason = " + list; } else { return 0; } int count = 0; try { String sql; if (!detailedOnly) { if (cacheType == CacheType.ALL) { sql = "select count(_id) from " + dbTableCaches + listSql; } else { sql = "select count(_id) from " + dbTableCaches + " where type = " + DatabaseUtils.sqlEscapeString(cacheType.id) + listSqlW; } } else { if (cacheType == CacheType.ALL) { sql = "select count(_id) from " + dbTableCaches + " where detailed = 1" + listSqlW; } else { sql = "select count(_id) from " + dbTableCaches + " where detailed = 1 and type = " + DatabaseUtils.sqlEscapeString(cacheType.id) + listSqlW; } } SQLiteStatement compiledStmnt = database.compileStatement(sql); count = (int) compiledStmnt.simpleQueryForLong(); compiledStmnt.close(); } catch (Exception e) { Log.e("cgData.loadAllStoredCachesCount: " + e.toString()); } return count; } public int getAllHistoricCachesCount() { init(); int count = 0; try { SQLiteStatement sqlCount = database.compileStatement("select count(_id) from " + dbTableCaches + " where visiteddate > 0"); count = (int) sqlCount.simpleQueryForLong(); sqlCount.close(); } catch (Exception e) { Log.e("cgData.getAllHistoricCachesCount: " + e.toString()); } return count; } /** * Return a batch of stored geocodes. * * @param detailedOnly * @param coords * the current coordinates to sort by distance, or null to sort by geocode * @param cacheType * @param listId * @return */ public Set<String> loadBatchOfStoredGeocodes(final boolean detailedOnly, final Geopoint coords, final CacheType cacheType, final int listId) { if (cacheType == null) { throw new IllegalArgumentException("cacheType must not be null"); } init(); Set<String> geocodes = new HashSet<String>(); StringBuilder specifySql = new StringBuilder(); specifySql.append("reason "); specifySql.append(listId != StoredList.ALL_LIST_ID ? "=" + Math.max(listId, 1) : ">= " + StoredList.STANDARD_LIST_ID); if (detailedOnly) { specifySql.append(" and detailed = 1 "); } if (cacheType != CacheType.ALL) { specifySql.append(" and type = "); specifySql.append(DatabaseUtils.sqlEscapeString(cacheType.id)); } try { Cursor cursor; if (coords != null) { cursor = database.query( dbTableCaches, new String[]{"geocode", "(abs(latitude-" + String.format((Locale) null, "%.6f", coords.getLatitude()) + ") + abs(longitude-" + String.format((Locale) null, "%.6f", coords.getLongitude()) + ")) as dif"}, specifySql.toString(), null, null, null, "dif", null); } else { cursor = database.query( dbTableCaches, new String[]{"geocode"}, specifySql.toString(), null, null, null, "geocode"); } if (cursor.moveToFirst()) { final int index = cursor.getColumnIndex("geocode"); do { geocodes.add(cursor.getString(index)); } while (cursor.moveToNext()); } cursor.close(); } catch (Exception e) { Log.e("cgData.loadBatchOfStoredGeocodes: " + e.toString()); } return geocodes; } public Set<String> loadBatchOfHistoricGeocodes(final boolean detailedOnly, final CacheType cacheType) { init(); Set<String> geocodes = new HashSet<String>(); StringBuilder specifySql = new StringBuilder(); specifySql.append("visiteddate > 0"); if (detailedOnly) { specifySql.append(" and detailed = 1"); } if (cacheType != CacheType.ALL) { specifySql.append(" and type = "); specifySql.append(DatabaseUtils.sqlEscapeString(cacheType.id)); } try { Cursor cursor = database.query( dbTableCaches, new String[]{"geocode"}, specifySql.toString(), null, null, null, "visiteddate", null); if (cursor != null) { if (cursor.getCount() > 0) { cursor.moveToFirst(); int index = cursor.getColumnIndex("geocode"); do { geocodes.add(cursor.getString(index)); } while (cursor.moveToNext()); } else { cursor.close(); return null; } cursor.close(); } } catch (Exception e) { Log.e("cgData.loadBatchOfHistoricGeocodes: " + e.toString()); } return geocodes; } /** Retrieve all stored caches from DB */ public Set<String> loadCachedInViewport(final Viewport viewport, final CacheType cacheType) { return loadInViewport(false, viewport, cacheType); } /** Retrieve stored caches from DB with listId >= 1 */ public Set<String> loadStoredInViewport(final Viewport viewport, final CacheType cacheType) { return loadInViewport(true, viewport, cacheType); } /** * Loads the geocodes of caches in a viewport from CacheCache and/or Database * * @param stored * True - query only stored caches, False - query cached ones as well * @param centerLat * @param centerLon * @param spanLat * @param spanLon * @param cacheType * @return Set with geocodes */ private Set<String> loadInViewport(final boolean stored, final Viewport viewport, final CacheType cacheType) { init(); final Set<String> geocodes = new HashSet<String>(); // if not stored only, get codes from CacheCache as well if (!stored) { geocodes.addAll(cacheCache.getInViewport(viewport, cacheType)); } // viewport limitation final StringBuilder where = new StringBuilder(buildCoordinateWhere(dbTableCaches, viewport)); // cacheType limitation if (cacheType != CacheType.ALL) { where.append(" and type = "); where.append(DatabaseUtils.sqlEscapeString(cacheType.id)); } // offline caches only if (stored) { where.append(" and reason >= " + StoredList.STANDARD_LIST_ID); } try { final Cursor cursor = database.query( dbTableCaches, new String[]{"geocode"}, where.toString(), null, null, null, null, "500"); if (cursor.moveToFirst()) { final int index = cursor.getColumnIndex("geocode"); do { geocodes.add(cursor.getString(index)); } while (cursor.moveToNext()); } cursor.close(); } catch (Exception e) { Log.e("cgData.loadInViewport: " + e.toString()); } return geocodes; } /** delete caches from the DB store 3 days or more before */ public void clean() { clean(false); } /** * Remove caches with listId = 0 * * @param more * true = all caches false = caches stored 3 days or more before */ public void clean(boolean more) { init(); Log.d("Database clean: started"); Cursor cursor; Set<String> geocodes = new HashSet<String>(); try { if (more) { cursor = database.query( dbTableCaches, new String[]{"geocode"}, "reason = 0", null, null, null, null, null); } else { long timestamp = System.currentTimeMillis() - DAYS_AFTER_CACHE_IS_DELETED; String timestampString = Long.toString(timestamp); cursor = database.query( dbTableCaches, new String[]{"geocode"}, "reason = 0 and detailed < ? and detailedupdate < ? and visiteddate < ?", new String[]{timestampString, timestampString, timestampString}, null, null, null, null); } if (cursor != null) { if (cursor.getCount() > 0) { cursor.moveToFirst(); final int index = cursor.getColumnIndex("geocode"); do { geocodes.add(cursor.getString(index)); } while (cursor.moveToNext()); } cursor.close(); } final int size = geocodes.size(); if (size > 0) { Log.d("Database clean: removing " + size + " geocaches from listId=0"); removeCaches(geocodes, LoadFlags.REMOVE_ALL); } final SQLiteStatement countSql = database.compileStatement("select count(_id) from " + dbTableCaches + " where reason = 0"); final int count = (int) countSql.simpleQueryForLong(); countSql.close(); Log.d("Database clean: " + count + " geocaches remaining for listId=0"); } catch (Exception e) { Log.w("cgData.clean: " + e.toString()); } Log.d("Database clean: finished"); } public void removeAllFromCache() { // clean up CacheCache cacheCache.removeAllFromCache(); } public void removeCache(final String geocode, EnumSet<LoadFlags.RemoveFlag> removeFlags) { Set<String> geocodes = new HashSet<String>(); geocodes.add(geocode); removeCaches(geocodes, removeFlags); } /** * Drop caches from the tables they are stored into, as well as the cache files * * @param geocodes * list of geocodes to drop from cache */ public void removeCaches(final Set<String> geocodes, EnumSet<LoadFlags.RemoveFlag> removeFlags) { if (CollectionUtils.isEmpty(geocodes)) { return; } init(); if (removeFlags.contains(RemoveFlag.REMOVE_CACHE)) { for (final String geocode : geocodes) { cacheCache.removeCacheFromCache(geocode); } } if (removeFlags.contains(RemoveFlag.REMOVE_DB)) { // Drop caches from the database final ArrayList<String> quotedGeocodes = new ArrayList<String>(geocodes.size()); for (final String geocode : geocodes) { quotedGeocodes.add(DatabaseUtils.sqlEscapeString(geocode)); } final String geocodeList = StringUtils.join(quotedGeocodes.toArray(), ','); final String baseWhereClause = "geocode in (" + geocodeList + ")"; database.beginTransaction(); try { database.delete(dbTableCaches, baseWhereClause, null); database.delete(dbTableAttributes, baseWhereClause, null); database.delete(dbTableSpoilers, baseWhereClause, null); database.delete(dbTableLogs, baseWhereClause, null); database.delete(dbTableLogCount, baseWhereClause, null); database.delete(dbTableLogsOffline, baseWhereClause, null); database.delete(dbTableWaypoints, baseWhereClause + " and type <> 'own'", null); database.delete(dbTableTrackables, baseWhereClause, null); database.setTransactionSuccessful(); } finally { database.endTransaction(); } // Delete cache directories for (final String geocode : geocodes) { LocalStorage.deleteDirectory(LocalStorage.getStorageDir(geocode)); } } } public boolean saveLogOffline(String geocode, Date date, LogType type, String log) { if (StringUtils.isBlank(geocode)) { Log.e("cgData.saveLogOffline: cannot log a blank geocode"); return false; } if (LogType.UNKNOWN == type && StringUtils.isBlank(log)) { Log.e("cgData.saveLogOffline: cannot log an unknown log type and no message"); return false; } init(); final ContentValues values = new ContentValues(); values.put("geocode", geocode); values.put("updated", System.currentTimeMillis()); values.put("type", type.id); values.put("log", log); values.put("date", date.getTime()); if (hasLogOffline(geocode)) { final int rows = database.update(dbTableLogsOffline, values, "geocode = ?", new String[] { geocode }); return rows > 0; } final long id = database.insert(dbTableLogsOffline, null, values); return id != -1; } public LogEntry loadLogOffline(String geocode) { if (StringUtils.isBlank(geocode)) { return null; } init(); LogEntry log = null; Cursor cursor = database.query( dbTableLogsOffline, new String[]{"_id", "type", "log", "date"}, "geocode = ?", new String[]{geocode}, null, null, "_id desc", "1"); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); log = new LogEntry( cursor.getLong(cursor.getColumnIndex("date")), LogType.getById(cursor.getInt(cursor.getColumnIndex("type"))), cursor.getString(cursor.getColumnIndex("log"))); log.id = cursor.getInt(cursor.getColumnIndex("_id")); } if (cursor != null) { cursor.close(); } return log; } public void clearLogOffline(String geocode) { if (StringUtils.isBlank(geocode)) { return; } init(); database.delete(dbTableLogsOffline, "geocode = ?", new String[]{geocode}); } private SQLiteStatement getStatementLogCount() { return getStatement("LogCountFromGeocode", "SELECT count(_id) FROM " + dbTableLogsOffline + " WHERE geocode = ?"); } private synchronized SQLiteStatement getStatement(final String key, final String query) { SQLiteStatement statement = statements.get(key); if (statement == null) { statement = database.compileStatement(query); statements.put(key, statement); } return statement; } private SQLiteStatement getStatementCountStandardList() { return getStatement("CountStandardList", "SELECT count(_id) FROM " + dbTableCaches + " WHERE reason = " + StoredList.STANDARD_LIST_ID); } private SQLiteStatement getStatementCountAllLists() { return getStatement("CountAllLists", "SELECT count(_id) FROM " + dbTableCaches + " WHERE reason >= " + StoredList.STANDARD_LIST_ID); } public boolean hasLogOffline(final String geocode) { if (StringUtils.isBlank(geocode)) { return false; } init(); try { final SQLiteStatement logCount = getStatementLogCount(); synchronized (logCount) { logCount.bindString(1, geocode); return logCount.simpleQueryForLong() > 0; } } catch (Exception e) { Log.e("cgData.hasLogOffline", e); } return false; } public void setVisitDate(List<String> geocodes, long visitedDate) { if (geocodes.isEmpty()) { return; } init(); database.beginTransaction(); try { ContentValues values = new ContentValues(); values.put("visiteddate", visitedDate); for (String geocode : geocodes) { database.update(dbTableCaches, values, "geocode = ?", new String[]{geocode}); } database.setTransactionSuccessful(); } finally { database.endTransaction(); } } public List<StoredList> getLists(Resources res) { init(); List<StoredList> lists = new ArrayList<StoredList>(); lists.add(new StoredList(StoredList.STANDARD_LIST_ID, res.getString(R.string.list_inbox), (int) getStatementCountStandardList().simpleQueryForLong())); try { String query = "SELECT l._id as _id, l.title as title, COUNT(c._id) as count" + " FROM " + dbTableLists + " l LEFT OUTER JOIN " + dbTableCaches + " c" + " ON l._id + " + customListIdOffset + " = c.reason" + " GROUP BY l._id" + " ORDER BY l.title COLLATE NOCASE ASC"; Cursor cursor = database.rawQuery(query, null); ArrayList<StoredList> storedLists = getListsFromCursor(cursor); lists.addAll(storedLists); } catch (Exception e) { Log.e("cgData.readLists: " + e.toString()); } return lists; } private static ArrayList<StoredList> getListsFromCursor(Cursor cursor) { ArrayList<StoredList> result = new ArrayList<StoredList>(); if (cursor != null) { if (cursor.getCount() > 0) { cursor.moveToFirst(); int indexId = cursor.getColumnIndex("_id"); int indexTitle = cursor.getColumnIndex("title"); int indexCount = cursor.getColumnIndex("count"); do { int count = 0; if (indexCount >= 0) { count = cursor.getInt(indexCount); } StoredList list = new StoredList(cursor.getInt(indexId) + customListIdOffset, cursor.getString(indexTitle), count); result.add(list); } while (cursor.moveToNext()); } cursor.close(); } return result; } public StoredList getList(int id, Resources res) { init(); if (id >= customListIdOffset) { Cursor cursor = database.query( dbTableLists, new String[]{"_id", "title"}, "_id = " + (id - customListIdOffset), null, null, null, null); ArrayList<StoredList> lists = getListsFromCursor(cursor); if (!lists.isEmpty()) { return lists.get(0); } } if (id == StoredList.ALL_LIST_ID) { return new StoredList(StoredList.ALL_LIST_ID, res.getString(R.string.list_all_lists), (int) getStatementCountAllLists().simpleQueryForLong()); } // fall back to standard list in case of invalid list id if (id == StoredList.STANDARD_LIST_ID || id >= customListIdOffset) { return new StoredList(StoredList.STANDARD_LIST_ID, res.getString(R.string.list_inbox), (int) getStatementCountStandardList().simpleQueryForLong()); } return null; } /** * Create a new list * * @param name * Name * @return new listId */ public int createList(String name) { int id = -1; if (StringUtils.isBlank(name)) { return id; } init(); database.beginTransaction(); try { ContentValues values = new ContentValues(); values.put("title", name); values.put("updated", System.currentTimeMillis()); id = (int) database.insert(dbTableLists, null, values); database.setTransactionSuccessful(); } finally { database.endTransaction(); } return id >= 0 ? id + customListIdOffset : -1; } /** * @param listId * List to change * @param name * New name of list * @return Number of lists changed */ public int renameList(final int listId, final String name) { if (StringUtils.isBlank(name) || StoredList.STANDARD_LIST_ID == listId) { return 0; } init(); int count = 0; database.beginTransaction(); try { ContentValues values = new ContentValues(); values.put("title", name); values.put("updated", System.currentTimeMillis()); count = database.update(dbTableLists, values, "_id = " + (listId - customListIdOffset), null); database.setTransactionSuccessful(); } finally { database.endTransaction(); } return count; } /** * Remove a list. Caches in the list are moved to the standard list. * * @param listId * @return true if the list got deleted, false else */ public boolean removeList(int listId) { boolean status = false; if (listId < customListIdOffset) { return status; } init(); database.beginTransaction(); try { int cnt = database.delete(dbTableLists, "_id = " + (listId - customListIdOffset), null); if (cnt > 0) { // move caches from deleted list to standard list ContentValues values = new ContentValues(); values.put("reason", StoredList.STANDARD_LIST_ID); database.update(dbTableCaches, values, "reason = " + listId, null); status = true; } database.setTransactionSuccessful(); } finally { database.endTransaction(); } return status; } public void moveToList(final List<cgCache> caches, final int listId) { if (listId == StoredList.ALL_LIST_ID) { return; } if (caches.isEmpty()) { return; } init(); final ContentValues values = new ContentValues(); values.put("reason", listId); database.beginTransaction(); try { for (cgCache cache : caches) { database.update(dbTableCaches, values, "geocode = ?", new String[]{cache.getGeocode()}); cache.setListId(listId); } database.setTransactionSuccessful(); } finally { database.endTransaction(); } } public synchronized boolean status() { return database != null; } public boolean removeSearchedDestination(Destination destination) { boolean success = true; if (destination == null) { success = false; } else { init(); database.beginTransaction(); try { database.delete(dbTableSearchDestionationHistory, "_id = " + destination.getId(), null); database.setTransactionSuccessful(); } catch (Exception e) { Log.e("Unable to remove searched destination", e); success = false; } finally { database.endTransaction(); } } return success; } private SQLiteStatement getStatementDescription() { return getStatement("descriptionFromGeocode", "SELECT description FROM " + dbTableCaches + " WHERE geocode = ?"); } private SQLiteStatement getStatementListIdFromGeocode() { return getStatement("listFromGeocode", "SELECT reason FROM " + dbTableCaches + " WHERE geocode = ?"); } private SQLiteStatement getStatementListIdFromGuid() { return getStatement("listFromGeocode", "SELECT reason FROM " + dbTableCaches + " WHERE guid = ?"); } private SQLiteStatement getStatementCacheId() { return getStatement("cacheIdFromGeocode", "SELECT cacheid FROM " + dbTableCaches + " WHERE geocode = ?"); } private SQLiteStatement getStatementGeocode() { return getStatement("geocodeFromGuid", "SELECT geocode FROM " + dbTableCaches + " WHERE guid = ?"); } public String getCacheDescription(String geocode) { if (StringUtils.isBlank(geocode)) { return null; } init(); try { final SQLiteStatement description = getStatementDescription(); synchronized (description) { description.bindString(1, geocode); return description.simpleQueryForString(); } } catch (SQLiteDoneException e) { // Do nothing, it only means we have no information on the cache } catch (Exception e) { Log.e("cgData.getCacheDescription", e); } return null; } /** * checks if this is a newly created database * * @return */ public static boolean isNewlyCreatedDatebase() { return newlyCreatedDatabase; } /** * resets flag for newly created database to avoid asking the user multiple times */ public static void resetNewlyCreatedDatabase() { newlyCreatedDatabase = false; } private static String whereGeocodeIn(Set<String> geocodes) { final StringBuilder where = new StringBuilder(); if (geocodes != null && geocodes.size() > 0) { StringBuilder all = new StringBuilder(); for (String geocode : geocodes) { if (all.length() > 0) { all.append(", "); } all.append(DatabaseUtils.sqlEscapeString(geocode)); } where.append("geocode in (").append(all).append(')'); } return where.toString(); } /** * Loads all Waypoints in the coordinate rectangle. * * @param excludeDisabled * @param excludeMine * @param type * @return */ public Set<cgWaypoint> loadWaypoints(final Viewport viewport, boolean excludeMine, boolean excludeDisabled, CacheType type) { final StringBuilder where = new StringBuilder(buildCoordinateWhere(dbTableWaypoints, viewport)); if (excludeMine) { where.append(" and ").append(dbTableCaches).append(".own == 0 and ").append(dbTableCaches).append(".found == 0"); } if (excludeDisabled) { where.append(" and ").append(dbTableCaches).append(".disabled == 0"); } if (type != CacheType.ALL) { where.append(" and ").append(dbTableCaches).append(".type == '").append(type.id).append("'"); } init(); final StringBuilder query = new StringBuilder("SELECT "); for (int i = 0; i < WAYPOINT_COLUMNS.length; i++) { query.append(i > 0 ? ", " : "").append(dbTableWaypoints).append('.').append(WAYPOINT_COLUMNS[i]).append(' '); } query.append(" FROM ").append(dbTableWaypoints).append(", ").append(dbTableCaches).append(" WHERE ").append(dbTableWaypoints).append(".geocode == ").append(dbTableCaches).append(".geocode and ").append(where); final Cursor cursor = database.rawQuery(query.toString(), null); try { if (!cursor.moveToFirst()) { return Collections.emptySet(); } final Set<cgWaypoint> waypoints = new HashSet<cgWaypoint>(); do { waypoints.add(createWaypointFromDatabaseContent(cursor)); } while (cursor.moveToNext()); return waypoints; } finally { cursor.close(); } } }
true
true
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.i("Upgrade database from ver. " + oldVersion + " to ver. " + newVersion + ": start"); try { if (db.isReadOnly()) { return; } db.beginTransaction(); if (oldVersion <= 0) { // new table dropDatabase(db); onCreate(db); Log.i("Database structure created."); } if (oldVersion > 0) { db.execSQL("delete from " + dbTableCaches + " where reason = 0"); if (oldVersion < 52) { // upgrade to 52 try { db.execSQL(dbCreateSearchDestinationHistory); Log.i("Added table " + dbTableSearchDestionationHistory + "."); } catch (Exception e) { Log.e("Failed to upgrade to ver. 52", e); } } if (oldVersion < 53) { // upgrade to 53 try { db.execSQL("alter table " + dbTableCaches + " add column onWatchlist integer"); Log.i("Column onWatchlist added to " + dbTableCaches + "."); } catch (Exception e) { Log.e("Failed to upgrade to ver. 53", e); } } if (oldVersion < 54) { // update to 54 try { db.execSQL(dbCreateLogImages); } catch (Exception e) { Log.e("Failed to upgrade to ver. 54: " + e.toString()); } } if (oldVersion < 55) { // update to 55 try { db.execSQL("alter table " + dbTableCaches + " add column personal_note text"); } catch (Exception e) { Log.e("Failed to upgrade to ver. 55: " + e.toString()); } } // make all internal attribute names lowercase // @see issue #299 if (oldVersion < 56) { // update to 56 try { db.execSQL("update " + dbTableAttributes + " set attribute = " + "lower(attribute) where attribute like \"%_yes\" " + "or attribute like \"%_no\""); } catch (Exception e) { Log.e("Failed to upgrade to ver. 56: " + e.toString()); } } // Create missing indices. See issue #435 if (oldVersion < 57) { // update to 57 try { db.execSQL("drop index in_a"); db.execSQL("drop index in_b"); db.execSQL("drop index in_c"); db.execSQL("drop index in_d"); db.execSQL("drop index in_e"); db.execSQL("drop index in_f"); createIndices(db); } catch (Exception e) { Log.e("Failed to upgrade to ver. 57: " + e.toString()); } } if (oldVersion < 58) { // upgrade to 58 try { db.beginTransaction(); final String dbTableCachesTemp = dbTableCaches + "_temp"; final String dbCreateCachesTemp = "" + "create table " + dbTableCachesTemp + " (" + "_id integer primary key autoincrement, " + "updated long not null, " + "detailed integer not null default 0, " + "detailedupdate long, " + "visiteddate long, " + "geocode text unique not null, " + "reason integer not null default 0, " + "cacheid text, " + "guid text, " + "type text, " + "name text, " + "own integer not null default 0, " + "owner text, " + "owner_real text, " + "hidden long, " + "hint text, " + "size text, " + "difficulty float, " + "terrain float, " + "latlon text, " + "location text, " + "direction double, " + "distance double, " + "latitude double, " + "longitude double, " + "reliable_latlon integer, " + "elevation double, " + "personal_note text, " + "shortdesc text, " + "description text, " + "favourite_cnt integer, " + "rating float, " + "votes integer, " + "myvote float, " + "disabled integer not null default 0, " + "archived integer not null default 0, " + "members integer not null default 0, " + "found integer not null default 0, " + "favourite integer not null default 0, " + "inventorycoins integer default 0, " + "inventorytags integer default 0, " + "inventoryunknown integer default 0, " + "onWatchlist integer default 0 " + "); "; db.execSQL(dbCreateCachesTemp); db.execSQL("insert into " + dbTableCachesTemp + " select _id,updated,detailed,detailedupdate,visiteddate,geocode,reason,cacheid,guid,type,name,own,owner,owner_real," + "hidden,hint,size,difficulty,terrain,latlon,location,direction,distance,latitude,longitude,reliable_latlon,elevation," + "personal_note,shortdesc,description,favourite_cnt,rating,votes,myvote,disabled,archived,members,found,favourite,inventorycoins," + "inventorytags,inventoryunknown,onWatchlist from " + dbTableCaches); db.execSQL("drop table " + dbTableCaches); db.execSQL("alter table " + dbTableCachesTemp + " rename to " + dbTableCaches); final String dbTableWaypointsTemp = dbTableWaypoints + "_temp"; final String dbCreateWaypointsTemp = "" + "create table " + dbTableWaypointsTemp + " (" + "_id integer primary key autoincrement, " + "geocode text not null, " + "updated long not null, " // date of save + "type text not null default 'waypoint', " + "prefix text, " + "lookup text, " + "name text, " + "latlon text, " + "latitude double, " + "longitude double, " + "note text " + "); "; db.execSQL(dbCreateWaypointsTemp); db.execSQL("insert into " + dbTableWaypointsTemp + " select _id, geocode, updated, type, prefix, lookup, name, latlon, latitude, longitude, note from " + dbTableWaypoints); db.execSQL("drop table " + dbTableWaypoints); db.execSQL("alter table " + dbTableWaypointsTemp + " rename to " + dbTableWaypoints); createIndices(db); db.setTransactionSuccessful(); Log.i("Removed latitude_string and longitude_string columns"); } catch (Exception e) { Log.e("Failed to upgrade to ver. 58", e); } finally { db.endTransaction(); } } if (oldVersion < 59) { try { // Add new indices and remove obsolete cache files createIndices(db); removeObsoleteCacheDirectories(db); } catch (Exception e) { Log.e("Failed to upgrade to ver. 59", e); } } if (oldVersion < 60) { try { removeSecEmptyDirs(); } catch (Exception e) { Log.e("Failed to upgrade to ver. 60", e); } } if (oldVersion < 61) { try { db.execSQL("alter table " + dbTableLogs + " add column friend integer"); db.execSQL("alter table " + dbTableCaches + " add column coordsChanged integer default 0"); } catch (Exception e) { Log.e("Failed to upgrade to ver. 61: " + e.toString()); } } // Introduces finalDefined on caches and own on waypoints if (oldVersion < 62) { try { db.execSQL("alter table " + dbTableCaches + " add column finalDefined integer default 0"); db.execSQL("alter table " + dbTableWaypoints + " add column own integer default 0"); db.execSQL("update " + dbTableWaypoints + " set own = 1 where type = 'own'"); } catch (Exception e) { Log.e("Failed to upgrade to ver. 62: " + e.toString()); } } if (oldVersion < 63) { try { removeDoubleUnderscoreMapFiles(); } catch (Exception e) { Log.e("Failed to upgrade to ver. 63: " + e.toString()); } } if (oldVersion < 64) { try { // No cache should ever be stored into the ALL_CACHES list. Here we use hardcoded list ids // rather than symbolic ones because the fix must be applied with the values at the time // of the problem. The problem was introduced in release 2012.06.01. db.execSQL("update " + dbTableCaches + " set reason=1 where reason=2"); } catch (Exception e) { Log.e("Failed to upgrade to ver. 64", e); } } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } Log.i("Upgrade database from ver. " + oldVersion + " to ver. " + newVersion + ": completed"); }
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.i("Upgrade database from ver. " + oldVersion + " to ver. " + newVersion + ": start"); try { if (db.isReadOnly()) { return; } db.beginTransaction(); if (oldVersion <= 0) { // new table dropDatabase(db); onCreate(db); Log.i("Database structure created."); } if (oldVersion > 0) { db.execSQL("delete from " + dbTableCaches + " where reason = 0"); if (oldVersion < 52) { // upgrade to 52 try { db.execSQL(dbCreateSearchDestinationHistory); Log.i("Added table " + dbTableSearchDestionationHistory + "."); } catch (Exception e) { Log.e("Failed to upgrade to ver. 52", e); } } if (oldVersion < 53) { // upgrade to 53 try { db.execSQL("alter table " + dbTableCaches + " add column onWatchlist integer"); Log.i("Column onWatchlist added to " + dbTableCaches + "."); } catch (Exception e) { Log.e("Failed to upgrade to ver. 53", e); } } if (oldVersion < 54) { // update to 54 try { db.execSQL(dbCreateLogImages); } catch (Exception e) { Log.e("Failed to upgrade to ver. 54: " + e.toString()); } } if (oldVersion < 55) { // update to 55 try { db.execSQL("alter table " + dbTableCaches + " add column personal_note text"); } catch (Exception e) { Log.e("Failed to upgrade to ver. 55: " + e.toString()); } } // make all internal attribute names lowercase // @see issue #299 if (oldVersion < 56) { // update to 56 try { db.execSQL("update " + dbTableAttributes + " set attribute = " + "lower(attribute) where attribute like \"%_yes\" " + "or attribute like \"%_no\""); } catch (Exception e) { Log.e("Failed to upgrade to ver. 56: " + e.toString()); } } // Create missing indices. See issue #435 if (oldVersion < 57) { // update to 57 try { db.execSQL("drop index in_a"); db.execSQL("drop index in_b"); db.execSQL("drop index in_c"); db.execSQL("drop index in_d"); db.execSQL("drop index in_e"); db.execSQL("drop index in_f"); createIndices(db); } catch (Exception e) { Log.e("Failed to upgrade to ver. 57: " + e.toString()); } } if (oldVersion < 58) { // upgrade to 58 try { db.beginTransaction(); final String dbTableCachesTemp = dbTableCaches + "_temp"; final String dbCreateCachesTemp = "" + "create table " + dbTableCachesTemp + " (" + "_id integer primary key autoincrement, " + "updated long not null, " + "detailed integer not null default 0, " + "detailedupdate long, " + "visiteddate long, " + "geocode text unique not null, " + "reason integer not null default 0, " + "cacheid text, " + "guid text, " + "type text, " + "name text, " + "own integer not null default 0, " + "owner text, " + "owner_real text, " + "hidden long, " + "hint text, " + "size text, " + "difficulty float, " + "terrain float, " + "latlon text, " + "location text, " + "direction double, " + "distance double, " + "latitude double, " + "longitude double, " + "reliable_latlon integer, " + "elevation double, " + "personal_note text, " + "shortdesc text, " + "description text, " + "favourite_cnt integer, " + "rating float, " + "votes integer, " + "myvote float, " + "disabled integer not null default 0, " + "archived integer not null default 0, " + "members integer not null default 0, " + "found integer not null default 0, " + "favourite integer not null default 0, " + "inventorycoins integer default 0, " + "inventorytags integer default 0, " + "inventoryunknown integer default 0, " + "onWatchlist integer default 0 " + "); "; db.execSQL(dbCreateCachesTemp); db.execSQL("insert into " + dbTableCachesTemp + " select _id,updated,detailed,detailedupdate,visiteddate,geocode,reason,cacheid,guid,type,name,own,owner,owner_real," + "hidden,hint,size,difficulty,terrain,latlon,location,direction,distance,latitude,longitude, 0,elevation," + "personal_note,shortdesc,description,favourite_cnt,rating,votes,myvote,disabled,archived,members,found,favourite,inventorycoins," + "inventorytags,inventoryunknown,onWatchlist from " + dbTableCaches); db.execSQL("drop table " + dbTableCaches); db.execSQL("alter table " + dbTableCachesTemp + " rename to " + dbTableCaches); final String dbTableWaypointsTemp = dbTableWaypoints + "_temp"; final String dbCreateWaypointsTemp = "" + "create table " + dbTableWaypointsTemp + " (" + "_id integer primary key autoincrement, " + "geocode text not null, " + "updated long not null, " // date of save + "type text not null default 'waypoint', " + "prefix text, " + "lookup text, " + "name text, " + "latlon text, " + "latitude double, " + "longitude double, " + "note text " + "); "; db.execSQL(dbCreateWaypointsTemp); db.execSQL("insert into " + dbTableWaypointsTemp + " select _id, geocode, updated, type, prefix, lookup, name, latlon, latitude, longitude, note from " + dbTableWaypoints); db.execSQL("drop table " + dbTableWaypoints); db.execSQL("alter table " + dbTableWaypointsTemp + " rename to " + dbTableWaypoints); createIndices(db); db.setTransactionSuccessful(); Log.i("Removed latitude_string and longitude_string columns"); } catch (Exception e) { Log.e("Failed to upgrade to ver. 58", e); } finally { db.endTransaction(); } } if (oldVersion < 59) { try { // Add new indices and remove obsolete cache files createIndices(db); removeObsoleteCacheDirectories(db); } catch (Exception e) { Log.e("Failed to upgrade to ver. 59", e); } } if (oldVersion < 60) { try { removeSecEmptyDirs(); } catch (Exception e) { Log.e("Failed to upgrade to ver. 60", e); } } if (oldVersion < 61) { try { db.execSQL("alter table " + dbTableLogs + " add column friend integer"); db.execSQL("alter table " + dbTableCaches + " add column coordsChanged integer default 0"); } catch (Exception e) { Log.e("Failed to upgrade to ver. 61: " + e.toString()); } } // Introduces finalDefined on caches and own on waypoints if (oldVersion < 62) { try { db.execSQL("alter table " + dbTableCaches + " add column finalDefined integer default 0"); db.execSQL("alter table " + dbTableWaypoints + " add column own integer default 0"); db.execSQL("update " + dbTableWaypoints + " set own = 1 where type = 'own'"); } catch (Exception e) { Log.e("Failed to upgrade to ver. 62: " + e.toString()); } } if (oldVersion < 63) { try { removeDoubleUnderscoreMapFiles(); } catch (Exception e) { Log.e("Failed to upgrade to ver. 63: " + e.toString()); } } if (oldVersion < 64) { try { // No cache should ever be stored into the ALL_CACHES list. Here we use hardcoded list ids // rather than symbolic ones because the fix must be applied with the values at the time // of the problem. The problem was introduced in release 2012.06.01. db.execSQL("update " + dbTableCaches + " set reason=1 where reason=2"); } catch (Exception e) { Log.e("Failed to upgrade to ver. 64", e); } } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } Log.i("Upgrade database from ver. " + oldVersion + " to ver. " + newVersion + ": completed"); }
diff --git a/particlephysics/src/minecraft/pixlepix/particlephysics/common/entity/LeafParticle.java b/particlephysics/src/minecraft/pixlepix/particlephysics/common/entity/LeafParticle.java index 4bbe163..6236239 100644 --- a/particlephysics/src/minecraft/pixlepix/particlephysics/common/entity/LeafParticle.java +++ b/particlephysics/src/minecraft/pixlepix/particlephysics/common/entity/LeafParticle.java @@ -1,33 +1,33 @@ package pixlepix.particlephysics.common.entity; import net.minecraft.world.World; import pixlepix.particlephysics.common.api.BaseParticle; public class LeafParticle extends BaseParticle { public LeafParticle(World par1World) { super(par1World); } @Override public float getStartingPotential() { // TODO Auto-generated method stub return 500; } @Override public String getName() { // TODO Auto-generated method stub return "Leaf"; } @Override public void onCollideWithParticle(BaseParticle particle) { - if(!(particle instanceof LeafParticle)){ + if((!(particle instanceof LeafParticle))&&particle.effect!=2){ particle.potential*=0.5; particle.effect=2; } } }
true
true
public void onCollideWithParticle(BaseParticle particle) { if(!(particle instanceof LeafParticle)){ particle.potential*=0.5; particle.effect=2; } }
public void onCollideWithParticle(BaseParticle particle) { if((!(particle instanceof LeafParticle))&&particle.effect!=2){ particle.potential*=0.5; particle.effect=2; } }
diff --git a/netbout/netbout-hub/src/test/java/com/netbout/hub/predicates/xml/DomTextTest.java b/netbout/netbout-hub/src/test/java/com/netbout/hub/predicates/xml/DomTextTest.java index 413d2b4ac..a12335bce 100644 --- a/netbout/netbout-hub/src/test/java/com/netbout/hub/predicates/xml/DomTextTest.java +++ b/netbout/netbout-hub/src/test/java/com/netbout/hub/predicates/xml/DomTextTest.java @@ -1,124 +1,132 @@ /** * Copyright (c) 2009-2011, netBout.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are PROHIBITED without prior written permission from * the author. This product may NOT be used anywhere and on any computer * except the server platform of netBout Inc. located at www.netbout.com. * Federal copyright law prohibits unauthorized reproduction by any means * and imposes fines up to $25,000 for violation. If you received * this code occasionally and without intent to use it, please report this * incident to the author by email. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package com.netbout.hub.predicates.xml; import com.netbout.hub.Hub; import com.netbout.hub.HubMocker; import com.rexsl.test.ContainerMocker; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; /** * Test case of {@link DomText}. * @author Yegor Bugayenko ([email protected]) * @version $Id$ */ public final class DomTextTest { /** * URL of XSD schema. */ private transient String xsd; /** * Valid XML document. */ private transient String xml; /** * Prepare a provider of XSD schema. * @throws Exception If there is some problem inside */ @Before public void prepareXsd() throws Exception { + final String schema = + // @checkstyle StringLiteralsConcatenation (3 lines) + "<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'" + + " xmlns:p='foo' targetNamespace='foo'" + + " elementFormDefault='qualified'>" + + "<xs:element name='root' type='p:main'/>" + + "<xs:complexType name='main'>" + + "<xs:sequence>" + + "<xs:element name='alpha' type='xs:string' />" + + "</xs:sequence>" + + "</xs:complexType>" + + "</xs:schema>"; this.xsd = new ContainerMocker() .expectMethod(Matchers.equalTo("GET")) - .returnBody( - // @checkstyle StringLiteralsConcatenation (3 lines) - "<schema xmlns='http://www.w3.org/2001/XMLSchema'" - + " xmlns:foo='foo' targetNamespace='foo'>" - + "<element name='root'/></schema>" - ) + .returnBody(schema) .returnHeader("Content-Type", "application/xml") .mock() .home() .toURL() .toString(); // @checkstyle StringLiteralsConcatenation (4 lines) this.xml = "<root xmlns='foo'" + " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" + String.format(" xsi:schemaLocation='foo %s'", this.xsd) - + "/>"; + + "><alpha>xxx</alpha></root>"; + System.out.println(this.xml); } /** * DomText can detect an XML document. * @throws Exception If there is some problem inside */ @Test public void positivelyMatchesXmlDocument() throws Exception { MatcherAssert.assertThat("it's an XML", new DomText("<root/>").isXml()); MatcherAssert.assertThat("it's not", !new DomText("test").isXml()); } /** * DomText can detect a namespace of XML document. * @throws Exception If there is some problem inside */ @Test public void detectsNamespaceOfXmlDocument() throws Exception { MatcherAssert.assertThat( new DomText(this.xml).namespace(), Matchers.equalTo("foo") ); } /** * DomText can validate a document through helpers. * @throws Exception If there is some problem inside */ @Test public void validatesCorrectDocument() throws Exception { final Hub hub = new HubMocker() .doReturn(this.xsd, "resolve-xml-namespace") .mock(); new DomText(this.xml).validate(hub); } /** * DomText throws exception for invalid document. * @throws Exception If there is some problem inside */ @Test(expected = DomValidationException.class) public void validatesIncorrectDocument() throws Exception { final Hub hub = new HubMocker().mock(); new DomText("<some-document/>").validate(hub); } }
false
true
public void prepareXsd() throws Exception { this.xsd = new ContainerMocker() .expectMethod(Matchers.equalTo("GET")) .returnBody( // @checkstyle StringLiteralsConcatenation (3 lines) "<schema xmlns='http://www.w3.org/2001/XMLSchema'" + " xmlns:foo='foo' targetNamespace='foo'>" + "<element name='root'/></schema>" ) .returnHeader("Content-Type", "application/xml") .mock() .home() .toURL() .toString(); // @checkstyle StringLiteralsConcatenation (4 lines) this.xml = "<root xmlns='foo'" + " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" + String.format(" xsi:schemaLocation='foo %s'", this.xsd) + "/>"; }
public void prepareXsd() throws Exception { final String schema = // @checkstyle StringLiteralsConcatenation (3 lines) "<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'" + " xmlns:p='foo' targetNamespace='foo'" + " elementFormDefault='qualified'>" + "<xs:element name='root' type='p:main'/>" + "<xs:complexType name='main'>" + "<xs:sequence>" + "<xs:element name='alpha' type='xs:string' />" + "</xs:sequence>" + "</xs:complexType>" + "</xs:schema>"; this.xsd = new ContainerMocker() .expectMethod(Matchers.equalTo("GET")) .returnBody(schema) .returnHeader("Content-Type", "application/xml") .mock() .home() .toURL() .toString(); // @checkstyle StringLiteralsConcatenation (4 lines) this.xml = "<root xmlns='foo'" + " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" + String.format(" xsi:schemaLocation='foo %s'", this.xsd) + "><alpha>xxx</alpha></root>"; System.out.println(this.xml); }
diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/admin/ShowBackgroundThreadsController.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/admin/ShowBackgroundThreadsController.java index f8241ca6b..0dacad944 100644 --- a/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/admin/ShowBackgroundThreadsController.java +++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/controller/admin/ShowBackgroundThreadsController.java @@ -1,97 +1,97 @@ /* $This file is distributed under the terms of the license in /doc/license.txt$ */ package edu.cornell.mannlib.vitro.webapp.controller.admin; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import com.ibm.icu.text.SimpleDateFormat; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerHttpServlet; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues; import edu.cornell.mannlib.vitro.webapp.utils.threads.VitroBackgroundThread; /** * Show the list of living background threads (instances of * VitroBackgroundThread), and their status. */ public class ShowBackgroundThreadsController extends FreemarkerHttpServlet { private static final String TEMPLATE_NAME = "admin-showThreads.ftl"; private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; @Override - protected ResponseValues processRequest(VitroRequest vreq) throws Exception { + protected ResponseValues processRequest(VitroRequest vreq) throws ExceptionXX { SortedMap<String, ThreadInfo> threadMap = new TreeMap<String, ThreadInfo>(); for (VitroBackgroundThread thread : VitroBackgroundThread .getLivingThreads()) { ThreadInfo threadInfo = getThreadInfo(thread); threadMap.put(threadInfo.getName(), threadInfo); } Map<String, Object> bodyMap = new HashMap<String, Object>(); bodyMap.put("threads", new ArrayList<ThreadInfo>(threadMap.values())); return new TemplateResponseValues(TEMPLATE_NAME, bodyMap); } private ThreadInfo getThreadInfo(VitroBackgroundThread thread) { try { String name = thread.getName(); String workLevel = String.valueOf(thread.getWorkLevel().getLevel()); String since = formatDate(thread.getWorkLevel().getSince()); String flags = String.valueOf(thread.getWorkLevel().getFlags()); return new ThreadInfo(name, workLevel, since, flags); } catch (Exception e) { return new ThreadInfo("UNKNOWN THREAD", "UNKNOWN", "UNKNOWN", e.toString()); } } private String formatDate(Date since) { return new SimpleDateFormat(DATE_FORMAT).format(since); } public static class ThreadInfo { private final String name; private final String workLevel; private final String since; private final String flags; public ThreadInfo(String name, String workLevel, String since, String flags) { this.name = name; this.workLevel = workLevel; this.since = since; this.flags = flags; } public String getName() { return name; } public String getWorkLevel() { return workLevel; } public String getSince() { return since; } public String getFlags() { return flags; } } }
true
true
protected ResponseValues processRequest(VitroRequest vreq) throws Exception { SortedMap<String, ThreadInfo> threadMap = new TreeMap<String, ThreadInfo>(); for (VitroBackgroundThread thread : VitroBackgroundThread .getLivingThreads()) { ThreadInfo threadInfo = getThreadInfo(thread); threadMap.put(threadInfo.getName(), threadInfo); } Map<String, Object> bodyMap = new HashMap<String, Object>(); bodyMap.put("threads", new ArrayList<ThreadInfo>(threadMap.values())); return new TemplateResponseValues(TEMPLATE_NAME, bodyMap); }
protected ResponseValues processRequest(VitroRequest vreq) throws ExceptionXX { SortedMap<String, ThreadInfo> threadMap = new TreeMap<String, ThreadInfo>(); for (VitroBackgroundThread thread : VitroBackgroundThread .getLivingThreads()) { ThreadInfo threadInfo = getThreadInfo(thread); threadMap.put(threadInfo.getName(), threadInfo); } Map<String, Object> bodyMap = new HashMap<String, Object>(); bodyMap.put("threads", new ArrayList<ThreadInfo>(threadMap.values())); return new TemplateResponseValues(TEMPLATE_NAME, bodyMap); }
diff --git a/slickij-data/src/main/java/org/tcrun/slickij/data/TestplanResourceImpl.java b/slickij-data/src/main/java/org/tcrun/slickij/data/TestplanResourceImpl.java index 2241931..4d16e6e 100644 --- a/slickij-data/src/main/java/org/tcrun/slickij/data/TestplanResourceImpl.java +++ b/slickij-data/src/main/java/org/tcrun/slickij/data/TestplanResourceImpl.java @@ -1,335 +1,335 @@ package org.tcrun.slickij.data; import com.google.code.morphia.query.Query; import com.google.inject.Inject; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; import org.bson.types.ObjectId; import org.tcrun.slickij.api.TestplanResource; import org.tcrun.slickij.api.data.Build; import org.tcrun.slickij.api.data.Configuration; import org.tcrun.slickij.api.data.ConfigurationOverride; import org.tcrun.slickij.api.data.DataDrivenPropertyType; import org.tcrun.slickij.api.data.DataExtension; import org.tcrun.slickij.api.data.InvalidDataError; import org.tcrun.slickij.api.data.Project; import org.tcrun.slickij.api.data.Release; import org.tcrun.slickij.api.data.Result; import org.tcrun.slickij.api.data.ResultStatus; import org.tcrun.slickij.api.data.RunStatus; import org.tcrun.slickij.api.data.Testcase; import org.tcrun.slickij.api.data.Testplan; import org.tcrun.slickij.api.data.TestplanRunParameters; import org.tcrun.slickij.api.data.Testrun; import org.tcrun.slickij.api.data.testqueries.NamedTestcaseQuery; import org.tcrun.slickij.api.data.dao.ConfigurationDAO; import org.tcrun.slickij.api.data.dao.ProjectDAO; import org.tcrun.slickij.api.data.dao.ResultDAO; import org.tcrun.slickij.api.data.dao.TestcaseDAO; import org.tcrun.slickij.api.data.dao.TestplanDAO; import org.tcrun.slickij.api.data.dao.TestrunDAO; /** * * @author jcorbett */ public class TestplanResourceImpl implements TestplanResource { TestplanDAO m_testplanDAO; TestcaseDAO m_testcaseDAO; TestrunDAO m_testrunDAO; ProjectDAO m_projectDAO; ResultDAO m_resultDAO; ConfigurationDAO m_configDAO; @Inject public TestplanResourceImpl(TestplanDAO p_testplanDAO, ProjectDAO p_projectDAO, TestcaseDAO p_testcaseDAO, TestrunDAO p_testrunDAO, ResultDAO p_resultDAO, ConfigurationDAO p_configDAO) { m_testplanDAO = p_testplanDAO; m_projectDAO = p_projectDAO; m_testcaseDAO = p_testcaseDAO; m_testrunDAO = p_testrunDAO; m_resultDAO = p_resultDAO; m_configDAO = p_configDAO; } @Override public List<Testplan> getTestPlans(String projectid, UriInfo uriInfo) { MultivaluedMap<String, String> params = uriInfo.getQueryParameters(); if(params.containsKey("username")) return getTestPlans(projectid, uriInfo.getQueryParameters().getFirst("username")); ObjectId projectId = null; Query<Testplan> query = m_testplanDAO.createQuery(); try { projectId = new ObjectId(projectid); query.criteria("project.id").equal(projectId); } catch(RuntimeException ex) { throw new WebApplicationException(ex, Status.BAD_REQUEST); } if(params.containsKey("createdby")) { query.criteria("createdBy").equal(params.getFirst("createdby")); } return query.asList(); } public List<Testplan> getTestPlans(String projectid, String username) { ObjectId projectId = null; try { projectId = new ObjectId(projectid); } catch(RuntimeException ex) { throw new WebApplicationException(ex, Status.BAD_REQUEST); } return m_testplanDAO.getAllTestplansForUser(projectId, username); } @Override public Testplan getTestPlan(String testplanId) { Testplan plan = m_testplanDAO.get(new ObjectId(testplanId)); if(plan == null) throw new WebApplicationException(new Exception("Cannot find testplan with id " + testplanId), Status.NOT_FOUND); return plan; } @Override public Testplan addNewTestplan(Testplan testplan) { try { testplan.validate(); } catch(InvalidDataError error) { throw new WebApplicationException(error, Status.BAD_REQUEST); } Project project = m_projectDAO.findByReference(testplan.getProject()); if(project == null) throw new WebApplicationException(new Exception("Cannot find project."), Status.BAD_REQUEST); m_testplanDAO.save(testplan); return testplan; } @Override public Testplan updateTestplan(String testplanId, Testplan update) { Testplan plan = getTestPlan(testplanId); if(update.getName() != null && !update.getName().equals("") && !update.getName().equals(plan.getName())) plan.setName(update.getName()); if(update.getCreatedBy() != null && !update.getCreatedBy().equals("") && !update.getCreatedBy().equals(plan.getCreatedBy())) plan.setCreatedBy(update.getCreatedBy()); if(update.getIsprivate() != null && !update.getIsprivate().equals(plan.getIsprivate())) plan.setIsprivate(update.getIsprivate()); if(update.getProject() != null) { Project project = m_projectDAO.findByReference(update.getProject()); if(project != null) plan.setProject(update.getProject()); else throw new WebApplicationException(new Exception("Unable to find project with id '" + update.getProject().getId() + "' and name '" + update.getProject().getName() + "'"), Status.BAD_REQUEST); } if(update.getSharedWith() != null) plan.setSharedWith(update.getSharedWith()); if(update.getQueries() != null) plan.setQueries(update.getQueries()); m_testplanDAO.save(plan); return plan; } @Override public Testrun runTestPlan(String testplanId) { Testplan plan = getTestPlan(testplanId); List<Testcase> testcases = getTestcases(plan); Testrun run = new Testrun(); run.setProject(plan.getProject()); run.setTestplanId(plan.getObjectId()); run.setName("Testrun for testplan " + plan.getName()); run.setDateCreated(new Date()); Project project = m_projectDAO.findByReference(plan.getProject()); if(project != null) { Release release = project.findRelease(project.getDefaultRelease()); if(release != null) { run.setRelease(release.createReference()); Build build = release.findBuild(release.getDefaultBuild()); if(build != null) run.setBuild(build.createReference()); } } m_testrunDAO.save(run); for(Testcase test : testcases) { Result result = new Result(); result.setTestcase(test.createReference()); result.setProject(test.getProject()); result.setStatus(ResultStatus.NO_RESULT); result.setRunstatus(RunStatus.TO_BE_RUN); result.setComponent(test.getComponent()); result.setTestrun(run.createReference()); result.setRelease(run.getRelease()); result.setBuild(run.getBuild()); m_resultDAO.save(result); } return run; } @Override public Testrun runTestPlan(String testplanId, TestplanRunParameters parameters) { Testplan plan = getTestPlan(testplanId); List<Testcase> testcases = getTestcases(plan); Date date = new Date(); Testrun run = new Testrun(); run.setProject(plan.getProject()); run.setTestplanId(plan.getObjectId()); run.setName("Testrun for testplan " + plan.getName()); run.setDateCreated(date); if(parameters.getConfig() != null) { Configuration config = m_configDAO.findConfigurationByReference(parameters.getConfig()); if(config != null) run.setConfig(parameters.getConfig()); else throw new NotFoundError(Configuration.class); } Project project = m_projectDAO.findByReference(plan.getProject()); if(project != null) { if(parameters.getRelease() != null) { Release release = project.findReleaseByReference(parameters.getRelease()); if(release != null) { run.setRelease(parameters.getRelease()); if(parameters.getBuild() != null) { Build build = release.findBuildByReference(parameters.getBuild()); if(build != null) run.setBuild(parameters.getBuild()); } } } } m_testrunDAO.save(run); for(Testcase test : testcases) { Result result = new Result(); result.setTestcase(test.createReference()); if(parameters.getOverrides() != null) { for(ConfigurationOverride override : parameters.getOverrides()) { - for(DataDrivenPropertyType ddtype : test.getDataDriven()) - { - if(override.getKey().equals(ddtype.getName())) - { + //for(DataDrivenPropertyType ddtype : test.getDataDriven()) + //{ + //if(override.getKey().equals(ddtype.getName())) + //{ if(result.getConfigurationOverride() == null) result.setConfigurationOverride(new ArrayList<ConfigurationOverride>()); result.getConfigurationOverride().add(override); - } - } + //} + //} } } if(parameters.getConfig() != null) result.setConfig(parameters.getConfig()); result.setProject(test.getProject()); result.setStatus(ResultStatus.NO_RESULT); result.setRunstatus(RunStatus.TO_BE_RUN); result.setComponent(test.getComponent()); result.setTestrun(run.createReference()); result.setRelease(run.getRelease()); result.setBuild(run.getBuild()); m_resultDAO.save(result); } return run; } protected List<Testcase> getTestcases(Testplan plan) { List<Testcase> tests = new ArrayList<Testcase>(); for(NamedTestcaseQuery query : plan.getQueries()) tests.addAll(m_testcaseDAO.findTestsByTestcaseQuery(query.getQuery())); return tests; } @Override public List<Testcase> getTestcases(String testplanId) { Testplan plan = getTestPlan(testplanId); return getTestcases(plan); } @Override public void deleteTestplan(String testplanId) { m_testplanDAO.deleteById(new ObjectId(testplanId)); } @Override public DataExtension<Testplan> addDataExtension(String testplanId, DataExtension<Testplan> dataExtension) { Testplan testplan = getTestPlan(testplanId); try { dataExtension.validate(); } catch(InvalidDataError ex) { throw new WebApplicationException(ex, Status.BAD_REQUEST); } testplan.getExtensions().add(dataExtension); m_testplanDAO.save(testplan); return dataExtension; } protected DataExtension<Testplan> findDataExtension(Testplan testplan, String extensionId) { DataExtension<Testplan> extension = null; for(DataExtension<Testplan> potential : testplan.getExtensions()) { if(extensionId.equals(potential.getId())) { extension = potential; break; } } if(extension == null) throw new WebApplicationException(new Exception("Cannot find extension with id " + extensionId), Status.NOT_FOUND); return extension; } @Override public DataExtension<Testplan> updateDataExtension(String testplanId, String extensionId, DataExtension<Testplan> dataExtension) { Testplan testplan = getTestPlan(testplanId); DataExtension<Testplan> extension = findDataExtension(testplan, extensionId); extension.update(dataExtension); m_testplanDAO.save(testplan); return extension; } @Override public List<DataExtension<Testplan>> deleteDataExtension(String testplanId, String extensionId) { Testplan testplan = getTestPlan(testplanId); DataExtension<Testplan> extension = findDataExtension(testplan, extensionId); testplan.getExtensions().remove(extension); m_testplanDAO.save(testplan); return testplan.getExtensions(); } }
false
true
public Testrun runTestPlan(String testplanId, TestplanRunParameters parameters) { Testplan plan = getTestPlan(testplanId); List<Testcase> testcases = getTestcases(plan); Date date = new Date(); Testrun run = new Testrun(); run.setProject(plan.getProject()); run.setTestplanId(plan.getObjectId()); run.setName("Testrun for testplan " + plan.getName()); run.setDateCreated(date); if(parameters.getConfig() != null) { Configuration config = m_configDAO.findConfigurationByReference(parameters.getConfig()); if(config != null) run.setConfig(parameters.getConfig()); else throw new NotFoundError(Configuration.class); } Project project = m_projectDAO.findByReference(plan.getProject()); if(project != null) { if(parameters.getRelease() != null) { Release release = project.findReleaseByReference(parameters.getRelease()); if(release != null) { run.setRelease(parameters.getRelease()); if(parameters.getBuild() != null) { Build build = release.findBuildByReference(parameters.getBuild()); if(build != null) run.setBuild(parameters.getBuild()); } } } } m_testrunDAO.save(run); for(Testcase test : testcases) { Result result = new Result(); result.setTestcase(test.createReference()); if(parameters.getOverrides() != null) { for(ConfigurationOverride override : parameters.getOverrides()) { for(DataDrivenPropertyType ddtype : test.getDataDriven()) { if(override.getKey().equals(ddtype.getName())) { if(result.getConfigurationOverride() == null) result.setConfigurationOverride(new ArrayList<ConfigurationOverride>()); result.getConfigurationOverride().add(override); } } } } if(parameters.getConfig() != null) result.setConfig(parameters.getConfig()); result.setProject(test.getProject()); result.setStatus(ResultStatus.NO_RESULT); result.setRunstatus(RunStatus.TO_BE_RUN); result.setComponent(test.getComponent()); result.setTestrun(run.createReference()); result.setRelease(run.getRelease()); result.setBuild(run.getBuild()); m_resultDAO.save(result); } return run; }
public Testrun runTestPlan(String testplanId, TestplanRunParameters parameters) { Testplan plan = getTestPlan(testplanId); List<Testcase> testcases = getTestcases(plan); Date date = new Date(); Testrun run = new Testrun(); run.setProject(plan.getProject()); run.setTestplanId(plan.getObjectId()); run.setName("Testrun for testplan " + plan.getName()); run.setDateCreated(date); if(parameters.getConfig() != null) { Configuration config = m_configDAO.findConfigurationByReference(parameters.getConfig()); if(config != null) run.setConfig(parameters.getConfig()); else throw new NotFoundError(Configuration.class); } Project project = m_projectDAO.findByReference(plan.getProject()); if(project != null) { if(parameters.getRelease() != null) { Release release = project.findReleaseByReference(parameters.getRelease()); if(release != null) { run.setRelease(parameters.getRelease()); if(parameters.getBuild() != null) { Build build = release.findBuildByReference(parameters.getBuild()); if(build != null) run.setBuild(parameters.getBuild()); } } } } m_testrunDAO.save(run); for(Testcase test : testcases) { Result result = new Result(); result.setTestcase(test.createReference()); if(parameters.getOverrides() != null) { for(ConfigurationOverride override : parameters.getOverrides()) { //for(DataDrivenPropertyType ddtype : test.getDataDriven()) //{ //if(override.getKey().equals(ddtype.getName())) //{ if(result.getConfigurationOverride() == null) result.setConfigurationOverride(new ArrayList<ConfigurationOverride>()); result.getConfigurationOverride().add(override); //} //} } } if(parameters.getConfig() != null) result.setConfig(parameters.getConfig()); result.setProject(test.getProject()); result.setStatus(ResultStatus.NO_RESULT); result.setRunstatus(RunStatus.TO_BE_RUN); result.setComponent(test.getComponent()); result.setTestrun(run.createReference()); result.setRelease(run.getRelease()); result.setBuild(run.getBuild()); m_resultDAO.save(result); } return run; }
diff --git a/org.springsource.loaded/src/main/java/org/springsource/loaded/NameRegistry.java b/org.springsource.loaded/src/main/java/org/springsource/loaded/NameRegistry.java index 749484d..4976634 100644 --- a/org.springsource.loaded/src/main/java/org/springsource/loaded/NameRegistry.java +++ b/org.springsource.loaded/src/main/java/org/springsource/loaded/NameRegistry.java @@ -1,101 +1,101 @@ /* * Copyright 2010-2012 VMware and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springsource.loaded; /** * Manages a mapping of names to numbers. The same number anywhere means the same name. This means that if some type a/b/C has been * loaded in two places (by different classloaders), it will have the same number in both. Only one of those a/b/C types will be * visible at the location in question, the tricky part could be working out which one (if classloaders are being naughty) but in * theory the first time we get confused (due to finding the name twice), we can work out which one is right and use that mapping * from then on. * * @author Andy Clement * @since 0.8.1 */ public class NameRegistry { private static int nextTypeId = 0; private static int size = 10; private static String[] allocatedIds = new String[size]; private NameRegistry() { } /** * Typically used by tests to ensure it looks like a fresh NameRegistry is being used. */ public static void reset() { nextTypeId = 0; size = 10; allocatedIds = new String[size]; } /** * Return the id for a particular type. This method will not allocate a new id if the type is unknown, it will return -1 * instead. * * @param slashedClassName a type name like java/lang/String * @return the allocated ID for that type or -1 if unknown */ public static int getIdFor(String slashedClassName) { assert Asserts.assertNotDotted(slashedClassName); for (int i = 0; i < nextTypeId; i++) { if (allocatedIds[i].equals(slashedClassName)) { return i; } } return -1; } /** * Return the id for a particular type. This method will not allocate a new id if the type is unknown, it will return -1 * instead. * * @param slashedClassName a type name like java/lang/String * @return the allocated ID for that type or -1 if unknown */ public static int getIdOrAllocateFor(String slashedClassName) { int id = getIdFor(slashedClassName); if (id == -1) { id = allocateId(slashedClassName); } return id; } private synchronized static int allocateId(String slashedClassName) { // Check again, in case two threads passed the -1 check in the getIdOrAllocateFor method int id = getIdFor(slashedClassName); if (id == -1) { id = nextTypeId++; - if (id >= allocatedIds.length) { + if (nextTypeId >= allocatedIds.length) { size = size + 10; // need to make more room String[] newAllocatedIds = new String[size]; System.arraycopy(allocatedIds, 0, newAllocatedIds, 0, allocatedIds.length); allocatedIds = newAllocatedIds; } allocatedIds[id] = slashedClassName; } return id; } public static String getTypenameById(int typeId) { if (typeId > size) { return null; } return allocatedIds[typeId]; } }
true
true
private synchronized static int allocateId(String slashedClassName) { // Check again, in case two threads passed the -1 check in the getIdOrAllocateFor method int id = getIdFor(slashedClassName); if (id == -1) { id = nextTypeId++; if (id >= allocatedIds.length) { size = size + 10; // need to make more room String[] newAllocatedIds = new String[size]; System.arraycopy(allocatedIds, 0, newAllocatedIds, 0, allocatedIds.length); allocatedIds = newAllocatedIds; } allocatedIds[id] = slashedClassName; } return id; }
private synchronized static int allocateId(String slashedClassName) { // Check again, in case two threads passed the -1 check in the getIdOrAllocateFor method int id = getIdFor(slashedClassName); if (id == -1) { id = nextTypeId++; if (nextTypeId >= allocatedIds.length) { size = size + 10; // need to make more room String[] newAllocatedIds = new String[size]; System.arraycopy(allocatedIds, 0, newAllocatedIds, 0, allocatedIds.length); allocatedIds = newAllocatedIds; } allocatedIds[id] = slashedClassName; } return id; }
diff --git a/bundles/org.eclipse.e4.tools.css.spy/src/org/eclipse/e4/tools/css/spy/CssSpyDialog.java b/bundles/org.eclipse.e4.tools.css.spy/src/org/eclipse/e4/tools/css/spy/CssSpyDialog.java index 2465e5be..e2ad3583 100644 --- a/bundles/org.eclipse.e4.tools.css.spy/src/org/eclipse/e4/tools/css/spy/CssSpyDialog.java +++ b/bundles/org.eclipse.e4.tools.css.spy/src/org/eclipse/e4/tools/css/spy/CssSpyDialog.java @@ -1,840 +1,839 @@ /******************************************************************************* * Copyright (c) 2011, 2012 Manumitting Technologies, Inc. * 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: * Brian de Alwis (MT) - initial API and implementation *******************************************************************************/ package org.eclipse.e4.tools.css.spy; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.e4.ui.css.core.dom.CSSStylableElement; import org.eclipse.e4.ui.css.core.engine.CSSEngine; import org.eclipse.e4.ui.css.swt.dom.WidgetElement; import org.eclipse.e4.ui.css.swt.engine.CSSSWTEngineImpl; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.layout.TableColumnLayout; import org.eclipse.jface.layout.TreeColumnLayout; import org.eclipse.jface.viewers.CellEditor; import org.eclipse.jface.viewers.ColumnLabelProvider; import org.eclipse.jface.viewers.ColumnViewerEditor; import org.eclipse.jface.viewers.ColumnViewerEditorActivationStrategy; import org.eclipse.jface.viewers.ColumnViewerToolTipSupport; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.EditingSupport; import org.eclipse.jface.viewers.FocusCellOwnerDrawHighlighter; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.jface.viewers.TableViewerEditor; import org.eclipse.jface.viewers.TableViewerFocusCellManager; import org.eclipse.jface.viewers.TextCellEditor; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.TreeViewerColumn; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerComparator; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseMoveListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.graphics.Region; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.ToolItem; import org.eclipse.swt.widgets.Widget; import org.w3c.css.sac.CSSParseException; import org.w3c.css.sac.SelectorList; import org.w3c.dom.NodeList; import org.w3c.dom.css.CSSStyleDeclaration; public class CssSpyDialog extends Dialog { /** @return the CSS element corresponding to the argument, or null if none */ public static CSSStylableElement getCSSElement(Object o) { if (o instanceof CSSStylableElement) { return (CSSStylableElement) o; } else { CSSEngine engine = getCSSEngine(o); if (engine != null) { return (CSSStylableElement) engine.getElement(o); } } return null; } /** @return the CSS engine governing the argument, or null if none */ public static CSSEngine getCSSEngine(Object o) { CSSEngine engine = null; if (o instanceof CSSStylableElement) { CSSStylableElement element = (CSSStylableElement) o; engine = WidgetElement.getEngine((Widget) element.getNativeWidget()); } if (engine == null && o instanceof Widget) { if (((Widget) o).isDisposed()) { return null; } engine = WidgetElement.getEngine((Widget) o); } if (engine == null && Display.getCurrent() != null) { engine = new CSSSWTEngineImpl(Display.getCurrent()); } return engine; } private Display display; private Widget specimen; private Widget shown; private TreeViewer widgetTreeViewer; private WidgetTreeProvider widgetTreeProvider; private Button showAllShells; private TableViewer cssPropertiesViewer; private Text cssRules; private List<Shell> highlights = new LinkedList<Shell>(); private List<Region> highlightRegions = new LinkedList<Region>(); private Text cssSearchBox; private Button showUnsetProperties; protected ViewerFilter unsetPropertyFilter = new ViewerFilter() { @Override public boolean select(Viewer viewer, Object parentElement, Object element) { if (element instanceof CSSPropertyProvider) { try { return ((CSSPropertyProvider) element).getValue() != null; } catch (Exception e) { return false; } } return false; } }; /** * Create the dialog. * * @param parentShell */ public CssSpyDialog(Shell parentShell) { super(parentShell); display = parentShell.getDisplay(); setShellStyle(SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX); } protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText("CSS Spy"); } public Widget getSpecimen() { return specimen; } private boolean isLive() { return specimen == null; } public void setSpecimen(Widget specimen) { this.specimen = specimen; update(); } private Widget getActiveSpecimen() { if (specimen != null) { return specimen; } return display.getCursorControl(); } protected boolean shouldDismissOnLostFocus() { return false; } protected void update() { if (getShell() == null) { return; } Widget current = getActiveSpecimen(); if (shown == current) { return; } shown = current; CSSEngine engine = getCSSEngine(shown); CSSStylableElement element = (CSSStylableElement) engine .getElement(shown); if (element == null) { return; } updateWidgetTreeInput(); revealAndSelect(Collections.singletonList(shown)); } private <T> void revealAndSelect(List<T> elements) { widgetTreeViewer.setSelection(new StructuredSelection(elements), true); } private void updateForWidgetSelection(ISelection sel) { disposeHighlights(); if (sel.isEmpty()) { return; } StructuredSelection selection = (StructuredSelection) sel; for (Object s : selection.toList()) { if (s instanceof Widget) { highlightWidget((Widget) s); } } populate(selection.size() == 1 && selection.getFirstElement() instanceof Widget ? (Widget) selection .getFirstElement() : null); } private void updateWidgetTreeInput() { if (showAllShells.getSelection()) { widgetTreeViewer.setInput(display); } else { widgetTreeViewer .setInput(new Object[] { shown instanceof Control ? ((Control) shown) .getShell() : shown }); } performCSSSearch(new NullProgressMonitor()); } protected void populate(Widget selected) { if (selected == null) { cssPropertiesViewer.setInput(null); cssRules.setText(""); return; } if (selected.isDisposed()) { cssPropertiesViewer.setInput(null); cssRules.setText("*DISPOSED*"); return; } CSSStylableElement element = getCSSElement(selected); if (element == null) { cssPropertiesViewer.setInput(null); cssRules.setText("Not a stylable element"); return; } cssPropertiesViewer.setInput(selected); StringBuilder sb = new StringBuilder(); CSSEngine engine = getCSSEngine(element); CSSStyleDeclaration decl = engine.getViewCSS().getComputedStyle( element, null); if (element.getCSSStyle() != null) { sb.append("\nCSS Inline Style(s):\n "); Activator.join(sb, element.getCSSStyle().split(";"), ";\n "); } if (decl != null) { sb.append("\n\nCSS Properties:\n"); try { if (decl != null) { sb.append(decl.getCssText()); } } catch (Throwable e) { sb.append(e); } } if (element.getStaticPseudoInstances().length > 0) { sb.append("\n\nStatic Pseudoinstances:\n "); Activator.join(sb, element.getStaticPseudoInstances(), "\n "); } if (element.getCSSClass() != null) { sb.append("\n\nCSS Classes:\n "); Activator.join(sb, element.getCSSClass().split(" +"), "\n "); } if (element.getAttribute("style") != null) { sb.append("\n\nSWT Style Bits:\n "); Activator.join(sb, element.getAttribute("style").split(" +"), "\n "); } sb.append("\n\nCSS Class Element:\n ").append( element.getClass().getName()); // this is useful for diagnosing issues if (element.getNativeWidget() instanceof Composite) { sb.append("\n\nSWT Layout: ").append( ((Composite) element.getNativeWidget()).getLayout()); } Rectangle bounds = getBounds(selected); if (bounds != null) { sb.append("\nBounds: x=").append(bounds.x).append(" y=") .append(bounds.y); sb.append(" h=").append(bounds.height).append(" w=") .append(bounds.width); } if (element.getNativeWidget() instanceof Widget) { Widget w = (Widget) element.getNativeWidget(); if (w.getData() != null) { sb.append("\nWidget data: ").append(w.getData()); } if (w.getData(SWT.SKIN_ID) != null) { sb.append("\nWidget Skin ID (").append(SWT.SKIN_ID) .append("): ").append(w.getData(SWT.SKIN_ID)); } if (w.getData(SWT.SKIN_CLASS) != null) { sb.append("\nWidget Skin Class (").append(SWT.SKIN_CLASS) .append("): ").append(w.getData(SWT.SKIN_CLASS)); } } cssRules.setText(sb.toString().trim()); disposeHighlights(); highlightWidget(selected); } private Shell getShell(Widget widget) { if (widget instanceof Control) { return ((Control) widget).getShell(); } return null; } /** Add a highlight-rectangle for the selected widget */ private void highlightWidget(Widget selected) { if (selected == null || selected.isDisposed()) { return; } Rectangle bounds = getBounds(selected); // relative to absolute display, // not the widget if (bounds == null /* || bounds.height == 0 || bounds.width == 0 */) { return; } // emulate a transparent background as per SWT Snippet180 Shell selectedShell = getShell(selected); if (selectedShell != null) { // bounds = slectedShell.getDisplay().map(null, selectedShell, // bounds); } Shell highlight = new Shell(selectedShell, SWT.NO_TRIM | SWT.MODELESS); // appears // on // top highlight.setBackground(display.getSystemColor(SWT.COLOR_RED)); Region highlightRegion = new Region(); highlightRegion.add(0, 0, 1, bounds.height + 2); highlightRegion.add(0, 0, bounds.width + 2, 1); highlightRegion.add(bounds.width + 1, 0, 1, bounds.height + 2); highlightRegion.add(0, bounds.height + 1, bounds.width + 2, 1); highlight.setRegion(highlightRegion); highlight.setBounds(bounds.x - 1, bounds.y - 1, bounds.width + 2, bounds.height + 2); highlight.setEnabled(false); highlight.setVisible(true); // not open(): setVisible() prevents taking // focus highlights.add(highlight); highlightRegions.add(highlightRegion); } private void disposeHighlights() { for (Shell highlight : highlights) { highlight.dispose(); } highlights.clear(); for (Region region : highlightRegions) { region.dispose(); } highlightRegions.clear(); } private Rectangle getBounds(Widget widget) { if (widget instanceof Shell) { // Shell bounds are already in display coordinates return ((Shell) widget).getBounds(); } else if (widget instanceof Control) { Control control = (Control) widget; Rectangle bounds = control.getBounds(); return control.getDisplay().map(control.getParent(), null, bounds); } else if (widget instanceof ToolItem) { ToolItem item = (ToolItem) widget; Rectangle bounds = item.getBounds(); return item.getDisplay().map(item.getParent(), null, bounds); } else if (widget instanceof CTabItem) { CTabItem item = (CTabItem) widget; Rectangle bounds = item.getBounds(); return item.getDisplay().map(item.getParent(), null, bounds); } // FIXME: figure out how to map items to a position return null; } /** * Create contents of the dialog. * * @param parent */ @Override protected Control createDialogArea(Composite parent) { Composite outer = (Composite) super.createDialogArea(parent); Composite top = new Composite(outer, SWT.NONE); GridLayoutFactory.swtDefaults().numColumns(2).applyTo(top); cssSearchBox = new Text(top, SWT.BORDER | SWT.SEARCH | SWT.ICON_SEARCH | SWT.ICON_CANCEL); cssSearchBox.setMessage("CSS Selector"); cssSearchBox.setToolTipText("Highlight matching widgets"); GridDataFactory.fillDefaults().grab(true, false).applyTo(cssSearchBox); showAllShells = new Button(top, SWT.CHECK); showAllShells.setText("All shells"); GridDataFactory.swtDefaults().applyTo(showAllShells); GridDataFactory.fillDefaults().applyTo(top); SashForm sashForm = new SashForm(outer, SWT.VERTICAL); sashForm.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); // / THE WIDGET TREE Composite widgetsComposite = new Composite(sashForm, SWT.NONE); widgetTreeViewer = new TreeViewer(widgetsComposite, SWT.BORDER | SWT.MULTI); widgetTreeProvider = new WidgetTreeProvider(); widgetTreeViewer.setContentProvider(widgetTreeProvider); widgetTreeViewer.setAutoExpandLevel(0); widgetTreeViewer.getTree().setLinesVisible(true); widgetTreeViewer.getTree().setHeaderVisible(true); ColumnViewerToolTipSupport.enableFor(widgetTreeViewer); TreeViewerColumn widgetTypeColumn = new TreeViewerColumn( widgetTreeViewer, SWT.NONE); widgetTypeColumn.getColumn().setWidth(100); widgetTypeColumn.getColumn().setText("Widget"); widgetTypeColumn.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object item) { CSSStylableElement element = CssSpyDialog.getCSSElement(item); return element.getLocalName() + " (" + element.getNamespaceURI() + ")"; } }); TreeViewerColumn widgetClassColumn = new TreeViewerColumn( widgetTreeViewer, SWT.NONE); widgetClassColumn.getColumn().setText("CSS Class"); widgetClassColumn.getColumn().setWidth(100); widgetClassColumn.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object item) { CSSStylableElement element = CssSpyDialog.getCSSElement(item); if (element.getCSSClass() == null) { return null; } String classes[] = element.getCSSClass().split(" +"); return classes.length <= 1 ? classes[0] : classes[0] + " (+" + (classes.length - 1) + " others)"; } @Override public String getToolTipText(Object item) { CSSStylableElement element = CssSpyDialog.getCSSElement(item); if (element == null) { return null; } StringBuilder sb = new StringBuilder(); sb.append(element.getLocalName()).append(" (") .append(element.getNamespaceURI()).append(")"); if (element.getCSSClass() != null) { sb.append("\nClasses:\n "); Activator.join(sb, element.getCSSClass().split(" +"), "\n "); } return sb.toString(); } }); TreeViewerColumn widgetIdColumn = new TreeViewerColumn( widgetTreeViewer, SWT.NONE); widgetIdColumn.getColumn().setWidth(100); widgetIdColumn.getColumn().setText("CSS Id"); widgetIdColumn.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object item) { CSSStylableElement element = CssSpyDialog.getCSSElement(item); return element.getCSSId(); } }); TreeColumnLayout widgetsTableLayout = new TreeColumnLayout(); widgetsTableLayout.setColumnData(widgetTypeColumn.getColumn(), new ColumnWeightData(50)); widgetsTableLayout.setColumnData(widgetIdColumn.getColumn(), new ColumnWeightData(40)); widgetsTableLayout.setColumnData(widgetClassColumn.getColumn(), new ColumnWeightData(40)); widgetsComposite.setLayout(widgetsTableLayout); // / HEADERS Composite container = new Composite(sashForm, SWT.NONE); container.setLayout(new GridLayout(2, true)); Label lblCssProperties = new Label(container, SWT.NONE); lblCssProperties.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); lblCssProperties.setText("CSS Properties"); Label lblCssRules = new Label(container, SWT.NONE); lblCssRules.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); lblCssRules.setText("CSS Rules"); // // THE CSS PROPERTIES TABLE - Composite propsComposite = new Composite(container, SWT.BORDER - | SWT.H_SCROLL | SWT.V_SCROLL); + Composite propsComposite = new Composite(container, SWT.BORDER); GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); gridData.minimumHeight = 50; propsComposite.setLayoutData(gridData); cssPropertiesViewer = new TableViewer(propsComposite, SWT.BORDER - | SWT.V_SCROLL | SWT.FULL_SELECTION); + | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION); cssPropertiesViewer .setContentProvider(new CSSPropertiesContentProvider()); cssPropertiesViewer.getTable().setLinesVisible(true); cssPropertiesViewer.getTable().setHeaderVisible(true); cssPropertiesViewer.setComparator(new ViewerComparator()); final TextCellEditor textCellEditor = new TextCellEditor( cssPropertiesViewer.getTable()); TableViewerEditor .create(cssPropertiesViewer, new TableViewerFocusCellManager(cssPropertiesViewer, new FocusCellOwnerDrawHighlighter( cssPropertiesViewer)), new ColumnViewerEditorActivationStrategy( cssPropertiesViewer), ColumnViewerEditor.TABBING_HORIZONTAL | ColumnViewerEditor.TABBING_MOVE_TO_ROW_NEIGHBOR | ColumnViewerEditor.TABBING_VERTICAL | ColumnViewerEditor.KEYBOARD_ACTIVATION); TableViewerColumn propName = new TableViewerColumn(cssPropertiesViewer, SWT.NONE); propName.getColumn().setWidth(100); propName.getColumn().setText("Property"); propName.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { return ((CSSPropertyProvider) element).getPropertyName(); } }); TableViewerColumn propValue = new TableViewerColumn( cssPropertiesViewer, SWT.NONE); propValue.getColumn().setWidth(100); propValue.getColumn().setText("Value"); propValue.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { try { return ((CSSPropertyProvider) element).getValue(); } catch (Exception e) { System.err.println("Error fetching property: " + element + ": " + e); return null; } } }); propValue.setEditingSupport(new EditingSupport(cssPropertiesViewer) { @Override protected CellEditor getCellEditor(Object element) { // do the fancy footwork here to return an appropriate editor to // the value-type return textCellEditor; } @Override protected boolean canEdit(Object element) { return true; } @Override protected Object getValue(Object element) { try { String value = ((CSSPropertyProvider) element).getValue(); return value == null ? "" : value; } catch (Exception e) { return ""; } } @Override protected void setValue(Object element, Object value) { try { if (value == null || ((String) value).trim().length() == 0) { return; } CSSPropertyProvider provider = (CSSPropertyProvider) element; provider.setValue((String) value); } catch (Throwable e) { MessageDialog.openError(getShell(), "Error", "Unable to set property:\n\n" + e.getMessage()); } cssPropertiesViewer.update(element, null); } }); TableColumnLayout propsTableLayout = new TableColumnLayout(); propsTableLayout.setColumnData(propName.getColumn(), new ColumnWeightData(50)); propsTableLayout.setColumnData(propValue.getColumn(), new ColumnWeightData(50)); propsComposite.setLayout(propsTableLayout); // / THE CSS RULES cssRules = new Text(container, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI); cssRules.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); // / THE CSS PROPERTIES TABLE (again) showUnsetProperties = new Button(container, SWT.CHECK); showUnsetProperties.setText("Show unset properties"); // and for balance new Label(container, SWT.NONE); // / The listeners cssSearchBox.addModifyListener(new ModifyListener() { private Runnable updater; private IProgressMonitor monitor; public void modifyText(ModifyEvent e) { if (monitor != null) { monitor.setCanceled(false); } display.timerExec(200, updater = new Runnable() { public void run() { if (updater == this) { performCSSSearch(monitor = new NullProgressMonitor()); } } }); } }); cssSearchBox.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.keyCode == SWT.ARROW_DOWN && (e.stateMask & SWT.MODIFIER_MASK) == 0) { widgetTreeViewer.getControl().setFocus(); } } }); widgetTreeViewer .addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { updateForWidgetSelection(event.getSelection()); } }); if (isLive()) { container.addMouseMoveListener(new MouseMoveListener() { public void mouseMove(MouseEvent e) { update(); } }); } if (shouldDismissOnLostFocus()) { container.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { setReturnCode(Window.OK); close(); } }); } container.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.character == SWT.ESC) { cancelPressed(); } else if (e.character == SWT.CR | e.character == SWT.LF) { okPressed(); } } }); showAllShells.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { updateWidgetTreeInput(); } }); outer.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { dispose(); } }); showUnsetProperties.setSelection(true); showUnsetProperties.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (showUnsetProperties.getSelection()) { cssPropertiesViewer.removeFilter(unsetPropertyFilter); } else { cssPropertiesViewer.addFilter(unsetPropertyFilter); } } }); update(); sashForm.setWeights(new int[] { 50, 50 }); widgetTreeViewer.getControl().setFocus(); return outer; } protected void performCSSSearch(IProgressMonitor progress) { List<Widget> widgets = new ArrayList<Widget>(); performCSSSearch(progress, cssSearchBox.getText(), widgets); if (!progress.isCanceled()) { revealAndSelect(widgets); } } private void performCSSSearch(IProgressMonitor monitor, String text, Collection<Widget> results) { if (text.trim().length() == 0) { return; } widgetTreeViewer.collapseAll(); Object[] roots = widgetTreeProvider.getElements(widgetTreeViewer .getInput()); monitor.beginTask("Searching for \"" + text + "\"", roots.length * 10); for (Object root : roots) { if (monitor.isCanceled()) { return; } CSSStylableElement element = getCSSElement(root); if (element == null) { continue; } CSSEngine engine = getCSSEngine(root); try { SelectorList selectors = engine.parseSelectors(text); monitor.worked(2); processCSSSearch(new SubProgressMonitor(monitor, 8), engine, selectors, element, null, results); } catch (CSSParseException e) { System.out.println(e.toString()); } catch (IOException e) { System.out.println(e.toString()); } } monitor.done(); } private void processCSSSearch(IProgressMonitor monitor, CSSEngine engine, SelectorList selectors, CSSStylableElement element, String pseudo, Collection<Widget> results) { if (monitor.isCanceled()) { return; } NodeList children = element.getChildNodes(); monitor.beginTask("Searching", 5 + 5 * children.getLength()); boolean matched = false; for (int i = 0; i < selectors.getLength(); i++) { if (matched = engine.matches(selectors.item(i), element, pseudo)) { break; } } if (matched) { results.add((Widget) element.getNativeWidget()); } monitor.worked(5); for (int i = 0; i < children.getLength(); i++) { if (monitor.isCanceled()) { return; } processCSSSearch(new SubProgressMonitor(monitor, 5), engine, selectors, (CSSStylableElement) children.item(i), pseudo, results); } monitor.done(); } protected void dispose() { disposeHighlights(); } /** * Create contents of the button bar. * * @param parent */ @Override protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); // createButton(parent, IDialogConstants.CANCEL_ID, // IDialogConstants.CANCEL_LABEL, false); } /** * Return the initial size of the dialog. */ @Override protected Point getInitialSize() { return new Point(600, 500); } }
false
true
protected Control createDialogArea(Composite parent) { Composite outer = (Composite) super.createDialogArea(parent); Composite top = new Composite(outer, SWT.NONE); GridLayoutFactory.swtDefaults().numColumns(2).applyTo(top); cssSearchBox = new Text(top, SWT.BORDER | SWT.SEARCH | SWT.ICON_SEARCH | SWT.ICON_CANCEL); cssSearchBox.setMessage("CSS Selector"); cssSearchBox.setToolTipText("Highlight matching widgets"); GridDataFactory.fillDefaults().grab(true, false).applyTo(cssSearchBox); showAllShells = new Button(top, SWT.CHECK); showAllShells.setText("All shells"); GridDataFactory.swtDefaults().applyTo(showAllShells); GridDataFactory.fillDefaults().applyTo(top); SashForm sashForm = new SashForm(outer, SWT.VERTICAL); sashForm.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); // / THE WIDGET TREE Composite widgetsComposite = new Composite(sashForm, SWT.NONE); widgetTreeViewer = new TreeViewer(widgetsComposite, SWT.BORDER | SWT.MULTI); widgetTreeProvider = new WidgetTreeProvider(); widgetTreeViewer.setContentProvider(widgetTreeProvider); widgetTreeViewer.setAutoExpandLevel(0); widgetTreeViewer.getTree().setLinesVisible(true); widgetTreeViewer.getTree().setHeaderVisible(true); ColumnViewerToolTipSupport.enableFor(widgetTreeViewer); TreeViewerColumn widgetTypeColumn = new TreeViewerColumn( widgetTreeViewer, SWT.NONE); widgetTypeColumn.getColumn().setWidth(100); widgetTypeColumn.getColumn().setText("Widget"); widgetTypeColumn.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object item) { CSSStylableElement element = CssSpyDialog.getCSSElement(item); return element.getLocalName() + " (" + element.getNamespaceURI() + ")"; } }); TreeViewerColumn widgetClassColumn = new TreeViewerColumn( widgetTreeViewer, SWT.NONE); widgetClassColumn.getColumn().setText("CSS Class"); widgetClassColumn.getColumn().setWidth(100); widgetClassColumn.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object item) { CSSStylableElement element = CssSpyDialog.getCSSElement(item); if (element.getCSSClass() == null) { return null; } String classes[] = element.getCSSClass().split(" +"); return classes.length <= 1 ? classes[0] : classes[0] + " (+" + (classes.length - 1) + " others)"; } @Override public String getToolTipText(Object item) { CSSStylableElement element = CssSpyDialog.getCSSElement(item); if (element == null) { return null; } StringBuilder sb = new StringBuilder(); sb.append(element.getLocalName()).append(" (") .append(element.getNamespaceURI()).append(")"); if (element.getCSSClass() != null) { sb.append("\nClasses:\n "); Activator.join(sb, element.getCSSClass().split(" +"), "\n "); } return sb.toString(); } }); TreeViewerColumn widgetIdColumn = new TreeViewerColumn( widgetTreeViewer, SWT.NONE); widgetIdColumn.getColumn().setWidth(100); widgetIdColumn.getColumn().setText("CSS Id"); widgetIdColumn.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object item) { CSSStylableElement element = CssSpyDialog.getCSSElement(item); return element.getCSSId(); } }); TreeColumnLayout widgetsTableLayout = new TreeColumnLayout(); widgetsTableLayout.setColumnData(widgetTypeColumn.getColumn(), new ColumnWeightData(50)); widgetsTableLayout.setColumnData(widgetIdColumn.getColumn(), new ColumnWeightData(40)); widgetsTableLayout.setColumnData(widgetClassColumn.getColumn(), new ColumnWeightData(40)); widgetsComposite.setLayout(widgetsTableLayout); // / HEADERS Composite container = new Composite(sashForm, SWT.NONE); container.setLayout(new GridLayout(2, true)); Label lblCssProperties = new Label(container, SWT.NONE); lblCssProperties.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); lblCssProperties.setText("CSS Properties"); Label lblCssRules = new Label(container, SWT.NONE); lblCssRules.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); lblCssRules.setText("CSS Rules"); // // THE CSS PROPERTIES TABLE Composite propsComposite = new Composite(container, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL); GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); gridData.minimumHeight = 50; propsComposite.setLayoutData(gridData); cssPropertiesViewer = new TableViewer(propsComposite, SWT.BORDER | SWT.V_SCROLL | SWT.FULL_SELECTION); cssPropertiesViewer .setContentProvider(new CSSPropertiesContentProvider()); cssPropertiesViewer.getTable().setLinesVisible(true); cssPropertiesViewer.getTable().setHeaderVisible(true); cssPropertiesViewer.setComparator(new ViewerComparator()); final TextCellEditor textCellEditor = new TextCellEditor( cssPropertiesViewer.getTable()); TableViewerEditor .create(cssPropertiesViewer, new TableViewerFocusCellManager(cssPropertiesViewer, new FocusCellOwnerDrawHighlighter( cssPropertiesViewer)), new ColumnViewerEditorActivationStrategy( cssPropertiesViewer), ColumnViewerEditor.TABBING_HORIZONTAL | ColumnViewerEditor.TABBING_MOVE_TO_ROW_NEIGHBOR | ColumnViewerEditor.TABBING_VERTICAL | ColumnViewerEditor.KEYBOARD_ACTIVATION); TableViewerColumn propName = new TableViewerColumn(cssPropertiesViewer, SWT.NONE); propName.getColumn().setWidth(100); propName.getColumn().setText("Property"); propName.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { return ((CSSPropertyProvider) element).getPropertyName(); } }); TableViewerColumn propValue = new TableViewerColumn( cssPropertiesViewer, SWT.NONE); propValue.getColumn().setWidth(100); propValue.getColumn().setText("Value"); propValue.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { try { return ((CSSPropertyProvider) element).getValue(); } catch (Exception e) { System.err.println("Error fetching property: " + element + ": " + e); return null; } } }); propValue.setEditingSupport(new EditingSupport(cssPropertiesViewer) { @Override protected CellEditor getCellEditor(Object element) { // do the fancy footwork here to return an appropriate editor to // the value-type return textCellEditor; } @Override protected boolean canEdit(Object element) { return true; } @Override protected Object getValue(Object element) { try { String value = ((CSSPropertyProvider) element).getValue(); return value == null ? "" : value; } catch (Exception e) { return ""; } } @Override protected void setValue(Object element, Object value) { try { if (value == null || ((String) value).trim().length() == 0) { return; } CSSPropertyProvider provider = (CSSPropertyProvider) element; provider.setValue((String) value); } catch (Throwable e) { MessageDialog.openError(getShell(), "Error", "Unable to set property:\n\n" + e.getMessage()); } cssPropertiesViewer.update(element, null); } }); TableColumnLayout propsTableLayout = new TableColumnLayout(); propsTableLayout.setColumnData(propName.getColumn(), new ColumnWeightData(50)); propsTableLayout.setColumnData(propValue.getColumn(), new ColumnWeightData(50)); propsComposite.setLayout(propsTableLayout); // / THE CSS RULES cssRules = new Text(container, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI); cssRules.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); // / THE CSS PROPERTIES TABLE (again) showUnsetProperties = new Button(container, SWT.CHECK); showUnsetProperties.setText("Show unset properties"); // and for balance new Label(container, SWT.NONE); // / The listeners cssSearchBox.addModifyListener(new ModifyListener() { private Runnable updater; private IProgressMonitor monitor; public void modifyText(ModifyEvent e) { if (monitor != null) { monitor.setCanceled(false); } display.timerExec(200, updater = new Runnable() { public void run() { if (updater == this) { performCSSSearch(monitor = new NullProgressMonitor()); } } }); } }); cssSearchBox.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.keyCode == SWT.ARROW_DOWN && (e.stateMask & SWT.MODIFIER_MASK) == 0) { widgetTreeViewer.getControl().setFocus(); } } }); widgetTreeViewer .addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { updateForWidgetSelection(event.getSelection()); } }); if (isLive()) { container.addMouseMoveListener(new MouseMoveListener() { public void mouseMove(MouseEvent e) { update(); } }); } if (shouldDismissOnLostFocus()) { container.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { setReturnCode(Window.OK); close(); } }); } container.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.character == SWT.ESC) { cancelPressed(); } else if (e.character == SWT.CR | e.character == SWT.LF) { okPressed(); } } }); showAllShells.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { updateWidgetTreeInput(); } }); outer.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { dispose(); } }); showUnsetProperties.setSelection(true); showUnsetProperties.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (showUnsetProperties.getSelection()) { cssPropertiesViewer.removeFilter(unsetPropertyFilter); } else { cssPropertiesViewer.addFilter(unsetPropertyFilter); } } }); update(); sashForm.setWeights(new int[] { 50, 50 }); widgetTreeViewer.getControl().setFocus(); return outer; }
protected Control createDialogArea(Composite parent) { Composite outer = (Composite) super.createDialogArea(parent); Composite top = new Composite(outer, SWT.NONE); GridLayoutFactory.swtDefaults().numColumns(2).applyTo(top); cssSearchBox = new Text(top, SWT.BORDER | SWT.SEARCH | SWT.ICON_SEARCH | SWT.ICON_CANCEL); cssSearchBox.setMessage("CSS Selector"); cssSearchBox.setToolTipText("Highlight matching widgets"); GridDataFactory.fillDefaults().grab(true, false).applyTo(cssSearchBox); showAllShells = new Button(top, SWT.CHECK); showAllShells.setText("All shells"); GridDataFactory.swtDefaults().applyTo(showAllShells); GridDataFactory.fillDefaults().applyTo(top); SashForm sashForm = new SashForm(outer, SWT.VERTICAL); sashForm.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); // / THE WIDGET TREE Composite widgetsComposite = new Composite(sashForm, SWT.NONE); widgetTreeViewer = new TreeViewer(widgetsComposite, SWT.BORDER | SWT.MULTI); widgetTreeProvider = new WidgetTreeProvider(); widgetTreeViewer.setContentProvider(widgetTreeProvider); widgetTreeViewer.setAutoExpandLevel(0); widgetTreeViewer.getTree().setLinesVisible(true); widgetTreeViewer.getTree().setHeaderVisible(true); ColumnViewerToolTipSupport.enableFor(widgetTreeViewer); TreeViewerColumn widgetTypeColumn = new TreeViewerColumn( widgetTreeViewer, SWT.NONE); widgetTypeColumn.getColumn().setWidth(100); widgetTypeColumn.getColumn().setText("Widget"); widgetTypeColumn.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object item) { CSSStylableElement element = CssSpyDialog.getCSSElement(item); return element.getLocalName() + " (" + element.getNamespaceURI() + ")"; } }); TreeViewerColumn widgetClassColumn = new TreeViewerColumn( widgetTreeViewer, SWT.NONE); widgetClassColumn.getColumn().setText("CSS Class"); widgetClassColumn.getColumn().setWidth(100); widgetClassColumn.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object item) { CSSStylableElement element = CssSpyDialog.getCSSElement(item); if (element.getCSSClass() == null) { return null; } String classes[] = element.getCSSClass().split(" +"); return classes.length <= 1 ? classes[0] : classes[0] + " (+" + (classes.length - 1) + " others)"; } @Override public String getToolTipText(Object item) { CSSStylableElement element = CssSpyDialog.getCSSElement(item); if (element == null) { return null; } StringBuilder sb = new StringBuilder(); sb.append(element.getLocalName()).append(" (") .append(element.getNamespaceURI()).append(")"); if (element.getCSSClass() != null) { sb.append("\nClasses:\n "); Activator.join(sb, element.getCSSClass().split(" +"), "\n "); } return sb.toString(); } }); TreeViewerColumn widgetIdColumn = new TreeViewerColumn( widgetTreeViewer, SWT.NONE); widgetIdColumn.getColumn().setWidth(100); widgetIdColumn.getColumn().setText("CSS Id"); widgetIdColumn.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object item) { CSSStylableElement element = CssSpyDialog.getCSSElement(item); return element.getCSSId(); } }); TreeColumnLayout widgetsTableLayout = new TreeColumnLayout(); widgetsTableLayout.setColumnData(widgetTypeColumn.getColumn(), new ColumnWeightData(50)); widgetsTableLayout.setColumnData(widgetIdColumn.getColumn(), new ColumnWeightData(40)); widgetsTableLayout.setColumnData(widgetClassColumn.getColumn(), new ColumnWeightData(40)); widgetsComposite.setLayout(widgetsTableLayout); // / HEADERS Composite container = new Composite(sashForm, SWT.NONE); container.setLayout(new GridLayout(2, true)); Label lblCssProperties = new Label(container, SWT.NONE); lblCssProperties.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); lblCssProperties.setText("CSS Properties"); Label lblCssRules = new Label(container, SWT.NONE); lblCssRules.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); lblCssRules.setText("CSS Rules"); // // THE CSS PROPERTIES TABLE Composite propsComposite = new Composite(container, SWT.BORDER); GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); gridData.minimumHeight = 50; propsComposite.setLayoutData(gridData); cssPropertiesViewer = new TableViewer(propsComposite, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION); cssPropertiesViewer .setContentProvider(new CSSPropertiesContentProvider()); cssPropertiesViewer.getTable().setLinesVisible(true); cssPropertiesViewer.getTable().setHeaderVisible(true); cssPropertiesViewer.setComparator(new ViewerComparator()); final TextCellEditor textCellEditor = new TextCellEditor( cssPropertiesViewer.getTable()); TableViewerEditor .create(cssPropertiesViewer, new TableViewerFocusCellManager(cssPropertiesViewer, new FocusCellOwnerDrawHighlighter( cssPropertiesViewer)), new ColumnViewerEditorActivationStrategy( cssPropertiesViewer), ColumnViewerEditor.TABBING_HORIZONTAL | ColumnViewerEditor.TABBING_MOVE_TO_ROW_NEIGHBOR | ColumnViewerEditor.TABBING_VERTICAL | ColumnViewerEditor.KEYBOARD_ACTIVATION); TableViewerColumn propName = new TableViewerColumn(cssPropertiesViewer, SWT.NONE); propName.getColumn().setWidth(100); propName.getColumn().setText("Property"); propName.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { return ((CSSPropertyProvider) element).getPropertyName(); } }); TableViewerColumn propValue = new TableViewerColumn( cssPropertiesViewer, SWT.NONE); propValue.getColumn().setWidth(100); propValue.getColumn().setText("Value"); propValue.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { try { return ((CSSPropertyProvider) element).getValue(); } catch (Exception e) { System.err.println("Error fetching property: " + element + ": " + e); return null; } } }); propValue.setEditingSupport(new EditingSupport(cssPropertiesViewer) { @Override protected CellEditor getCellEditor(Object element) { // do the fancy footwork here to return an appropriate editor to // the value-type return textCellEditor; } @Override protected boolean canEdit(Object element) { return true; } @Override protected Object getValue(Object element) { try { String value = ((CSSPropertyProvider) element).getValue(); return value == null ? "" : value; } catch (Exception e) { return ""; } } @Override protected void setValue(Object element, Object value) { try { if (value == null || ((String) value).trim().length() == 0) { return; } CSSPropertyProvider provider = (CSSPropertyProvider) element; provider.setValue((String) value); } catch (Throwable e) { MessageDialog.openError(getShell(), "Error", "Unable to set property:\n\n" + e.getMessage()); } cssPropertiesViewer.update(element, null); } }); TableColumnLayout propsTableLayout = new TableColumnLayout(); propsTableLayout.setColumnData(propName.getColumn(), new ColumnWeightData(50)); propsTableLayout.setColumnData(propValue.getColumn(), new ColumnWeightData(50)); propsComposite.setLayout(propsTableLayout); // / THE CSS RULES cssRules = new Text(container, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI); cssRules.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); // / THE CSS PROPERTIES TABLE (again) showUnsetProperties = new Button(container, SWT.CHECK); showUnsetProperties.setText("Show unset properties"); // and for balance new Label(container, SWT.NONE); // / The listeners cssSearchBox.addModifyListener(new ModifyListener() { private Runnable updater; private IProgressMonitor monitor; public void modifyText(ModifyEvent e) { if (monitor != null) { monitor.setCanceled(false); } display.timerExec(200, updater = new Runnable() { public void run() { if (updater == this) { performCSSSearch(monitor = new NullProgressMonitor()); } } }); } }); cssSearchBox.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.keyCode == SWT.ARROW_DOWN && (e.stateMask & SWT.MODIFIER_MASK) == 0) { widgetTreeViewer.getControl().setFocus(); } } }); widgetTreeViewer .addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { updateForWidgetSelection(event.getSelection()); } }); if (isLive()) { container.addMouseMoveListener(new MouseMoveListener() { public void mouseMove(MouseEvent e) { update(); } }); } if (shouldDismissOnLostFocus()) { container.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { setReturnCode(Window.OK); close(); } }); } container.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.character == SWT.ESC) { cancelPressed(); } else if (e.character == SWT.CR | e.character == SWT.LF) { okPressed(); } } }); showAllShells.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { updateWidgetTreeInput(); } }); outer.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { dispose(); } }); showUnsetProperties.setSelection(true); showUnsetProperties.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (showUnsetProperties.getSelection()) { cssPropertiesViewer.removeFilter(unsetPropertyFilter); } else { cssPropertiesViewer.addFilter(unsetPropertyFilter); } } }); update(); sashForm.setWeights(new int[] { 50, 50 }); widgetTreeViewer.getControl().setFocus(); return outer; }
diff --git a/src/gui/MainFrame.java b/src/gui/MainFrame.java index c1c9184..387a5a7 100644 --- a/src/gui/MainFrame.java +++ b/src/gui/MainFrame.java @@ -1,147 +1,147 @@ package gui; import icons.IconManager; import javax.swing.*; import wombat.Wombat; import util.KawaWrap; import util.OutputIntercept; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import net.infonode.docking.*; import net.infonode.docking.util.*; /** * Create a main frame. */ public class MainFrame extends JFrame { private static final long serialVersionUID = 2574330949324570164L; // Woo singletons. static MainFrame me; // Things we may need access to. public RootWindow Root; public DocumentManager Documents; public HistoryTextArea History; public REPLTextArea REPL; public KawaWrap kawa; public JToolBar ToolBar; /** * Don't directly create this, use me(). * Use this method to set it up though. */ private MainFrame() { // Set frame options. setTitle("Wombat - Build " + Wombat.VERSION); setSize(Options.DisplayWidth, Options.DisplayHeight); setLocation(Options.DisplayLeft, Options.DisplayTop); setLayout(new BorderLayout(5, 5)); + setDefaultCloseOperation(EXIT_ON_CLOSE); try { setIconImage(IconManager.icon("Wombat.png").getImage()); } catch(NullPointerException ex) { } // Wait for the program to end. addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { Documents.CloseAll(); Options.DisplayTop = Math.max(0, e.getWindow().getLocation().y); Options.DisplayLeft = Math.max(0, e.getWindow().getLocation().x); Options.DisplayWidth = Math.max(400, e.getWindow().getWidth()); Options.DisplayHeight = Math.max(400, e.getWindow().getHeight()); Options.save(); - System.exit(0); } }); // Set up the menus using the above definitions. setJMenuBar(MenuManager.menu()); // Create a display for any open documents. TabWindow documents = new TabWindow(); StringViewMap viewMap = new StringViewMap(); Documents = new DocumentManager(viewMap, documents); Documents.New(); // Create displays for a split REPL. History = new HistoryTextArea(); REPL = new REPLTextArea(); viewMap.addView("REPL - Execute", new View("REPL - Execute", null, REPL)); viewMap.addView("REPL - History", new View("REPL - History", null, History)); SplitWindow replSplit = new SplitWindow(false, viewMap.getView("REPL - Execute"), viewMap.getView("REPL - History")); viewMap.getView("REPL - Execute").getWindowProperties().setCloseEnabled(false); viewMap.getView("REPL - History").getWindowProperties().setCloseEnabled(false); // Put everything together into the actual dockable display. SplitWindow fullSplit = new SplitWindow(false, 0.6f, documents, replSplit); Root = DockingUtil.createRootWindow(new ViewMap(), true); Root.setWindow(fullSplit); add(Root); // Connect to Kawa. kawa = new KawaWrap(); // Bind a to catch anything that goes to stdout or stderr. Thread t = new Thread(new Runnable() { public void run() { while (true) { if (OutputIntercept.hasContent()) History.append(OutputIntercept.getContent() + "\n"); try { Thread.sleep(50); } catch(Exception e) {} } } }); t.setDaemon(true); t.start(); // Add a toolbar. ToolBar = new JToolBar(); ToolBar.setFloatable(false); for (Action a : new Action[]{new actions.New(), new actions.Open(), new actions.Save(), new actions.Close()}) ToolBar.add(a); ToolBar.addSeparator(); for (Action a : new Action[]{new actions.Run(), new actions.Format(), new actions.Reset()}) ToolBar.add(a); add(ToolBar, BorderLayout.PAGE_START); ToolBar.setVisible(Options.DisplayToolbar); } /** * Run a command. * * @param command The command to run. */ void doCommand(String command) { command = command.trim(); if (command.length() == 0) return; History.append("\n� " + command.replace("\n", "\n ") + "\n"); Object result = kawa.eval(command); if (result != null) History.append(result.toString() + "\n"); } /** * Access the frame. * * @return The singleton frame. */ public static MainFrame me() { if (me == null) me = new MainFrame(); return me; } }
false
true
private MainFrame() { // Set frame options. setTitle("Wombat - Build " + Wombat.VERSION); setSize(Options.DisplayWidth, Options.DisplayHeight); setLocation(Options.DisplayLeft, Options.DisplayTop); setLayout(new BorderLayout(5, 5)); try { setIconImage(IconManager.icon("Wombat.png").getImage()); } catch(NullPointerException ex) { } // Wait for the program to end. addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { Documents.CloseAll(); Options.DisplayTop = Math.max(0, e.getWindow().getLocation().y); Options.DisplayLeft = Math.max(0, e.getWindow().getLocation().x); Options.DisplayWidth = Math.max(400, e.getWindow().getWidth()); Options.DisplayHeight = Math.max(400, e.getWindow().getHeight()); Options.save(); System.exit(0); } }); // Set up the menus using the above definitions. setJMenuBar(MenuManager.menu()); // Create a display for any open documents. TabWindow documents = new TabWindow(); StringViewMap viewMap = new StringViewMap(); Documents = new DocumentManager(viewMap, documents); Documents.New(); // Create displays for a split REPL. History = new HistoryTextArea(); REPL = new REPLTextArea(); viewMap.addView("REPL - Execute", new View("REPL - Execute", null, REPL)); viewMap.addView("REPL - History", new View("REPL - History", null, History)); SplitWindow replSplit = new SplitWindow(false, viewMap.getView("REPL - Execute"), viewMap.getView("REPL - History")); viewMap.getView("REPL - Execute").getWindowProperties().setCloseEnabled(false); viewMap.getView("REPL - History").getWindowProperties().setCloseEnabled(false); // Put everything together into the actual dockable display. SplitWindow fullSplit = new SplitWindow(false, 0.6f, documents, replSplit); Root = DockingUtil.createRootWindow(new ViewMap(), true); Root.setWindow(fullSplit); add(Root); // Connect to Kawa. kawa = new KawaWrap(); // Bind a to catch anything that goes to stdout or stderr. Thread t = new Thread(new Runnable() { public void run() { while (true) { if (OutputIntercept.hasContent()) History.append(OutputIntercept.getContent() + "\n"); try { Thread.sleep(50); } catch(Exception e) {} } } }); t.setDaemon(true); t.start(); // Add a toolbar. ToolBar = new JToolBar(); ToolBar.setFloatable(false); for (Action a : new Action[]{new actions.New(), new actions.Open(), new actions.Save(), new actions.Close()}) ToolBar.add(a); ToolBar.addSeparator(); for (Action a : new Action[]{new actions.Run(), new actions.Format(), new actions.Reset()}) ToolBar.add(a); add(ToolBar, BorderLayout.PAGE_START); ToolBar.setVisible(Options.DisplayToolbar); }
private MainFrame() { // Set frame options. setTitle("Wombat - Build " + Wombat.VERSION); setSize(Options.DisplayWidth, Options.DisplayHeight); setLocation(Options.DisplayLeft, Options.DisplayTop); setLayout(new BorderLayout(5, 5)); setDefaultCloseOperation(EXIT_ON_CLOSE); try { setIconImage(IconManager.icon("Wombat.png").getImage()); } catch(NullPointerException ex) { } // Wait for the program to end. addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { Documents.CloseAll(); Options.DisplayTop = Math.max(0, e.getWindow().getLocation().y); Options.DisplayLeft = Math.max(0, e.getWindow().getLocation().x); Options.DisplayWidth = Math.max(400, e.getWindow().getWidth()); Options.DisplayHeight = Math.max(400, e.getWindow().getHeight()); Options.save(); } }); // Set up the menus using the above definitions. setJMenuBar(MenuManager.menu()); // Create a display for any open documents. TabWindow documents = new TabWindow(); StringViewMap viewMap = new StringViewMap(); Documents = new DocumentManager(viewMap, documents); Documents.New(); // Create displays for a split REPL. History = new HistoryTextArea(); REPL = new REPLTextArea(); viewMap.addView("REPL - Execute", new View("REPL - Execute", null, REPL)); viewMap.addView("REPL - History", new View("REPL - History", null, History)); SplitWindow replSplit = new SplitWindow(false, viewMap.getView("REPL - Execute"), viewMap.getView("REPL - History")); viewMap.getView("REPL - Execute").getWindowProperties().setCloseEnabled(false); viewMap.getView("REPL - History").getWindowProperties().setCloseEnabled(false); // Put everything together into the actual dockable display. SplitWindow fullSplit = new SplitWindow(false, 0.6f, documents, replSplit); Root = DockingUtil.createRootWindow(new ViewMap(), true); Root.setWindow(fullSplit); add(Root); // Connect to Kawa. kawa = new KawaWrap(); // Bind a to catch anything that goes to stdout or stderr. Thread t = new Thread(new Runnable() { public void run() { while (true) { if (OutputIntercept.hasContent()) History.append(OutputIntercept.getContent() + "\n"); try { Thread.sleep(50); } catch(Exception e) {} } } }); t.setDaemon(true); t.start(); // Add a toolbar. ToolBar = new JToolBar(); ToolBar.setFloatable(false); for (Action a : new Action[]{new actions.New(), new actions.Open(), new actions.Save(), new actions.Close()}) ToolBar.add(a); ToolBar.addSeparator(); for (Action a : new Action[]{new actions.Run(), new actions.Format(), new actions.Reset()}) ToolBar.add(a); add(ToolBar, BorderLayout.PAGE_START); ToolBar.setVisible(Options.DisplayToolbar); }
diff --git a/src/joshua/decoder/DecoderThread.java b/src/joshua/decoder/DecoderThread.java index 1324e6da..b174175e 100644 --- a/src/joshua/decoder/DecoderThread.java +++ b/src/joshua/decoder/DecoderThread.java @@ -1,490 +1,490 @@ /* This file is part of the Joshua Machine Translation System. * * Joshua is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ package joshua.decoder; import java.io.BufferedWriter; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import joshua.corpus.suffix_array.Pattern; import joshua.corpus.syntax.ArraySyntaxTree; import joshua.corpus.syntax.SyntaxTree; import joshua.corpus.vocab.SymbolTable; import joshua.decoder.chart_parser.Chart; import joshua.decoder.ff.FeatureFunction; import joshua.decoder.ff.lm.LanguageModelFF; import joshua.decoder.ff.state_maintenance.StateComputer; import joshua.decoder.ff.tm.Grammar; import joshua.decoder.ff.tm.GrammarFactory; import joshua.decoder.hypergraph.DiskHyperGraph; import joshua.decoder.hypergraph.HyperGraph; import joshua.decoder.hypergraph.KBestExtractor; import joshua.decoder.segment_file.HackishSegmentParser; import joshua.decoder.segment_file.PlainSegmentParser; import joshua.decoder.segment_file.Segment; import joshua.decoder.segment_file.SegmentFileParser; import joshua.decoder.segment_file.sax_parser.SAXSegmentParser; import joshua.lattice.Lattice; import joshua.oracle.OracleExtractor; import joshua.ui.hypergraph_visualizer.HyperGraphViewer; import joshua.util.CoIterator; import joshua.util.FileUtility; import joshua.util.io.LineReader; import joshua.util.io.NullReader; import joshua.util.io.Reader; import joshua.util.io.UncheckedIOException; /** * this class implements: * (1) interact with the chart-parsing functions to do the true * decoding * * @author Zhifei Li, <[email protected]> * @version $LastChangedDate: 2010-05-02 11:19:17 -0400 (Sun, 02 May 2010) $ */ // BUG: known synchronization problem: LM cache; srilm call; public class DecoderThread extends Thread { /* these variables may be the same across all threads (e.g., * just copy from DecoderFactory), or differ from thread * to thread */ private final List<GrammarFactory> grammarFactories; private final boolean useMaxLMCostForOOV; private final List<FeatureFunction> featureFunctions; private final List<StateComputer> stateComputers; /** * Shared symbol table for source language terminals, target * language terminals, and shared nonterminals. * <p> * It may be that separate tables should be maintained for * the source and target languages. * <p> * This class explicitly uses the symbol table to get integer * IDs for the source language sentence. */ private final SymbolTable symbolTable; //more test set specific final String testFile; private final String oracleFile; final String nbestFile; // package-private for DecoderFactory private BufferedWriter nbestWriter; // set in decodeTestFile private final int startSentenceID; private final KBestExtractor kbestExtractor; DiskHyperGraph hypergraphSerializer; // package-private for DecoderFactory private static final Logger logger = Logger.getLogger(DecoderThread.class.getName()); //=============================================================== // Constructor //=============================================================== public DecoderThread( List<GrammarFactory> grammarFactories, boolean useMaxLMCostForOOV, List<FeatureFunction> featureFunctions, List<StateComputer> stateComputers, SymbolTable symbolTable, String testFile, String nbestFile, String oracleFile, int startSentenceID ) throws IOException { this.grammarFactories = grammarFactories; this.useMaxLMCostForOOV = useMaxLMCostForOOV; this.featureFunctions = featureFunctions; this.stateComputers = stateComputers; this.symbolTable = symbolTable; this.testFile = testFile; this.nbestFile = nbestFile; this.oracleFile = oracleFile; this.startSentenceID = startSentenceID; this.kbestExtractor = new KBestExtractor( this.symbolTable, JoshuaConfiguration.use_unique_nbest, JoshuaConfiguration.use_tree_nbest, JoshuaConfiguration.include_align_index, JoshuaConfiguration.add_combined_cost, false, (oracleFile==null)); if (JoshuaConfiguration.save_disk_hg) { FeatureFunction languageModel = null; for (FeatureFunction ff : this.featureFunctions) { if (ff instanceof LanguageModelFF) { languageModel = ff; break; } } int lmFeatID = -1; if (null == languageModel) { logger.warning("No language model feature function found, but save disk hg"); }else{ lmFeatID = languageModel.getFeatureID(); } this.hypergraphSerializer = new DiskHyperGraph( this.symbolTable, lmFeatID, true, // always store model cost this.featureFunctions); this.hypergraphSerializer.initWrite( this.nbestFile + ".hg.items", JoshuaConfiguration.forest_pruning, JoshuaConfiguration.forest_pruning_threshold); } } //=============================================================== // Methods //=============================================================== // Overriding of Thread.run() cannot throw anything public void run() { try { this.decodeTestFile(); //this.hypergraphSerializer.closeReaders(); } catch (Throwable e) { // if we throw anything (e.g. OutOfMemoryError) // we should stop all threads // because it is impossible for decoding // to finish successfully e.printStackTrace(); System.exit(1); } } // BUG: log file is not properly handled for parallel decoding void decodeTestFile() throws IOException { SegmentFileParser segmentParser; // BUG: As written, this will need duplicating in DecoderFactory // TODO: Fix JoshuaConfiguration so we can make this less gross. // // TODO: maybe using real reflection would be cleaner. If it weren't for // the argument for HackishSegmentParser then we could do all this over // in the JoshuaConfiguration class instead final String className = JoshuaConfiguration.segmentFileParserClass; if (null == className) { // Use old behavior by default segmentParser = new HackishSegmentParser(this.startSentenceID); } else if ("PlainSegmentParser".equals(className)) { segmentParser = new PlainSegmentParser(); } else if ("HackishSegmentParser".equals(className)) { segmentParser = new HackishSegmentParser(this.startSentenceID); } else if ("SAXSegmentParser".equals(className)) { segmentParser = new SAXSegmentParser(); } else { throw new IllegalArgumentException( "Unknown SegmentFileParser class: " + className); } // TODO: we need to run the segmentParser over the file once in order to // catch any errors before we do the actual translation. Getting formatting // errors asynchronously after a long time is a Bad Thing(tm). Some errors // may be recoverable (e.g. by skipping the sentence that's invalid), but // we're going to call all exceptions errors for now. // TODO: we should unwrapper SAXExceptions and give good error messages // March 2011: reading from STDIN does not permit two passes ove if (! testFile.equals("-")) { segmentParser.parseSegmentFile( LineReader.getInputStream(this.testFile), new CoIterator<Segment>() { public void coNext(Segment seg) { // Consume Segment and do nothing (for now) } public void finish() { // Nothing to clean up } }); } // TODO: we should also have the CoIterator<Segment> test compatibility with // a given grammar, e.g. count of grammatical feature functions match, // nonterminals match,... // TODO: we may also want to validate that all segments have different ids //=== Translate the test file this.nbestWriter = FileUtility.getWriteFileStream(this.nbestFile); try { try { // This method will analyze the input file (to generate segments), and // then translate segments one by one segmentParser.parseSegmentFile( LineReader.getInputStream(this.testFile), new TranslateCoiterator( null == this.oracleFile ? new NullReader<String>() : new LineReader(this.oracleFile) ) ); } catch (UncheckedIOException e) { e.throwCheckedException(); } } finally { this.nbestWriter.flush(); this.nbestWriter.close(); } } /** * This coiterator is for calling the DecoderThread.translate * method on each Segment to be translated. All interface * methods can throw {@link UncheckedIOException}, which * should be converted back into a {@link IOException} once * it's possible. */ private class TranslateCoiterator implements CoIterator<Segment> { // TODO: it would be nice if we could somehow push this into the // parseSegmentFile call and use a coiterator over some subclass // of Segment which has another method for returning the oracular // sentence. That may take some work though, since Java hates // mixins so much. private Reader<String> oracleReader; public TranslateCoiterator(Reader<String> oracleReader) { this.oracleReader = oracleReader; } public void coNext(Segment segment) { try { if (logger.isLoggable(Level.FINE)) logger.fine("Segment id: " + segment.id()); DecoderThread.this.translate( segment, this.oracleReader.readLine()); } catch (IOException ioe) { throw new UncheckedIOException(ioe); } } public void finish() { try { this.oracleReader.close(); } catch (IOException ioe) { throw new UncheckedIOException(ioe); } } } // End inner class TranslateCoiterator /** * Translate a sentence. * * @param segment The sentence to be translated. * @param oracleSentence */ private void translate(Segment segment, String oracleSentence) throws IOException { long startTime = 0; if (logger.isLoggable(Level.FINER)) startTime = System.currentTimeMillis(); if (logger.isLoggable(Level.FINE)) logger.fine("now translating\n" + segment.sentence()); Chart chart; { // TODO: we should not use strings to decide what the input type is final boolean looks_like_lattice = segment.sentence().startsWith("((("); - final boolean looks_like_parse_tree = segment.sentence().startsWith("(TOP"); + final boolean looks_like_parse_tree = segment.sentence().matches("^\\(+[A-Z]+ .*"); Lattice<Integer> input_lattice = null; SyntaxTree syntax_tree = null; Pattern sentence = null; if (!looks_like_lattice) { int[] int_sentence; if (looks_like_parse_tree) { syntax_tree = new ArraySyntaxTree(segment.sentence(), symbolTable); int_sentence = syntax_tree.getTerminals(); } else { int_sentence = this.symbolTable.getIDs(segment.sentence()); } if (logger.isLoggable(Level.FINEST)) logger.finest("Converted \"" + segment.sentence() + "\" into " + Arrays.toString(int_sentence)); input_lattice = Lattice.createLattice(int_sentence); sentence = new Pattern(this.symbolTable, int_sentence); } else { input_lattice = Lattice.createFromString(segment.sentence(), this.symbolTable); sentence = null; // TODO: suffix array needs to accept lattices! } if (logger.isLoggable(Level.FINEST)) logger.finest("Translating input lattice:\n" + input_lattice.toString()); Grammar[] grammars = new Grammar[grammarFactories.size()]; for (int i = 0; i<grammarFactories.size(); i++) { grammars[i] = grammarFactories.get(i).getGrammarForSentence(sentence); // For batch grammar, we do not want to sort it every time if (!grammars[i].isSorted()) { System.out.println("!!!!!!!!!!!! called again"); // TODO: check to see if this is ever called here. It probably is not grammars[i].sortGrammar(this.featureFunctions); } } /* Seeding: the chart only sees the grammars, not the factories */ chart = new Chart( input_lattice, this.featureFunctions, this.stateComputers, this.symbolTable, Integer.parseInt(segment.id()), grammars, this.useMaxLMCostForOOV, JoshuaConfiguration.goal_symbol, segment.constraints(), syntax_tree); if (logger.isLoggable(Level.FINER)) logger.finer("after seed, time: " + ((double)(System.currentTimeMillis() - startTime) / 1000.0) + " seconds"); } /* Parsing */ HyperGraph hypergraph = chart.expand(); // unsuccessful parse, pass through input if (hypergraph == null) { StringBuffer passthrough_buffer = new StringBuffer(); passthrough_buffer.append(Integer.parseInt(segment.id())); passthrough_buffer.append(" ||| "); passthrough_buffer.append(segment.sentence()); passthrough_buffer.append(" ||| "); for (int i=0; i<this.featureFunctions.size(); i++) passthrough_buffer.append("0.0 "); passthrough_buffer.append("||| 0.0\n"); this.nbestWriter.write(passthrough_buffer.toString()); return; } if (JoshuaConfiguration.visualize_hypergraph) { HyperGraphViewer.visualizeHypergraphInFrame(hypergraph, symbolTable); } if (logger.isLoggable(Level.FINER)) logger.finer("after expand, time: " + ((double)(System.currentTimeMillis() - startTime) / 1000.0) + " seconds"); if (oracleSentence != null) { logger.fine("Creating oracle extractor"); OracleExtractor extractor = new OracleExtractor(this.symbolTable); logger.finer("Extracting oracle hypergraph..."); HyperGraph oracle = extractor.getOracle(hypergraph, 3, oracleSentence); logger.finer("... Done Extracting. Getting k-best..."); this.kbestExtractor.lazyKBestExtractOnHG( oracle, this.featureFunctions, JoshuaConfiguration.topN, Integer.parseInt(segment.id()), this.nbestWriter); logger.finer("... Done getting k-best"); } else { /* k-best extraction */ this.kbestExtractor.lazyKBestExtractOnHG( hypergraph, this.featureFunctions, JoshuaConfiguration.topN, Integer.parseInt(segment.id()), this.nbestWriter); if (logger.isLoggable(Level.FINER)) logger.finer("after k-best, time: " + ((double)(System.currentTimeMillis() - startTime) / 1000.0) + " seconds"); } if (null != this.hypergraphSerializer) { if(JoshuaConfiguration.use_kbest_hg){ HyperGraph kbestHG = this.kbestExtractor.extractKbestIntoHyperGraph(hypergraph, JoshuaConfiguration.topN); this.hypergraphSerializer.saveHyperGraph(kbestHG); }else{ this.hypergraphSerializer.saveHyperGraph(hypergraph); } } /* //debug if (JoshuaConfiguration.use_variational_decoding) { ConstituentVariationalDecoder vd = new ConstituentVariationalDecoder(); vd.decoding(hypergraph); System.out.println("#### new 1best is #####\n" + HyperGraph.extract_best_string(p_main_controller.p_symbol, hypergraph.goal_item)); } // end */ //debug //g_con.get_confusion_in_hyper_graph_cell_specific(hypergraph, hypergraph.sent_len); } /**decode a sentence, and return a hypergraph*/ public HyperGraph getHyperGraph(String sentence) { Chart chart; int[] intSentence = this.symbolTable.getIDs(sentence); Lattice<Integer> inputLattice = Lattice.createLattice(intSentence); Grammar[] grammars = new Grammar[grammarFactories.size()]; int i = 0; for (GrammarFactory factory : this.grammarFactories) { grammars[i] = factory.getGrammarForSentence( new Pattern(this.symbolTable, intSentence)); // For batch grammar, we do not want to sort it every time if (! grammars[i].isSorted()) { grammars[i].sortGrammar(this.featureFunctions); } i++; } chart = new Chart( inputLattice, this.featureFunctions, this.stateComputers, this.symbolTable, 0, grammars, this.useMaxLMCostForOOV, JoshuaConfiguration.goal_symbol, null, null); return chart.expand(); } }
true
true
private void translate(Segment segment, String oracleSentence) throws IOException { long startTime = 0; if (logger.isLoggable(Level.FINER)) startTime = System.currentTimeMillis(); if (logger.isLoggable(Level.FINE)) logger.fine("now translating\n" + segment.sentence()); Chart chart; { // TODO: we should not use strings to decide what the input type is final boolean looks_like_lattice = segment.sentence().startsWith("((("); final boolean looks_like_parse_tree = segment.sentence().startsWith("(TOP"); Lattice<Integer> input_lattice = null; SyntaxTree syntax_tree = null; Pattern sentence = null; if (!looks_like_lattice) { int[] int_sentence; if (looks_like_parse_tree) { syntax_tree = new ArraySyntaxTree(segment.sentence(), symbolTable); int_sentence = syntax_tree.getTerminals(); } else { int_sentence = this.symbolTable.getIDs(segment.sentence()); } if (logger.isLoggable(Level.FINEST)) logger.finest("Converted \"" + segment.sentence() + "\" into " + Arrays.toString(int_sentence)); input_lattice = Lattice.createLattice(int_sentence); sentence = new Pattern(this.symbolTable, int_sentence); } else { input_lattice = Lattice.createFromString(segment.sentence(), this.symbolTable); sentence = null; // TODO: suffix array needs to accept lattices! } if (logger.isLoggable(Level.FINEST)) logger.finest("Translating input lattice:\n" + input_lattice.toString()); Grammar[] grammars = new Grammar[grammarFactories.size()]; for (int i = 0; i<grammarFactories.size(); i++) { grammars[i] = grammarFactories.get(i).getGrammarForSentence(sentence); // For batch grammar, we do not want to sort it every time if (!grammars[i].isSorted()) { System.out.println("!!!!!!!!!!!! called again"); // TODO: check to see if this is ever called here. It probably is not grammars[i].sortGrammar(this.featureFunctions); } } /* Seeding: the chart only sees the grammars, not the factories */ chart = new Chart( input_lattice, this.featureFunctions, this.stateComputers, this.symbolTable, Integer.parseInt(segment.id()), grammars, this.useMaxLMCostForOOV, JoshuaConfiguration.goal_symbol, segment.constraints(), syntax_tree); if (logger.isLoggable(Level.FINER)) logger.finer("after seed, time: " + ((double)(System.currentTimeMillis() - startTime) / 1000.0) + " seconds"); } /* Parsing */ HyperGraph hypergraph = chart.expand(); // unsuccessful parse, pass through input if (hypergraph == null) { StringBuffer passthrough_buffer = new StringBuffer(); passthrough_buffer.append(Integer.parseInt(segment.id())); passthrough_buffer.append(" ||| "); passthrough_buffer.append(segment.sentence()); passthrough_buffer.append(" ||| "); for (int i=0; i<this.featureFunctions.size(); i++) passthrough_buffer.append("0.0 "); passthrough_buffer.append("||| 0.0\n"); this.nbestWriter.write(passthrough_buffer.toString()); return; } if (JoshuaConfiguration.visualize_hypergraph) { HyperGraphViewer.visualizeHypergraphInFrame(hypergraph, symbolTable); } if (logger.isLoggable(Level.FINER)) logger.finer("after expand, time: " + ((double)(System.currentTimeMillis() - startTime) / 1000.0) + " seconds"); if (oracleSentence != null) { logger.fine("Creating oracle extractor"); OracleExtractor extractor = new OracleExtractor(this.symbolTable); logger.finer("Extracting oracle hypergraph..."); HyperGraph oracle = extractor.getOracle(hypergraph, 3, oracleSentence); logger.finer("... Done Extracting. Getting k-best..."); this.kbestExtractor.lazyKBestExtractOnHG( oracle, this.featureFunctions, JoshuaConfiguration.topN, Integer.parseInt(segment.id()), this.nbestWriter); logger.finer("... Done getting k-best"); } else { /* k-best extraction */ this.kbestExtractor.lazyKBestExtractOnHG( hypergraph, this.featureFunctions, JoshuaConfiguration.topN, Integer.parseInt(segment.id()), this.nbestWriter); if (logger.isLoggable(Level.FINER)) logger.finer("after k-best, time: " + ((double)(System.currentTimeMillis() - startTime) / 1000.0) + " seconds"); } if (null != this.hypergraphSerializer) { if(JoshuaConfiguration.use_kbest_hg){ HyperGraph kbestHG = this.kbestExtractor.extractKbestIntoHyperGraph(hypergraph, JoshuaConfiguration.topN); this.hypergraphSerializer.saveHyperGraph(kbestHG); }else{ this.hypergraphSerializer.saveHyperGraph(hypergraph); } } /* //debug if (JoshuaConfiguration.use_variational_decoding) { ConstituentVariationalDecoder vd = new ConstituentVariationalDecoder(); vd.decoding(hypergraph); System.out.println("#### new 1best is #####\n" + HyperGraph.extract_best_string(p_main_controller.p_symbol, hypergraph.goal_item)); } // end */ //debug //g_con.get_confusion_in_hyper_graph_cell_specific(hypergraph, hypergraph.sent_len); }
private void translate(Segment segment, String oracleSentence) throws IOException { long startTime = 0; if (logger.isLoggable(Level.FINER)) startTime = System.currentTimeMillis(); if (logger.isLoggable(Level.FINE)) logger.fine("now translating\n" + segment.sentence()); Chart chart; { // TODO: we should not use strings to decide what the input type is final boolean looks_like_lattice = segment.sentence().startsWith("((("); final boolean looks_like_parse_tree = segment.sentence().matches("^\\(+[A-Z]+ .*"); Lattice<Integer> input_lattice = null; SyntaxTree syntax_tree = null; Pattern sentence = null; if (!looks_like_lattice) { int[] int_sentence; if (looks_like_parse_tree) { syntax_tree = new ArraySyntaxTree(segment.sentence(), symbolTable); int_sentence = syntax_tree.getTerminals(); } else { int_sentence = this.symbolTable.getIDs(segment.sentence()); } if (logger.isLoggable(Level.FINEST)) logger.finest("Converted \"" + segment.sentence() + "\" into " + Arrays.toString(int_sentence)); input_lattice = Lattice.createLattice(int_sentence); sentence = new Pattern(this.symbolTable, int_sentence); } else { input_lattice = Lattice.createFromString(segment.sentence(), this.symbolTable); sentence = null; // TODO: suffix array needs to accept lattices! } if (logger.isLoggable(Level.FINEST)) logger.finest("Translating input lattice:\n" + input_lattice.toString()); Grammar[] grammars = new Grammar[grammarFactories.size()]; for (int i = 0; i<grammarFactories.size(); i++) { grammars[i] = grammarFactories.get(i).getGrammarForSentence(sentence); // For batch grammar, we do not want to sort it every time if (!grammars[i].isSorted()) { System.out.println("!!!!!!!!!!!! called again"); // TODO: check to see if this is ever called here. It probably is not grammars[i].sortGrammar(this.featureFunctions); } } /* Seeding: the chart only sees the grammars, not the factories */ chart = new Chart( input_lattice, this.featureFunctions, this.stateComputers, this.symbolTable, Integer.parseInt(segment.id()), grammars, this.useMaxLMCostForOOV, JoshuaConfiguration.goal_symbol, segment.constraints(), syntax_tree); if (logger.isLoggable(Level.FINER)) logger.finer("after seed, time: " + ((double)(System.currentTimeMillis() - startTime) / 1000.0) + " seconds"); } /* Parsing */ HyperGraph hypergraph = chart.expand(); // unsuccessful parse, pass through input if (hypergraph == null) { StringBuffer passthrough_buffer = new StringBuffer(); passthrough_buffer.append(Integer.parseInt(segment.id())); passthrough_buffer.append(" ||| "); passthrough_buffer.append(segment.sentence()); passthrough_buffer.append(" ||| "); for (int i=0; i<this.featureFunctions.size(); i++) passthrough_buffer.append("0.0 "); passthrough_buffer.append("||| 0.0\n"); this.nbestWriter.write(passthrough_buffer.toString()); return; } if (JoshuaConfiguration.visualize_hypergraph) { HyperGraphViewer.visualizeHypergraphInFrame(hypergraph, symbolTable); } if (logger.isLoggable(Level.FINER)) logger.finer("after expand, time: " + ((double)(System.currentTimeMillis() - startTime) / 1000.0) + " seconds"); if (oracleSentence != null) { logger.fine("Creating oracle extractor"); OracleExtractor extractor = new OracleExtractor(this.symbolTable); logger.finer("Extracting oracle hypergraph..."); HyperGraph oracle = extractor.getOracle(hypergraph, 3, oracleSentence); logger.finer("... Done Extracting. Getting k-best..."); this.kbestExtractor.lazyKBestExtractOnHG( oracle, this.featureFunctions, JoshuaConfiguration.topN, Integer.parseInt(segment.id()), this.nbestWriter); logger.finer("... Done getting k-best"); } else { /* k-best extraction */ this.kbestExtractor.lazyKBestExtractOnHG( hypergraph, this.featureFunctions, JoshuaConfiguration.topN, Integer.parseInt(segment.id()), this.nbestWriter); if (logger.isLoggable(Level.FINER)) logger.finer("after k-best, time: " + ((double)(System.currentTimeMillis() - startTime) / 1000.0) + " seconds"); } if (null != this.hypergraphSerializer) { if(JoshuaConfiguration.use_kbest_hg){ HyperGraph kbestHG = this.kbestExtractor.extractKbestIntoHyperGraph(hypergraph, JoshuaConfiguration.topN); this.hypergraphSerializer.saveHyperGraph(kbestHG); }else{ this.hypergraphSerializer.saveHyperGraph(hypergraph); } } /* //debug if (JoshuaConfiguration.use_variational_decoding) { ConstituentVariationalDecoder vd = new ConstituentVariationalDecoder(); vd.decoding(hypergraph); System.out.println("#### new 1best is #####\n" + HyperGraph.extract_best_string(p_main_controller.p_symbol, hypergraph.goal_item)); } // end */ //debug //g_con.get_confusion_in_hyper_graph_cell_specific(hypergraph, hypergraph.sent_len); }
diff --git a/src/com/jidesoft/swing/Searchable.java b/src/com/jidesoft/swing/Searchable.java index d41722f0..a91b55dd 100644 --- a/src/com/jidesoft/swing/Searchable.java +++ b/src/com/jidesoft/swing/Searchable.java @@ -1,1676 +1,1678 @@ /* * @(#)${NAME} * * Copyright 2002 - 2004 JIDE Software Inc. All rights reserved. */ package com.jidesoft.swing; import com.jidesoft.plaf.UIDefaultsLookup; import com.jidesoft.popup.JidePopup; import com.jidesoft.swing.event.SearchableEvent; import com.jidesoft.swing.event.SearchableListener; import com.jidesoft.utils.DefaultWildcardSupport; import com.jidesoft.utils.WildcardSupport; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.EventListenerList; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.HashSet; import java.util.Locale; import java.util.Set; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** * JList, JTable and JTree are three data-rich components. They can be used to display a huge amount of data so * searching function will be very a useful feature in those components. <code>Searchable</code> is such a class that * can make JList, JTable and JTree searchable. User can simply type in any string they want to search for and use arrow * keys to navigate to next or previous occurrence. * <p/> * <code>Searchable</code> is a base abstract class. <code>ListSearchable</code>, <code>TableSearchable</code> and * <code>TreeSearchable</code> are implementations to make JList, JTable and JTree searchable respectively. For each * implementation, there are five methods need to be implemented. <ul> <li><code>protected abstract int * getSelectedIndex()</code> <li><code>protected abstract void setSelectedIndex(int index, boolean incremental)</code> * <li><code>protected abstract int getElementCount()</code> <li><code>protected abstract Object getElementAt(int * index)</code> <li><code>protected abstract String convertElementToString(Object element)</code> </ul> * <p/> * Please look at the javadoc of each method to learn more details. * <p/> * The keys used by this class are fully customizable. Subclass can override the methods such as {@link * #isActivateKey(java.awt.event.KeyEvent)}, {@link #isDeactivateKey(java.awt.event.KeyEvent)}, {@link * #isFindFirstKey(java.awt.event.KeyEvent)},{@link #isFindLastKey(java.awt.event.KeyEvent)}, {@link * #isFindNextKey(java.awt.event.KeyEvent)}, {@link #isFindPreviousKey(java.awt.event.KeyEvent)} to provide its own set * of keys. * <p/> * In addition to press up/down arrow to find next occurrence or previous occurrence of particular string, there are * several other features that are very handy. * <p/> * Multiple selection feature - If you press CTRL key and hold it while pressing up and down arrow, it will find * next/previous occurrence while keeping existing selections. <br> Select all feature - If you type in a searching text * and press CTRL+A, all the occurrences of that searching string will be selected. This is a very handy feature. For * example you want to delete all rows in a table whose name column begins with "old". So you can type in "old" and * press CTRL+A, now all rows beginning with "old" will be selected. Pressing delete will delete all of them. <br> Basic * regular expression support - It allows '?' to match any letter or digit, or '*' to match several letters or digits. * Even though it's possible to implement full regular expression support, we don't want to do that. The reason is the * regular expression is very complex, it's probably not a good idea to let user type in such a complex expression in a * small popup window. However if your user is very familiar with regular expression, you can add the feature to * <code>Searchable</code>. All you need to do is to override {@link #compare(String,String)} method and implement by * yourself. * <p/> * As this is an abstract class, please refer to to javadoc of {@link ListSearchable},{@link TreeSearchable}, and {@link * TableSearchable} to find out how to use it with JList, JTree and JTable respectively. * <p/> * This component has a timer. If user types very fast, it will accumulate them together and generate only one searching * action. The timer can be controlled by {@link #setSearchingDelay(int)}. * <p/> * By default we will use lightweight popup for the sake of performance. But if you use heavyweight component which * could obscure the lightweight popup, you can call {@link #setHeavyweightComponentEnabled(boolean)} to true so that * heavyweight popup will be used. * <p/> * When a <code>Searchable</code> is installed on a component, component.getClientProperty(Searchable.CLIENT_PROPERTY_SEARCHABLE) * will give you the Searchable instance. You can use static method {@link #getSearchable(javax.swing.JComponent)} to * get it too. * <p/> * Last but not the least, only one Searchable is allowed on a component. If you install another one, it will remove the * first one and then install the new one. */ public abstract class Searchable { private final PropertyChangeSupport _propertyChangeSupport = new PropertyChangeSupport(this); protected final JComponent _component; private SearchPopup _popup; private JLayeredPane _layeredPane; private boolean _heavyweightComponentEnabled; /** * optional SearchableProvider */ private SearchableProvider _searchableProvider; private Pattern _pattern; private String _searchText; private String _previousSearchText; private boolean _fromStart = true; private boolean _caseSensitive = false; private boolean _repeats = false; private boolean _wildcardEnabled = true; private WildcardSupport _wildcardSupport = null; private Color _mismatchForeground; private Color _foreground = null; private Color _background = null; protected ComponentListener _componentListener; protected KeyListener _keyListener; protected FocusListener _focusListener; public static final String PROPERTY_SEARCH_TEXT = "searchText"; private int _cursor = -1; private String _searchLabel = null; /** * The popup location */ private int _popupLocation = SwingConstants.TOP; private int _searchingDelay = 0; private boolean _reverseOrder = false; /** * A list of event listeners for this component. */ protected EventListenerList listenerList = new EventListenerList(); private Component _popupLocationRelativeTo; /** * The client property for Searchable instance. When Searchable is installed on a component, this client property * has the Searchable. */ public static final String CLIENT_PROPERTY_SEARCHABLE = "Searchable"; private Set<Integer> _selection; private boolean _processModelChangeEvent = true; /** * Creates a Searchable. * * @param component component where the Searchable will be installed. */ public Searchable(JComponent component) { _previousSearchText = null; _component = component; _selection = new HashSet<Integer>(); installListeners(); updateClientProperty(_component, this); } /** * Creates a Searchable. * * @param component component where the Searchable will be installed. * @param searchableProvider the Searchable Provider. */ public Searchable(JComponent component, SearchableProvider searchableProvider) { _searchableProvider = searchableProvider; _previousSearchText = null; _component = component; _selection = new HashSet<Integer>(); installListeners(); updateClientProperty(_component, this); } /** * Gets the selected index in the component. The concrete implementation should call methods on the component to * retrieve the current selected index. If the component supports multiple selection, it's OK just return the index * of the first selection. <p>Here are some examples. In the case of JList, the index is the row index. In the case * of JTree, the index is the row index too. In the case of JTable, depending on the selection mode, the index could * be row index (in row selection mode), could be column index (in column selection mode) or could the cell index * (in cell selection mode). * * @return the selected index. */ protected abstract int getSelectedIndex(); /** * Sets the selected index. The concrete implementation should call methods on the component to select the element * at the specified index. The incremental flag is used to do multiple select. If the flag is true, the element at * the index should be added to current selection. If false, you should clear previous selection and then select the * element. * * @param index the index to be selected * @param incremental a flag to enable multiple selection. If the flag is true, the element at the index should be * added to current selection. If false, you should clear previous selection and then select the * element. */ protected abstract void setSelectedIndex(int index, boolean incremental); /** * Sets the selected index. The reason we have this method is just for back compatibility. All the method do is just * to invoke {@link #setSelectedIndex(int, boolean)}. * <p/> * Please do NOT try to override this method. Always override {@link #setSelectedIndex(int, boolean)} instead. * * @param index the index to be selected * @param incremental a flag to enable multiple selection. If the flag is true, the element at the index should be * added to current selection. If false, you should clear previous selection and then select the * element. */ public void adjustSelectedIndex(int index, boolean incremental) { setSelectedIndex(index, incremental); } /** * Gets the total element count in the component. Different concrete implementation could have different * interpretation of the count. This is totally OK as long as it's consistent in all the methods. For example, the * index parameter in other methods should be always a valid value within the total count. * * @return the total element count. */ protected abstract int getElementCount(); /** * Gets the element at the specified index. The element could be any data structure that internally used in the * component. The convertElementToString method will give you a chance to convert the element to string which is * used to compare with the string that user types in. * * @param index the index * @return the element at the specified index. */ protected abstract Object getElementAt(int index); /** * Converts the element that returns from getElementAt() to string. * * @param element the element to be converted * @return the string representing the element in the component. */ protected abstract String convertElementToString(Object element); /** * A text field for searching text. */ protected class SearchField extends JTextField { SearchField() { JideSwingUtilities.setTextComponentTransparent(this); } @Override public Dimension getPreferredSize() { Dimension size = super.getPreferredSize(); size.width = getFontMetrics(getFont()).stringWidth(getText()) + 4; return size; } @Override public void processKeyEvent(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode == KeyEvent.VK_BACK_SPACE && getDocument().getLength() == 0) { e.consume(); return; } final boolean isNavigationKey = isNavigationKey(e); if (isDeactivateKey(e) && !isNavigationKey) { hidePopup(); if (keyCode == KeyEvent.VK_ESCAPE) e.consume(); return; } super.processKeyEvent(e); if (keyCode == KeyEvent.VK_BACK_SPACE || isNavigationKey) e.consume(); if (isSelectAllKey(e)) { e.consume(); } } } /** * The popup panel for search label and search text field. */ private class DefaultSearchPopup extends SearchPopup { private JLabel _label; private JLabel _noMatch; public DefaultSearchPopup(String text) { initComponents(text); } private void initComponents(String text) { final Color foreground = Searchable.this.getForeground(); final Color background = Searchable.this.getBackground(); // setup the label _label = new JLabel(getSearchLabel()); _label.setForeground(foreground); _label.setVerticalAlignment(JLabel.BOTTOM); _noMatch = new JLabel(); _noMatch.setForeground(getMismatchForeground()); _noMatch.setVerticalAlignment(JLabel.BOTTOM); //setup text field _textField = new SearchField(); _textField.setFocusable(false); _textField.setBorder(BorderFactory.createEmptyBorder()); _textField.setForeground(foreground); _textField.setCursor(getCursor()); _textField.getDocument().addDocumentListener(new DocumentListener() { private Timer timer = new Timer(200, new ActionListener() { public void actionPerformed(ActionEvent e) { applyText(); } }); public void insertUpdate(DocumentEvent e) { startTimer(); } public void removeUpdate(DocumentEvent e) { startTimer(); } public void changedUpdate(DocumentEvent e) { startTimer(); } protected void applyText() { String text = _textField.getText().trim(); firePropertyChangeEvent(text); if (text.length() != 0) { int found = findFromCursor(text); if (found == -1) { _textField.setForeground(getMismatchForeground()); } else { _textField.setForeground(foreground); } select(found, null, text); } else { + _textField.setForeground(foreground); + _noMatch.setText(""); hidePopup(); } } void startTimer() { updatePopupBounds(); if (getSearchingDelay() > 0) { timer.setInitialDelay(getSearchingDelay()); if (timer.isRunning()) { timer.restart(); } else { timer.setRepeats(false); timer.start(); } } else { applyText(); } } }); _textField.setText(text); setBackground(background); setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(UIDefaultsLookup.getColor("controlShadow"), 1), BorderFactory.createEmptyBorder(0, 6, 1, 8))); setLayout(new BorderLayout(2, 0)); Dimension size = _label.getPreferredSize(); size.height = _textField.getPreferredSize().height; _label.setPreferredSize(size); add(_label, BorderLayout.BEFORE_LINE_BEGINS); add(_textField, BorderLayout.CENTER); add(_noMatch, BorderLayout.AFTER_LINE_ENDS); setPopupBorder(BorderFactory.createEmptyBorder()); } @Override protected void select(int index, KeyEvent e, String searchingText) { if (index != -1) { boolean incremental = e != null && isIncrementalSelectKey(e); setSelectedIndex(index, incremental); Searchable.this.setCursor(index, incremental); _textField.setForeground(getForeground()); _noMatch.setText(""); } else { _textField.setForeground(getMismatchForeground()); _noMatch.setText(getResourceString("Searchable.noMatch")); } updatePopupBounds(); if (index != -1) { Object element = getElementAt(index); fireSearchableEvent(new SearchableEvent(Searchable.this, SearchableEvent.SEARCHABLE_MATCH, searchingText, element, convertElementToString(element))); } else { fireSearchableEvent(new SearchableEvent(Searchable.this, SearchableEvent.SEARCHABLE_NOMATCH, searchingText)); } } private void updatePopupBounds() { if (_popup != null) { _textField.invalidate(); try { if (!isHeavyweightComponentEnabled()) { Dimension size = _noMatch.getPreferredSize(); size.width += _label.getPreferredSize().width; size.width += new JLabel(_textField.getText()).getPreferredSize().width + 24; size.height = _popup.getSize().height; _popup.setSize(size); _popup.validate(); } else { _popup.packPopup(); } } catch (Exception e) { // catch any potential exception // see bug report at http://www.jidesoft.com/forum/viewtopic.php?p=8557#8557 } } } } /** * Hides the popup. */ public void hidePopup() { if (_popup != null) { if (isHeavyweightComponentEnabled()) { _popup.hidePopupImmediately(); } else { if (_layeredPane != null) { _layeredPane.remove(_popup); _layeredPane.validate(); _layeredPane.repaint(); _layeredPane = null; } } _popup = null; _searchableProvider = null; fireSearchableEvent(new SearchableEvent(Searchable.this, SearchableEvent.SEARCHABLE_END, "", getCurrentIndex(), _previousSearchText)); } setCursor(-1); } public SearchableProvider getSearchableProvider() { return _searchableProvider; } public void setSearchableProvider(SearchableProvider searchableProvider) { _searchableProvider = searchableProvider; } /** * Installs necessary listeners to the component. This method will be called automatically when Searchable is * created. */ public void installListeners() { if (_componentListener == null) { _componentListener = createComponentListener(); } _component.addComponentListener(_componentListener); Component scrollPane = JideSwingUtilities.getScrollPane(_component); if (scrollPane != null) { scrollPane.addComponentListener(_componentListener); } if (_keyListener == null) { _keyListener = createKeyListener(); } JideSwingUtilities.insertKeyListener(getComponent(), _keyListener, 0); if (_focusListener == null) { _focusListener = createFocusListener(); } getComponent().addFocusListener(_focusListener); } /** * Creates a component listener that updates the popup when component is hidden, moved or resized. * * @return a ComponentListener. */ protected ComponentListener createComponentListener() { return new ComponentAdapter() { @Override public void componentHidden(ComponentEvent e) { super.componentHidden(e); boolean passive = _searchableProvider == null || _searchableProvider.isPassive(); if (passive) { hidePopup(); } } @Override public void componentResized(ComponentEvent e) { super.componentResized(e); boolean passive = _searchableProvider == null || _searchableProvider.isPassive(); if (passive) { updateSizeAndLocation(); } } @Override public void componentMoved(ComponentEvent e) { super.componentMoved(e); boolean passive = _searchableProvider == null || _searchableProvider.isPassive(); if (passive) { updateSizeAndLocation(); } } }; } /** * Creates the KeyListener and listen to key typed in the component. * * @return the KeyListener. */ protected KeyListener createKeyListener() { return new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { boolean passive = _searchableProvider == null || _searchableProvider.isPassive(); if (passive) { keyTypedOrPressed(e); } } @Override public void keyPressed(KeyEvent e) { boolean passive = _searchableProvider == null || _searchableProvider.isPassive(); if (passive) { keyTypedOrPressed(e); } } }; } /** * Creates a FocusListener. We use it to hide the popup when the component loses focus. * * @return a FocusListener. */ protected FocusListener createFocusListener() { return new FocusAdapter() { @Override public void focusLost(FocusEvent focusevent) { boolean passive = _searchableProvider == null || _searchableProvider.isPassive(); if (passive) { hidePopup(); } } }; } /** * Uninstall the listeners that installed before. This method is never called because we don't have the control of * the life cycle of the component. However you can call this method if you don't want the searchable component not * searchable. */ public void uninstallListeners() { if (_componentListener != null) { getComponent().removeComponentListener(_componentListener); Component scrollPane = JideSwingUtilities.getScrollPane(getComponent()); if (scrollPane != null) { scrollPane.removeComponentListener(_componentListener); } _componentListener = null; } if (_keyListener != null) { getComponent().removeKeyListener(_keyListener); _keyListener = null; } if (_focusListener != null) { getComponent().removeFocusListener(_focusListener); _focusListener = null; } } /** * Adds the property change listener. The only property change event that will be fired is the "searchText" property * which will be fired when user types in a different search text in the popup. * * @param propertychangelistener the listener */ public void addPropertyChangeListener(PropertyChangeListener propertychangelistener) { _propertyChangeSupport.addPropertyChangeListener(propertychangelistener); } /** * Removes the property change listener. * * @param propertychangelistener the listener */ public void removePropertyChangeListener(PropertyChangeListener propertychangelistener) { _propertyChangeSupport.removePropertyChangeListener(propertychangelistener); } public void firePropertyChangeEvent(String searchingText) { if (!searchingText.equals(_previousSearchText)) { _propertyChangeSupport.firePropertyChange(PROPERTY_SEARCH_TEXT, _previousSearchText, searchingText); fireSearchableEvent(new SearchableEvent(this, SearchableEvent.SEARCHABLE_CHANGE, searchingText, getCurrentIndex(), _previousSearchText)); _previousSearchText = searchingText; } } /** * Checks if the element matches the searching text. * * @param element the element to be checked * @param searchingText the searching text * @return true if matches. */ protected boolean compare(Object element, String searchingText) { String text = convertElementToString(element); return text != null && compare(isCaseSensitive() ? text : text.toLowerCase(), searchingText); } /** * Checks if the element string matches the searching text. Different from {@link #compare(Object,String)}, this * method is after the element has been converted to string using {@link #convertElementToString(Object)}. * * @param text the text to be checked * @param searchingText the searching text * @return true if matches. */ protected boolean compare(String text, String searchingText) { if (searchingText == null || searchingText.trim().length() == 0) { return true; } if (!isWildcardEnabled()) { return searchingText != null && (searchingText.equals(text) || searchingText.length() > 0 && (isFromStart() ? text.startsWith(searchingText) : text.indexOf(searchingText) != -1)); } else { // use the previous pattern since nothing changed. if (_searchText != null && _searchText.equals(searchingText) && _pattern != null) { return _pattern.matcher(text).find(); } WildcardSupport wildcardSupport = getWildcardSupport(); String s = wildcardSupport.convert(searchingText); if (searchingText.equals(s)) { return isFromStart() ? text.startsWith(searchingText) : text.indexOf(searchingText) != -1; } _searchText = searchingText; try { _pattern = Pattern.compile(isFromStart() ? "^" + s : s, isCaseSensitive() ? 0 : Pattern.CASE_INSENSITIVE); return _pattern.matcher(text).find(); } catch (PatternSyntaxException e) { return false; } } } /** * Gets the cursor which is the index of current location when searching. The value will be used in findNext and * findPrevious. * * @return the current position of the cursor. */ public int getCursor() { return _cursor; } /** * Sets the cursor which is the index of current location when searching. The value will be used in findNext and * findPrevious. * * @param cursor the new position of the cursor. */ public void setCursor(int cursor) { setCursor(cursor, false); } /** * Sets the cursor which is the index of current location when searching. The value will be used in findNext and * findPrevious. We will call this method automatically inside this class. However, if you ever call {@link * #setSelectedIndex(int, boolean)} method from your code, you should call this method with the same parameters. * * @param cursor the new position of the cursor. * @param incremental a flag to enable multiple selection. If the flag is true, the element at the index should be * added to current selection. If false, you should clear previous selection and then select the * element. */ public void setCursor(int cursor, boolean incremental) { if (!incremental || _cursor < 0) _selection.clear(); if (_cursor >= 0) _selection.add(cursor); _cursor = cursor; } /** * Finds the next matching index from the cursor. * * @param s the searching text * @return the next index that the element matches the searching text. */ public int findNext(String s) { String str = isCaseSensitive() ? s : s.toLowerCase(); int count = getElementCount(); if (count == 0) return s.length() > 0 ? -1 : 0; int selectedIndex = getCurrentIndex(); for (int i = selectedIndex + 1; i < count; i++) { Object element = getElementAt(i); if (compare(element, str)) return i; } if (isRepeats()) { for (int i = 0; i < selectedIndex; i++) { Object element = getElementAt(i); if (compare(element, str)) return i; } } return selectedIndex == -1 ? -1 : (compare(getElementAt(selectedIndex), str) ? selectedIndex : -1); } protected int getCurrentIndex() { if (_selection.contains(getSelectedIndex())) { return _cursor != -1 ? _cursor : getSelectedIndex(); } else { _selection.clear(); return getSelectedIndex(); } } /** * Finds the previous matching index from the cursor. * * @param s the searching text * @return the previous index that the element matches the searching text. */ public int findPrevious(String s) { String str = isCaseSensitive() ? s : s.toLowerCase(); int count = getElementCount(); if (count == 0) return s.length() > 0 ? -1 : 0; int selectedIndex = getCurrentIndex(); for (int i = selectedIndex - 1; i >= 0; i--) { Object element = getElementAt(i); if (compare(element, str)) return i; } if (isRepeats()) { for (int i = count - 1; i >= selectedIndex; i--) { Object element = getElementAt(i); if (compare(element, str)) return i; } } return selectedIndex == -1 ? -1 : (compare(getElementAt(selectedIndex), str) ? selectedIndex : -1); } /** * Finds the next matching index from the cursor. If it reaches the end, it will restart from the beginning. However * is the reverseOrder flag is true, it will finds the previous matching index from the cursor. If it reaches the * beginning, it will restart from the end. * * @param s the searching text * @return the next index that the element matches the searching text. */ public int findFromCursor(String s) { if (isReverseOrder()) { return reverseFindFromCursor(s); } String str = isCaseSensitive() ? s : s.toLowerCase(); int selectedIndex = getCurrentIndex(); if (selectedIndex < 0) selectedIndex = 0; int count = getElementCount(); if (count == 0) return -1; // no match // find from cursor for (int i = selectedIndex; i < count; i++) { Object element = getElementAt(i); if (compare(element, str)) return i; } // if not found, start over from the beginning for (int i = 0; i < selectedIndex; i++) { Object element = getElementAt(i); if (compare(element, str)) return i; } return -1; } /** * Finds the previous matching index from the cursor. If it reaches the beginning, it will restart from the end. * * @param s the searching text * @return the next index that the element matches the searching text. */ public int reverseFindFromCursor(String s) { if (!isReverseOrder()) { return findFromCursor(s); } String str = isCaseSensitive() ? s : s.toLowerCase(); int selectedIndex = getCurrentIndex(); if (selectedIndex < 0) selectedIndex = 0; int count = getElementCount(); if (count == 0) return -1; // no match // find from cursor to beginning for (int i = selectedIndex; i >= 0; i--) { Object element = getElementAt(i); if (compare(element, str)) return i; } // if not found, start over from the end for (int i = count - 1; i >= selectedIndex; i--) { Object element = getElementAt(i); if (compare(element, str)) return i; } return -1; } /** * Finds the first element that matches the searching text. * * @param s the searching text * @return the first element that matches with the searching text. */ public int findFirst(String s) { String str = isCaseSensitive() ? s : s.toLowerCase(); int count = getElementCount(); if (count == 0) return s.length() > 0 ? -1 : 0; for (int i = 0; i < count; i++) { int index = getIndex(count, i); Object element = getElementAt(index); if (compare(element, str)) return index; } return -1; } /** * Finds the last element that matches the searching text. * * @param s the searching text * @return the last element that matches the searching text. */ public int findLast(String s) { String str = isCaseSensitive() ? s : s.toLowerCase(); int count = getElementCount(); if (count == 0) return s.length() > 0 ? -1 : 0; for (int i = count - 1; i >= 0; i--) { Object element = getElementAt(i); if (compare(element, str)) return i; } return -1; } /** * This method is called when a key is typed or pressed. * * @param e the KeyEvent. */ protected void keyTypedOrPressed(KeyEvent e) { if (_searchableProvider != null && _searchableProvider.isPassive()) { _searchableProvider.processKeyEvent(e); return; } if (isActivateKey(e)) { String searchingText = ""; if (e.getID() == KeyEvent.KEY_TYPED) { if (((e.getModifiers() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0)) { // if alt key is pressed return; } if (e.isAltDown()) { return; } searchingText = String.valueOf(e.getKeyChar()); } showPopup(searchingText); if (e.getKeyCode() != KeyEvent.VK_ENTER) { e.consume(); } } } private int getIndex(int count, int index) { return isReverseOrder() ? count - index - 1 : index; } /** * Shows the search popup. By default, the search popup will be visible automatically when user types in the first * key (in the case of JList, JTree, JTable) or types in designated keystroke (in the case of JTextComponent). So * this method is only used when you want to show the popup manually. * * @param searchingText the searching text */ public void showPopup(String searchingText) { if (_searchableProvider == null) { fireSearchableEvent(new SearchableEvent(this, SearchableEvent.SEARCHABLE_START, searchingText)); showPopup(createSearchPopup(searchingText)); _searchableProvider = new SearchableProvider() { public String getSearchingText() { return _popup != null ? _popup.getSearchingText() : ""; } public boolean isPassive() { return true; } public void processKeyEvent(KeyEvent e) { if (_popup != null) { _popup.processKeyEvent(e); } } }; } } /** * Creates the popup to hold the searching text. * * @param searchingText the searching text * @return the searching popup. */ protected SearchPopup createSearchPopup(String searchingText) { return new DefaultSearchPopup(searchingText); } /** * Gets the searching text. * * @return the searching text. */ public String getSearchingText() { return _searchableProvider != null ? _searchableProvider.getSearchingText() : ""; } private void showPopup(SearchPopup searchpopup) { JRootPane rootPane = _component.getRootPane(); if (rootPane != null) _layeredPane = rootPane.getLayeredPane(); else { _layeredPane = null; } if (_layeredPane == null || isHeavyweightComponentEnabled()) { _popup = searchpopup; Point location = updateSizeAndLocation(); if (location != null) { searchpopup.showPopup(location.x, location.y); _popup.setVisible(true); } else { _popup = null; } } else { if (_popup != null && _layeredPane != null) { _layeredPane.remove(_popup); _layeredPane.validate(); _layeredPane.repaint(); _layeredPane = null; } else if (!_component.isShowing()) _popup = null; else _popup = searchpopup; if (_popup == null || !_component.isDisplayable()) return; if (_layeredPane == null) { System.err.println("Failed to find layeredPane."); return; } _layeredPane.add(_popup, JLayeredPane.POPUP_LAYER); updateSizeAndLocation(); _popup.setVisible(true); _popup.validate(); } } private Point updateSizeAndLocation() { Component component = getPopupLocationRelativeTo(); if (component == null) { component = JideSwingUtilities.getScrollPane(_component); } if (component == null) { component = _component; } Point componentLocation; if (_popup != null) { Dimension size = _popup.getPreferredSize(); switch (getPopupLocation()) { case SwingConstants.BOTTOM: try { componentLocation = component.getLocationOnScreen(); componentLocation.y += component.getHeight(); if (!isHeavyweightComponentEnabled()) { SwingUtilities.convertPointFromScreen(componentLocation, _layeredPane); if ((componentLocation.y + size.height > _layeredPane.getHeight())) { componentLocation.y = _layeredPane.getHeight() - size.height; } } } catch (IllegalComponentStateException e) { return null; // can't get the location so just return. } break; case SwingConstants.TOP: default: try { componentLocation = component.getLocationOnScreen(); if (!isHeavyweightComponentEnabled()) { SwingUtilities.convertPointFromScreen(componentLocation, _layeredPane); } componentLocation.y -= size.height; if ((componentLocation.y < 0)) { componentLocation.y = 0; } } catch (IllegalComponentStateException e) { return null; // can't get the location so just return. } break; } if (!isHeavyweightComponentEnabled()) { _popup.setLocation(componentLocation); _popup.setSize(size); } else { _popup.packPopup(); } return componentLocation; } else { return null; } } /** * Checks if the key is used as a key to find the first occurrence. * * @param e the key event * @return true if the key in KeyEvent is a key to find the firstoccurrencee. By default, home key is used. */ protected boolean isFindFirstKey(KeyEvent e) { return e.getKeyCode() == KeyEvent.VK_HOME; } /** * Checks if the key is used as a key to find the last occurrence. * * @param e the key event * @return true if the key in KeyEvent is a key to find the last occurrence. By default, end key is used. */ protected boolean isFindLastKey(KeyEvent e) { return e.getKeyCode() == KeyEvent.VK_END; } /** * Checks if the key is used as a key to find the previous occurrence. * * @param e the key event * @return true if the key in KeyEvent is a key to find the previous occurrence. By default, up arrow key is used. */ protected boolean isFindPreviousKey(KeyEvent e) { return e.getKeyCode() == KeyEvent.VK_UP; } /** * Checks if the key is used as a key to find the next occurrence. * * @param e the key event * @return true if the key in KeyEvent is a key to find the next occurrence. By default, down arrow key is used. */ protected boolean isFindNextKey(KeyEvent e) { return e.getKeyCode() == KeyEvent.VK_DOWN; } /** * Checks if the key is used as a navigation key. Navigation keys are keys which are used to navigate to other * occurrences of the searching string. * * @param e the key event * @return true if the key in KeyEvent is a navigation key. */ protected boolean isNavigationKey(KeyEvent e) { return isFindFirstKey(e) || isFindLastKey(e) || isFindNextKey(e) || isFindPreviousKey(e); } /** * Checks if the key in KeyEvent should activate the search popup. * * @param e the key event * @return true if the keyChar is a letter or a digit or '*' or '?'. */ protected boolean isActivateKey(KeyEvent e) { char keyChar = e.getKeyChar(); return e.getID() == KeyEvent.KEY_TYPED && (Character.isLetterOrDigit(keyChar) || keyChar == '*' || keyChar == '?'); } /** * Checks if the key in KeyEvent should hide the search popup. If this method return true and the key is not used * for navigation purpose ({@link #isNavigationKey(java.awt.event.KeyEvent)} return false), the popup will be * hidden. * * @param e the key event * @return true if the keyCode in the KeyEvent is escape key, enter key, or any of the arrow keys such as page up, * page down, home, end, left, right, up and down. */ protected boolean isDeactivateKey(KeyEvent e) { int keyCode = e.getKeyCode(); return keyCode == KeyEvent.VK_ENTER || keyCode == KeyEvent.VK_ESCAPE || keyCode == KeyEvent.VK_PAGE_UP || keyCode == KeyEvent.VK_PAGE_DOWN || keyCode == KeyEvent.VK_HOME || keyCode == KeyEvent.VK_END || keyCode == KeyEvent.VK_LEFT || keyCode == KeyEvent.VK_RIGHT || keyCode == KeyEvent.VK_UP || keyCode == KeyEvent.VK_DOWN; } /** * Checks if the key will trigger selecting all. * * @param e the key event * @return true if the key in KeyEvent is a key to trigger selecting all. */ protected boolean isSelectAllKey(KeyEvent e) { return ((e.getModifiers() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0) && e.getKeyCode() == KeyEvent.VK_A; } /** * Checks if the key will trigger incremental selection. * * @param e the key event * @return true if the key in KeyEvent is a key to trigger incremental selection. By default, ctrl down key is * used. */ protected boolean isIncrementalSelectKey(KeyEvent e) { return (e.getModifiers() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0; } /** * Gets the foreground color when the searching text doesn't match with any of the elements in the component. * * @return the foreground color for mismatch. If you never call {@link #setMismatchForeground(java.awt.Color)}. red * color will be used. */ public Color getMismatchForeground() { if (_mismatchForeground == null) { return Color.RED; } else { return _mismatchForeground; } } /** * Sets the foreground for mismatch. * * @param mismatchForeground mismatch forground */ public void setMismatchForeground(Color mismatchForeground) { _mismatchForeground = mismatchForeground; } /** * Checks if the case is sensitive during searching. * * @return true if the searching is case sensitive. */ public boolean isCaseSensitive() { return _caseSensitive; } /** * Sets the case sensitive flag. By default, it's false meaning it's a case insensitive search. * * @param caseSensitive the flag if searching is case sensitive */ public void setCaseSensitive(boolean caseSensitive) { _caseSensitive = caseSensitive; } /** * If it returns a positive number, it will wait for that many ms before doing the search. When the searching is * complex, this flag will be useful to make the searching efficient. In the other words, if user types in several * keys very quickly, there will be only one search. If it returns 0 or negative number, each key will generate a * search. * * @return the number of ms delay before searching starts. */ public int getSearchingDelay() { return _searchingDelay; } /** * If this flag is set to a positive number, it will wait for that many ms before doing the search. When the * searching is complex, this flag will be useful to make the searching efficient. In the other words, if user types * in several keys very quickly, there will be only one search. If this flag is set to 0 or a negative number, each * key will generate a search with no delay. * * @param searchingDelay the number of ms delay before searching start. */ public void setSearchingDelay(int searchingDelay) { _searchingDelay = searchingDelay; } /** * Checks if restart from the beginning when searching reaches the end or restart from the end when reaches * beginning. Default is false. * * @return true or false. */ public boolean isRepeats() { return _repeats; } /** * Sets the repeat flag. By default, it's false meaning it will stop searching when reaching the end or reaching the * beginning. * * @param repeats the repeat flag */ public void setRepeats(boolean repeats) { _repeats = repeats; } /** * Gets the foreground color used inn the search popup. * * @return the foreground. By default it will use the foreground of tooltip. */ public Color getForeground() { if (_foreground == null) { return UIDefaultsLookup.getColor("ToolTip.foreground"); } else { return _foreground; } } /** * Sets the foreground color used by popup. * * @param foreground the foreground */ public void setForeground(Color foreground) { _foreground = foreground; } /** * Gets the background color used inn the search popup. * * @return the background. By default it will use the background of tooltip. */ public Color getBackground() { if (_background == null) { return UIDefaultsLookup.getColor("ToolTip.background"); } else { return _background; } } /** * Sets the background color used by popup. * * @param background the background */ public void setBackground(Color background) { _background = background; } /** * Checks if it supports wildcard in searching text. By default it is true which means user can type in "*" or "?" * to match with any characters or any character. If it's false, it will treat "*" or "?" as a regular character. * * @return true if it supports wildcard. */ public boolean isWildcardEnabled() { return _wildcardEnabled; } /** * Enable or disable the usage of wildcard. * * @param wildcardEnabled the flag if wildcard is enabled * @see #isWildcardEnabled() */ public void setWildcardEnabled(boolean wildcardEnabled) { _wildcardEnabled = wildcardEnabled; } /** * Gets the WildcardSupport. If user never sets it, {@link DefaultWildcardSupport} will be used. * * @return the WildcardSupport. */ public WildcardSupport getWildcardSupport() { if (_wildcardSupport == null) { _wildcardSupport = new DefaultWildcardSupport(); } return _wildcardSupport; } /** * Sets the WildcardSupport. This class allows you to define what wildcards to use and how to convert the wildcard * strings to a regular expression string which is eventually used to search. * * @param wildcardSupport the new WildCardSupport. */ public void setWildcardSupport(WildcardSupport wildcardSupport) { _wildcardSupport = wildcardSupport; } /** * Gets the current text that appears in the search popup. By default it is "Search for: ". * * @return the text that appears in the search popup. */ public String getSearchLabel() { if (_searchLabel == null) { return getResourceString("Searchable.searchFor"); } else { return _searchLabel; } } /** * Sets the text that appears in the search popup. * * @param searchLabel the search label */ public void setSearchLabel(String searchLabel) { _searchLabel = searchLabel; } /** * Adds the specified listener to receive searchable events from this searchable. * * @param l the searchable listener */ public void addSearchableListener(SearchableListener l) { listenerList.add(SearchableListener.class, l); } /** * Removes the specified searchable listener so that it no longer receives searchable events. * * @param l the searchable listener */ public void removeSearchableListener(SearchableListener l) { listenerList.remove(SearchableListener.class, l); } /** * Returns an array of all the <code>SearchableListener</code>s added to this <code>SearchableGroup</code> with * <code>addSearchableListener</code>. * * @return all of the <code>SearchableListener</code>s added or an empty array if no listeners have been added * * @see #addSearchableListener */ public SearchableListener[] getSearchableListeners() { return listenerList.getListeners(SearchableListener.class); } /** * Fires a searchable event. * * @param e the event */ protected void fireSearchableEvent(SearchableEvent e) { Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == SearchableListener.class) { ((SearchableListener) listeners[i + 1]).searchableEventFired(e); } } } /** * Gets the actual component which installed this Searchable. * * @return the actual component which installed this Searchable. */ public Component getComponent() { return _component; } /** * Gets the popup location. It could be either {@link SwingConstants#TOP} or {@link SwingConstants#BOTTOM}. * * @return the popup location. */ public int getPopupLocation() { return _popupLocation; } /** * Sets the popup location. * * @param popupLocation the popup location. The valid values are either {@link SwingConstants#TOP} or {@link * SwingConstants#BOTTOM}. */ public void setPopupLocation(int popupLocation) { _popupLocation = popupLocation; } public abstract class SearchPopup extends JidePopup { protected SearchField _textField; @Override public void processKeyEvent(KeyEvent e) { _textField.processKeyEvent(e); if (e.isConsumed()) { String text = getSearchingText(); if (text.length() == 0) { return; } if (isSelectAllKey(e)) { selectAll(e, text); return; } int found; if (isFindPreviousKey(e)) { found = findPrevious(text); select(found, e, text); } else if (isFindNextKey(e)) { found = findNext(text); select(found, e, text); } else if (isFindFirstKey(e)) { found = findFirst(text); select(found, e, text); } else if (isFindLastKey(e)) { found = findLast(text); select(found, e, text); } // else { // found = findFromCursor(text); // } } if (e.getKeyCode() != KeyEvent.VK_ENTER) { e.consume(); } } private void selectAll(KeyEvent e, String text) { boolean oldReverseOrder = isReverseOrder(); // keep the old reverse order and we will set it back. if (oldReverseOrder) { setReverseOrder(false); } int index = findFirst(text); if (index != -1) { setSelectedIndex(index, false); // clear side effect of ctrl-a will select all items Searchable.this.setCursor(index); // as setSelectedIndex is used directly, we have to manually set the cursor value. } boolean oldRepeats = isRepeats(); // set repeats to false and set it back later. if (oldRepeats) { setRepeats(false); } while (index != -1) { int newIndex = findNext(text); if (index == newIndex) { index = -1; } else { index = newIndex; } if (index == -1) { break; } select(index, e, text); } if (oldRepeats) { setRepeats(oldRepeats); } if (oldReverseOrder) { setReverseOrder(oldReverseOrder); } } public String getSearchingText() { return _textField != null ? _textField.getText() : ""; } abstract protected void select(int index, KeyEvent e, String searchingText); } /** * Checks the searching order. By default the searchable starts searching from top to bottom. If this flag is false, * it searches from bottom to top. * * @return the reverseOrder flag. */ public boolean isReverseOrder() { return _reverseOrder; } /** * Sets the searching order. By default the searchable starts searching from top to bottom. If this flag is false, * it searches from bottom to top. * * @param reverseOrder the flag if searching from top to bottom or from bottom to top */ public void setReverseOrder(boolean reverseOrder) { _reverseOrder = reverseOrder; } /** * Gets the localized string from resource bundle. Subclass can override it to provide its own string. Available * keys are defined in swing.properties that begin with "Searchable.". * * @param key the resource string key * @return the localized string. */ protected String getResourceString(String key) { return Resource.getResourceBundle(_component != null ? _component.getLocale() : Locale.getDefault()).getString(key); } /** * Check if the searchable popup is visible. * * @return true if visible. Otherwise, false. */ public boolean isPopupVisible() { return _popup != null; } public boolean isHeavyweightComponentEnabled() { return _heavyweightComponentEnabled; } public void setHeavyweightComponentEnabled(boolean heavyweightComponentEnabled) { _heavyweightComponentEnabled = heavyweightComponentEnabled; } /** * Gets the component that the location of the popup relative to. * * @return the component that the location of the popup relative to. */ public Component getPopupLocationRelativeTo() { return _popupLocationRelativeTo; } /** * Sets the location of the popup relative to the specified component. Then based on the value of {@link * #getPopupLocation()}. If you never set, we will use the searchable component or its scroll pane (if exists) as * the popupLocationRelativeTo component. * * @param popupLocationRelativeTo the relative component */ public void setPopupLocationRelativeTo(Component popupLocationRelativeTo) { _popupLocationRelativeTo = popupLocationRelativeTo; } /** * This is a property of how to compare searching text with the data. If it is true, it will use {@link * String#startsWith(String)} to do the comparison. Otherwise, it will use {@link String#indexOf(String)} to do the * comparison. * * @return true or false. */ public boolean isFromStart() { return _fromStart; } /** * Sets the fromStart property. * * @param fromStart true if the comparison matches from the start of the text only. Otherwise false. The difference * is if true, it will use String's <code>startWith</code> method to match. If false, it will use * <code>indedxOf</code> method. */ public void setFromStart(boolean fromStart) { hidePopup(); _fromStart = fromStart; } /** * Gets the Searchable installed on the component. Null is no Searchable was installed. * * @param component the component * @return the Searchable installed. Null is no Searchable was installed. */ public static Searchable getSearchable(JComponent component) { Object clientProperty = component.getClientProperty(CLIENT_PROPERTY_SEARCHABLE); if (clientProperty instanceof Searchable) { return ((Searchable) clientProperty); } else { return null; } } private void updateClientProperty(JComponent component, Searchable searchable) { if (component != null) { Object clientProperty = _component.getClientProperty(CLIENT_PROPERTY_SEARCHABLE); if (clientProperty instanceof Searchable) { ((Searchable) clientProperty).uninstallListeners(); } component.putClientProperty(CLIENT_PROPERTY_SEARCHABLE, searchable); } } /** * Get the flag if we should process model change event. * <p/> * By default, the value is true, which means the model change event should be processed. * <p/> * In <code>ListShrinkSearchableSupport</code> case, since we will fire this event while applying filters. This flag * will be switched to false before we fire the event and set it back to true. * <p/> * In normal case, please do not set this flag. * * @return true if we should process model change event. Otherwise false. */ public boolean isProcessModelChangeEvent() { return _processModelChangeEvent; } /** * Set the flag if we should process model change event. * <p/> * In normal case, please do not set this flag. * <p/> * @see #isProcessModelChangeEvent() * * @param processModelChangeEvent the flag */ public void setProcessModelChangeEvent(boolean processModelChangeEvent) { _processModelChangeEvent = processModelChangeEvent; } }
true
true
private void initComponents(String text) { final Color foreground = Searchable.this.getForeground(); final Color background = Searchable.this.getBackground(); // setup the label _label = new JLabel(getSearchLabel()); _label.setForeground(foreground); _label.setVerticalAlignment(JLabel.BOTTOM); _noMatch = new JLabel(); _noMatch.setForeground(getMismatchForeground()); _noMatch.setVerticalAlignment(JLabel.BOTTOM); //setup text field _textField = new SearchField(); _textField.setFocusable(false); _textField.setBorder(BorderFactory.createEmptyBorder()); _textField.setForeground(foreground); _textField.setCursor(getCursor()); _textField.getDocument().addDocumentListener(new DocumentListener() { private Timer timer = new Timer(200, new ActionListener() { public void actionPerformed(ActionEvent e) { applyText(); } }); public void insertUpdate(DocumentEvent e) { startTimer(); } public void removeUpdate(DocumentEvent e) { startTimer(); } public void changedUpdate(DocumentEvent e) { startTimer(); } protected void applyText() { String text = _textField.getText().trim(); firePropertyChangeEvent(text); if (text.length() != 0) { int found = findFromCursor(text); if (found == -1) { _textField.setForeground(getMismatchForeground()); } else { _textField.setForeground(foreground); } select(found, null, text); } else { hidePopup(); } } void startTimer() { updatePopupBounds(); if (getSearchingDelay() > 0) { timer.setInitialDelay(getSearchingDelay()); if (timer.isRunning()) { timer.restart(); } else { timer.setRepeats(false); timer.start(); } } else { applyText(); } } }); _textField.setText(text); setBackground(background); setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(UIDefaultsLookup.getColor("controlShadow"), 1), BorderFactory.createEmptyBorder(0, 6, 1, 8))); setLayout(new BorderLayout(2, 0)); Dimension size = _label.getPreferredSize(); size.height = _textField.getPreferredSize().height; _label.setPreferredSize(size); add(_label, BorderLayout.BEFORE_LINE_BEGINS); add(_textField, BorderLayout.CENTER); add(_noMatch, BorderLayout.AFTER_LINE_ENDS); setPopupBorder(BorderFactory.createEmptyBorder()); }
private void initComponents(String text) { final Color foreground = Searchable.this.getForeground(); final Color background = Searchable.this.getBackground(); // setup the label _label = new JLabel(getSearchLabel()); _label.setForeground(foreground); _label.setVerticalAlignment(JLabel.BOTTOM); _noMatch = new JLabel(); _noMatch.setForeground(getMismatchForeground()); _noMatch.setVerticalAlignment(JLabel.BOTTOM); //setup text field _textField = new SearchField(); _textField.setFocusable(false); _textField.setBorder(BorderFactory.createEmptyBorder()); _textField.setForeground(foreground); _textField.setCursor(getCursor()); _textField.getDocument().addDocumentListener(new DocumentListener() { private Timer timer = new Timer(200, new ActionListener() { public void actionPerformed(ActionEvent e) { applyText(); } }); public void insertUpdate(DocumentEvent e) { startTimer(); } public void removeUpdate(DocumentEvent e) { startTimer(); } public void changedUpdate(DocumentEvent e) { startTimer(); } protected void applyText() { String text = _textField.getText().trim(); firePropertyChangeEvent(text); if (text.length() != 0) { int found = findFromCursor(text); if (found == -1) { _textField.setForeground(getMismatchForeground()); } else { _textField.setForeground(foreground); } select(found, null, text); } else { _textField.setForeground(foreground); _noMatch.setText(""); hidePopup(); } } void startTimer() { updatePopupBounds(); if (getSearchingDelay() > 0) { timer.setInitialDelay(getSearchingDelay()); if (timer.isRunning()) { timer.restart(); } else { timer.setRepeats(false); timer.start(); } } else { applyText(); } } }); _textField.setText(text); setBackground(background); setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(UIDefaultsLookup.getColor("controlShadow"), 1), BorderFactory.createEmptyBorder(0, 6, 1, 8))); setLayout(new BorderLayout(2, 0)); Dimension size = _label.getPreferredSize(); size.height = _textField.getPreferredSize().height; _label.setPreferredSize(size); add(_label, BorderLayout.BEFORE_LINE_BEGINS); add(_textField, BorderLayout.CENTER); add(_noMatch, BorderLayout.AFTER_LINE_ENDS); setPopupBorder(BorderFactory.createEmptyBorder()); }
diff --git a/Tendu/src/it/chalmers/tendu/Tendu.java b/Tendu/src/it/chalmers/tendu/Tendu.java index 71f6f4e..8e2af02 100644 --- a/Tendu/src/it/chalmers/tendu/Tendu.java +++ b/Tendu/src/it/chalmers/tendu/Tendu.java @@ -1,187 +1,186 @@ //***Main entry of the libgdx-project**** package it.chalmers.tendu; import it.chalmers.tendu.controllers.InputController; import it.chalmers.tendu.defaults.Constants; import it.chalmers.tendu.gamemodel.MiniGame; import it.chalmers.tendu.gamemodel.Player; import it.chalmers.tendu.gamemodel.SessionResult; import it.chalmers.tendu.network.INetworkHandler; import it.chalmers.tendu.screens.GameOverScreen; import it.chalmers.tendu.screens.InterimScreen; import it.chalmers.tendu.screens.MainMenuScreen; import it.chalmers.tendu.screens.MiniGameScreenFactory; import it.chalmers.tendu.screens.Screen; import it.chalmers.tendu.tbd.C; import it.chalmers.tendu.tbd.EventBus; import it.chalmers.tendu.tbd.EventMessage; import it.chalmers.tendu.tbd.Listener; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.SpriteBatch; public class Tendu implements ApplicationListener, Listener { public static final String TAG = "Tendu"; // Tag for logging private Screen screen; // contains whats shown on device screen in any // given moment. Changes depending current // minigame or if in a menu etc private float accum = 0; // used to help lock frame rate in 60 frames per // second private InputController input; // used for handling input (obviously) private OrthographicCamera camera; // The use of a camera helps us to work // on one screen size no matter the // actual screen sizes of different // devices private INetworkHandler networkHandler; // handle to all network related // stuff (Android specific, at least // for now) public SpriteBatch spriteBatch; // used for drawing of graphics public Tendu(INetworkHandler networkHandler) { setNetworkHandler(networkHandler); EventBus.INSTANCE.addListener(this); } @Override public void create() { String mac = networkHandler.getMacAddress(); Player.getInstance().setMac(mac); Gdx.app.log(TAG, Player.getInstance().getMac()); spriteBatch = new SpriteBatch(); setScreen(new MainMenuScreen(this)); // setup the camera camera = new OrthographicCamera(); camera.setToOrtho(false, Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT); // create an inputController and register it with Gdx input = new InputController(camera); Gdx.input.setInputProcessor(input); } // clean up @Override public void dispose() { spriteBatch.dispose(); networkHandler.destroy(); } // **The games main loop, everything but early setup happens here @Override public void render() { // clear the entire screen // setScreenByNetworkState(); //changes to some error screen if // connections is lost? // clear the entire screen Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); //Gdx.gl.glClearColor(0.12f, 0.6f, 0.98f, 1); //Gdx.gl.glClearColor(1f, 1f, 0f, 1); //Gdx.gl.glClearColor(1f, 1f, 1f, 1); // makes sure the game runs in 60 fps accum += Gdx.graphics.getDeltaTime(); while (accum > 1.0f / 60.0f) { screen.tick(input); // runs tick in the current screen witch should // handle all input and game logic for that // specific minigame/menu input.tick(); // updates input accum -= 1.0f / 60.0f; } camera.update(); spriteBatch.setProjectionMatrix(camera.combined); spriteBatch.begin(); screen.render(); // draw all graphic for the current frame spriteBatch.end(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } // sets a new screen and cleans up the previous one public void setScreen(Screen newScreen) { if (screen != null) { screen.removed(); } screen = newScreen; } // the screens need access to the camera to handle translations between // actual screen pixels and our defined in game pixels public OrthographicCamera getCamera() { return camera; } //screens need access to the network public INetworkHandler getNetworkHandler() { return networkHandler; } private void setNetworkHandler(INetworkHandler networkHandler) { this.networkHandler = networkHandler; } @Override public void onBroadcast(EventMessage message) { if(message.tag == C.Tag.TO_SELF){ if (message.msg == C.Msg.CREATE_SCREEN) { MiniGame game = (MiniGame) message.content; Screen screen = MiniGameScreenFactory.createMiniGameScreen(this, game); setScreen(screen); EventMessage msg = new EventMessage(C.Tag.TO_SELF, C.Msg.WAITING_TO_START_GAME, Player.getInstance().getMac()); EventBus.INSTANCE.broadcast(msg); } else if (message.msg == C.Msg.SHOW_INTERIM_SCREEN) { SessionResult sessionResult = (SessionResult)message.content; Screen screen = new InterimScreen(this, sessionResult); setScreen(screen); } else if (message.msg == C.Msg.SHOW_GAME_OVER_SCREEN){ SessionResult sessionResult = (SessionResult)message.content; Screen screen = new GameOverScreen(this, sessionResult); setScreen(screen); - networkHandler.resetNetwork(); } else if (message.msg == C.Msg.RESTART){ // TODO: Unregister network Screen screen = new MainMenuScreen(this); setScreen(screen); } else if (message.msg == C.Msg.STOP_ACCEPTING_CONNECTIONS); networkHandler.stopAcceptingConnections(); } } @Override public void unregister() { // TODO: Will this ever be called? ( maybe on dispose() ) EventBus.INSTANCE.removeListener(this); } }
true
true
public void onBroadcast(EventMessage message) { if(message.tag == C.Tag.TO_SELF){ if (message.msg == C.Msg.CREATE_SCREEN) { MiniGame game = (MiniGame) message.content; Screen screen = MiniGameScreenFactory.createMiniGameScreen(this, game); setScreen(screen); EventMessage msg = new EventMessage(C.Tag.TO_SELF, C.Msg.WAITING_TO_START_GAME, Player.getInstance().getMac()); EventBus.INSTANCE.broadcast(msg); } else if (message.msg == C.Msg.SHOW_INTERIM_SCREEN) { SessionResult sessionResult = (SessionResult)message.content; Screen screen = new InterimScreen(this, sessionResult); setScreen(screen); } else if (message.msg == C.Msg.SHOW_GAME_OVER_SCREEN){ SessionResult sessionResult = (SessionResult)message.content; Screen screen = new GameOverScreen(this, sessionResult); setScreen(screen); networkHandler.resetNetwork(); } else if (message.msg == C.Msg.RESTART){ // TODO: Unregister network Screen screen = new MainMenuScreen(this); setScreen(screen); } else if (message.msg == C.Msg.STOP_ACCEPTING_CONNECTIONS); networkHandler.stopAcceptingConnections(); } }
public void onBroadcast(EventMessage message) { if(message.tag == C.Tag.TO_SELF){ if (message.msg == C.Msg.CREATE_SCREEN) { MiniGame game = (MiniGame) message.content; Screen screen = MiniGameScreenFactory.createMiniGameScreen(this, game); setScreen(screen); EventMessage msg = new EventMessage(C.Tag.TO_SELF, C.Msg.WAITING_TO_START_GAME, Player.getInstance().getMac()); EventBus.INSTANCE.broadcast(msg); } else if (message.msg == C.Msg.SHOW_INTERIM_SCREEN) { SessionResult sessionResult = (SessionResult)message.content; Screen screen = new InterimScreen(this, sessionResult); setScreen(screen); } else if (message.msg == C.Msg.SHOW_GAME_OVER_SCREEN){ SessionResult sessionResult = (SessionResult)message.content; Screen screen = new GameOverScreen(this, sessionResult); setScreen(screen); } else if (message.msg == C.Msg.RESTART){ // TODO: Unregister network Screen screen = new MainMenuScreen(this); setScreen(screen); } else if (message.msg == C.Msg.STOP_ACCEPTING_CONNECTIONS); networkHandler.stopAcceptingConnections(); } }
diff --git a/src/com/phonegap/api/impl/FileCommand.java b/src/com/phonegap/api/impl/FileCommand.java index d4be7da..6bd1c17 100644 --- a/src/com/phonegap/api/impl/FileCommand.java +++ b/src/com/phonegap/api/impl/FileCommand.java @@ -1,52 +1,52 @@ package com.phonegap.api.impl; import com.phonegap.PhoneGap; import com.phonegap.api.Command; public class FileCommand implements Command { private static final String CODE = "PhoneGap=file"; private static final int READ_COMMAND = 0; /** * Determines whether the specified instruction is accepted by the command. * @param instruction The string instruction passed from JavaScript via cookie. * @return true if the Command accepts the instruction, false otherwise. */ public boolean accept(String instruction) { return instruction != null && instruction.startsWith(CODE); } /** * Invokes internal phone application. */ public String execute(String instruction) { switch (getCommand(instruction)) { case READ_COMMAND: try { String filePath = instruction.substring(CODE.length() + 6); - return ";if (navigator.file.read_success != null) { navigator.file.read_success("+escapeString(filePath)+"); };"; + return ";if (navigator.file.read_success != null) { navigator.file.read_success('"+escapeString(filePath)+"'); };"; } catch (Exception e) { return ";if (navigator.file.read_error != null) { navigator.file.read_error('Exception: " + e.getMessage().replace('\'', '`') + "'); };"; } } return null; } private int getCommand(String instruction) { String command = instruction.substring(CODE.length()+1); if (command.startsWith("read")) return READ_COMMAND; return -1; } private String escapeString(String value) { // Replace the following: // => \ with \\ // => " with \" // => ' with \' value = PhoneGap.replace(value, "\\", "\\\\"); value = PhoneGap.replace(value, "\"", "\\\""); value = PhoneGap.replace(value, "'", "\\'"); return value; } }
true
true
public String execute(String instruction) { switch (getCommand(instruction)) { case READ_COMMAND: try { String filePath = instruction.substring(CODE.length() + 6); return ";if (navigator.file.read_success != null) { navigator.file.read_success("+escapeString(filePath)+"); };"; } catch (Exception e) { return ";if (navigator.file.read_error != null) { navigator.file.read_error('Exception: " + e.getMessage().replace('\'', '`') + "'); };"; } } return null; }
public String execute(String instruction) { switch (getCommand(instruction)) { case READ_COMMAND: try { String filePath = instruction.substring(CODE.length() + 6); return ";if (navigator.file.read_success != null) { navigator.file.read_success('"+escapeString(filePath)+"'); };"; } catch (Exception e) { return ";if (navigator.file.read_error != null) { navigator.file.read_error('Exception: " + e.getMessage().replace('\'', '`') + "'); };"; } } return null; }
diff --git a/org.eclipse.mylyn.resources.ui/src/org/eclipse/mylyn/internal/resources/ResourceChangeMonitor.java b/org.eclipse.mylyn.resources.ui/src/org/eclipse/mylyn/internal/resources/ResourceChangeMonitor.java index 93305bd41..8d5bd21ca 100644 --- a/org.eclipse.mylyn.resources.ui/src/org/eclipse/mylyn/internal/resources/ResourceChangeMonitor.java +++ b/org.eclipse.mylyn.resources.ui/src/org/eclipse/mylyn/internal/resources/ResourceChangeMonitor.java @@ -1,105 +1,105 @@ /******************************************************************************* * Copyright (c) 2004 - 2006 University Of British Columbia 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: * University Of British Columbia - initial API and implementation *******************************************************************************/ package org.eclipse.mylar.internal.resources; import java.util.HashSet; import java.util.Set; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IResourceDeltaVisitor; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.mylar.context.core.ContextCorePlugin; import org.eclipse.mylar.context.core.InteractionEvent; import org.eclipse.mylar.context.core.MylarStatusHandler; import org.eclipse.mylar.resources.MylarResourcesPlugin; /** * @author Mik Kersten */ public class ResourceChangeMonitor implements IResourceChangeListener { private boolean enabled = true; public void resourceChanged(IResourceChangeEvent event) { if (!enabled || !ContextCorePlugin.getContextManager().isContextActive()) { return; } if (event.getType() != IResourceChangeEvent.POST_CHANGE) { return; } final Set<IResource> addedResources = new HashSet<IResource>(); final Set<IResource> changedResources = new HashSet<IResource>(); final Set<String> excludedPatterns = MylarResourcesPlugin.getDefault().getExcludedResourcePatterns(); IResourceDelta rootDelta = event.getDelta(); IResourceDeltaVisitor visitor = new IResourceDeltaVisitor() { public boolean visit(IResourceDelta delta) { IResourceDelta[] added = delta.getAffectedChildren(IResourceDelta.ADDED); for (int i = 0; i < added.length; i++) { IResource resource = added[i].getResource(); if ((resource instanceof IFile || resource instanceof IFolder) && !isExcluded(resource.getProjectRelativePath(), excludedPatterns)) { addedResources.add(resource); } } // int changeMask = IResourceDelta.CONTENT | IResourceDelta.REMOVED | IResourceDelta.MOVED_TO | IResourceDelta.MOVED_FROM; - IResourceDelta[] changed = delta.getAffectedChildren(IResourceDelta.CHANGED); + IResourceDelta[] changed = delta.getAffectedChildren(IResourceDelta.CHANGED | IResourceDelta.REMOVED); for (int i = 0; i < changed.length; i++) { IResource resource = changed[i].getResource(); if (resource instanceof IFile) { changedResources.add(resource); } } return true; } }; try { rootDelta.accept(visitor); MylarResourcesPlugin.getDefault().getInterestUpdater().addResourceToContext(changedResources, InteractionEvent.Kind.PREDICTION); MylarResourcesPlugin.getDefault().getInterestUpdater().addResourceToContext(addedResources, InteractionEvent.Kind.SELECTION); } catch (CoreException e) { MylarStatusHandler.log(e, "could not accept marker visitor"); } } /** * Public for testing. */ public boolean isExcluded(IPath path, Set<String> excludedPatterns) { if (path == null) { return false; } // NOTE: n^2 time complexity, but should not be a bottleneck boolean excluded = false; for (String pattern : excludedPatterns) { for (String segment : path.segments()) { boolean matches = segment.matches(pattern.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*")); if (matches) { excluded = true; } } } return excluded; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } }
true
true
public void resourceChanged(IResourceChangeEvent event) { if (!enabled || !ContextCorePlugin.getContextManager().isContextActive()) { return; } if (event.getType() != IResourceChangeEvent.POST_CHANGE) { return; } final Set<IResource> addedResources = new HashSet<IResource>(); final Set<IResource> changedResources = new HashSet<IResource>(); final Set<String> excludedPatterns = MylarResourcesPlugin.getDefault().getExcludedResourcePatterns(); IResourceDelta rootDelta = event.getDelta(); IResourceDeltaVisitor visitor = new IResourceDeltaVisitor() { public boolean visit(IResourceDelta delta) { IResourceDelta[] added = delta.getAffectedChildren(IResourceDelta.ADDED); for (int i = 0; i < added.length; i++) { IResource resource = added[i].getResource(); if ((resource instanceof IFile || resource instanceof IFolder) && !isExcluded(resource.getProjectRelativePath(), excludedPatterns)) { addedResources.add(resource); } } // int changeMask = IResourceDelta.CONTENT | IResourceDelta.REMOVED | IResourceDelta.MOVED_TO | IResourceDelta.MOVED_FROM; IResourceDelta[] changed = delta.getAffectedChildren(IResourceDelta.CHANGED); for (int i = 0; i < changed.length; i++) { IResource resource = changed[i].getResource(); if (resource instanceof IFile) { changedResources.add(resource); } } return true; } }; try { rootDelta.accept(visitor); MylarResourcesPlugin.getDefault().getInterestUpdater().addResourceToContext(changedResources, InteractionEvent.Kind.PREDICTION); MylarResourcesPlugin.getDefault().getInterestUpdater().addResourceToContext(addedResources, InteractionEvent.Kind.SELECTION); } catch (CoreException e) { MylarStatusHandler.log(e, "could not accept marker visitor"); } }
public void resourceChanged(IResourceChangeEvent event) { if (!enabled || !ContextCorePlugin.getContextManager().isContextActive()) { return; } if (event.getType() != IResourceChangeEvent.POST_CHANGE) { return; } final Set<IResource> addedResources = new HashSet<IResource>(); final Set<IResource> changedResources = new HashSet<IResource>(); final Set<String> excludedPatterns = MylarResourcesPlugin.getDefault().getExcludedResourcePatterns(); IResourceDelta rootDelta = event.getDelta(); IResourceDeltaVisitor visitor = new IResourceDeltaVisitor() { public boolean visit(IResourceDelta delta) { IResourceDelta[] added = delta.getAffectedChildren(IResourceDelta.ADDED); for (int i = 0; i < added.length; i++) { IResource resource = added[i].getResource(); if ((resource instanceof IFile || resource instanceof IFolder) && !isExcluded(resource.getProjectRelativePath(), excludedPatterns)) { addedResources.add(resource); } } // int changeMask = IResourceDelta.CONTENT | IResourceDelta.REMOVED | IResourceDelta.MOVED_TO | IResourceDelta.MOVED_FROM; IResourceDelta[] changed = delta.getAffectedChildren(IResourceDelta.CHANGED | IResourceDelta.REMOVED); for (int i = 0; i < changed.length; i++) { IResource resource = changed[i].getResource(); if (resource instanceof IFile) { changedResources.add(resource); } } return true; } }; try { rootDelta.accept(visitor); MylarResourcesPlugin.getDefault().getInterestUpdater().addResourceToContext(changedResources, InteractionEvent.Kind.PREDICTION); MylarResourcesPlugin.getDefault().getInterestUpdater().addResourceToContext(addedResources, InteractionEvent.Kind.SELECTION); } catch (CoreException e) { MylarStatusHandler.log(e, "could not accept marker visitor"); } }
diff --git a/src/com/kkbox/toolkit/utils/KKEventQueue.java b/src/com/kkbox/toolkit/utils/KKEventQueue.java index 36693c3..1e9b19f 100644 --- a/src/com/kkbox/toolkit/utils/KKEventQueue.java +++ b/src/com/kkbox/toolkit/utils/KKEventQueue.java @@ -1,146 +1,147 @@ /* Copyright (C) 2013 KKBOX 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. */ /** * KKEventQueue */ package com.kkbox.toolkit.utils; import java.util.ArrayList; public class KKEventQueue { public static class ThreadType { public static final int CALLER_THREAD = 0; public static final int NEW_THREAD = 1; } private class KKEvent { public Runnable runnable; public int threadType; public Runnable postEventRunnable; } private final ArrayList<KKEvent> queue = new ArrayList<KKEvent>(); private KKEventQueueListener listener; private boolean isRunning = false; private ArrayList<Integer> threadUnlockId = new ArrayList<Integer>(); private boolean threadUnlockFlag = false; private final Object threadLock = new Object(); public void add(Runnable runnable, int threadType) { final KKEvent newEvent = new KKEvent(); newEvent.runnable = runnable; newEvent.threadType = threadType; queue.add(newEvent); } public void addNewThreadEvent(Runnable newThreadRunnable, Runnable postEventRunnable) { final KKEvent newEvent = new KKEvent(); newEvent.runnable = newThreadRunnable; newEvent.threadType = ThreadType.NEW_THREAD; newEvent.postEventRunnable = postEventRunnable; queue.add(newEvent); } public void addCallerThreadEventWithLock(Runnable callerThreadRunnable, final int lockId) { add(callerThreadRunnable, ThreadType.CALLER_THREAD); add(new Runnable() { @Override public void run() { while (!threadUnlockId.contains(lockId) && !threadUnlockFlag) { try { synchronized (threadLock) { threadLock.wait(); } } catch (final InterruptedException e) {} } threadUnlockId.clear(); } }, ThreadType.NEW_THREAD); } public void unlockEvent(int lockId) { synchronized (threadLock) { threadUnlockId.add(lockId); threadLock.notifyAll(); } } public void unlockAllEvents() { synchronized (threadLock) { threadUnlockFlag = true; threadLock.notifyAll(); } } public void clearPendingEvents() { if (!isRunning) { queue.clear(); } else { while (queue.size() > 1) { queue.remove(1); } } } public boolean isRunning() { return isRunning; } public void start() { if (!isRunning) { run(); } } public void setListener(KKEventQueueListener listener) { this.listener = listener; } private void run() { - if (queue.size() == 0) { + if (queue.size() > 0) { + isRunning = true; + } else { isRunning = false; threadUnlockFlag = false; threadUnlockId.clear(); if (listener != null) { listener.onQueueCompleted(); } return; } - isRunning = true; final KKEvent event = queue.get(0); if (event.threadType == ThreadType.NEW_THREAD) { new UserTask<Void, Void, Void>() { @Override public Void doInBackground(Void... params) { event.runnable.run(); return null; } @Override public void onPostExecute(Void v) { if (event.postEventRunnable != null) { event.postEventRunnable.run(); } queue.remove(0); run(); } }.execute(); } else if (event.threadType == ThreadType.CALLER_THREAD) { event.runnable.run(); queue.remove(0); run(); } } }
false
true
private void run() { if (queue.size() == 0) { isRunning = false; threadUnlockFlag = false; threadUnlockId.clear(); if (listener != null) { listener.onQueueCompleted(); } return; } isRunning = true; final KKEvent event = queue.get(0); if (event.threadType == ThreadType.NEW_THREAD) { new UserTask<Void, Void, Void>() { @Override public Void doInBackground(Void... params) { event.runnable.run(); return null; } @Override public void onPostExecute(Void v) { if (event.postEventRunnable != null) { event.postEventRunnable.run(); } queue.remove(0); run(); } }.execute(); } else if (event.threadType == ThreadType.CALLER_THREAD) { event.runnable.run(); queue.remove(0); run(); } }
private void run() { if (queue.size() > 0) { isRunning = true; } else { isRunning = false; threadUnlockFlag = false; threadUnlockId.clear(); if (listener != null) { listener.onQueueCompleted(); } return; } final KKEvent event = queue.get(0); if (event.threadType == ThreadType.NEW_THREAD) { new UserTask<Void, Void, Void>() { @Override public Void doInBackground(Void... params) { event.runnable.run(); return null; } @Override public void onPostExecute(Void v) { if (event.postEventRunnable != null) { event.postEventRunnable.run(); } queue.remove(0); run(); } }.execute(); } else if (event.threadType == ThreadType.CALLER_THREAD) { event.runnable.run(); queue.remove(0); run(); } }
diff --git a/src/main/java/org/generationcp/ibpworkbench/actions/LaunchWorkbenchToolAction.java b/src/main/java/org/generationcp/ibpworkbench/actions/LaunchWorkbenchToolAction.java index d82b7df..34ca1a2 100644 --- a/src/main/java/org/generationcp/ibpworkbench/actions/LaunchWorkbenchToolAction.java +++ b/src/main/java/org/generationcp/ibpworkbench/actions/LaunchWorkbenchToolAction.java @@ -1,97 +1,97 @@ package org.generationcp.ibpworkbench.actions; import java.io.File; import java.io.IOException; import org.generationcp.ibpworkbench.comp.window.IContentWindow; import org.generationcp.ibpworkbench.datasource.helper.DatasourceConfig; import org.generationcp.middleware.manager.api.WorkbenchDataManager; import org.generationcp.middleware.pojos.workbench.Tool; import org.generationcp.middleware.pojos.workbench.ToolType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import com.vaadin.terminal.ExternalResource; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.Embedded; import com.vaadin.ui.Window; import com.vaadin.ui.Window.Notification; @Configurable public class LaunchWorkbenchToolAction implements ClickListener { private static final long serialVersionUID = 1L; private final static Logger log = LoggerFactory.getLogger(LaunchWorkbenchToolAction.class); public static enum ToolId { GERMPLASM_BROWSER("germplasm_browser") ,GERMPLASM_PHENOTYPIC("germplasm_phenotypic") ,GDMS("gdms") ,FIELDBOOK("fieldbook") ,OPTIMAS("optimas") ; String toolId; ToolId(String toolId) { this.toolId = toolId; } public String getToolId() { return toolId; } } private ToolId toolId; private DatasourceConfig dataSourceConfig; public LaunchWorkbenchToolAction(ToolId toolId) { this.toolId = toolId; } @Autowired(required = true) public void setDataSourceConfig(DatasourceConfig dataSourceConfig) { this.dataSourceConfig = dataSourceConfig; } @Override public void buttonClick(ClickEvent event) { Window window = event.getComponent().getWindow(); WorkbenchDataManager workbenchDataManager = dataSourceConfig.getManagerFactory().getWorkbenchDataManager(); Tool tool = workbenchDataManager.getToolWithName(toolId.getToolId()); if (tool == null) { log.warn("Cannot find tool " + toolId); window.showNotification("Launch Error", "Cannot launch tool.", Notification.TYPE_ERROR_MESSAGE); return; } if (tool.getToolType() == ToolType.NATIVE) { - File absoluteToolFile = new File(tool.getPath()); + File absoluteToolFile = new File(tool.getPath()).getAbsoluteFile(); Runtime runtime = Runtime.getRuntime(); try { runtime.exec(absoluteToolFile.getAbsolutePath()); } catch (IOException e) { log.error("Cannot launch " + absoluteToolFile.getAbsolutePath(), e); window.showNotification("Launch Error", "Cannot launch tool at " + absoluteToolFile.getAbsolutePath(), Notification.TYPE_ERROR_MESSAGE); } } else { Embedded browser = new Embedded("", new ExternalResource(tool.getPath())); browser.setType(Embedded.TYPE_BROWSER); browser.setSizeFull(); IContentWindow contentWindow = (IContentWindow) event.getComponent().getWindow(); contentWindow.showContent(browser); } } }
true
true
public void buttonClick(ClickEvent event) { Window window = event.getComponent().getWindow(); WorkbenchDataManager workbenchDataManager = dataSourceConfig.getManagerFactory().getWorkbenchDataManager(); Tool tool = workbenchDataManager.getToolWithName(toolId.getToolId()); if (tool == null) { log.warn("Cannot find tool " + toolId); window.showNotification("Launch Error", "Cannot launch tool.", Notification.TYPE_ERROR_MESSAGE); return; } if (tool.getToolType() == ToolType.NATIVE) { File absoluteToolFile = new File(tool.getPath()); Runtime runtime = Runtime.getRuntime(); try { runtime.exec(absoluteToolFile.getAbsolutePath()); } catch (IOException e) { log.error("Cannot launch " + absoluteToolFile.getAbsolutePath(), e); window.showNotification("Launch Error", "Cannot launch tool at " + absoluteToolFile.getAbsolutePath(), Notification.TYPE_ERROR_MESSAGE); } } else { Embedded browser = new Embedded("", new ExternalResource(tool.getPath())); browser.setType(Embedded.TYPE_BROWSER); browser.setSizeFull(); IContentWindow contentWindow = (IContentWindow) event.getComponent().getWindow(); contentWindow.showContent(browser); } }
public void buttonClick(ClickEvent event) { Window window = event.getComponent().getWindow(); WorkbenchDataManager workbenchDataManager = dataSourceConfig.getManagerFactory().getWorkbenchDataManager(); Tool tool = workbenchDataManager.getToolWithName(toolId.getToolId()); if (tool == null) { log.warn("Cannot find tool " + toolId); window.showNotification("Launch Error", "Cannot launch tool.", Notification.TYPE_ERROR_MESSAGE); return; } if (tool.getToolType() == ToolType.NATIVE) { File absoluteToolFile = new File(tool.getPath()).getAbsoluteFile(); Runtime runtime = Runtime.getRuntime(); try { runtime.exec(absoluteToolFile.getAbsolutePath()); } catch (IOException e) { log.error("Cannot launch " + absoluteToolFile.getAbsolutePath(), e); window.showNotification("Launch Error", "Cannot launch tool at " + absoluteToolFile.getAbsolutePath(), Notification.TYPE_ERROR_MESSAGE); } } else { Embedded browser = new Embedded("", new ExternalResource(tool.getPath())); browser.setType(Embedded.TYPE_BROWSER); browser.setSizeFull(); IContentWindow contentWindow = (IContentWindow) event.getComponent().getWindow(); contentWindow.showContent(browser); } }
diff --git a/src/com/android/exchange/adapter/ProvisionParser.java b/src/com/android/exchange/adapter/ProvisionParser.java index 057ffaff..5ba43e4b 100644 --- a/src/com/android/exchange/adapter/ProvisionParser.java +++ b/src/com/android/exchange/adapter/ProvisionParser.java @@ -1,450 +1,446 @@ /* 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.exchange.adapter; import com.android.email.SecurityPolicy; import com.android.email.SecurityPolicy.PolicySet; import com.android.exchange.EasSyncService; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; /** * Parse the result of the Provision command * * Assuming a successful parse, we store the PolicySet and the policy key */ public class ProvisionParser extends Parser { private EasSyncService mService; PolicySet mPolicySet = null; String mPolicyKey = null; boolean mRemoteWipe = false; boolean mIsSupportable = true; public ProvisionParser(InputStream in, EasSyncService service) throws IOException { super(in); mService = service; } public PolicySet getPolicySet() { return mPolicySet; } public String getPolicyKey() { return mPolicyKey; } public boolean getRemoteWipe() { return mRemoteWipe; } public boolean hasSupportablePolicySet() { return (mPolicySet != null) && mIsSupportable; } private void parseProvisionDocWbxml() throws IOException { int minPasswordLength = 0; int passwordMode = PolicySet.PASSWORD_MODE_NONE; int maxPasswordFails = 0; int maxScreenLockTime = 0; int passwordExpiration = 0; int passwordHistory = 0; int passwordComplexChars = 0; while (nextTag(Tags.PROVISION_EAS_PROVISION_DOC) != END) { boolean tagIsSupported = true; switch (tag) { case Tags.PROVISION_DEVICE_PASSWORD_ENABLED: if (getValueInt() == 1) { if (passwordMode == PolicySet.PASSWORD_MODE_NONE) { passwordMode = PolicySet.PASSWORD_MODE_SIMPLE; } } break; case Tags.PROVISION_MIN_DEVICE_PASSWORD_LENGTH: minPasswordLength = getValueInt(); break; case Tags.PROVISION_ALPHA_DEVICE_PASSWORD_ENABLED: if (getValueInt() == 1) { passwordMode = PolicySet.PASSWORD_MODE_STRONG; } break; case Tags.PROVISION_MAX_INACTIVITY_TIME_DEVICE_LOCK: // EAS gives us seconds, which is, happily, what the PolicySet requires maxScreenLockTime = getValueInt(); break; case Tags.PROVISION_MAX_DEVICE_PASSWORD_FAILED_ATTEMPTS: maxPasswordFails = getValueInt(); break; case Tags.PROVISION_DEVICE_PASSWORD_EXPIRATION: passwordExpiration = getValueInt(); // We don't yet support this if (passwordExpiration > 0) { tagIsSupported = false; } break; case Tags.PROVISION_DEVICE_PASSWORD_HISTORY: passwordHistory = getValueInt(); break; case Tags.PROVISION_ALLOW_SIMPLE_DEVICE_PASSWORD: // Ignore this unless there's any MSFT documentation for what this means // Hint: I haven't seen any that's more specific than "simple" getValue(); break; // The following policies, if false, can't be supported at the moment case Tags.PROVISION_ATTACHMENTS_ENABLED: case Tags.PROVISION_ALLOW_STORAGE_CARD: case Tags.PROVISION_ALLOW_CAMERA: case Tags.PROVISION_ALLOW_UNSIGNED_APPLICATIONS: case Tags.PROVISION_ALLOW_UNSIGNED_INSTALLATION_PACKAGES: case Tags.PROVISION_ALLOW_WIFI: case Tags.PROVISION_ALLOW_TEXT_MESSAGING: case Tags.PROVISION_ALLOW_POP_IMAP_EMAIL: case Tags.PROVISION_ALLOW_IRDA: case Tags.PROVISION_ALLOW_HTML_EMAIL: case Tags.PROVISION_ALLOW_BROWSER: case Tags.PROVISION_ALLOW_CONSUMER_EMAIL: case Tags.PROVISION_ALLOW_INTERNET_SHARING: if (getValueInt() == 0) { tagIsSupported = false; } break; // Bluetooth: 0 = no bluetooth; 1 = only hands-free; 2 = allowed case Tags.PROVISION_ALLOW_BLUETOOTH: if (getValueInt() != 2) { tagIsSupported = false; } break; // The following policies, if true, can't be supported at the moment case Tags.PROVISION_DEVICE_ENCRYPTION_ENABLED: case Tags.PROVISION_PASSWORD_RECOVERY_ENABLED: case Tags.PROVISION_REQUIRE_DEVICE_ENCRYPTION: case Tags.PROVISION_REQUIRE_SIGNED_SMIME_MESSAGES: case Tags.PROVISION_REQUIRE_ENCRYPTED_SMIME_MESSAGES: case Tags.PROVISION_REQUIRE_SIGNED_SMIME_ALGORITHM: case Tags.PROVISION_REQUIRE_ENCRYPTION_SMIME_ALGORITHM: case Tags.PROVISION_REQUIRE_MANUAL_SYNC_WHEN_ROAMING: if (getValueInt() == 1) { tagIsSupported = false; } break; // The following, if greater than zero, can't be supported at the moment case Tags.PROVISION_MAX_ATTACHMENT_SIZE: if (getValueInt() > 0) { tagIsSupported = false; } break; - // Complex character setting is only used if we're in "strong" (alphanumeric) mode + // Complex characters are supported case Tags.PROVISION_MIN_DEVICE_PASSWORD_COMPLEX_CHARS: passwordComplexChars = getValueInt(); - if ((passwordMode != PolicySet.PASSWORD_MODE_STRONG) && - (passwordComplexChars > 0)) { - tagIsSupported = false; - } break; // The following policies are moot; they allow functionality that we don't support case Tags.PROVISION_ALLOW_DESKTOP_SYNC: case Tags.PROVISION_ALLOW_SMIME_ENCRYPTION_NEGOTIATION: case Tags.PROVISION_ALLOW_SMIME_SOFT_CERTS: case Tags.PROVISION_ALLOW_REMOTE_DESKTOP: skipTag(); break; // We don't handle approved/unapproved application lists case Tags.PROVISION_UNAPPROVED_IN_ROM_APPLICATION_LIST: case Tags.PROVISION_APPROVED_APPLICATION_LIST: // Parse and throw away the content if (specifiesApplications(tag)) { tagIsSupported = false; } break; // NOTE: We can support these entirely within the email application if we choose case Tags.PROVISION_MAX_CALENDAR_AGE_FILTER: case Tags.PROVISION_MAX_EMAIL_AGE_FILTER: // 0 indicates no specified filter if (getValueInt() != 0) { tagIsSupported = false; } break; // NOTE: We can support these entirely within the email application if we choose case Tags.PROVISION_MAX_EMAIL_BODY_TRUNCATION_SIZE: case Tags.PROVISION_MAX_EMAIL_HTML_BODY_TRUNCATION_SIZE: String value = getValue(); // -1 indicates no required truncation if (!value.equals("-1")) { tagIsSupported = false; } break; default: skipTag(); } if (!tagIsSupported) { log("Policy not supported: " + tag); mIsSupportable = false; } } mPolicySet = new SecurityPolicy.PolicySet(minPasswordLength, passwordMode, maxPasswordFails, maxScreenLockTime, true, passwordExpiration, passwordHistory, passwordComplexChars); } /** * Return whether or not either of the application list tags specifies any applications * @param endTag the tag whose children we're walking through * @return whether any applications were specified (by name or by hash) * @throws IOException */ private boolean specifiesApplications(int endTag) throws IOException { boolean specifiesApplications = false; while (nextTag(endTag) != END) { switch (tag) { case Tags.PROVISION_APPLICATION_NAME: case Tags.PROVISION_HASH: specifiesApplications = true; break; default: skipTag(); } } return specifiesApplications; } class ShadowPolicySet { int mMinPasswordLength = 0; int mPasswordMode = PolicySet.PASSWORD_MODE_NONE; int mMaxPasswordFails = 0; int mMaxScreenLockTime = 0; int mPasswordExpiration = 0; int mPasswordHistory = 0; int mPasswordComplexChars = 0; } /*package*/ void parseProvisionDocXml(String doc) throws IOException { ShadowPolicySet sps = new ShadowPolicySet(); try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser parser = factory.newPullParser(); parser.setInput(new ByteArrayInputStream(doc.getBytes()), "UTF-8"); int type = parser.getEventType(); if (type == XmlPullParser.START_DOCUMENT) { type = parser.next(); if (type == XmlPullParser.START_TAG) { String tagName = parser.getName(); if (tagName.equals("wap-provisioningdoc")) { parseWapProvisioningDoc(parser, sps); } } } } catch (XmlPullParserException e) { throw new IOException(); } mPolicySet = new PolicySet(sps.mMinPasswordLength, sps.mPasswordMode, sps.mMaxPasswordFails, sps.mMaxScreenLockTime, true, sps.mPasswordExpiration, sps.mPasswordHistory, sps.mPasswordComplexChars); } /** * Return true if password is required; otherwise false. */ private boolean parseSecurityPolicy(XmlPullParser parser, ShadowPolicySet sps) throws XmlPullParserException, IOException { boolean passwordRequired = true; while (true) { int type = parser.nextTag(); if (type == XmlPullParser.END_TAG && parser.getName().equals("characteristic")) { break; } else if (type == XmlPullParser.START_TAG) { String tagName = parser.getName(); if (tagName.equals("parm")) { String name = parser.getAttributeValue(null, "name"); if (name.equals("4131")) { String value = parser.getAttributeValue(null, "value"); if (value.equals("1")) { passwordRequired = false; } } } } } return passwordRequired; } private void parseCharacteristic(XmlPullParser parser, ShadowPolicySet sps) throws XmlPullParserException, IOException { boolean enforceInactivityTimer = true; while (true) { int type = parser.nextTag(); if (type == XmlPullParser.END_TAG && parser.getName().equals("characteristic")) { break; } else if (type == XmlPullParser.START_TAG) { if (parser.getName().equals("parm")) { String name = parser.getAttributeValue(null, "name"); String value = parser.getAttributeValue(null, "value"); if (name.equals("AEFrequencyValue")) { if (enforceInactivityTimer) { if (value.equals("0")) { sps.mMaxScreenLockTime = 1; } else { sps.mMaxScreenLockTime = 60*Integer.parseInt(value); } } } else if (name.equals("AEFrequencyType")) { // "0" here means we don't enforce an inactivity timeout if (value.equals("0")) { enforceInactivityTimer = false; } } else if (name.equals("DeviceWipeThreshold")) { sps.mMaxPasswordFails = Integer.parseInt(value); } else if (name.equals("CodewordFrequency")) { // Ignore; has no meaning for us } else if (name.equals("MinimumPasswordLength")) { sps.mMinPasswordLength = Integer.parseInt(value); } else if (name.equals("PasswordComplexity")) { if (value.equals("0")) { sps.mPasswordMode = PolicySet.PASSWORD_MODE_STRONG; } else { sps.mPasswordMode = PolicySet.PASSWORD_MODE_SIMPLE; } } } } } } private void parseRegistry(XmlPullParser parser, ShadowPolicySet sps) throws XmlPullParserException, IOException { while (true) { int type = parser.nextTag(); if (type == XmlPullParser.END_TAG && parser.getName().equals("characteristic")) { break; } else if (type == XmlPullParser.START_TAG) { String name = parser.getName(); if (name.equals("characteristic")) { parseCharacteristic(parser, sps); } } } } private void parseWapProvisioningDoc(XmlPullParser parser, ShadowPolicySet sps) throws XmlPullParserException, IOException { while (true) { int type = parser.nextTag(); if (type == XmlPullParser.END_TAG && parser.getName().equals("wap-provisioningdoc")) { break; } else if (type == XmlPullParser.START_TAG) { String name = parser.getName(); if (name.equals("characteristic")) { String atype = parser.getAttributeValue(null, "type"); if (atype.equals("SecurityPolicy")) { // If a password isn't required, stop here if (!parseSecurityPolicy(parser, sps)) { return; } } else if (atype.equals("Registry")) { parseRegistry(parser, sps); return; } } } } } private void parseProvisionData() throws IOException { while (nextTag(Tags.PROVISION_DATA) != END) { if (tag == Tags.PROVISION_EAS_PROVISION_DOC) { parseProvisionDocWbxml(); } else { skipTag(); } } } private void parsePolicy() throws IOException { String policyType = null; while (nextTag(Tags.PROVISION_POLICY) != END) { switch (tag) { case Tags.PROVISION_POLICY_TYPE: policyType = getValue(); mService.userLog("Policy type: ", policyType); break; case Tags.PROVISION_POLICY_KEY: mPolicyKey = getValue(); break; case Tags.PROVISION_STATUS: mService.userLog("Policy status: ", getValue()); break; case Tags.PROVISION_DATA: if (policyType.equalsIgnoreCase(EasSyncService.EAS_2_POLICY_TYPE)) { // Parse the old style XML document parseProvisionDocXml(getValue()); } else { // Parse the newer WBXML data parseProvisionData(); } break; default: skipTag(); } } } private void parsePolicies() throws IOException { while (nextTag(Tags.PROVISION_POLICIES) != END) { if (tag == Tags.PROVISION_POLICY) { parsePolicy(); } else { skipTag(); } } } @Override public boolean parse() throws IOException { boolean res = false; if (nextTag(START_DOCUMENT) != Tags.PROVISION_PROVISION) { throw new IOException(); } while (nextTag(START_DOCUMENT) != END_DOCUMENT) { switch (tag) { case Tags.PROVISION_STATUS: int status = getValueInt(); mService.userLog("Provision status: ", status); res = (status == 1); break; case Tags.PROVISION_POLICIES: parsePolicies(); break; case Tags.PROVISION_REMOTE_WIPE: // Indicate remote wipe command received mRemoteWipe = true; break; default: skipTag(); } } return res; } }
false
true
private void parseProvisionDocWbxml() throws IOException { int minPasswordLength = 0; int passwordMode = PolicySet.PASSWORD_MODE_NONE; int maxPasswordFails = 0; int maxScreenLockTime = 0; int passwordExpiration = 0; int passwordHistory = 0; int passwordComplexChars = 0; while (nextTag(Tags.PROVISION_EAS_PROVISION_DOC) != END) { boolean tagIsSupported = true; switch (tag) { case Tags.PROVISION_DEVICE_PASSWORD_ENABLED: if (getValueInt() == 1) { if (passwordMode == PolicySet.PASSWORD_MODE_NONE) { passwordMode = PolicySet.PASSWORD_MODE_SIMPLE; } } break; case Tags.PROVISION_MIN_DEVICE_PASSWORD_LENGTH: minPasswordLength = getValueInt(); break; case Tags.PROVISION_ALPHA_DEVICE_PASSWORD_ENABLED: if (getValueInt() == 1) { passwordMode = PolicySet.PASSWORD_MODE_STRONG; } break; case Tags.PROVISION_MAX_INACTIVITY_TIME_DEVICE_LOCK: // EAS gives us seconds, which is, happily, what the PolicySet requires maxScreenLockTime = getValueInt(); break; case Tags.PROVISION_MAX_DEVICE_PASSWORD_FAILED_ATTEMPTS: maxPasswordFails = getValueInt(); break; case Tags.PROVISION_DEVICE_PASSWORD_EXPIRATION: passwordExpiration = getValueInt(); // We don't yet support this if (passwordExpiration > 0) { tagIsSupported = false; } break; case Tags.PROVISION_DEVICE_PASSWORD_HISTORY: passwordHistory = getValueInt(); break; case Tags.PROVISION_ALLOW_SIMPLE_DEVICE_PASSWORD: // Ignore this unless there's any MSFT documentation for what this means // Hint: I haven't seen any that's more specific than "simple" getValue(); break; // The following policies, if false, can't be supported at the moment case Tags.PROVISION_ATTACHMENTS_ENABLED: case Tags.PROVISION_ALLOW_STORAGE_CARD: case Tags.PROVISION_ALLOW_CAMERA: case Tags.PROVISION_ALLOW_UNSIGNED_APPLICATIONS: case Tags.PROVISION_ALLOW_UNSIGNED_INSTALLATION_PACKAGES: case Tags.PROVISION_ALLOW_WIFI: case Tags.PROVISION_ALLOW_TEXT_MESSAGING: case Tags.PROVISION_ALLOW_POP_IMAP_EMAIL: case Tags.PROVISION_ALLOW_IRDA: case Tags.PROVISION_ALLOW_HTML_EMAIL: case Tags.PROVISION_ALLOW_BROWSER: case Tags.PROVISION_ALLOW_CONSUMER_EMAIL: case Tags.PROVISION_ALLOW_INTERNET_SHARING: if (getValueInt() == 0) { tagIsSupported = false; } break; // Bluetooth: 0 = no bluetooth; 1 = only hands-free; 2 = allowed case Tags.PROVISION_ALLOW_BLUETOOTH: if (getValueInt() != 2) { tagIsSupported = false; } break; // The following policies, if true, can't be supported at the moment case Tags.PROVISION_DEVICE_ENCRYPTION_ENABLED: case Tags.PROVISION_PASSWORD_RECOVERY_ENABLED: case Tags.PROVISION_REQUIRE_DEVICE_ENCRYPTION: case Tags.PROVISION_REQUIRE_SIGNED_SMIME_MESSAGES: case Tags.PROVISION_REQUIRE_ENCRYPTED_SMIME_MESSAGES: case Tags.PROVISION_REQUIRE_SIGNED_SMIME_ALGORITHM: case Tags.PROVISION_REQUIRE_ENCRYPTION_SMIME_ALGORITHM: case Tags.PROVISION_REQUIRE_MANUAL_SYNC_WHEN_ROAMING: if (getValueInt() == 1) { tagIsSupported = false; } break; // The following, if greater than zero, can't be supported at the moment case Tags.PROVISION_MAX_ATTACHMENT_SIZE: if (getValueInt() > 0) { tagIsSupported = false; } break; // Complex character setting is only used if we're in "strong" (alphanumeric) mode case Tags.PROVISION_MIN_DEVICE_PASSWORD_COMPLEX_CHARS: passwordComplexChars = getValueInt(); if ((passwordMode != PolicySet.PASSWORD_MODE_STRONG) && (passwordComplexChars > 0)) { tagIsSupported = false; } break; // The following policies are moot; they allow functionality that we don't support case Tags.PROVISION_ALLOW_DESKTOP_SYNC: case Tags.PROVISION_ALLOW_SMIME_ENCRYPTION_NEGOTIATION: case Tags.PROVISION_ALLOW_SMIME_SOFT_CERTS: case Tags.PROVISION_ALLOW_REMOTE_DESKTOP: skipTag(); break; // We don't handle approved/unapproved application lists case Tags.PROVISION_UNAPPROVED_IN_ROM_APPLICATION_LIST: case Tags.PROVISION_APPROVED_APPLICATION_LIST: // Parse and throw away the content if (specifiesApplications(tag)) { tagIsSupported = false; } break; // NOTE: We can support these entirely within the email application if we choose case Tags.PROVISION_MAX_CALENDAR_AGE_FILTER: case Tags.PROVISION_MAX_EMAIL_AGE_FILTER: // 0 indicates no specified filter if (getValueInt() != 0) { tagIsSupported = false; } break; // NOTE: We can support these entirely within the email application if we choose case Tags.PROVISION_MAX_EMAIL_BODY_TRUNCATION_SIZE: case Tags.PROVISION_MAX_EMAIL_HTML_BODY_TRUNCATION_SIZE: String value = getValue(); // -1 indicates no required truncation if (!value.equals("-1")) { tagIsSupported = false; } break; default: skipTag(); } if (!tagIsSupported) { log("Policy not supported: " + tag); mIsSupportable = false; } } mPolicySet = new SecurityPolicy.PolicySet(minPasswordLength, passwordMode, maxPasswordFails, maxScreenLockTime, true, passwordExpiration, passwordHistory, passwordComplexChars); }
private void parseProvisionDocWbxml() throws IOException { int minPasswordLength = 0; int passwordMode = PolicySet.PASSWORD_MODE_NONE; int maxPasswordFails = 0; int maxScreenLockTime = 0; int passwordExpiration = 0; int passwordHistory = 0; int passwordComplexChars = 0; while (nextTag(Tags.PROVISION_EAS_PROVISION_DOC) != END) { boolean tagIsSupported = true; switch (tag) { case Tags.PROVISION_DEVICE_PASSWORD_ENABLED: if (getValueInt() == 1) { if (passwordMode == PolicySet.PASSWORD_MODE_NONE) { passwordMode = PolicySet.PASSWORD_MODE_SIMPLE; } } break; case Tags.PROVISION_MIN_DEVICE_PASSWORD_LENGTH: minPasswordLength = getValueInt(); break; case Tags.PROVISION_ALPHA_DEVICE_PASSWORD_ENABLED: if (getValueInt() == 1) { passwordMode = PolicySet.PASSWORD_MODE_STRONG; } break; case Tags.PROVISION_MAX_INACTIVITY_TIME_DEVICE_LOCK: // EAS gives us seconds, which is, happily, what the PolicySet requires maxScreenLockTime = getValueInt(); break; case Tags.PROVISION_MAX_DEVICE_PASSWORD_FAILED_ATTEMPTS: maxPasswordFails = getValueInt(); break; case Tags.PROVISION_DEVICE_PASSWORD_EXPIRATION: passwordExpiration = getValueInt(); // We don't yet support this if (passwordExpiration > 0) { tagIsSupported = false; } break; case Tags.PROVISION_DEVICE_PASSWORD_HISTORY: passwordHistory = getValueInt(); break; case Tags.PROVISION_ALLOW_SIMPLE_DEVICE_PASSWORD: // Ignore this unless there's any MSFT documentation for what this means // Hint: I haven't seen any that's more specific than "simple" getValue(); break; // The following policies, if false, can't be supported at the moment case Tags.PROVISION_ATTACHMENTS_ENABLED: case Tags.PROVISION_ALLOW_STORAGE_CARD: case Tags.PROVISION_ALLOW_CAMERA: case Tags.PROVISION_ALLOW_UNSIGNED_APPLICATIONS: case Tags.PROVISION_ALLOW_UNSIGNED_INSTALLATION_PACKAGES: case Tags.PROVISION_ALLOW_WIFI: case Tags.PROVISION_ALLOW_TEXT_MESSAGING: case Tags.PROVISION_ALLOW_POP_IMAP_EMAIL: case Tags.PROVISION_ALLOW_IRDA: case Tags.PROVISION_ALLOW_HTML_EMAIL: case Tags.PROVISION_ALLOW_BROWSER: case Tags.PROVISION_ALLOW_CONSUMER_EMAIL: case Tags.PROVISION_ALLOW_INTERNET_SHARING: if (getValueInt() == 0) { tagIsSupported = false; } break; // Bluetooth: 0 = no bluetooth; 1 = only hands-free; 2 = allowed case Tags.PROVISION_ALLOW_BLUETOOTH: if (getValueInt() != 2) { tagIsSupported = false; } break; // The following policies, if true, can't be supported at the moment case Tags.PROVISION_DEVICE_ENCRYPTION_ENABLED: case Tags.PROVISION_PASSWORD_RECOVERY_ENABLED: case Tags.PROVISION_REQUIRE_DEVICE_ENCRYPTION: case Tags.PROVISION_REQUIRE_SIGNED_SMIME_MESSAGES: case Tags.PROVISION_REQUIRE_ENCRYPTED_SMIME_MESSAGES: case Tags.PROVISION_REQUIRE_SIGNED_SMIME_ALGORITHM: case Tags.PROVISION_REQUIRE_ENCRYPTION_SMIME_ALGORITHM: case Tags.PROVISION_REQUIRE_MANUAL_SYNC_WHEN_ROAMING: if (getValueInt() == 1) { tagIsSupported = false; } break; // The following, if greater than zero, can't be supported at the moment case Tags.PROVISION_MAX_ATTACHMENT_SIZE: if (getValueInt() > 0) { tagIsSupported = false; } break; // Complex characters are supported case Tags.PROVISION_MIN_DEVICE_PASSWORD_COMPLEX_CHARS: passwordComplexChars = getValueInt(); break; // The following policies are moot; they allow functionality that we don't support case Tags.PROVISION_ALLOW_DESKTOP_SYNC: case Tags.PROVISION_ALLOW_SMIME_ENCRYPTION_NEGOTIATION: case Tags.PROVISION_ALLOW_SMIME_SOFT_CERTS: case Tags.PROVISION_ALLOW_REMOTE_DESKTOP: skipTag(); break; // We don't handle approved/unapproved application lists case Tags.PROVISION_UNAPPROVED_IN_ROM_APPLICATION_LIST: case Tags.PROVISION_APPROVED_APPLICATION_LIST: // Parse and throw away the content if (specifiesApplications(tag)) { tagIsSupported = false; } break; // NOTE: We can support these entirely within the email application if we choose case Tags.PROVISION_MAX_CALENDAR_AGE_FILTER: case Tags.PROVISION_MAX_EMAIL_AGE_FILTER: // 0 indicates no specified filter if (getValueInt() != 0) { tagIsSupported = false; } break; // NOTE: We can support these entirely within the email application if we choose case Tags.PROVISION_MAX_EMAIL_BODY_TRUNCATION_SIZE: case Tags.PROVISION_MAX_EMAIL_HTML_BODY_TRUNCATION_SIZE: String value = getValue(); // -1 indicates no required truncation if (!value.equals("-1")) { tagIsSupported = false; } break; default: skipTag(); } if (!tagIsSupported) { log("Policy not supported: " + tag); mIsSupportable = false; } } mPolicySet = new SecurityPolicy.PolicySet(minPasswordLength, passwordMode, maxPasswordFails, maxScreenLockTime, true, passwordExpiration, passwordHistory, passwordComplexChars); }
diff --git a/app/controllers/Application.java b/app/controllers/Application.java index 4bd6020..8792e37 100644 --- a/app/controllers/Application.java +++ b/app/controllers/Application.java @@ -1,147 +1,147 @@ package controllers; import controllers.securesocial.*; import models.*; import play.i18n.*; import play.mvc.*; import securesocial.provider.*; import java.util.*; @With(SecureSocial.class) public class Application extends Controller { // List of rewards for flowers public static Map<Integer,Reward> rewards = new HashMap<Integer, Reward>(); static { rewards.put(1, new Reward("Väike lill", 5)); rewards.put(2, new Reward("Keskmine lill", 10)); rewards.put(3, new Reward("Suur lill", 15)); } public static User getUser() { return (User)renderArgs.get("fanUser"); } @Before public static void before() { FanUser fanUser = (FanUser)SecureSocial.getCurrentUser(); if (fanUser != null) renderArgs.put("fanUser", User.findById(fanUser.userId)); } public static void index() { render(); } /** * AJAX query endpoint for liking / disliking productions * * @param productionId * @param rating */ public static void rateProduction(Long productionId, String rating) { EventRating eventRating = EventRating.find("web_event_id = ? and user_id = ?", productionId, getUser().id).first(); if (eventRating != null) { eventRating.rating = EventRatings.valueOf(rating); } else { eventRating = new EventRating(getUser(), Production.<Production>findById(productionId), EventRatings.valueOf(rating)); } eventRating.save(); renderText(""); } public static void buyTicket(Long eventId, Integer count) { Event event = Event.findById(eventId); try { TicketPurchase ticket = TicketPurchase.register(event, getUser(), count == null ? 1 : count); renderTemplate("Application/ticket.html", ticket); } catch (OutOfTicketsException e) { error(400, Messages.get("Pole piisavalt pileteid!")); } catch (OutOfPointsException e) { error(400, Messages.get("Pole piisavalt punkte!")); } error(500, "Pileti ostmine ebaõnnestus"); } public static void patActor(int actorId, int rewardId, String description) { try { Actor a = createActors().get(actorId); Reward r = rewards.get(rewardId); if(a == null || r == null) { flash.error("Palun täida kõik väljad"); } else { try { ActorPatting.register(getUser(), r.points, Messages.get("Saaja") + ": " + a.name + " / " + Messages.get("Teade") + ": " + description); - flash.success("Aitäh! ...hea meel"); + flash.success("Suur aitäh, lilled on saadetud!"); } catch (OutOfPointsException e) { flash.error("Pole piisavalt punkte!"); } } } catch (Exception e) { flash.error("Tehniline probleem"); System.out.println(e); } flowers(); } public static void supportTheatre() { try { PointTransaction.register(getUser(), 1, Messages.get("Teatri toetamine")); } catch (OutOfPointsException e) { error(Messages.get("Pole piisavalt punkte!")); } renderText("OK"); } public static void kava() { SocialUser user = SecureSocial.getCurrentUser(); List<Event> events = Event.find("time > ? and event_id != 0 order by time asc", new Date()).fetch(); render(user, events); } public static void kava_ext(long eventId) { Event event = Event.findById(eventId); Production production = event.production; render(event, production); } public static void account() { render(); } public static void support() { render(); } public static void flowers() { Map<Integer, Reward> rewards = Application.rewards; Map<Integer, Actor> actors = createActors(); render(rewards,actors); } private static Map<Integer, Actor> createActors() { Map<Integer, Actor> actors = new HashMap<Integer, Actor>(); actors.put(1,new Actor("Rasmus Kaljujärv")); actors.put(2,new Actor("Eve Klemets")); actors.put(3,new Actor("Risto Kübar")); actors.put(4,new Actor("Mirtel Pohla")); actors.put(5,new Actor("Jaak Prints")); actors.put(6,new Actor("Gert Raudsepp")); actors.put(7,new Actor("Stig Rästa")); actors.put(8,new Actor("Inga Salurand")); actors.put(9,new Actor("Tambet Tuisk")); actors.put(10,new Actor("Marika Vaarik")); actors.put(11,new Actor("Sergo Vares")); return actors; } }
true
true
public static void patActor(int actorId, int rewardId, String description) { try { Actor a = createActors().get(actorId); Reward r = rewards.get(rewardId); if(a == null || r == null) { flash.error("Palun täida kõik väljad"); } else { try { ActorPatting.register(getUser(), r.points, Messages.get("Saaja") + ": " + a.name + " / " + Messages.get("Teade") + ": " + description); flash.success("Aitäh! ...hea meel"); } catch (OutOfPointsException e) { flash.error("Pole piisavalt punkte!"); } } } catch (Exception e) { flash.error("Tehniline probleem"); System.out.println(e); } flowers(); }
public static void patActor(int actorId, int rewardId, String description) { try { Actor a = createActors().get(actorId); Reward r = rewards.get(rewardId); if(a == null || r == null) { flash.error("Palun täida kõik väljad"); } else { try { ActorPatting.register(getUser(), r.points, Messages.get("Saaja") + ": " + a.name + " / " + Messages.get("Teade") + ": " + description); flash.success("Suur aitäh, lilled on saadetud!"); } catch (OutOfPointsException e) { flash.error("Pole piisavalt punkte!"); } } } catch (Exception e) { flash.error("Tehniline probleem"); System.out.println(e); } flowers(); }
diff --git a/src/com/android/settings/DisplaySettings.java b/src/com/android/settings/DisplaySettings.java index 60e5931fd..d88c2f1e1 100644 --- a/src/com/android/settings/DisplaySettings.java +++ b/src/com/android/settings/DisplaySettings.java @@ -1,437 +1,437 @@ /* * 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.settings; import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT; import android.app.ActivityManagerNative; import android.app.Dialog; import android.app.admin.DevicePolicyManager; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Configuration; import android.content.res.Resources; import android.database.ContentObserver; import android.hardware.display.DisplayManager; import android.hardware.display.WifiDisplayStatus; import android.os.Bundle; import android.os.Handler; import android.os.RemoteException; import android.preference.CheckBoxPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceCategory; import android.preference.PreferenceScreen; import android.provider.Settings; import android.util.Log; import com.android.internal.view.RotationPolicy; import com.android.settings.cyanogenmod.DisplayRotation; import com.android.settings.Utils; import java.util.ArrayList; public class DisplaySettings extends SettingsPreferenceFragment implements Preference.OnPreferenceChangeListener, OnPreferenceClickListener { private static final String TAG = "DisplaySettings"; // If there is no setting in the provider, use this private static final int FALLBACK_SCREEN_TIMEOUT_VALUE = 30000; private static final String KEY_SCREEN_TIMEOUT = "screen_timeout"; private static final String KEY_FONT_SIZE = "font_size"; private static final String KEY_SCREEN_SAVER = "screensaver"; private static final String KEY_WIFI_DISPLAY = "wifi_display"; private static final String KEY_DISPLAY_ROTATION = "display_rotation"; private static final String KEY_WAKEUP_CATEGORY = "category_wakeup_options"; private static final String KEY_VOLUME_WAKE = "pref_volume_wake"; // Strings used for building the summary private static final String ROTATION_ANGLE_0 = "0"; private static final String ROTATION_ANGLE_90 = "90"; private static final String ROTATION_ANGLE_180 = "180"; private static final String ROTATION_ANGLE_270 = "270"; private static final int DLG_GLOBAL_CHANGE_WARNING = 1; private DisplayManager mDisplayManager; private CheckBoxPreference mVolumeWake; private PreferenceScreen mDisplayRotationPreference; private WarnedListPreference mFontSizePref; private final Configuration mCurConfig = new Configuration(); private ListPreference mScreenTimeoutPreference; private Preference mScreenSaverPreference; private WifiDisplayStatus mWifiDisplayStatus; private Preference mWifiDisplayPreference; private ContentObserver mAccelerometerRotationObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { updateDisplayRotationPreferenceDescription(); } }; private final RotationPolicy.RotationPolicyListener mRotationPolicyListener = new RotationPolicy.RotationPolicyListener() { @Override public void onChange() { updateDisplayRotationPreferenceDescription(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ContentResolver resolver = getActivity().getContentResolver(); addPreferencesFromResource(R.xml.display_settings); mDisplayRotationPreference = (PreferenceScreen) findPreference(KEY_DISPLAY_ROTATION); mScreenSaverPreference = findPreference(KEY_SCREEN_SAVER); if (mScreenSaverPreference != null && getResources().getBoolean( com.android.internal.R.bool.config_dreamsSupported) == false) { getPreferenceScreen().removePreference(mScreenSaverPreference); } mScreenTimeoutPreference = (ListPreference) findPreference(KEY_SCREEN_TIMEOUT); final long currentTimeout = Settings.System.getLong(resolver, SCREEN_OFF_TIMEOUT, FALLBACK_SCREEN_TIMEOUT_VALUE); mScreenTimeoutPreference.setValue(String.valueOf(currentTimeout)); mScreenTimeoutPreference.setOnPreferenceChangeListener(this); disableUnusableTimeouts(mScreenTimeoutPreference); updateTimeoutPreferenceDescription(currentTimeout); updateDisplayRotationPreferenceDescription(); mFontSizePref = (WarnedListPreference) findPreference(KEY_FONT_SIZE); mFontSizePref.setOnPreferenceChangeListener(this); mFontSizePref.setOnPreferenceClickListener(this); mDisplayManager = (DisplayManager)getActivity().getSystemService( Context.DISPLAY_SERVICE); mWifiDisplayStatus = mDisplayManager.getWifiDisplayStatus(); mWifiDisplayPreference = (Preference)findPreference(KEY_WIFI_DISPLAY); if (mWifiDisplayStatus.getFeatureState() == WifiDisplayStatus.FEATURE_STATE_UNAVAILABLE) { getPreferenceScreen().removePreference(mWifiDisplayPreference); mWifiDisplayPreference = null; } mVolumeWake = (CheckBoxPreference) findPreference(KEY_VOLUME_WAKE); if (mVolumeWake != null) { if (!getResources().getBoolean(R.bool.config_show_volumeRockerWake) - && !Utils.hasVolumeRocker(getActivity())) { + || !Utils.hasVolumeRocker(getActivity())) { getPreferenceScreen().removePreference(mVolumeWake); getPreferenceScreen().removePreference((PreferenceCategory) findPreference(KEY_WAKEUP_CATEGORY)); } else { mVolumeWake.setChecked(Settings.System.getInt(resolver, Settings.System.VOLUME_WAKE_SCREEN, 0) == 1); } } } private void updateDisplayRotationPreferenceDescription() { if (mDisplayRotationPreference == null) { // The preference was removed, do nothing return; } // We have a preference, lets update the summary StringBuilder summary = new StringBuilder(); Boolean rotationEnabled = Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0) != 0; int mode = Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION_ANGLES, DisplayRotation.ROTATION_0_MODE|DisplayRotation.ROTATION_90_MODE|DisplayRotation.ROTATION_270_MODE); if (!rotationEnabled) { summary.append(getString(R.string.display_rotation_disabled)); } else { ArrayList<String> rotationList = new ArrayList<String>(); String delim = ""; if ((mode & DisplayRotation.ROTATION_0_MODE) != 0) { rotationList.add(ROTATION_ANGLE_0); } if ((mode & DisplayRotation.ROTATION_90_MODE) != 0) { rotationList.add(ROTATION_ANGLE_90); } if ((mode & DisplayRotation.ROTATION_180_MODE) != 0) { rotationList.add(ROTATION_ANGLE_180); } if ((mode & DisplayRotation.ROTATION_270_MODE) != 0) { rotationList.add(ROTATION_ANGLE_270); } for (int i = 0; i < rotationList.size(); i++) { summary.append(delim).append(rotationList.get(i)); if ((rotationList.size() - i) > 2) { delim = ", "; } else { delim = " & "; } } summary.append(" " + getString(R.string.display_rotation_unit)); } mDisplayRotationPreference.setSummary(summary); } private void updateTimeoutPreferenceDescription(long currentTimeout) { ListPreference preference = mScreenTimeoutPreference; String summary; if (currentTimeout < 0) { // Unsupported value summary = ""; } else { final CharSequence[] entries = preference.getEntries(); final CharSequence[] values = preference.getEntryValues(); if (entries == null || entries.length == 0) { summary = ""; } else { int best = 0; for (int i = 0; i < values.length; i++) { long timeout = Long.parseLong(values[i].toString()); if (currentTimeout >= timeout) { best = i; } } summary = preference.getContext().getString(R.string.screen_timeout_summary, entries[best]); } } preference.setSummary(summary); } private void disableUnusableTimeouts(ListPreference screenTimeoutPreference) { final DevicePolicyManager dpm = (DevicePolicyManager) getActivity().getSystemService( Context.DEVICE_POLICY_SERVICE); final long maxTimeout = dpm != null ? dpm.getMaximumTimeToLock(null) : 0; if (maxTimeout == 0) { return; // policy not enforced } final CharSequence[] entries = screenTimeoutPreference.getEntries(); final CharSequence[] values = screenTimeoutPreference.getEntryValues(); ArrayList<CharSequence> revisedEntries = new ArrayList<CharSequence>(); ArrayList<CharSequence> revisedValues = new ArrayList<CharSequence>(); for (int i = 0; i < values.length; i++) { long timeout = Long.parseLong(values[i].toString()); if (timeout <= maxTimeout) { revisedEntries.add(entries[i]); revisedValues.add(values[i]); } } if (revisedEntries.size() != entries.length || revisedValues.size() != values.length) { screenTimeoutPreference.setEntries( revisedEntries.toArray(new CharSequence[revisedEntries.size()])); screenTimeoutPreference.setEntryValues( revisedValues.toArray(new CharSequence[revisedValues.size()])); final int userPreference = Integer.parseInt(screenTimeoutPreference.getValue()); if (userPreference <= maxTimeout) { screenTimeoutPreference.setValue(String.valueOf(userPreference)); } else { // There will be no highlighted selection since nothing in the list matches // maxTimeout. The user can still select anything less than maxTimeout. // TODO: maybe append maxTimeout to the list and mark selected. } } screenTimeoutPreference.setEnabled(revisedEntries.size() > 0); } int floatToIndex(float val) { String[] indices = getResources().getStringArray(R.array.entryvalues_font_size); float lastVal = Float.parseFloat(indices[0]); for (int i = 1; i < indices.length; i++) { float thisVal = Float.parseFloat(indices[i]); if (val < (lastVal + (thisVal-lastVal)*.5f)) { return i - 1; } lastVal = thisVal; } return indices.length - 1; } public void readFontSizePreference(ListPreference pref) { try { mCurConfig.updateFrom(ActivityManagerNative.getDefault().getConfiguration()); } catch (RemoteException e) { Log.w(TAG, "Unable to retrieve font size"); } // mark the appropriate item in the preferences list int index = floatToIndex(mCurConfig.fontScale); pref.setValueIndex(index); // report the current size in the summary text final Resources res = getResources(); String[] fontSizeNames = res.getStringArray(R.array.entries_font_size); pref.setSummary(String.format(res.getString(R.string.summary_font_size), fontSizeNames[index])); } @Override public void onResume() { super.onResume(); updateDisplayRotationPreferenceDescription(); RotationPolicy.registerRotationPolicyListener(getActivity(), mRotationPolicyListener); // Display rotation observer getContentResolver().registerContentObserver( Settings.System.getUriFor(Settings.System.ACCELEROMETER_ROTATION), true, mAccelerometerRotationObserver); if (mWifiDisplayPreference != null) { getActivity().registerReceiver(mReceiver, new IntentFilter( DisplayManager.ACTION_WIFI_DISPLAY_STATUS_CHANGED)); mWifiDisplayStatus = mDisplayManager.getWifiDisplayStatus(); } updateState(); } @Override public void onPause() { super.onPause(); RotationPolicy.unregisterRotationPolicyListener(getActivity(), mRotationPolicyListener); // Display rotation observer getContentResolver().unregisterContentObserver(mAccelerometerRotationObserver); if (mWifiDisplayPreference != null) { getActivity().unregisterReceiver(mReceiver); } } @Override public Dialog onCreateDialog(int dialogId) { if (dialogId == DLG_GLOBAL_CHANGE_WARNING) { return Utils.buildGlobalChangeWarningDialog(getActivity(), R.string.global_font_change_title, new Runnable() { public void run() { mFontSizePref.click(); } }); } return null; } private void updateState() { readFontSizePreference(mFontSizePref); updateScreenSaverSummary(); updateWifiDisplaySummary(); } private void updateScreenSaverSummary() { if (mScreenSaverPreference != null) { mScreenSaverPreference.setSummary( DreamSettings.getSummaryTextWithDreamName(getActivity())); } } private void updateWifiDisplaySummary() { if (mWifiDisplayPreference != null) { switch (mWifiDisplayStatus.getFeatureState()) { case WifiDisplayStatus.FEATURE_STATE_OFF: mWifiDisplayPreference.setSummary(R.string.wifi_display_summary_off); break; case WifiDisplayStatus.FEATURE_STATE_ON: mWifiDisplayPreference.setSummary(R.string.wifi_display_summary_on); break; case WifiDisplayStatus.FEATURE_STATE_DISABLED: default: mWifiDisplayPreference.setSummary(R.string.wifi_display_summary_disabled); break; } } } public void writeFontSizePreference(Object objValue) { try { mCurConfig.fontScale = Float.parseFloat(objValue.toString()); ActivityManagerNative.getDefault().updatePersistentConfiguration(mCurConfig); } catch (RemoteException e) { Log.w(TAG, "Unable to save font size"); } } @Override public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { if (preference == mVolumeWake) { Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_WAKE_SCREEN, mVolumeWake.isChecked() ? 1 : 0); return true; } return super.onPreferenceTreeClick(preferenceScreen, preference); } public boolean onPreferenceChange(Preference preference, Object objValue) { final String key = preference.getKey(); if (KEY_SCREEN_TIMEOUT.equals(key)) { int value = Integer.parseInt((String) objValue); try { Settings.System.putInt(getContentResolver(), SCREEN_OFF_TIMEOUT, value); updateTimeoutPreferenceDescription(value); } catch (NumberFormatException e) { Log.e(TAG, "could not persist screen timeout setting", e); } } if (KEY_FONT_SIZE.equals(key)) { writeFontSizePreference(objValue); } return true; } private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(DisplayManager.ACTION_WIFI_DISPLAY_STATUS_CHANGED)) { mWifiDisplayStatus = (WifiDisplayStatus)intent.getParcelableExtra( DisplayManager.EXTRA_WIFI_DISPLAY_STATUS); updateWifiDisplaySummary(); } } }; @Override public boolean onPreferenceClick(Preference preference) { if (preference == mFontSizePref) { if (Utils.hasMultipleUsers(getActivity())) { showDialog(DLG_GLOBAL_CHANGE_WARNING); return true; } else { mFontSizePref.click(); } } return false; } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ContentResolver resolver = getActivity().getContentResolver(); addPreferencesFromResource(R.xml.display_settings); mDisplayRotationPreference = (PreferenceScreen) findPreference(KEY_DISPLAY_ROTATION); mScreenSaverPreference = findPreference(KEY_SCREEN_SAVER); if (mScreenSaverPreference != null && getResources().getBoolean( com.android.internal.R.bool.config_dreamsSupported) == false) { getPreferenceScreen().removePreference(mScreenSaverPreference); } mScreenTimeoutPreference = (ListPreference) findPreference(KEY_SCREEN_TIMEOUT); final long currentTimeout = Settings.System.getLong(resolver, SCREEN_OFF_TIMEOUT, FALLBACK_SCREEN_TIMEOUT_VALUE); mScreenTimeoutPreference.setValue(String.valueOf(currentTimeout)); mScreenTimeoutPreference.setOnPreferenceChangeListener(this); disableUnusableTimeouts(mScreenTimeoutPreference); updateTimeoutPreferenceDescription(currentTimeout); updateDisplayRotationPreferenceDescription(); mFontSizePref = (WarnedListPreference) findPreference(KEY_FONT_SIZE); mFontSizePref.setOnPreferenceChangeListener(this); mFontSizePref.setOnPreferenceClickListener(this); mDisplayManager = (DisplayManager)getActivity().getSystemService( Context.DISPLAY_SERVICE); mWifiDisplayStatus = mDisplayManager.getWifiDisplayStatus(); mWifiDisplayPreference = (Preference)findPreference(KEY_WIFI_DISPLAY); if (mWifiDisplayStatus.getFeatureState() == WifiDisplayStatus.FEATURE_STATE_UNAVAILABLE) { getPreferenceScreen().removePreference(mWifiDisplayPreference); mWifiDisplayPreference = null; } mVolumeWake = (CheckBoxPreference) findPreference(KEY_VOLUME_WAKE); if (mVolumeWake != null) { if (!getResources().getBoolean(R.bool.config_show_volumeRockerWake) && !Utils.hasVolumeRocker(getActivity())) { getPreferenceScreen().removePreference(mVolumeWake); getPreferenceScreen().removePreference((PreferenceCategory) findPreference(KEY_WAKEUP_CATEGORY)); } else { mVolumeWake.setChecked(Settings.System.getInt(resolver, Settings.System.VOLUME_WAKE_SCREEN, 0) == 1); } } }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ContentResolver resolver = getActivity().getContentResolver(); addPreferencesFromResource(R.xml.display_settings); mDisplayRotationPreference = (PreferenceScreen) findPreference(KEY_DISPLAY_ROTATION); mScreenSaverPreference = findPreference(KEY_SCREEN_SAVER); if (mScreenSaverPreference != null && getResources().getBoolean( com.android.internal.R.bool.config_dreamsSupported) == false) { getPreferenceScreen().removePreference(mScreenSaverPreference); } mScreenTimeoutPreference = (ListPreference) findPreference(KEY_SCREEN_TIMEOUT); final long currentTimeout = Settings.System.getLong(resolver, SCREEN_OFF_TIMEOUT, FALLBACK_SCREEN_TIMEOUT_VALUE); mScreenTimeoutPreference.setValue(String.valueOf(currentTimeout)); mScreenTimeoutPreference.setOnPreferenceChangeListener(this); disableUnusableTimeouts(mScreenTimeoutPreference); updateTimeoutPreferenceDescription(currentTimeout); updateDisplayRotationPreferenceDescription(); mFontSizePref = (WarnedListPreference) findPreference(KEY_FONT_SIZE); mFontSizePref.setOnPreferenceChangeListener(this); mFontSizePref.setOnPreferenceClickListener(this); mDisplayManager = (DisplayManager)getActivity().getSystemService( Context.DISPLAY_SERVICE); mWifiDisplayStatus = mDisplayManager.getWifiDisplayStatus(); mWifiDisplayPreference = (Preference)findPreference(KEY_WIFI_DISPLAY); if (mWifiDisplayStatus.getFeatureState() == WifiDisplayStatus.FEATURE_STATE_UNAVAILABLE) { getPreferenceScreen().removePreference(mWifiDisplayPreference); mWifiDisplayPreference = null; } mVolumeWake = (CheckBoxPreference) findPreference(KEY_VOLUME_WAKE); if (mVolumeWake != null) { if (!getResources().getBoolean(R.bool.config_show_volumeRockerWake) || !Utils.hasVolumeRocker(getActivity())) { getPreferenceScreen().removePreference(mVolumeWake); getPreferenceScreen().removePreference((PreferenceCategory) findPreference(KEY_WAKEUP_CATEGORY)); } else { mVolumeWake.setChecked(Settings.System.getInt(resolver, Settings.System.VOLUME_WAKE_SCREEN, 0) == 1); } } }
diff --git a/src/main/java/net/LoadingChunks/SyncingFeeling/util/SQLWrapper.java b/src/main/java/net/LoadingChunks/SyncingFeeling/util/SQLWrapper.java index db33df2..d56f150 100644 --- a/src/main/java/net/LoadingChunks/SyncingFeeling/util/SQLWrapper.java +++ b/src/main/java/net/LoadingChunks/SyncingFeeling/util/SQLWrapper.java @@ -1,197 +1,198 @@ package net.LoadingChunks.SyncingFeeling.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import net.LoadingChunks.SyncingFeeling.SyncingFeeling; import net.LoadingChunks.SyncingFeeling.Inventory.SerializableInventory; public class SQLWrapper { static private SyncingFeeling plugin; static private Connection con; static private boolean success; static private String user; static private String password; static private String host; static private String db; static public void setPlugin(SyncingFeeling plugin) { SQLWrapper.plugin = plugin; } static public void setConfig(String user, String password, String host, String db) { SQLWrapper.user = user; SQLWrapper.password = password; SQLWrapper.host = host; SQLWrapper.db = db; } public static SyncingFeeling getPlugin() { return plugin; } static public boolean connect() { success = true; try { Class.forName("com.mysql.jdbc.Driver"); SQLWrapper.con = DriverManager.getConnection("jdbc:mysql://" + SQLWrapper.host + ":3306/" + SQLWrapper.db, SQLWrapper.user, SQLWrapper.password); } catch(SQLException e) { e.printStackTrace(); SQLWrapper.success = false; } catch (ClassNotFoundException e) { e.printStackTrace(); SQLWrapper.success = false; } return success; } static public boolean reconnect() { try { if(con.isClosed()) { return connect(); } } catch(SQLException e) { e.printStackTrace(); return false; } return true; } static public void commitSlot(Player p, Integer slot, ItemStack stack) { try { reconnect(); PreparedStatement stat = con.prepareStatement("REPLACE INTO `inv_slots` (`server`,`player`,`json`,`slot`,`hash`) VALUES (?,?,?,?,MD5(?))"); stat.setString(1, SQLWrapper.plugin.getConfig().getString("general.server.name")); stat.setString(2, p.getName()); JSONObject obj = new JSONObject(); obj.putAll(stack.serialize()); stat.setString(3, obj.toJSONString()); stat.setInt(4, slot); stat.setString(5, obj.toJSONString()); stat.execute(); } catch (SQLException e) { e.printStackTrace(); } } static public void commitSlots(Player p, SerializableInventory inv) { try { reconnect(); String sqlstring = "REPLACE INTO `inv_slots` (`server`,`player`,`json`,`slot`) VALUES "; if(inv.getSlots().size() == 0) return; for(int i = 0; i < inv.getSlots().size(); i++) { sqlstring = sqlstring.concat("(?,?,?,?,MD5(?))"); if(i < inv.getSlots().size()-1) sqlstring = sqlstring.concat(","); } PreparedStatement stat = con.prepareStatement(sqlstring); int i = 0; String name = SQLWrapper.plugin.getConfig().getString("general.server.name"); for(Entry<Integer, ItemStack> slot : inv.getSlots().entrySet()) { stat.setString((i*5) + 1, name); stat.setString((i*5) + 2, p.getName()); JSONObject obj = new JSONObject(); obj.putAll(SerializableInventory.serialize(slot.getValue())); stat.setString((i*5) + 3, obj.toJSONString()); stat.setInt((i*5) + 4, slot.getKey()); + stat.setString((i*5) + 5, obj.toJSONString()); i++; } if(plugin.isDebugMode) plugin.getLogger().info("Committing Slot Array: " + stat.toString()); stat.execute(); } catch (SQLException e) { e.printStackTrace(); } } static public void commitInventory(SerializableInventory inv, Player p, boolean clear) { try { reconnect(); PreparedStatement stat = con.prepareStatement("REPLACE INTO `inv_inventories` (`server`,`player`) VALUES (?,?,MD5(?))"); stat.setString(1, SQLWrapper.plugin.getConfig().getString("general.server.name")); stat.setString(2, p.getName()); stat.execute(); if(clear) { PreparedStatement statclear = con.prepareStatement("DELETE FROM `inv_slots` WHERE `server` = ? AND `player` = ?"); statclear.setString(1, SQLWrapper.plugin.getConfig().getString("general.server.name")); statclear.setString(2, p.getName()); statclear.execute(); } } catch(SQLException e) { e.printStackTrace(); } } public static String checkLatest(Player p) { try { reconnect(); PreparedStatement stat = con.prepareStatement("SELECT `server`,`hash` FROM `inv_inventories` WHERE `player` = ? ORDER BY `timestamp` DESC LIMIT 1"); stat.setString(1, p.getName()); stat.execute(); ResultSet set = stat.getResultSet(); set.last(); if(set.getRow() == 0) return ""; return set.getString("server"); } catch(SQLException e) { e.printStackTrace(); return SQLWrapper.plugin.getConfig().getString("general.server.name"); } } public static void recoverLatest(Player p, String server) { try { reconnect(); PreparedStatement stat = con.prepareStatement("SELECT * FROM `inv_slots` WHERE `server` = ? AND `player` = ?"); stat.setString(1, server); stat.setString(2, p.getName()); stat.execute(); ResultSet result = stat.getResultSet(); while(result.next()) { int slot = result.getInt("slot"); JSONParser parser = new JSONParser(); try { Map<String, Object> map = (Map<String, Object>) parser.parse(result.getString("json")); ItemStack stack = (ItemStack) SerializableInventory.deserialize(map); if(slot == Slots.HELMET.slotNum()) { p.getInventory().setHelmet(stack); } else if(slot == Slots.CHEST.slotNum()) { p.getInventory().setChestplate(stack); } else if(slot == Slots.LEGGINGS.slotNum()) { p.getInventory().setLeggings(stack); } else if(slot == Slots.BOOTS.slotNum()) { p.getInventory().setBoots(stack); } else { p.getInventory().setItem(slot, stack); } } catch (ParseException e) { e.printStackTrace(); } } } catch(SQLException e) { e.printStackTrace(); } } }
true
true
static public void commitSlots(Player p, SerializableInventory inv) { try { reconnect(); String sqlstring = "REPLACE INTO `inv_slots` (`server`,`player`,`json`,`slot`) VALUES "; if(inv.getSlots().size() == 0) return; for(int i = 0; i < inv.getSlots().size(); i++) { sqlstring = sqlstring.concat("(?,?,?,?,MD5(?))"); if(i < inv.getSlots().size()-1) sqlstring = sqlstring.concat(","); } PreparedStatement stat = con.prepareStatement(sqlstring); int i = 0; String name = SQLWrapper.plugin.getConfig().getString("general.server.name"); for(Entry<Integer, ItemStack> slot : inv.getSlots().entrySet()) { stat.setString((i*5) + 1, name); stat.setString((i*5) + 2, p.getName()); JSONObject obj = new JSONObject(); obj.putAll(SerializableInventory.serialize(slot.getValue())); stat.setString((i*5) + 3, obj.toJSONString()); stat.setInt((i*5) + 4, slot.getKey()); i++; } if(plugin.isDebugMode) plugin.getLogger().info("Committing Slot Array: " + stat.toString()); stat.execute(); } catch (SQLException e) { e.printStackTrace(); } }
static public void commitSlots(Player p, SerializableInventory inv) { try { reconnect(); String sqlstring = "REPLACE INTO `inv_slots` (`server`,`player`,`json`,`slot`) VALUES "; if(inv.getSlots().size() == 0) return; for(int i = 0; i < inv.getSlots().size(); i++) { sqlstring = sqlstring.concat("(?,?,?,?,MD5(?))"); if(i < inv.getSlots().size()-1) sqlstring = sqlstring.concat(","); } PreparedStatement stat = con.prepareStatement(sqlstring); int i = 0; String name = SQLWrapper.plugin.getConfig().getString("general.server.name"); for(Entry<Integer, ItemStack> slot : inv.getSlots().entrySet()) { stat.setString((i*5) + 1, name); stat.setString((i*5) + 2, p.getName()); JSONObject obj = new JSONObject(); obj.putAll(SerializableInventory.serialize(slot.getValue())); stat.setString((i*5) + 3, obj.toJSONString()); stat.setInt((i*5) + 4, slot.getKey()); stat.setString((i*5) + 5, obj.toJSONString()); i++; } if(plugin.isDebugMode) plugin.getLogger().info("Committing Slot Array: " + stat.toString()); stat.execute(); } catch (SQLException e) { e.printStackTrace(); } }
diff --git a/src/de/azapps/mirakel/sync/taskwarrior/TaskWarriorSync.java b/src/de/azapps/mirakel/sync/taskwarrior/TaskWarriorSync.java index 42ce6259..6d0849f2 100644 --- a/src/de/azapps/mirakel/sync/taskwarrior/TaskWarriorSync.java +++ b/src/de/azapps/mirakel/sync/taskwarrior/TaskWarriorSync.java @@ -1,547 +1,547 @@ package de.azapps.mirakel.sync.taskwarrior; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.charset.MalformedInputException; import java.security.cert.CertificateException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Map; import android.accounts.Account; import android.accounts.AccountManager; import android.annotation.SuppressLint; import android.content.Context; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import de.azapps.mirakel.DefinitionsHelper.NoSuchListException; import de.azapps.mirakel.DefinitionsHelper.SYNC_STATE; import de.azapps.mirakel.helper.Helpers; import de.azapps.mirakel.helper.MirakelCommonPreferences; import de.azapps.mirakel.model.account.AccountMirakel; import de.azapps.mirakel.model.list.ListMirakel; import de.azapps.mirakel.model.task.Task; import de.azapps.mirakel.sync.R; import de.azapps.mirakel.sync.SyncAdapter; import de.azapps.tools.FileUtils; import de.azapps.tools.Log; public class TaskWarriorSync { public enum TW_ERRORS { ACCESS_DENIED, ACCOUNT_SUSPENDED, CANNOT_CREATE_SOCKET, CANNOT_PARSE_MESSAGE, CONFIG_PARSE_ERROR, MESSAGE_ERRORS, NO_ERROR, NOT_ENABLED, TRY_LATER; public static TW_ERRORS getError(int code) { switch (code) { case 200: Log.d(TAG, "Success"); break; case 201: Log.d(TAG, "No change"); break; case 300: Log.d(TAG, "Deprecated message type\n" + "This message will not be supported in future task server releases."); break; case 301: Log.d(TAG, "Redirect\n" + "Further requests should be made to the specified server/port."); // TODO break; case 302: Log.d(TAG, "Retry\n" + "The client is requested to wait and retry the same request. The wait\n" + "time is not specified, and further retry responses are possible."); return TW_ERRORS.TRY_LATER; case 400: Log.e(TAG, "Malformed data"); return TW_ERRORS.MESSAGE_ERRORS; case 401: Log.e(TAG, "Unsupported encoding"); return TW_ERRORS.MESSAGE_ERRORS; case 420: Log.e(TAG, "Server temporarily unavailable"); return TW_ERRORS.TRY_LATER; case 421: Log.e(TAG, "Server shutting down at operator request"); return TW_ERRORS.TRY_LATER; case 430: Log.e(TAG, "Access denied"); return TW_ERRORS.ACCESS_DENIED; case 431: Log.e(TAG, "Account suspended"); return TW_ERRORS.ACCOUNT_SUSPENDED; case 432: Log.e(TAG, "Account terminated"); return TW_ERRORS.ACCOUNT_SUSPENDED; case 500: Log.e(TAG, "Syntax error in request"); return TW_ERRORS.MESSAGE_ERRORS; case 501: Log.e(TAG, "Syntax error, illegal parameters"); return TW_ERRORS.MESSAGE_ERRORS; case 502: Log.e(TAG, "Not implemented"); return TW_ERRORS.MESSAGE_ERRORS; case 503: Log.e(TAG, "Command parameter not implemented"); return TW_ERRORS.MESSAGE_ERRORS; case 504: Log.e(TAG, "Request too big"); return TW_ERRORS.MESSAGE_ERRORS; default: Log.d(TAG, "Unkown code: " + code); break; } return NO_ERROR; } } // Outgoing. // private static int _debug_level = 0; // private static int _limit = (1024 * 1024); private static String _host = "localhost"; private static String _key = ""; private static String _org = ""; private static int _port = 6544; private static String _user = ""; public static final String CA_FILE = FileUtils.getMirakelDir() + "ca.cert.pem"; public static final String CLIENT_CERT_FILE = FileUtils.getMirakelDir() + "client.cert.pem"; public static final String CLIENT_KEY_FILE = FileUtils.getMirakelDir() + "client.key.pem"; public static final String NO_PROJECT = "NO_PROJECT"; private static File root; private static final String TAG = "TaskWarroirSync"; public static final String TYPE = "TaskWarrior"; private static File user_ca; private static File user_key; /** * Handle an error * * @param what * @param code */ private static void error(String what, int code) { Log.e(TAG, what + " (Code: " + code + ")"); // Toast.makeText(mContext, what, Toast.LENGTH_SHORT).show(); } private static String escape(String string) { return string.replace("\"", "\\\""); } public static void longInfo(String str) { if (str.length() > 4000) { Log.i(TAG, str.substring(0, 4000)); longInfo(str.substring(4000)); } else { Log.i(TAG, str); } } private Account account; private AccountManager accountManager; private HashMap<String, String[]> dependencies; private final Context mContext; public TaskWarriorSync(Context ctx) { this.mContext = ctx; } private TW_ERRORS doSync(Account a, Msg sync) { AccountMirakel accountMirakel = AccountMirakel.get(this.account); longInfo(sync.getPayload()); TLSClient client = new TLSClient(); try { client.init(root, user_ca, user_key); } catch (ParseException e) { Log.e(TAG,"cannot open certificate"); return TW_ERRORS.CONFIG_PARSE_ERROR; } catch (CertificateException e) { Log.e(TAG, "general problem with init"); return TW_ERRORS.CONFIG_PARSE_ERROR; } try { client.connect(_host, _port); } catch (IOException e) { Log.e(TAG, "cannot create Socket"); return TW_ERRORS.CANNOT_CREATE_SOCKET; } client.send(sync.serialize()); String response = client.recv(); if (MirakelCommonPreferences.isEnabledDebugMenu() && MirakelCommonPreferences.isDumpTw()) { try { FileUtils.writeToFile(new File(FileUtils.getLogDir(), getTime() + ".tw_down.log"), response); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } // longInfo(response); Msg remotes = new Msg(); try { remotes.parse(response); } catch (MalformedInputException e) { Log.e(TAG, "cannot parse Message"); return TW_ERRORS.CANNOT_PARSE_MESSAGE; } catch (NullPointerException e) { Log.wtf(TAG, "remotes.pars throwed NullPointer"); return TW_ERRORS.CANNOT_PARSE_MESSAGE; } int code = Integer.parseInt(remotes.get("code")); TW_ERRORS error = TW_ERRORS.getError(code); if (error != TW_ERRORS.NO_ERROR) return error; if (remotes.get("status").equals("Client sync key not found.")) { Log.d(TAG, "reset sync-key"); this.accountManager.setUserData(a, SyncAdapter.TASKWARRIOR_KEY, null); sync(a); } // parse tasks if (remotes.getPayload() == null || remotes.getPayload().equals("")) { Log.i(TAG, "there is no Payload"); } else { String tasksString[] = remotes.getPayload().split("\n"); for (String taskString : tasksString) { if (taskString.charAt(0) != '{') { Log.d(TAG, "Key: " + taskString); this.accountManager.setUserData(a, SyncAdapter.TASKWARRIOR_KEY, taskString); continue; } JsonObject taskObject; Task local_task; Task server_task; try { taskObject = new JsonParser().parse(taskString) .getAsJsonObject(); Log.i(TAG, taskString); - server_task = Task.parse_json(taskObject, accountMirakel); + server_task = Task.parse_json(taskObject, accountMirakel,true); if (server_task.getList() == null || server_task.getList().getAccount().getId() != accountMirakel .getId()) { ListMirakel list = ListMirakel .getInboxList(accountMirakel); server_task.setList(list, false); Log.d(TAG, "no list"); server_task.addAdditionalEntry(NO_PROJECT, "true"); } this.dependencies.put(server_task.getUUID(), server_task.getDependencies()); local_task = Task.getByUUID(server_task.getUUID()); } catch (Exception e) { Log.d(TAG, Log.getStackTraceString(e)); Log.e(TAG, "malformed JSON"); Log.e(TAG, taskString); continue; } if (server_task.getSyncState() == SYNC_STATE.DELETE) { Log.d(TAG, "destroy " + server_task.getName()); if (local_task != null) { local_task.destroy(true); } } else if (local_task == null) { try { server_task.create(false); Log.d(TAG, "create " + server_task.getName()); } catch (NoSuchListException e) { Log.wtf(TAG, "List vanish"); // Looper.prepare(); // Toast.makeText(mContext, R.string.no_lists, // Toast.LENGTH_LONG).show(); } } else { server_task.setId(local_task.getId()); Log.d(TAG, "update " + server_task.getName()); server_task.safeSave(); } } } String message = remotes.get("message"); if (message != null && message != "") { // Toast.makeText(mContext, // mContext.getString(R.string.message_from_server, message), // Toast.LENGTH_LONG).show(); Log.v(TAG, "Message from Server: " + message); } client.close(); return TW_ERRORS.NO_ERROR; } /** * Format a Calendar to the taskwarrior-date-format * * @param c * @return */ @SuppressLint("SimpleDateFormat") private String formatCal(Calendar c) { SimpleDateFormat df = new SimpleDateFormat( this.mContext.getString(R.string.TWDateFormat)); return df.format(c.getTime()); } /** * Initialize the variables */ private void init() { String server = this.accountManager.getUserData(this.account, SyncAdapter.BUNDLE_SERVER_URL); String srv[] = server.trim().split(":"); if (srv.length != 2) { error("port", 1376235889); } String key = this.accountManager.getPassword(this.account); if (key.length() != 0 && key.length() != 36) { error("key", 1376235890); } File r = new File(CA_FILE); File user_cert = new File(CLIENT_CERT_FILE); File userKey = new File(CLIENT_KEY_FILE); if (!r.exists() || !r.canRead() || !user_cert.exists() || !user_cert.canRead() || !userKey.exists() || !userKey.canRead()) { error("cert", 1376235891); } _host = srv[0]; _port = Integer.parseInt(srv[1]); _user = this.account.name; _org = this.accountManager.getUserData(this.account, SyncAdapter.BUNDLE_ORG); _key = this.accountManager.getPassword(this.account); TaskWarriorSync.root = r; TaskWarriorSync.user_ca = user_cert; TaskWarriorSync.user_key = userKey; } private void setDependencies() { for (String uuid : this.dependencies.keySet()) { Task parent = Task.getByUUID(uuid); if (uuid == null || this.dependencies == null) { continue; } String[] childs = this.dependencies.get(uuid); if (childs == null) { continue; } for (String childUuid : childs) { Task child = Task.getByUUID(childUuid); if (child == null) { continue; } if (child.isSubtaskOf(parent)) { continue; } try { parent.addSubtask(child); } catch (Exception e) { //eat it } } } } public String getTime() { return new SimpleDateFormat("dd-MM-yyyy_hh-mm-ss", Helpers.getLocal(this.mContext)).format(new Date()); } public TW_ERRORS sync(Account a) { this.accountManager = AccountManager.get(this.mContext); this.account = a; AccountMirakel aMirakel = AccountMirakel.get(a); if (!aMirakel.isEnabeld()) return TW_ERRORS.NOT_ENABLED; init(); Msg sync = new Msg(); String payload = ""; sync.set("protocol", "v1"); sync.set("type", "sync"); sync.set("org", _org); sync.set("user", _user); sync.set("key", _key); List<Task> local_tasks = Task.getTasksToSync(a); for (Task task : local_tasks) { payload += taskToJson(task) + "\n"; } // Format: {UUID:[UUID]} this.dependencies = new HashMap<String, String[]>(); // for (int i = 0; i < parts; i++) { String old_key = this.accountManager.getUserData(a, SyncAdapter.TASKWARRIOR_KEY); if (old_key != null && !old_key.equals("")) { payload += old_key + "\n"; } // Build sync-request sync.setPayload(payload); if (MirakelCommonPreferences.isDumpTw()) { try { FileWriter f = new FileWriter(new File(FileUtils.getLogDir(), getTime() + ".tw_up.log")); f.write(payload); f.close(); } catch (Exception e) { //eat it } } TW_ERRORS error = doSync(a, sync); if (error == TW_ERRORS.NO_ERROR) { Log.w(TAG, "clear sync state"); Task.resetSyncState(local_tasks); } else { setDependencies(); return error; } // } setDependencies(); return TW_ERRORS.NO_ERROR; } /** * Converts a task to the json-format we need * * @param task * @return */ public String taskToJson(Task task) { Map<String, String> additionals=task.getAdditionalEntries(); String end = null; String status = "pending"; if (task.getSyncState() == SYNC_STATE.DELETE) { status = "deleted"; end = formatCal(new GregorianCalendar()); } else if (task.isDone()) { status = "completed"; if(additionals.containsKey("end")){ end=additionals.get("end"); end=end.substring(1,end.length()-1); // Clear redundant \" }else{ end = formatCal(new GregorianCalendar()); } } Log.i(TAG, "Status waiting / recurring is not implemented now"); // TODO String priority = null; switch (task.getPriority()) { case -2: case -1: priority = "L"; break; case 1: priority = "M"; break; case 2: priority = "H"; break; default: Log.wtf(TAG, "unkown priority"); break; } String json = "{"; json += "\"uuid\":\"" + task.getUUID() + "\""; json += ",\"status\":\"" + status + "\""; json += ",\"entry\":\"" + formatCal(task.getCreatedAt()) + "\""; json += ",\"description\":\"" + escape(task.getName()) + "\""; if (task.getDue() != null) { json += ",\"due\":\"" + formatCal(task.getDue()) + "\""; } if (task.getList() != null && !additionals.containsKey(NO_PROJECT)) { json += ",\"project\":\"" + task.getList().getName() + "\""; } if (priority != null) { json += ",\"priority\":\"" + priority + "\""; } json += ",\"modified\":\"" + formatCal(task.getUpdatedAt()) + "\""; if (task.getReminder() != null) { json += ",\"reminder\":\"" + formatCal(task.getReminder()) + "\""; } if (end != null) { json += ",\"end\":\"" + end + "\""; } json += ",\"progress\":" + task.getProgress(); // Annotations if (task.getContent() != null && !task.getContent().equals("")) { json += ",\"annotations\":["; /* * An annotation in taskd is a line of content in Mirakel! */ String annotations[] = escape(task.getContent()).split("\n"); boolean first = true; Calendar d = task.getUpdatedAt(); for (String a : annotations) { if (first) { first = false; } else { json += ","; } json += "{\"entry\":\"" + formatCal(d) + "\","; json += "\"description\":\"" + a.trim().replace("\n", "") + "\"}"; d.add(Calendar.SECOND, 1); } json += "]"; } // Anotations end // TW.depends==Mirakel.subtasks! // Dependencies if (task.getSubtaskCount() > 0) { json += ",\"depends\":\""; boolean first1 = true; for (Task subtask : task.getSubtasks()) { if (first1) { first1 = false; } else { json += ","; } json += subtask.getUUID(); } json += "\""; } // end Dependencies // Additional Strings if (additionals != null) { for (String key : additionals.keySet()) { if (!key.equals(NO_PROJECT)) { json += ",\"" + key + "\":" + additionals.get(key); } } } // end Additional Strings json += "}"; return json; } }
true
true
private TW_ERRORS doSync(Account a, Msg sync) { AccountMirakel accountMirakel = AccountMirakel.get(this.account); longInfo(sync.getPayload()); TLSClient client = new TLSClient(); try { client.init(root, user_ca, user_key); } catch (ParseException e) { Log.e(TAG,"cannot open certificate"); return TW_ERRORS.CONFIG_PARSE_ERROR; } catch (CertificateException e) { Log.e(TAG, "general problem with init"); return TW_ERRORS.CONFIG_PARSE_ERROR; } try { client.connect(_host, _port); } catch (IOException e) { Log.e(TAG, "cannot create Socket"); return TW_ERRORS.CANNOT_CREATE_SOCKET; } client.send(sync.serialize()); String response = client.recv(); if (MirakelCommonPreferences.isEnabledDebugMenu() && MirakelCommonPreferences.isDumpTw()) { try { FileUtils.writeToFile(new File(FileUtils.getLogDir(), getTime() + ".tw_down.log"), response); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } // longInfo(response); Msg remotes = new Msg(); try { remotes.parse(response); } catch (MalformedInputException e) { Log.e(TAG, "cannot parse Message"); return TW_ERRORS.CANNOT_PARSE_MESSAGE; } catch (NullPointerException e) { Log.wtf(TAG, "remotes.pars throwed NullPointer"); return TW_ERRORS.CANNOT_PARSE_MESSAGE; } int code = Integer.parseInt(remotes.get("code")); TW_ERRORS error = TW_ERRORS.getError(code); if (error != TW_ERRORS.NO_ERROR) return error; if (remotes.get("status").equals("Client sync key not found.")) { Log.d(TAG, "reset sync-key"); this.accountManager.setUserData(a, SyncAdapter.TASKWARRIOR_KEY, null); sync(a); } // parse tasks if (remotes.getPayload() == null || remotes.getPayload().equals("")) { Log.i(TAG, "there is no Payload"); } else { String tasksString[] = remotes.getPayload().split("\n"); for (String taskString : tasksString) { if (taskString.charAt(0) != '{') { Log.d(TAG, "Key: " + taskString); this.accountManager.setUserData(a, SyncAdapter.TASKWARRIOR_KEY, taskString); continue; } JsonObject taskObject; Task local_task; Task server_task; try { taskObject = new JsonParser().parse(taskString) .getAsJsonObject(); Log.i(TAG, taskString); server_task = Task.parse_json(taskObject, accountMirakel); if (server_task.getList() == null || server_task.getList().getAccount().getId() != accountMirakel .getId()) { ListMirakel list = ListMirakel .getInboxList(accountMirakel); server_task.setList(list, false); Log.d(TAG, "no list"); server_task.addAdditionalEntry(NO_PROJECT, "true"); } this.dependencies.put(server_task.getUUID(), server_task.getDependencies()); local_task = Task.getByUUID(server_task.getUUID()); } catch (Exception e) { Log.d(TAG, Log.getStackTraceString(e)); Log.e(TAG, "malformed JSON"); Log.e(TAG, taskString); continue; } if (server_task.getSyncState() == SYNC_STATE.DELETE) { Log.d(TAG, "destroy " + server_task.getName()); if (local_task != null) { local_task.destroy(true); } } else if (local_task == null) { try { server_task.create(false); Log.d(TAG, "create " + server_task.getName()); } catch (NoSuchListException e) { Log.wtf(TAG, "List vanish"); // Looper.prepare(); // Toast.makeText(mContext, R.string.no_lists, // Toast.LENGTH_LONG).show(); } } else { server_task.setId(local_task.getId()); Log.d(TAG, "update " + server_task.getName()); server_task.safeSave(); } } } String message = remotes.get("message"); if (message != null && message != "") { // Toast.makeText(mContext, // mContext.getString(R.string.message_from_server, message), // Toast.LENGTH_LONG).show(); Log.v(TAG, "Message from Server: " + message); } client.close(); return TW_ERRORS.NO_ERROR; }
private TW_ERRORS doSync(Account a, Msg sync) { AccountMirakel accountMirakel = AccountMirakel.get(this.account); longInfo(sync.getPayload()); TLSClient client = new TLSClient(); try { client.init(root, user_ca, user_key); } catch (ParseException e) { Log.e(TAG,"cannot open certificate"); return TW_ERRORS.CONFIG_PARSE_ERROR; } catch (CertificateException e) { Log.e(TAG, "general problem with init"); return TW_ERRORS.CONFIG_PARSE_ERROR; } try { client.connect(_host, _port); } catch (IOException e) { Log.e(TAG, "cannot create Socket"); return TW_ERRORS.CANNOT_CREATE_SOCKET; } client.send(sync.serialize()); String response = client.recv(); if (MirakelCommonPreferences.isEnabledDebugMenu() && MirakelCommonPreferences.isDumpTw()) { try { FileUtils.writeToFile(new File(FileUtils.getLogDir(), getTime() + ".tw_down.log"), response); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } // longInfo(response); Msg remotes = new Msg(); try { remotes.parse(response); } catch (MalformedInputException e) { Log.e(TAG, "cannot parse Message"); return TW_ERRORS.CANNOT_PARSE_MESSAGE; } catch (NullPointerException e) { Log.wtf(TAG, "remotes.pars throwed NullPointer"); return TW_ERRORS.CANNOT_PARSE_MESSAGE; } int code = Integer.parseInt(remotes.get("code")); TW_ERRORS error = TW_ERRORS.getError(code); if (error != TW_ERRORS.NO_ERROR) return error; if (remotes.get("status").equals("Client sync key not found.")) { Log.d(TAG, "reset sync-key"); this.accountManager.setUserData(a, SyncAdapter.TASKWARRIOR_KEY, null); sync(a); } // parse tasks if (remotes.getPayload() == null || remotes.getPayload().equals("")) { Log.i(TAG, "there is no Payload"); } else { String tasksString[] = remotes.getPayload().split("\n"); for (String taskString : tasksString) { if (taskString.charAt(0) != '{') { Log.d(TAG, "Key: " + taskString); this.accountManager.setUserData(a, SyncAdapter.TASKWARRIOR_KEY, taskString); continue; } JsonObject taskObject; Task local_task; Task server_task; try { taskObject = new JsonParser().parse(taskString) .getAsJsonObject(); Log.i(TAG, taskString); server_task = Task.parse_json(taskObject, accountMirakel,true); if (server_task.getList() == null || server_task.getList().getAccount().getId() != accountMirakel .getId()) { ListMirakel list = ListMirakel .getInboxList(accountMirakel); server_task.setList(list, false); Log.d(TAG, "no list"); server_task.addAdditionalEntry(NO_PROJECT, "true"); } this.dependencies.put(server_task.getUUID(), server_task.getDependencies()); local_task = Task.getByUUID(server_task.getUUID()); } catch (Exception e) { Log.d(TAG, Log.getStackTraceString(e)); Log.e(TAG, "malformed JSON"); Log.e(TAG, taskString); continue; } if (server_task.getSyncState() == SYNC_STATE.DELETE) { Log.d(TAG, "destroy " + server_task.getName()); if (local_task != null) { local_task.destroy(true); } } else if (local_task == null) { try { server_task.create(false); Log.d(TAG, "create " + server_task.getName()); } catch (NoSuchListException e) { Log.wtf(TAG, "List vanish"); // Looper.prepare(); // Toast.makeText(mContext, R.string.no_lists, // Toast.LENGTH_LONG).show(); } } else { server_task.setId(local_task.getId()); Log.d(TAG, "update " + server_task.getName()); server_task.safeSave(); } } } String message = remotes.get("message"); if (message != null && message != "") { // Toast.makeText(mContext, // mContext.getString(R.string.message_from_server, message), // Toast.LENGTH_LONG).show(); Log.v(TAG, "Message from Server: " + message); } client.close(); return TW_ERRORS.NO_ERROR; }
diff --git a/orig/trunk/vnc_javasrc/VncViewer.java b/orig/trunk/vnc_javasrc/VncViewer.java index 885aed02..6ae877ba 100644 --- a/orig/trunk/vnc_javasrc/VncViewer.java +++ b/orig/trunk/vnc_javasrc/VncViewer.java @@ -1,831 +1,832 @@ // // Copyright (C) 2001-2003 HorizonLive.com, Inc. All Rights Reserved. // Copyright (C) 2002 Constantin Kaplinsky. All Rights Reserved. // Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved. // // This 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 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this software; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. // // // VncViewer.java - the VNC viewer applet. This class mainly just sets up the // user interface, leaving it to the VncCanvas to do the actual rendering of // a VNC desktop. // import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; public class VncViewer extends java.applet.Applet implements java.lang.Runnable, WindowListener { boolean inAnApplet = true; boolean inSeparateFrame = false; // // main() is called when run as a java program from the command line. // It simply runs the applet inside a newly-created frame. // public static void main(String[] argv) { VncViewer v = new VncViewer(); v.mainArgs = argv; v.inAnApplet = false; v.inSeparateFrame = true; v.init(); v.start(); } String[] mainArgs; RfbProto rfb; Thread rfbThread; Frame vncFrame; Container vncContainer; ScrollPane desktopScrollPane; GridBagLayout gridbag; ButtonPanel buttonPanel; Label connStatusLabel; AuthPanel authenticator; VncCanvas vc; OptionsFrame options; ClipboardFrame clipboard; RecordingFrame rec; // Control session recording. Object recordingSync; String sessionFileName; boolean recordingActive; boolean recordingStatusChanged; String cursorUpdatesDef; String eightBitColorsDef; // Variables read from parameter values. String socketFactory; String host; int port; boolean showControls; boolean offerRelogin; boolean showOfflineDesktop; int deferScreenUpdates; int deferCursorUpdates; int deferUpdateRequests; // Reference to this applet for inter-applet communication. public static java.applet.Applet refApplet; // // init() // public void init() { readParameters(); refApplet = this; if (inSeparateFrame) { vncFrame = new Frame("TightVNC"); if (!inAnApplet) { vncFrame.add("Center", this); } vncContainer = vncFrame; } else { vncContainer = this; } recordingSync = new Object(); options = new OptionsFrame(this); clipboard = new ClipboardFrame(this); authenticator = new AuthPanel(this); if (RecordingFrame.checkSecurity()) rec = new RecordingFrame(this); sessionFileName = null; recordingActive = false; recordingStatusChanged = false; cursorUpdatesDef = null; eightBitColorsDef = null; if (inSeparateFrame) vncFrame.addWindowListener(this); rfbThread = new Thread(this); rfbThread.start(); } public void update(Graphics g) { } // // run() - executed by the rfbThread to deal with the RFB socket. // public void run() { gridbag = new GridBagLayout(); vncContainer.setLayout(gridbag); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.anchor = GridBagConstraints.NORTHWEST; if (showControls) { buttonPanel = new ButtonPanel(this); gridbag.setConstraints(buttonPanel, gbc); vncContainer.add(buttonPanel); } try { connectAndAuthenticate(); doProtocolInitialisation(); vc = new VncCanvas(this); gbc.weightx = 1.0; gbc.weighty = 1.0; if (inSeparateFrame) { // Create a panel which itself is resizeable and can hold // non-resizeable VncCanvas component at the top left corner. Panel canvasPanel = new Panel(); canvasPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0)); canvasPanel.add(vc); // Create a ScrollPane which will hold a panel with VncCanvas // inside. desktopScrollPane = new ScrollPane(ScrollPane.SCROLLBARS_AS_NEEDED); gbc.fill = GridBagConstraints.BOTH; gridbag.setConstraints(desktopScrollPane, gbc); desktopScrollPane.add(canvasPanel); // Finally, add our ScrollPane to the Frame window. vncFrame.add(desktopScrollPane); vncFrame.setTitle(rfb.desktopName); vncFrame.pack(); vc.resizeDesktopFrame(); } else { // Just add the VncCanvas component to the Applet. gridbag.setConstraints(vc, gbc); add(vc); validate(); } if (showControls) buttonPanel.enableButtons(); + moveFocusToDesktop(); processNormalProtocol(); } catch (NoRouteToHostException e) { fatalError("Network error: no route to server: " + host, e); } catch (UnknownHostException e) { fatalError("Network error: server name unknown: " + host, e); } catch (ConnectException e) { fatalError("Network error: could not connect to server: " + host + ":" + port, e); } catch (EOFException e) { if (showOfflineDesktop) { e.printStackTrace(); System.out.println("Network error: remote side closed connection"); if (vc != null) { vc.enableInput(false); } if (inSeparateFrame) { vncFrame.setTitle(rfb.desktopName + " [disconnected]"); } if (rfb != null && !rfb.closed()) rfb.close(); if (showControls && buttonPanel != null) { buttonPanel.disableButtonsOnDisconnect(); if (inSeparateFrame) { vncFrame.pack(); } else { validate(); } } } else { fatalError("Network error: remote side closed connection", e); } } catch (IOException e) { String str = e.getMessage(); if (str != null && str.length() != 0) { fatalError("Network Error: " + str, e); } else { fatalError(e.toString(), e); } } catch (Exception e) { String str = e.getMessage(); if (str != null && str.length() != 0) { fatalError("Error: " + str, e); } else { fatalError(e.toString(), e); } } } // // Process RFB socket messages. // If the rfbThread is being stopped, ignore any exceptions, // otherwise rethrow the exception so it can be handled. // void processNormalProtocol() throws Exception { try { vc.processNormalProtocol(); } catch (Exception e) { if (rfbThread == null) { System.out.println("Ignoring RFB socket exceptions" + " because applet is stopping"); } else { throw e; } } } // // Connect to the RFB server and authenticate the user. // void connectAndAuthenticate() throws Exception { showConnectionStatus("Initializing..."); if (inSeparateFrame) { vncFrame.pack(); vncFrame.show(); } else { validate(); } while (!tryAuthenticate()) { if (!authenticator.isInteractionNecessary()) { throw new Exception("VNC authentication failed"); } authenticator.retry(); } } // // Try to connect and authenticate. // boolean tryAuthenticate() throws Exception { showConnectionStatus("Connecting to " + host + ", port " + port + "..."); rfb = new RfbProto(host, port, this); rfb.readVersionMsg(); showConnectionStatus("RFB server supports protocol version " + rfb.serverMajor + "." + rfb.serverMinor); rfb.writeVersionMsg(); int authScheme = rfb.readAuthScheme(); boolean success = false; switch (authScheme) { case RfbProto.NoAuth: showConnectionStatus("No authentication needed"); success = true; break; case RfbProto.VncAuth: if (authenticator.isInteractionNecessary()) { showAuthPanel(); } success = authenticator.tryAuthenticate(rfb); if (authenticator.isInteractionNecessary()) { vncContainer.remove(authenticator); } else { // Don't retry non-interactive authentication. if (!success) throw new Exception("Authentication failed"); } break; default: throw new Exception("Unknown authentication scheme " + authScheme); } if (!success) rfb.close(); return success; } // // Show a message describing the connection status. // To hide the connection status label, use (msg == null). // void showConnectionStatus(String msg) { if (msg == null) { if (vncContainer.isAncestorOf(connStatusLabel)) { vncContainer.remove(connStatusLabel); } return; } System.out.println(msg); if (connStatusLabel == null) { connStatusLabel = new Label("Status: " + msg); connStatusLabel.setFont(new Font("Helvetica", Font.PLAIN, 12)); } else { connStatusLabel.setText("Status: " + msg); } if (!vncContainer.isAncestorOf(connStatusLabel)) { GridBagConstraints gbc = new GridBagConstraints(); gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.anchor = GridBagConstraints.NORTHWEST; gbc.weightx = 1.0; gbc.weighty = 1.0; gbc.insets = new Insets(20, 30, 20, 30); gridbag.setConstraints(connStatusLabel, gbc); vncContainer.add(connStatusLabel); } if (inSeparateFrame) { vncFrame.pack(); } else { validate(); } } // // Show an authentication panel. // void showAuthPanel() { showConnectionStatus(null); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.anchor = GridBagConstraints.NORTHWEST; gbc.weightx = 1.0; gbc.weighty = 1.0; gbc.ipadx = 100; gbc.ipady = 50; gridbag.setConstraints(authenticator, gbc); vncContainer.add(authenticator); if (inSeparateFrame) { vncFrame.pack(); } else { validate(); // FIXME: here moveFocusToDefaultField() does not always work // under Netscape 4.7x/Java 1.1.5/Linux. It seems like this call // is being executed before the password field of the // authenticator is fully drawn and activated, therefore // requestFocus() does not work. Currently, I don't know how to // solve this problem. // -- const authenticator.moveFocusToDefaultField(); } } // // Do the rest of the protocol initialisation. // void doProtocolInitialisation() throws IOException { rfb.writeClientInit(); rfb.readServerInit(); System.out.println("Desktop name is " + rfb.desktopName); System.out.println("Desktop size is " + rfb.framebufferWidth + " x " + rfb.framebufferHeight); setEncodings(); showConnectionStatus(null); } // // Send current encoding list to the RFB server. // void setEncodings() { try { if (rfb != null && rfb.inNormalProtocol) { rfb.writeSetEncodings(options.encodings, options.nEncodings); if (vc != null) { vc.softCursorFree(); } } } catch (Exception e) { e.printStackTrace(); } } // // setCutText() - send the given cut text to the RFB server. // void setCutText(String text) { try { if (rfb != null && rfb.inNormalProtocol) { rfb.writeClientCutText(text); } } catch (Exception e) { e.printStackTrace(); } } // // Order change in session recording status. To stop recording, pass // null in place of the fname argument. // void setRecordingStatus(String fname) { synchronized(recordingSync) { sessionFileName = fname; recordingStatusChanged = true; } } // // Start or stop session recording. Returns true if this method call // causes recording of a new session. // boolean checkRecordingStatus() throws IOException { synchronized(recordingSync) { if (recordingStatusChanged) { recordingStatusChanged = false; if (sessionFileName != null) { startRecording(); return true; } else { stopRecording(); } } } return false; } // // Start session recording. // protected void startRecording() throws IOException { synchronized(recordingSync) { if (!recordingActive) { // Save settings to restore them after recording the session. cursorUpdatesDef = options.choices[options.cursorUpdatesIndex].getSelectedItem(); eightBitColorsDef = options.choices[options.eightBitColorsIndex].getSelectedItem(); // Set options to values suitable for recording. options.choices[options.cursorUpdatesIndex].select("Disable"); options.choices[options.cursorUpdatesIndex].setEnabled(false); options.setEncodings(); options.choices[options.eightBitColorsIndex].select("No"); options.choices[options.eightBitColorsIndex].setEnabled(false); options.setColorFormat(); } else { rfb.closeSession(); } System.out.println("Recording the session in " + sessionFileName); rfb.startSession(sessionFileName); recordingActive = true; } } // // Stop session recording. // protected void stopRecording() throws IOException { synchronized(recordingSync) { if (recordingActive) { // Restore options. options.choices[options.cursorUpdatesIndex].select(cursorUpdatesDef); options.choices[options.cursorUpdatesIndex].setEnabled(true); options.setEncodings(); options.choices[options.eightBitColorsIndex].select(eightBitColorsDef); options.choices[options.eightBitColorsIndex].setEnabled(true); options.setColorFormat(); rfb.closeSession(); System.out.println("Session recording stopped."); } sessionFileName = null; recordingActive = false; } } // // readParameters() - read parameters from the html source or from the // command line. On the command line, the arguments are just a sequence of // param_name/param_value pairs where the names and values correspond to // those expected in the html applet tag source. // public void readParameters() { host = readParameter("HOST", !inAnApplet); if (host == null) { host = getCodeBase().getHost(); if (host.equals("")) { fatalError("HOST parameter not specified"); } } String str = readParameter("PORT", true); port = Integer.parseInt(str); if (inAnApplet) { str = readParameter("Open New Window", false); if (str != null && str.equalsIgnoreCase("Yes")) inSeparateFrame = true; } // "Show Controls" set to "No" disables button panel. showControls = true; str = readParameter("Show Controls", false); if (str != null && str.equalsIgnoreCase("No")) showControls = false; // "Offer Relogin" set to "No" disables "Login again" and "Close // window" buttons under error messages in applet mode. offerRelogin = true; str = readParameter("Offer Relogin", false); if (str != null && str.equalsIgnoreCase("No")) offerRelogin = false; // Do we continue showing desktop on remote disconnect? showOfflineDesktop = false; str = readParameter("Show Offline Desktop", false); if (str != null && str.equalsIgnoreCase("Yes")) showOfflineDesktop = true; // Fine tuning options. deferScreenUpdates = readIntParameter("Defer screen updates", 20); deferCursorUpdates = readIntParameter("Defer cursor updates", 10); deferUpdateRequests = readIntParameter("Defer update requests", 50); // SocketFactory. socketFactory = readParameter("SocketFactory", false); } public String readParameter(String name, boolean required) { if (inAnApplet) { String s = getParameter(name); if ((s == null) && required) { fatalError(name + " parameter not specified"); } return s; } for (int i = 0; i < mainArgs.length; i += 2) { if (mainArgs[i].equalsIgnoreCase(name)) { try { return mainArgs[i+1]; } catch (Exception e) { if (required) { fatalError(name + " parameter not specified"); } return null; } } } if (required) { fatalError(name + " parameter not specified"); } return null; } int readIntParameter(String name, int defaultValue) { String str = readParameter(name, false); int result = defaultValue; if (str != null) { try { result = Integer.parseInt(str); } catch (NumberFormatException e) { } } return result; } // // moveFocusToDesktop() - move keyboard focus either to the // VncCanvas or to the AuthPanel. // void moveFocusToDesktop() { if (vncContainer != null) { if (vc != null && vncContainer.isAncestorOf(vc)) { vc.requestFocus(); } else if (vncContainer.isAncestorOf(authenticator)) { authenticator.moveFocusToDefaultField(); } } } // // disconnect() - close connection to server. // synchronized public void disconnect() { System.out.println("Disconnect"); if (rfb != null && !rfb.closed()) rfb.close(); options.dispose(); clipboard.dispose(); if (rec != null) rec.dispose(); if (inAnApplet) { showMessage("Disconnected"); } else { System.exit(0); } } // // fatalError() - print out a fatal error message. // synchronized public void fatalError(String str) { System.out.println(str); if (inAnApplet) { // vncContainer null, applet not inited, // can not present the error to the user. Thread.currentThread().stop(); } else { System.exit(1); } } synchronized public void fatalError(String str, Exception e) { if (rfb != null) { // Not necessary to show error message if the error was caused // by I/O problems after the rfb.close() method call. if (rfb.closed()) { System.out.println("RFB thread finished"); return; } rfb.close(); } e.printStackTrace(); System.out.println(str); if (inAnApplet) { showMessage(str); } else { System.exit(1); } } // // Show message text and optionally "Relogin" and "Close" buttons. // void showMessage(String msg) { vncContainer.removeAll(); Label errLabel = new Label(msg, Label.CENTER); errLabel.setFont(new Font("Helvetica", Font.PLAIN, 12)); if (offerRelogin) { Panel gridPanel = new Panel(new GridLayout(0, 1)); Panel outerPanel = new Panel(new FlowLayout(FlowLayout.LEFT)); outerPanel.add(gridPanel); vncContainer.setLayout(new FlowLayout(FlowLayout.LEFT, 30, 16)); vncContainer.add(outerPanel); Panel textPanel = new Panel(new FlowLayout(FlowLayout.CENTER)); textPanel.add(errLabel); gridPanel.add(textPanel); gridPanel.add(new ReloginPanel(this)); } else { vncContainer.setLayout(new FlowLayout(FlowLayout.LEFT, 30, 30)); vncContainer.add(errLabel); } if (inSeparateFrame) { vncFrame.pack(); } else { validate(); } } // // Stop the applet. // Main applet thread will terminate on first exception // after seeing that rfbThread has been set to null. // public void stop() { System.out.println("Stopping applet"); rfbThread = null; } // // This method is called before the applet is destroyed. // public void destroy() { System.out.println("Destroying applet"); vncContainer.removeAll(); options.dispose(); clipboard.dispose(); if (rec != null) rec.dispose(); if (rfb != null && !rfb.closed()) rfb.close(); if (inSeparateFrame) vncFrame.dispose(); } // // Start/stop receiving mouse events. // public void enableInput(boolean enable) { vc.enableInput(enable); } // // Close application properly on window close event. // public void windowClosing(WindowEvent evt) { System.out.println("Closing window"); if (rfb != null) disconnect(); vncContainer.hide(); if (!inAnApplet) { System.exit(0); } } // // Move the keyboard focus to the password field on window activation. // public void windowActivated(WindowEvent evt) { if (vncFrame.isAncestorOf(authenticator)) authenticator.moveFocusToDefaultField(); } // // Ignore window events we're not interested in. // public void windowDeactivated (WindowEvent evt) {} public void windowOpened(WindowEvent evt) {} public void windowClosed(WindowEvent evt) {} public void windowIconified(WindowEvent evt) {} public void windowDeiconified(WindowEvent evt) {} }
true
true
public void run() { gridbag = new GridBagLayout(); vncContainer.setLayout(gridbag); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.anchor = GridBagConstraints.NORTHWEST; if (showControls) { buttonPanel = new ButtonPanel(this); gridbag.setConstraints(buttonPanel, gbc); vncContainer.add(buttonPanel); } try { connectAndAuthenticate(); doProtocolInitialisation(); vc = new VncCanvas(this); gbc.weightx = 1.0; gbc.weighty = 1.0; if (inSeparateFrame) { // Create a panel which itself is resizeable and can hold // non-resizeable VncCanvas component at the top left corner. Panel canvasPanel = new Panel(); canvasPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0)); canvasPanel.add(vc); // Create a ScrollPane which will hold a panel with VncCanvas // inside. desktopScrollPane = new ScrollPane(ScrollPane.SCROLLBARS_AS_NEEDED); gbc.fill = GridBagConstraints.BOTH; gridbag.setConstraints(desktopScrollPane, gbc); desktopScrollPane.add(canvasPanel); // Finally, add our ScrollPane to the Frame window. vncFrame.add(desktopScrollPane); vncFrame.setTitle(rfb.desktopName); vncFrame.pack(); vc.resizeDesktopFrame(); } else { // Just add the VncCanvas component to the Applet. gridbag.setConstraints(vc, gbc); add(vc); validate(); } if (showControls) buttonPanel.enableButtons(); processNormalProtocol(); } catch (NoRouteToHostException e) { fatalError("Network error: no route to server: " + host, e); } catch (UnknownHostException e) { fatalError("Network error: server name unknown: " + host, e); } catch (ConnectException e) { fatalError("Network error: could not connect to server: " + host + ":" + port, e); } catch (EOFException e) { if (showOfflineDesktop) { e.printStackTrace(); System.out.println("Network error: remote side closed connection"); if (vc != null) { vc.enableInput(false); } if (inSeparateFrame) { vncFrame.setTitle(rfb.desktopName + " [disconnected]"); } if (rfb != null && !rfb.closed()) rfb.close(); if (showControls && buttonPanel != null) { buttonPanel.disableButtonsOnDisconnect(); if (inSeparateFrame) { vncFrame.pack(); } else { validate(); } } } else { fatalError("Network error: remote side closed connection", e); } } catch (IOException e) { String str = e.getMessage(); if (str != null && str.length() != 0) { fatalError("Network Error: " + str, e); } else { fatalError(e.toString(), e); } } catch (Exception e) { String str = e.getMessage(); if (str != null && str.length() != 0) { fatalError("Error: " + str, e); } else { fatalError(e.toString(), e); } } }
public void run() { gridbag = new GridBagLayout(); vncContainer.setLayout(gridbag); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.anchor = GridBagConstraints.NORTHWEST; if (showControls) { buttonPanel = new ButtonPanel(this); gridbag.setConstraints(buttonPanel, gbc); vncContainer.add(buttonPanel); } try { connectAndAuthenticate(); doProtocolInitialisation(); vc = new VncCanvas(this); gbc.weightx = 1.0; gbc.weighty = 1.0; if (inSeparateFrame) { // Create a panel which itself is resizeable and can hold // non-resizeable VncCanvas component at the top left corner. Panel canvasPanel = new Panel(); canvasPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0)); canvasPanel.add(vc); // Create a ScrollPane which will hold a panel with VncCanvas // inside. desktopScrollPane = new ScrollPane(ScrollPane.SCROLLBARS_AS_NEEDED); gbc.fill = GridBagConstraints.BOTH; gridbag.setConstraints(desktopScrollPane, gbc); desktopScrollPane.add(canvasPanel); // Finally, add our ScrollPane to the Frame window. vncFrame.add(desktopScrollPane); vncFrame.setTitle(rfb.desktopName); vncFrame.pack(); vc.resizeDesktopFrame(); } else { // Just add the VncCanvas component to the Applet. gridbag.setConstraints(vc, gbc); add(vc); validate(); } if (showControls) buttonPanel.enableButtons(); moveFocusToDesktop(); processNormalProtocol(); } catch (NoRouteToHostException e) { fatalError("Network error: no route to server: " + host, e); } catch (UnknownHostException e) { fatalError("Network error: server name unknown: " + host, e); } catch (ConnectException e) { fatalError("Network error: could not connect to server: " + host + ":" + port, e); } catch (EOFException e) { if (showOfflineDesktop) { e.printStackTrace(); System.out.println("Network error: remote side closed connection"); if (vc != null) { vc.enableInput(false); } if (inSeparateFrame) { vncFrame.setTitle(rfb.desktopName + " [disconnected]"); } if (rfb != null && !rfb.closed()) rfb.close(); if (showControls && buttonPanel != null) { buttonPanel.disableButtonsOnDisconnect(); if (inSeparateFrame) { vncFrame.pack(); } else { validate(); } } } else { fatalError("Network error: remote side closed connection", e); } } catch (IOException e) { String str = e.getMessage(); if (str != null && str.length() != 0) { fatalError("Network Error: " + str, e); } else { fatalError(e.toString(), e); } } catch (Exception e) { String str = e.getMessage(); if (str != null && str.length() != 0) { fatalError("Error: " + str, e); } else { fatalError(e.toString(), e); } } }
diff --git a/src/com/fsck/k9/activity/setup/AccountSettings.java b/src/com/fsck/k9/activity/setup/AccountSettings.java index b39f9bab9..f171a8bc5 100644 --- a/src/com/fsck/k9/activity/setup/AccountSettings.java +++ b/src/com/fsck/k9/activity/setup/AccountSettings.java @@ -1,1086 +1,1087 @@ package com.fsck.k9.activity.setup; import android.app.Dialog; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Vibrator; import android.preference.CheckBoxPreference; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.PreferenceScreen; import android.preference.RingtonePreference; import android.util.Log; import com.fsck.k9.Account; import com.fsck.k9.Account.FolderMode; import com.fsck.k9.Account.QuoteStyle; import com.fsck.k9.K9; import com.fsck.k9.NotificationSetting; import com.fsck.k9.Preferences; import com.fsck.k9.R; import com.fsck.k9.activity.ChooseFolder; import com.fsck.k9.activity.ChooseIdentity; import com.fsck.k9.activity.ColorPickerDialog; import com.fsck.k9.activity.K9PreferenceActivity; import com.fsck.k9.activity.ManageIdentities; import com.fsck.k9.crypto.Apg; import com.fsck.k9.mail.Folder; import com.fsck.k9.mail.Store; import com.fsck.k9.mail.store.LocalStore.LocalFolder; import com.fsck.k9.mail.store.StorageManager; import com.fsck.k9.service.MailService; public class AccountSettings extends K9PreferenceActivity { private static final String EXTRA_ACCOUNT = "account"; private static final int DIALOG_COLOR_PICKER_ACCOUNT = 1; private static final int DIALOG_COLOR_PICKER_LED = 2; private static final int SELECT_AUTO_EXPAND_FOLDER = 1; private static final int ACTIVITY_MANAGE_IDENTITIES = 2; private static final String PREFERENCE_SCREEN_MAIN = "main"; private static final String PREFERENCE_SCREEN_COMPOSING = "composing"; private static final String PREFERENCE_SCREEN_INCOMING = "incoming_prefs"; private static final String PREFERENCE_SCREEN_PUSH_ADVANCED = "push_advanced"; private static final String PREFERENCE_SCREEN_NOTIFICATIONS = "notifications"; private static final String PREFERENCE_SCREEN_SEARCH = "search"; private static final String PREFERENCE_DESCRIPTION = "account_description"; private static final String PREFERENCE_MARK_MESSAGE_AS_READ_ON_VIEW = "mark_message_as_read_on_view"; private static final String PREFERENCE_COMPOSITION = "composition"; private static final String PREFERENCE_MANAGE_IDENTITIES = "manage_identities"; private static final String PREFERENCE_FREQUENCY = "account_check_frequency"; private static final String PREFERENCE_DISPLAY_COUNT = "account_display_count"; private static final String PREFERENCE_DEFAULT = "account_default"; private static final String PREFERENCE_SHOW_PICTURES = "show_pictures_enum"; private static final String PREFERENCE_NOTIFY = "account_notify"; private static final String PREFERENCE_NOTIFY_SELF = "account_notify_self"; private static final String PREFERENCE_NOTIFY_SYNC = "account_notify_sync"; private static final String PREFERENCE_VIBRATE = "account_vibrate"; private static final String PREFERENCE_VIBRATE_PATTERN = "account_vibrate_pattern"; private static final String PREFERENCE_VIBRATE_TIMES = "account_vibrate_times"; private static final String PREFERENCE_RINGTONE = "account_ringtone"; private static final String PREFERENCE_NOTIFICATION_LED = "account_led"; private static final String PREFERENCE_INCOMING = "incoming"; private static final String PREFERENCE_OUTGOING = "outgoing"; private static final String PREFERENCE_DISPLAY_MODE = "folder_display_mode"; private static final String PREFERENCE_SYNC_MODE = "folder_sync_mode"; private static final String PREFERENCE_PUSH_MODE = "folder_push_mode"; private static final String PREFERENCE_PUSH_POLL_ON_CONNECT = "push_poll_on_connect"; private static final String PREFERENCE_MAX_PUSH_FOLDERS = "max_push_folders"; private static final String PREFERENCE_IDLE_REFRESH_PERIOD = "idle_refresh_period"; private static final String PREFERENCE_TARGET_MODE = "folder_target_mode"; private static final String PREFERENCE_DELETE_POLICY = "delete_policy"; private static final String PREFERENCE_EXPUNGE_POLICY = "expunge_policy"; private static final String PREFERENCE_AUTO_EXPAND_FOLDER = "account_setup_auto_expand_folder"; private static final String PREFERENCE_SEARCHABLE_FOLDERS = "searchable_folders"; private static final String PREFERENCE_CHIP_COLOR = "chip_color"; private static final String PREFERENCE_LED_COLOR = "led_color"; private static final String PREFERENCE_NOTIFICATION_OPENS_UNREAD = "notification_opens_unread"; private static final String PREFERENCE_NOTIFICATION_UNREAD_COUNT = "notification_unread_count"; private static final String PREFERENCE_MESSAGE_AGE = "account_message_age"; private static final String PREFERENCE_MESSAGE_SIZE = "account_autodownload_size"; private static final String PREFERENCE_MESSAGE_FORMAT = "message_format"; private static final String PREFERENCE_MESSAGE_READ_RECEIPT = "message_read_receipt"; private static final String PREFERENCE_QUOTE_PREFIX = "account_quote_prefix"; private static final String PREFERENCE_QUOTE_STYLE = "quote_style"; private static final String PREFERENCE_DEFAULT_QUOTED_TEXT_SHOWN = "default_quoted_text_shown"; private static final String PREFERENCE_REPLY_AFTER_QUOTE = "reply_after_quote"; private static final String PREFERENCE_STRIP_SIGNATURE = "strip_signature"; private static final String PREFERENCE_SYNC_REMOTE_DELETIONS = "account_sync_remote_deletetions"; private static final String PREFERENCE_CRYPTO = "crypto"; private static final String PREFERENCE_CRYPTO_APP = "crypto_app"; private static final String PREFERENCE_CRYPTO_AUTO_SIGNATURE = "crypto_auto_signature"; private static final String PREFERENCE_CRYPTO_AUTO_ENCRYPT = "crypto_auto_encrypt"; private static final String PREFERENCE_CLOUD_SEARCH_ENABLED = "remote_search_enabled"; private static final String PREFERENCE_REMOTE_SEARCH_NUM_RESULTS = "account_remote_search_num_results"; private static final String PREFERENCE_REMOTE_SEARCH_FULL_TEXT = "account_remote_search_full_text"; private static final String PREFERENCE_LOCAL_STORAGE_PROVIDER = "local_storage_provider"; private static final String PREFERENCE_CATEGORY_FOLDERS = "folders"; private static final String PREFERENCE_ARCHIVE_FOLDER = "archive_folder"; private static final String PREFERENCE_DRAFTS_FOLDER = "drafts_folder"; private static final String PREFERENCE_SENT_FOLDER = "sent_folder"; private static final String PREFERENCE_SPAM_FOLDER = "spam_folder"; private static final String PREFERENCE_TRASH_FOLDER = "trash_folder"; private static final String PREFERENCE_ALWAYS_SHOW_CC_BCC = "always_show_cc_bcc"; private Account mAccount; private boolean mIsMoveCapable = false; private boolean mIsPushCapable = false; private boolean mIsExpungeCapable = false; private boolean mIsSeenFlagSupported = false; private PreferenceScreen mMainScreen; private PreferenceScreen mComposingScreen; private EditTextPreference mAccountDescription; private CheckBoxPreference mMarkMessageAsReadOnView; private ListPreference mCheckFrequency; private ListPreference mDisplayCount; private ListPreference mMessageAge; private ListPreference mMessageSize; private CheckBoxPreference mAccountDefault; private CheckBoxPreference mAccountNotify; private CheckBoxPreference mAccountNotifySelf; private ListPreference mAccountShowPictures; private CheckBoxPreference mAccountNotifySync; private CheckBoxPreference mAccountVibrate; private CheckBoxPreference mAccountLed; private ListPreference mAccountVibratePattern; private ListPreference mAccountVibrateTimes; private RingtonePreference mAccountRingtone; private ListPreference mDisplayMode; private ListPreference mSyncMode; private ListPreference mPushMode; private ListPreference mTargetMode; private ListPreference mDeletePolicy; private ListPreference mExpungePolicy; private ListPreference mSearchableFolders; private ListPreference mAutoExpandFolder; private Preference mChipColor; private Preference mLedColor; private boolean mIncomingChanged = false; private CheckBoxPreference mNotificationOpensUnread; private CheckBoxPreference mNotificationUnreadCount; private ListPreference mMessageFormat; private CheckBoxPreference mMessageReadReceipt; private ListPreference mQuoteStyle; private EditTextPreference mAccountQuotePrefix; private CheckBoxPreference mAccountDefaultQuotedTextShown; private CheckBoxPreference mReplyAfterQuote; private CheckBoxPreference mStripSignature; private CheckBoxPreference mSyncRemoteDeletions; private CheckBoxPreference mPushPollOnConnect; private ListPreference mIdleRefreshPeriod; private ListPreference mMaxPushFolders; private boolean mHasCrypto = false; private ListPreference mCryptoApp; private CheckBoxPreference mCryptoAutoSignature; private CheckBoxPreference mCryptoAutoEncrypt; private PreferenceScreen mSearchScreen; private CheckBoxPreference mCloudSearchEnabled; private ListPreference mRemoteSearchNumResults; /* * Temporarily removed because search results aren't displayed to the user. * So this feature is useless. */ //private CheckBoxPreference mRemoteSearchFullText; private ListPreference mLocalStorageProvider; private ListPreference mArchiveFolder; private ListPreference mDraftsFolder; private ListPreference mSentFolder; private ListPreference mSpamFolder; private ListPreference mTrashFolder; private CheckBoxPreference mAlwaysShowCcBcc; public static void actionSettings(Context context, Account account) { Intent i = new Intent(context, AccountSettings.class); i.putExtra(EXTRA_ACCOUNT, account.getUuid()); context.startActivity(i); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String accountUuid = getIntent().getStringExtra(EXTRA_ACCOUNT); mAccount = Preferences.getPreferences(this).getAccount(accountUuid); try { final Store store = mAccount.getRemoteStore(); mIsMoveCapable = store.isMoveCapable(); mIsPushCapable = store.isPushCapable(); mIsExpungeCapable = store.isExpungeCapable(); mIsSeenFlagSupported = store.isSeenFlagSupported(); } catch (Exception e) { Log.e(K9.LOG_TAG, "Could not get remote store", e); } addPreferencesFromResource(R.xml.account_settings_preferences); mMainScreen = (PreferenceScreen) findPreference(PREFERENCE_SCREEN_MAIN); mAccountDescription = (EditTextPreference) findPreference(PREFERENCE_DESCRIPTION); mAccountDescription.setSummary(mAccount.getDescription()); mAccountDescription.setText(mAccount.getDescription()); mAccountDescription.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); mAccountDescription.setSummary(summary); mAccountDescription.setText(summary); return false; } }); mMarkMessageAsReadOnView = (CheckBoxPreference) findPreference(PREFERENCE_MARK_MESSAGE_AS_READ_ON_VIEW); mMarkMessageAsReadOnView.setChecked(mAccount.isMarkMessageAsReadOnView()); mMessageFormat = (ListPreference) findPreference(PREFERENCE_MESSAGE_FORMAT); mMessageFormat.setValue(mAccount.getMessageFormat().name()); mMessageFormat.setSummary(mMessageFormat.getEntry()); mMessageFormat.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mMessageFormat.findIndexOfValue(summary); mMessageFormat.setSummary(mMessageFormat.getEntries()[index]); mMessageFormat.setValue(summary); return false; } }); mAlwaysShowCcBcc = (CheckBoxPreference) findPreference(PREFERENCE_ALWAYS_SHOW_CC_BCC); mAlwaysShowCcBcc.setChecked(mAccount.isAlwaysShowCcBcc()); mMessageReadReceipt = (CheckBoxPreference) findPreference(PREFERENCE_MESSAGE_READ_RECEIPT); mMessageReadReceipt.setChecked(mAccount.isMessageReadReceiptAlways()); mAccountQuotePrefix = (EditTextPreference) findPreference(PREFERENCE_QUOTE_PREFIX); mAccountQuotePrefix.setSummary(mAccount.getQuotePrefix()); mAccountQuotePrefix.setText(mAccount.getQuotePrefix()); mAccountQuotePrefix.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { final String value = newValue.toString(); mAccountQuotePrefix.setSummary(value); mAccountQuotePrefix.setText(value); return false; } }); mAccountDefaultQuotedTextShown = (CheckBoxPreference) findPreference(PREFERENCE_DEFAULT_QUOTED_TEXT_SHOWN); mAccountDefaultQuotedTextShown.setChecked(mAccount.isDefaultQuotedTextShown()); mReplyAfterQuote = (CheckBoxPreference) findPreference(PREFERENCE_REPLY_AFTER_QUOTE); mReplyAfterQuote.setChecked(mAccount.isReplyAfterQuote()); mStripSignature = (CheckBoxPreference) findPreference(PREFERENCE_STRIP_SIGNATURE); mStripSignature.setChecked(mAccount.isStripSignature()); mComposingScreen = (PreferenceScreen) findPreference(PREFERENCE_SCREEN_COMPOSING); Preference.OnPreferenceChangeListener quoteStyleListener = new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { final QuoteStyle style = QuoteStyle.valueOf(newValue.toString()); int index = mQuoteStyle.findIndexOfValue(newValue.toString()); mQuoteStyle.setSummary(mQuoteStyle.getEntries()[index]); if (style == QuoteStyle.PREFIX) { mComposingScreen.addPreference(mAccountQuotePrefix); mComposingScreen.addPreference(mReplyAfterQuote); } else if (style == QuoteStyle.HEADER) { mComposingScreen.removePreference(mAccountQuotePrefix); mComposingScreen.removePreference(mReplyAfterQuote); } return true; } }; mQuoteStyle = (ListPreference) findPreference(PREFERENCE_QUOTE_STYLE); mQuoteStyle.setValue(mAccount.getQuoteStyle().name()); mQuoteStyle.setSummary(mQuoteStyle.getEntry()); mQuoteStyle.setOnPreferenceChangeListener(quoteStyleListener); // Call the onPreferenceChange() handler on startup to update the Preference dialogue based // upon the existing quote style setting. quoteStyleListener.onPreferenceChange(mQuoteStyle, mAccount.getQuoteStyle().name()); mCheckFrequency = (ListPreference) findPreference(PREFERENCE_FREQUENCY); mCheckFrequency.setValue(String.valueOf(mAccount.getAutomaticCheckIntervalMinutes())); mCheckFrequency.setSummary(mCheckFrequency.getEntry()); mCheckFrequency.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mCheckFrequency.findIndexOfValue(summary); mCheckFrequency.setSummary(mCheckFrequency.getEntries()[index]); mCheckFrequency.setValue(summary); return false; } }); mDisplayMode = (ListPreference) findPreference(PREFERENCE_DISPLAY_MODE); mDisplayMode.setValue(mAccount.getFolderDisplayMode().name()); mDisplayMode.setSummary(mDisplayMode.getEntry()); mDisplayMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mDisplayMode.findIndexOfValue(summary); mDisplayMode.setSummary(mDisplayMode.getEntries()[index]); mDisplayMode.setValue(summary); return false; } }); mSyncMode = (ListPreference) findPreference(PREFERENCE_SYNC_MODE); mSyncMode.setValue(mAccount.getFolderSyncMode().name()); mSyncMode.setSummary(mSyncMode.getEntry()); mSyncMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mSyncMode.findIndexOfValue(summary); mSyncMode.setSummary(mSyncMode.getEntries()[index]); mSyncMode.setValue(summary); return false; } }); mTargetMode = (ListPreference) findPreference(PREFERENCE_TARGET_MODE); mTargetMode.setValue(mAccount.getFolderTargetMode().name()); mTargetMode.setSummary(mTargetMode.getEntry()); mTargetMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mTargetMode.findIndexOfValue(summary); mTargetMode.setSummary(mTargetMode.getEntries()[index]); mTargetMode.setValue(summary); return false; } }); mDeletePolicy = (ListPreference) findPreference(PREFERENCE_DELETE_POLICY); if (!mIsSeenFlagSupported) { removeListEntry(mDeletePolicy, Integer.toString(Account.DELETE_POLICY_MARK_AS_READ)); } mDeletePolicy.setValue(Integer.toString(mAccount.getDeletePolicy())); mDeletePolicy.setSummary(mDeletePolicy.getEntry()); mDeletePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mDeletePolicy.findIndexOfValue(summary); mDeletePolicy.setSummary(mDeletePolicy.getEntries()[index]); mDeletePolicy.setValue(summary); return false; } }); mExpungePolicy = (ListPreference) findPreference(PREFERENCE_EXPUNGE_POLICY); if (mIsExpungeCapable) { mExpungePolicy.setValue(mAccount.getExpungePolicy()); mExpungePolicy.setSummary(mExpungePolicy.getEntry()); mExpungePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mExpungePolicy.findIndexOfValue(summary); mExpungePolicy.setSummary(mExpungePolicy.getEntries()[index]); mExpungePolicy.setValue(summary); return false; } }); } else { ((PreferenceScreen) findPreference(PREFERENCE_SCREEN_INCOMING)).removePreference(mExpungePolicy); } mSyncRemoteDeletions = (CheckBoxPreference) findPreference(PREFERENCE_SYNC_REMOTE_DELETIONS); mSyncRemoteDeletions.setChecked(mAccount.syncRemoteDeletions()); mSearchableFolders = (ListPreference) findPreference(PREFERENCE_SEARCHABLE_FOLDERS); mSearchableFolders.setValue(mAccount.getSearchableFolders().name()); mSearchableFolders.setSummary(mSearchableFolders.getEntry()); mSearchableFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mSearchableFolders.findIndexOfValue(summary); mSearchableFolders.setSummary(mSearchableFolders.getEntries()[index]); mSearchableFolders.setValue(summary); return false; } }); mDisplayCount = (ListPreference) findPreference(PREFERENCE_DISPLAY_COUNT); mDisplayCount.setValue(String.valueOf(mAccount.getDisplayCount())); mDisplayCount.setSummary(mDisplayCount.getEntry()); mDisplayCount.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mDisplayCount.findIndexOfValue(summary); mDisplayCount.setSummary(mDisplayCount.getEntries()[index]); mDisplayCount.setValue(summary); return false; } }); mMessageAge = (ListPreference) findPreference(PREFERENCE_MESSAGE_AGE); if (!mAccount.isSearchByDateCapable()) { ((PreferenceScreen) findPreference(PREFERENCE_SCREEN_INCOMING)).removePreference(mMessageAge); } else { mMessageAge.setValue(String.valueOf(mAccount.getMaximumPolledMessageAge())); mMessageAge.setSummary(mMessageAge.getEntry()); mMessageAge.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mMessageAge.findIndexOfValue(summary); mMessageAge.setSummary(mMessageAge.getEntries()[index]); mMessageAge.setValue(summary); return false; } }); } mMessageSize = (ListPreference) findPreference(PREFERENCE_MESSAGE_SIZE); mMessageSize.setValue(String.valueOf(mAccount.getMaximumAutoDownloadMessageSize())); mMessageSize.setSummary(mMessageSize.getEntry()); mMessageSize.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mMessageSize.findIndexOfValue(summary); mMessageSize.setSummary(mMessageSize.getEntries()[index]); mMessageSize.setValue(summary); return false; } }); mAccountDefault = (CheckBoxPreference) findPreference(PREFERENCE_DEFAULT); mAccountDefault.setChecked( mAccount.equals(Preferences.getPreferences(this).getDefaultAccount())); mAccountShowPictures = (ListPreference) findPreference(PREFERENCE_SHOW_PICTURES); mAccountShowPictures.setValue("" + mAccount.getShowPictures()); mAccountShowPictures.setSummary(mAccountShowPictures.getEntry()); mAccountShowPictures.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mAccountShowPictures.findIndexOfValue(summary); mAccountShowPictures.setSummary(mAccountShowPictures.getEntries()[index]); mAccountShowPictures.setValue(summary); return false; } }); mLocalStorageProvider = (ListPreference) findPreference(PREFERENCE_LOCAL_STORAGE_PROVIDER); { final Map<String, String> providers; providers = StorageManager.getInstance(K9.app).getAvailableProviders(); int i = 0; final String[] providerLabels = new String[providers.size()]; final String[] providerIds = new String[providers.size()]; for (final Map.Entry<String, String> entry : providers.entrySet()) { providerIds[i] = entry.getKey(); providerLabels[i] = entry.getValue(); i++; } mLocalStorageProvider.setEntryValues(providerIds); mLocalStorageProvider.setEntries(providerLabels); mLocalStorageProvider.setValue(mAccount.getLocalStorageProviderId()); mLocalStorageProvider.setSummary(providers.get(mAccount.getLocalStorageProviderId())); mLocalStorageProvider.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { mLocalStorageProvider.setSummary(providers.get(newValue)); return true; } }); } // IMAP-specific preferences mSearchScreen = (PreferenceScreen) findPreference(PREFERENCE_SCREEN_SEARCH); mCloudSearchEnabled = (CheckBoxPreference) findPreference(PREFERENCE_CLOUD_SEARCH_ENABLED); mRemoteSearchNumResults = (ListPreference) findPreference(PREFERENCE_REMOTE_SEARCH_NUM_RESULTS); mRemoteSearchNumResults.setOnPreferenceChangeListener( new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference pref, Object newVal) { updateRemoteSearchLimit((String)newVal); return true; } } ); - updateRemoteSearchLimit(mRemoteSearchNumResults.getValue()); //mRemoteSearchFullText = (CheckBoxPreference) findPreference(PREFERENCE_REMOTE_SEARCH_FULL_TEXT); mPushPollOnConnect = (CheckBoxPreference) findPreference(PREFERENCE_PUSH_POLL_ON_CONNECT); mIdleRefreshPeriod = (ListPreference) findPreference(PREFERENCE_IDLE_REFRESH_PERIOD); mMaxPushFolders = (ListPreference) findPreference(PREFERENCE_MAX_PUSH_FOLDERS); if (mIsPushCapable) { mPushPollOnConnect.setChecked(mAccount.isPushPollOnConnect()); mCloudSearchEnabled.setChecked(mAccount.allowRemoteSearch()); - mRemoteSearchNumResults.setValue(Integer.toString(mAccount.getRemoteSearchNumResults())); + String searchNumResults = Integer.toString(mAccount.getRemoteSearchNumResults()); + mRemoteSearchNumResults.setValue(searchNumResults); + updateRemoteSearchLimit(searchNumResults); //mRemoteSearchFullText.setChecked(mAccount.isRemoteSearchFullText()); mIdleRefreshPeriod.setValue(String.valueOf(mAccount.getIdleRefreshMinutes())); mIdleRefreshPeriod.setSummary(mIdleRefreshPeriod.getEntry()); mIdleRefreshPeriod.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mIdleRefreshPeriod.findIndexOfValue(summary); mIdleRefreshPeriod.setSummary(mIdleRefreshPeriod.getEntries()[index]); mIdleRefreshPeriod.setValue(summary); return false; } }); mMaxPushFolders.setValue(String.valueOf(mAccount.getMaxPushFolders())); mMaxPushFolders.setSummary(mMaxPushFolders.getEntry()); mMaxPushFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mMaxPushFolders.findIndexOfValue(summary); mMaxPushFolders.setSummary(mMaxPushFolders.getEntries()[index]); mMaxPushFolders.setValue(summary); return false; } }); mPushMode = (ListPreference) findPreference(PREFERENCE_PUSH_MODE); mPushMode.setValue(mAccount.getFolderPushMode().name()); mPushMode.setSummary(mPushMode.getEntry()); mPushMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mPushMode.findIndexOfValue(summary); mPushMode.setSummary(mPushMode.getEntries()[index]); mPushMode.setValue(summary); return false; } }); } else { PreferenceScreen incomingPrefs = (PreferenceScreen) findPreference(PREFERENCE_SCREEN_INCOMING); incomingPrefs.removePreference((PreferenceScreen) findPreference(PREFERENCE_SCREEN_PUSH_ADVANCED)); incomingPrefs.removePreference((ListPreference) findPreference(PREFERENCE_PUSH_MODE)); mMainScreen.removePreference(mSearchScreen); } mAccountNotify = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY); mAccountNotify.setChecked(mAccount.isNotifyNewMail()); mAccountNotifySelf = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY_SELF); mAccountNotifySelf.setChecked(mAccount.isNotifySelfNewMail()); mAccountNotifySync = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY_SYNC); mAccountNotifySync.setChecked(mAccount.isShowOngoing()); mAccountRingtone = (RingtonePreference) findPreference(PREFERENCE_RINGTONE); // XXX: The following two lines act as a workaround for the RingtonePreference // which does not let us set/get the value programmatically SharedPreferences prefs = mAccountRingtone.getPreferenceManager().getSharedPreferences(); String currentRingtone = (!mAccount.getNotificationSetting().shouldRing() ? null : mAccount.getNotificationSetting().getRingtone()); prefs.edit().putString(PREFERENCE_RINGTONE, currentRingtone).commit(); mAccountVibrate = (CheckBoxPreference) findPreference(PREFERENCE_VIBRATE); mAccountVibrate.setChecked(mAccount.getNotificationSetting().shouldVibrate()); mAccountVibratePattern = (ListPreference) findPreference(PREFERENCE_VIBRATE_PATTERN); mAccountVibratePattern.setValue(String.valueOf(mAccount.getNotificationSetting().getVibratePattern())); mAccountVibratePattern.setSummary(mAccountVibratePattern.getEntry()); mAccountVibratePattern.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mAccountVibratePattern.findIndexOfValue(summary); mAccountVibratePattern.setSummary(mAccountVibratePattern.getEntries()[index]); mAccountVibratePattern.setValue(summary); doVibrateTest(preference); return false; } }); mAccountVibrateTimes = (ListPreference) findPreference(PREFERENCE_VIBRATE_TIMES); mAccountVibrateTimes.setValue(String.valueOf(mAccount.getNotificationSetting().getVibrateTimes())); mAccountVibrateTimes.setSummary(String.valueOf(mAccount.getNotificationSetting().getVibrateTimes())); mAccountVibrateTimes.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { final String value = newValue.toString(); mAccountVibrateTimes.setSummary(value); mAccountVibrateTimes.setValue(value); doVibrateTest(preference); return false; } }); mAccountLed = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFICATION_LED); mAccountLed.setChecked(mAccount.getNotificationSetting().isLed()); mNotificationOpensUnread = (CheckBoxPreference)findPreference(PREFERENCE_NOTIFICATION_OPENS_UNREAD); mNotificationOpensUnread.setChecked(mAccount.goToUnreadMessageSearch()); CheckBoxPreference notificationUnreadCount = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFICATION_UNREAD_COUNT); /* * Honeycomb and newer don't show the notification number as overlay on the notification * icon in the status bar, so we hide the setting. * * See http://code.google.com/p/android/issues/detail?id=21477 */ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { PreferenceScreen notificationsPrefs = (PreferenceScreen) findPreference(PREFERENCE_SCREEN_NOTIFICATIONS); notificationsPrefs.removePreference(notificationUnreadCount); } else { notificationUnreadCount.setChecked(mAccount.isNotificationShowsUnreadCount()); mNotificationUnreadCount = notificationUnreadCount; } new PopulateFolderPrefsTask().execute(); mChipColor = findPreference(PREFERENCE_CHIP_COLOR); mChipColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { onChooseChipColor(); return false; } }); mLedColor = findPreference(PREFERENCE_LED_COLOR); mLedColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { onChooseLedColor(); return false; } }); findPreference(PREFERENCE_COMPOSITION).setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { onCompositionSettings(); return true; } }); findPreference(PREFERENCE_MANAGE_IDENTITIES).setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { onManageIdentities(); return true; } }); findPreference(PREFERENCE_INCOMING).setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { mIncomingChanged = true; onIncomingSettings(); return true; } }); findPreference(PREFERENCE_OUTGOING).setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { onOutgoingSettings(); return true; } }); mHasCrypto = new Apg().isAvailable(this); if (mHasCrypto) { mCryptoApp = (ListPreference) findPreference(PREFERENCE_CRYPTO_APP); mCryptoApp.setValue(String.valueOf(mAccount.getCryptoApp())); mCryptoApp.setSummary(mCryptoApp.getEntry()); mCryptoApp.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { String value = newValue.toString(); int index = mCryptoApp.findIndexOfValue(value); mCryptoApp.setSummary(mCryptoApp.getEntries()[index]); mCryptoApp.setValue(value); handleCryptoAppDependencies(); if (Apg.NAME.equals(value)) { Apg.createInstance(null).test(AccountSettings.this); } return false; } }); mCryptoAutoSignature = (CheckBoxPreference) findPreference(PREFERENCE_CRYPTO_AUTO_SIGNATURE); mCryptoAutoSignature.setChecked(mAccount.getCryptoAutoSignature()); mCryptoAutoEncrypt = (CheckBoxPreference) findPreference(PREFERENCE_CRYPTO_AUTO_ENCRYPT); mCryptoAutoEncrypt.setChecked(mAccount.isCryptoAutoEncrypt()); handleCryptoAppDependencies(); } else { final Preference mCryptoMenu = findPreference(PREFERENCE_CRYPTO); mCryptoMenu.setEnabled(false); mCryptoMenu.setSummary(R.string.account_settings_crypto_apg_not_installed); } } private void removeListEntry(ListPreference listPreference, String remove) { CharSequence[] entryValues = listPreference.getEntryValues(); CharSequence[] entries = listPreference.getEntries(); CharSequence[] newEntryValues = new String[entryValues.length - 1]; CharSequence[] newEntries = new String[entryValues.length - 1]; for (int i = 0, out = 0; i < entryValues.length; i++) { CharSequence value = entryValues[i]; if (!value.equals(remove)) { newEntryValues[out] = value; newEntries[out] = entries[i]; out++; } } listPreference.setEntryValues(newEntryValues); listPreference.setEntries(newEntries); } private void handleCryptoAppDependencies() { if ("".equals(mCryptoApp.getValue())) { mCryptoAutoSignature.setEnabled(false); mCryptoAutoEncrypt.setEnabled(false); } else { mCryptoAutoSignature.setEnabled(true); mCryptoAutoEncrypt.setEnabled(true); } } private void saveSettings() { if (mAccountDefault.isChecked()) { Preferences.getPreferences(this).setDefaultAccount(mAccount); } mAccount.setDescription(mAccountDescription.getText()); mAccount.setMarkMessageAsReadOnView(mMarkMessageAsReadOnView.isChecked()); mAccount.setNotifyNewMail(mAccountNotify.isChecked()); mAccount.setNotifySelfNewMail(mAccountNotifySelf.isChecked()); mAccount.setShowOngoing(mAccountNotifySync.isChecked()); mAccount.setDisplayCount(Integer.parseInt(mDisplayCount.getValue())); mAccount.setMaximumAutoDownloadMessageSize(Integer.parseInt(mMessageSize.getValue())); if (mAccount.isSearchByDateCapable()) { mAccount.setMaximumPolledMessageAge(Integer.parseInt(mMessageAge.getValue())); } mAccount.getNotificationSetting().setVibrate(mAccountVibrate.isChecked()); mAccount.getNotificationSetting().setVibratePattern(Integer.parseInt(mAccountVibratePattern.getValue())); mAccount.getNotificationSetting().setVibrateTimes(Integer.parseInt(mAccountVibrateTimes.getValue())); mAccount.getNotificationSetting().setLed(mAccountLed.isChecked()); mAccount.setGoToUnreadMessageSearch(mNotificationOpensUnread.isChecked()); if (mNotificationUnreadCount != null) { mAccount.setNotificationShowsUnreadCount(mNotificationUnreadCount.isChecked()); } mAccount.setFolderTargetMode(Account.FolderMode.valueOf(mTargetMode.getValue())); mAccount.setDeletePolicy(Integer.parseInt(mDeletePolicy.getValue())); if (mIsExpungeCapable) { mAccount.setExpungePolicy(mExpungePolicy.getValue()); } mAccount.setSyncRemoteDeletions(mSyncRemoteDeletions.isChecked()); mAccount.setSearchableFolders(Account.Searchable.valueOf(mSearchableFolders.getValue())); mAccount.setMessageFormat(Account.MessageFormat.valueOf(mMessageFormat.getValue())); mAccount.setAlwaysShowCcBcc(mAlwaysShowCcBcc.isChecked()); mAccount.setMessageReadReceipt(mMessageReadReceipt.isChecked()); mAccount.setQuoteStyle(QuoteStyle.valueOf(mQuoteStyle.getValue())); mAccount.setQuotePrefix(mAccountQuotePrefix.getText()); mAccount.setDefaultQuotedTextShown(mAccountDefaultQuotedTextShown.isChecked()); mAccount.setReplyAfterQuote(mReplyAfterQuote.isChecked()); mAccount.setStripSignature(mStripSignature.isChecked()); mAccount.setLocalStorageProviderId(mLocalStorageProvider.getValue()); if (mHasCrypto) { mAccount.setCryptoApp(mCryptoApp.getValue()); mAccount.setCryptoAutoSignature(mCryptoAutoSignature.isChecked()); mAccount.setCryptoAutoEncrypt(mCryptoAutoEncrypt.isChecked()); } // In webdav account we use the exact folder name also for inbox, // since it varies because of internationalization if (mAccount.getStoreUri().startsWith("webdav")) mAccount.setAutoExpandFolderName(mAutoExpandFolder.getValue()); else mAccount.setAutoExpandFolderName(reverseTranslateFolder(mAutoExpandFolder.getValue())); if (mIsMoveCapable) { mAccount.setArchiveFolderName(mArchiveFolder.getValue()); mAccount.setDraftsFolderName(mDraftsFolder.getValue()); mAccount.setSentFolderName(mSentFolder.getValue()); mAccount.setSpamFolderName(mSpamFolder.getValue()); mAccount.setTrashFolderName(mTrashFolder.getValue()); } //IMAP stuff if (mIsPushCapable) { mAccount.setPushPollOnConnect(mPushPollOnConnect.isChecked()); mAccount.setIdleRefreshMinutes(Integer.parseInt(mIdleRefreshPeriod.getValue())); mAccount.setMaxPushFolders(Integer.parseInt(mMaxPushFolders.getValue())); mAccount.setAllowRemoteSearch(mCloudSearchEnabled.isChecked()); mAccount.setRemoteSearchNumResults(Integer.parseInt(mRemoteSearchNumResults.getValue())); //mAccount.setRemoteSearchFullText(mRemoteSearchFullText.isChecked()); } boolean needsRefresh = mAccount.setAutomaticCheckIntervalMinutes(Integer.parseInt(mCheckFrequency.getValue())); needsRefresh |= mAccount.setFolderSyncMode(Account.FolderMode.valueOf(mSyncMode.getValue())); boolean displayModeChanged = mAccount.setFolderDisplayMode(Account.FolderMode.valueOf(mDisplayMode.getValue())); SharedPreferences prefs = mAccountRingtone.getPreferenceManager().getSharedPreferences(); String newRingtone = prefs.getString(PREFERENCE_RINGTONE, null); if (newRingtone != null) { mAccount.getNotificationSetting().setRing(true); mAccount.getNotificationSetting().setRingtone(newRingtone); } else { if (mAccount.getNotificationSetting().shouldRing()) { mAccount.getNotificationSetting().setRingtone(null); } } mAccount.setShowPictures(Account.ShowPictures.valueOf(mAccountShowPictures.getValue())); //IMAP specific stuff if (mIsPushCapable) { boolean needsPushRestart = mAccount.setFolderPushMode(Account.FolderMode.valueOf(mPushMode.getValue())); if (mAccount.getFolderPushMode() != FolderMode.NONE) { needsPushRestart |= displayModeChanged; needsPushRestart |= mIncomingChanged; } if (needsRefresh && needsPushRestart) { MailService.actionReset(this, null); } else if (needsRefresh) { MailService.actionReschedulePoll(this, null); } else if (needsPushRestart) { MailService.actionRestartPushers(this, null); } } // TODO: refresh folder list here mAccount.save(Preferences.getPreferences(this)); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { switch (requestCode) { case SELECT_AUTO_EXPAND_FOLDER: mAutoExpandFolder.setSummary(translateFolder(data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER))); break; } } super.onActivityResult(requestCode, resultCode, data); } @Override protected void onPause() { saveSettings(); super.onPause(); } private void onCompositionSettings() { AccountSetupComposition.actionEditCompositionSettings(this, mAccount); } private void onManageIdentities() { Intent intent = new Intent(this, ManageIdentities.class); intent.putExtra(ChooseIdentity.EXTRA_ACCOUNT, mAccount.getUuid()); startActivityForResult(intent, ACTIVITY_MANAGE_IDENTITIES); } private void onIncomingSettings() { AccountSetupIncoming.actionEditIncomingSettings(this, mAccount); } private void onOutgoingSettings() { AccountSetupOutgoing.actionEditOutgoingSettings(this, mAccount); } public void onChooseChipColor() { showDialog(DIALOG_COLOR_PICKER_ACCOUNT); } public void onChooseLedColor() { showDialog(DIALOG_COLOR_PICKER_LED); } @Override public Dialog onCreateDialog(int id) { Dialog dialog = null; switch (id) { case DIALOG_COLOR_PICKER_ACCOUNT: { dialog = new ColorPickerDialog(this, new ColorPickerDialog.OnColorChangedListener() { public void colorChanged(int color) { mAccount.setChipColor(color); } }, mAccount.getChipColor()); break; } case DIALOG_COLOR_PICKER_LED: { dialog = new ColorPickerDialog(this, new ColorPickerDialog.OnColorChangedListener() { public void colorChanged(int color) { mAccount.getNotificationSetting().setLedColor(color); } }, mAccount.getNotificationSetting().getLedColor()); break; } } return dialog; } @Override public void onPrepareDialog(int id, Dialog dialog) { switch (id) { case DIALOG_COLOR_PICKER_ACCOUNT: { ColorPickerDialog colorPicker = (ColorPickerDialog) dialog; colorPicker.setColor(mAccount.getChipColor()); break; } case DIALOG_COLOR_PICKER_LED: { ColorPickerDialog colorPicker = (ColorPickerDialog) dialog; colorPicker.setColor(mAccount.getNotificationSetting().getLedColor()); break; } } } public void onChooseAutoExpandFolder() { Intent selectIntent = new Intent(this, ChooseFolder.class); selectIntent.putExtra(ChooseFolder.EXTRA_ACCOUNT, mAccount.getUuid()); selectIntent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, mAutoExpandFolder.getSummary()); selectIntent.putExtra(ChooseFolder.EXTRA_SHOW_CURRENT, "yes"); selectIntent.putExtra(ChooseFolder.EXTRA_SHOW_FOLDER_NONE, "yes"); selectIntent.putExtra(ChooseFolder.EXTRA_SHOW_DISPLAYABLE_ONLY, "yes"); startActivityForResult(selectIntent, SELECT_AUTO_EXPAND_FOLDER); } private String translateFolder(String in) { if (mAccount.getInboxFolderName().equalsIgnoreCase(in)) { return getString(R.string.special_mailbox_name_inbox); } else { return in; } } private String reverseTranslateFolder(String in) { if (getString(R.string.special_mailbox_name_inbox).equals(in)) { return mAccount.getInboxFolderName(); } else { return in; } } private void doVibrateTest(Preference preference) { // Do the vibration to show the user what it's like. Vibrator vibrate = (Vibrator)preference.getContext().getSystemService(Context.VIBRATOR_SERVICE); vibrate.vibrate(NotificationSetting.getVibration( Integer.parseInt(mAccountVibratePattern.getValue()), Integer.parseInt(mAccountVibrateTimes.getValue())), -1); } /** * Remote search result limit summary contains the current limit. On load or change, update this value. * @param maxResults Search limit to update the summary with. */ private void updateRemoteSearchLimit(String maxResults) { if (maxResults != null) { if (maxResults.equals("0")) { maxResults = getString(R.string.account_settings_remote_search_num_results_entries_all); } mRemoteSearchNumResults.setSummary(String.format(getString(R.string.account_settings_remote_search_num_summary), maxResults)); } } private class PopulateFolderPrefsTask extends AsyncTask<Void, Void, Void> { List <? extends Folder > folders = new LinkedList<LocalFolder>(); String[] allFolderValues; String[] allFolderLabels; @Override protected Void doInBackground(Void... params) { try { folders = mAccount.getLocalStore().getPersonalNamespaces(false); } catch (Exception e) { /// this can't be checked in } // TODO: In the future the call above should be changed to only return remote folders. // For now we just remove the Outbox folder if present. Iterator <? extends Folder > iter = folders.iterator(); while (iter.hasNext()) { Folder folder = iter.next(); if (mAccount.getOutboxFolderName().equals(folder.getName())) { iter.remove(); } } allFolderValues = new String[folders.size() + 1]; allFolderLabels = new String[folders.size() + 1]; allFolderValues[0] = K9.FOLDER_NONE; allFolderLabels[0] = K9.FOLDER_NONE; int i = 1; for (Folder folder : folders) { allFolderLabels[i] = folder.getName(); allFolderValues[i] = folder.getName(); i++; } return null; } @Override protected void onPreExecute() { mAutoExpandFolder = (ListPreference)findPreference(PREFERENCE_AUTO_EXPAND_FOLDER); mAutoExpandFolder.setEnabled(false); mArchiveFolder = (ListPreference)findPreference(PREFERENCE_ARCHIVE_FOLDER); mArchiveFolder.setEnabled(false); mDraftsFolder = (ListPreference)findPreference(PREFERENCE_DRAFTS_FOLDER); mDraftsFolder.setEnabled(false); mSentFolder = (ListPreference)findPreference(PREFERENCE_SENT_FOLDER); mSentFolder.setEnabled(false); mSpamFolder = (ListPreference)findPreference(PREFERENCE_SPAM_FOLDER); mSpamFolder.setEnabled(false); mTrashFolder = (ListPreference)findPreference(PREFERENCE_TRASH_FOLDER); mTrashFolder.setEnabled(false); if (!mIsMoveCapable) { PreferenceScreen foldersCategory = (PreferenceScreen) findPreference(PREFERENCE_CATEGORY_FOLDERS); foldersCategory.removePreference(mArchiveFolder); foldersCategory.removePreference(mSpamFolder); foldersCategory.removePreference(mDraftsFolder); foldersCategory.removePreference(mSentFolder); foldersCategory.removePreference(mTrashFolder); } } @Override protected void onPostExecute(Void res) { initListPreference(mAutoExpandFolder, mAccount.getAutoExpandFolderName(), allFolderLabels, allFolderValues); mAutoExpandFolder.setEnabled(true); if (mIsMoveCapable) { initListPreference(mArchiveFolder, mAccount.getArchiveFolderName(), allFolderLabels, allFolderValues); initListPreference(mDraftsFolder, mAccount.getDraftsFolderName(), allFolderLabels, allFolderValues); initListPreference(mSentFolder, mAccount.getSentFolderName(), allFolderLabels, allFolderValues); initListPreference(mSpamFolder, mAccount.getSpamFolderName(), allFolderLabels, allFolderValues); initListPreference(mTrashFolder, mAccount.getTrashFolderName(), allFolderLabels, allFolderValues); mArchiveFolder.setEnabled(true); mSpamFolder.setEnabled(true); mDraftsFolder.setEnabled(true); mSentFolder.setEnabled(true); mTrashFolder.setEnabled(true); } } } }
false
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String accountUuid = getIntent().getStringExtra(EXTRA_ACCOUNT); mAccount = Preferences.getPreferences(this).getAccount(accountUuid); try { final Store store = mAccount.getRemoteStore(); mIsMoveCapable = store.isMoveCapable(); mIsPushCapable = store.isPushCapable(); mIsExpungeCapable = store.isExpungeCapable(); mIsSeenFlagSupported = store.isSeenFlagSupported(); } catch (Exception e) { Log.e(K9.LOG_TAG, "Could not get remote store", e); } addPreferencesFromResource(R.xml.account_settings_preferences); mMainScreen = (PreferenceScreen) findPreference(PREFERENCE_SCREEN_MAIN); mAccountDescription = (EditTextPreference) findPreference(PREFERENCE_DESCRIPTION); mAccountDescription.setSummary(mAccount.getDescription()); mAccountDescription.setText(mAccount.getDescription()); mAccountDescription.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); mAccountDescription.setSummary(summary); mAccountDescription.setText(summary); return false; } }); mMarkMessageAsReadOnView = (CheckBoxPreference) findPreference(PREFERENCE_MARK_MESSAGE_AS_READ_ON_VIEW); mMarkMessageAsReadOnView.setChecked(mAccount.isMarkMessageAsReadOnView()); mMessageFormat = (ListPreference) findPreference(PREFERENCE_MESSAGE_FORMAT); mMessageFormat.setValue(mAccount.getMessageFormat().name()); mMessageFormat.setSummary(mMessageFormat.getEntry()); mMessageFormat.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mMessageFormat.findIndexOfValue(summary); mMessageFormat.setSummary(mMessageFormat.getEntries()[index]); mMessageFormat.setValue(summary); return false; } }); mAlwaysShowCcBcc = (CheckBoxPreference) findPreference(PREFERENCE_ALWAYS_SHOW_CC_BCC); mAlwaysShowCcBcc.setChecked(mAccount.isAlwaysShowCcBcc()); mMessageReadReceipt = (CheckBoxPreference) findPreference(PREFERENCE_MESSAGE_READ_RECEIPT); mMessageReadReceipt.setChecked(mAccount.isMessageReadReceiptAlways()); mAccountQuotePrefix = (EditTextPreference) findPreference(PREFERENCE_QUOTE_PREFIX); mAccountQuotePrefix.setSummary(mAccount.getQuotePrefix()); mAccountQuotePrefix.setText(mAccount.getQuotePrefix()); mAccountQuotePrefix.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { final String value = newValue.toString(); mAccountQuotePrefix.setSummary(value); mAccountQuotePrefix.setText(value); return false; } }); mAccountDefaultQuotedTextShown = (CheckBoxPreference) findPreference(PREFERENCE_DEFAULT_QUOTED_TEXT_SHOWN); mAccountDefaultQuotedTextShown.setChecked(mAccount.isDefaultQuotedTextShown()); mReplyAfterQuote = (CheckBoxPreference) findPreference(PREFERENCE_REPLY_AFTER_QUOTE); mReplyAfterQuote.setChecked(mAccount.isReplyAfterQuote()); mStripSignature = (CheckBoxPreference) findPreference(PREFERENCE_STRIP_SIGNATURE); mStripSignature.setChecked(mAccount.isStripSignature()); mComposingScreen = (PreferenceScreen) findPreference(PREFERENCE_SCREEN_COMPOSING); Preference.OnPreferenceChangeListener quoteStyleListener = new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { final QuoteStyle style = QuoteStyle.valueOf(newValue.toString()); int index = mQuoteStyle.findIndexOfValue(newValue.toString()); mQuoteStyle.setSummary(mQuoteStyle.getEntries()[index]); if (style == QuoteStyle.PREFIX) { mComposingScreen.addPreference(mAccountQuotePrefix); mComposingScreen.addPreference(mReplyAfterQuote); } else if (style == QuoteStyle.HEADER) { mComposingScreen.removePreference(mAccountQuotePrefix); mComposingScreen.removePreference(mReplyAfterQuote); } return true; } }; mQuoteStyle = (ListPreference) findPreference(PREFERENCE_QUOTE_STYLE); mQuoteStyle.setValue(mAccount.getQuoteStyle().name()); mQuoteStyle.setSummary(mQuoteStyle.getEntry()); mQuoteStyle.setOnPreferenceChangeListener(quoteStyleListener); // Call the onPreferenceChange() handler on startup to update the Preference dialogue based // upon the existing quote style setting. quoteStyleListener.onPreferenceChange(mQuoteStyle, mAccount.getQuoteStyle().name()); mCheckFrequency = (ListPreference) findPreference(PREFERENCE_FREQUENCY); mCheckFrequency.setValue(String.valueOf(mAccount.getAutomaticCheckIntervalMinutes())); mCheckFrequency.setSummary(mCheckFrequency.getEntry()); mCheckFrequency.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mCheckFrequency.findIndexOfValue(summary); mCheckFrequency.setSummary(mCheckFrequency.getEntries()[index]); mCheckFrequency.setValue(summary); return false; } }); mDisplayMode = (ListPreference) findPreference(PREFERENCE_DISPLAY_MODE); mDisplayMode.setValue(mAccount.getFolderDisplayMode().name()); mDisplayMode.setSummary(mDisplayMode.getEntry()); mDisplayMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mDisplayMode.findIndexOfValue(summary); mDisplayMode.setSummary(mDisplayMode.getEntries()[index]); mDisplayMode.setValue(summary); return false; } }); mSyncMode = (ListPreference) findPreference(PREFERENCE_SYNC_MODE); mSyncMode.setValue(mAccount.getFolderSyncMode().name()); mSyncMode.setSummary(mSyncMode.getEntry()); mSyncMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mSyncMode.findIndexOfValue(summary); mSyncMode.setSummary(mSyncMode.getEntries()[index]); mSyncMode.setValue(summary); return false; } }); mTargetMode = (ListPreference) findPreference(PREFERENCE_TARGET_MODE); mTargetMode.setValue(mAccount.getFolderTargetMode().name()); mTargetMode.setSummary(mTargetMode.getEntry()); mTargetMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mTargetMode.findIndexOfValue(summary); mTargetMode.setSummary(mTargetMode.getEntries()[index]); mTargetMode.setValue(summary); return false; } }); mDeletePolicy = (ListPreference) findPreference(PREFERENCE_DELETE_POLICY); if (!mIsSeenFlagSupported) { removeListEntry(mDeletePolicy, Integer.toString(Account.DELETE_POLICY_MARK_AS_READ)); } mDeletePolicy.setValue(Integer.toString(mAccount.getDeletePolicy())); mDeletePolicy.setSummary(mDeletePolicy.getEntry()); mDeletePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mDeletePolicy.findIndexOfValue(summary); mDeletePolicy.setSummary(mDeletePolicy.getEntries()[index]); mDeletePolicy.setValue(summary); return false; } }); mExpungePolicy = (ListPreference) findPreference(PREFERENCE_EXPUNGE_POLICY); if (mIsExpungeCapable) { mExpungePolicy.setValue(mAccount.getExpungePolicy()); mExpungePolicy.setSummary(mExpungePolicy.getEntry()); mExpungePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mExpungePolicy.findIndexOfValue(summary); mExpungePolicy.setSummary(mExpungePolicy.getEntries()[index]); mExpungePolicy.setValue(summary); return false; } }); } else { ((PreferenceScreen) findPreference(PREFERENCE_SCREEN_INCOMING)).removePreference(mExpungePolicy); } mSyncRemoteDeletions = (CheckBoxPreference) findPreference(PREFERENCE_SYNC_REMOTE_DELETIONS); mSyncRemoteDeletions.setChecked(mAccount.syncRemoteDeletions()); mSearchableFolders = (ListPreference) findPreference(PREFERENCE_SEARCHABLE_FOLDERS); mSearchableFolders.setValue(mAccount.getSearchableFolders().name()); mSearchableFolders.setSummary(mSearchableFolders.getEntry()); mSearchableFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mSearchableFolders.findIndexOfValue(summary); mSearchableFolders.setSummary(mSearchableFolders.getEntries()[index]); mSearchableFolders.setValue(summary); return false; } }); mDisplayCount = (ListPreference) findPreference(PREFERENCE_DISPLAY_COUNT); mDisplayCount.setValue(String.valueOf(mAccount.getDisplayCount())); mDisplayCount.setSummary(mDisplayCount.getEntry()); mDisplayCount.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mDisplayCount.findIndexOfValue(summary); mDisplayCount.setSummary(mDisplayCount.getEntries()[index]); mDisplayCount.setValue(summary); return false; } }); mMessageAge = (ListPreference) findPreference(PREFERENCE_MESSAGE_AGE); if (!mAccount.isSearchByDateCapable()) { ((PreferenceScreen) findPreference(PREFERENCE_SCREEN_INCOMING)).removePreference(mMessageAge); } else { mMessageAge.setValue(String.valueOf(mAccount.getMaximumPolledMessageAge())); mMessageAge.setSummary(mMessageAge.getEntry()); mMessageAge.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mMessageAge.findIndexOfValue(summary); mMessageAge.setSummary(mMessageAge.getEntries()[index]); mMessageAge.setValue(summary); return false; } }); } mMessageSize = (ListPreference) findPreference(PREFERENCE_MESSAGE_SIZE); mMessageSize.setValue(String.valueOf(mAccount.getMaximumAutoDownloadMessageSize())); mMessageSize.setSummary(mMessageSize.getEntry()); mMessageSize.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mMessageSize.findIndexOfValue(summary); mMessageSize.setSummary(mMessageSize.getEntries()[index]); mMessageSize.setValue(summary); return false; } }); mAccountDefault = (CheckBoxPreference) findPreference(PREFERENCE_DEFAULT); mAccountDefault.setChecked( mAccount.equals(Preferences.getPreferences(this).getDefaultAccount())); mAccountShowPictures = (ListPreference) findPreference(PREFERENCE_SHOW_PICTURES); mAccountShowPictures.setValue("" + mAccount.getShowPictures()); mAccountShowPictures.setSummary(mAccountShowPictures.getEntry()); mAccountShowPictures.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mAccountShowPictures.findIndexOfValue(summary); mAccountShowPictures.setSummary(mAccountShowPictures.getEntries()[index]); mAccountShowPictures.setValue(summary); return false; } }); mLocalStorageProvider = (ListPreference) findPreference(PREFERENCE_LOCAL_STORAGE_PROVIDER); { final Map<String, String> providers; providers = StorageManager.getInstance(K9.app).getAvailableProviders(); int i = 0; final String[] providerLabels = new String[providers.size()]; final String[] providerIds = new String[providers.size()]; for (final Map.Entry<String, String> entry : providers.entrySet()) { providerIds[i] = entry.getKey(); providerLabels[i] = entry.getValue(); i++; } mLocalStorageProvider.setEntryValues(providerIds); mLocalStorageProvider.setEntries(providerLabels); mLocalStorageProvider.setValue(mAccount.getLocalStorageProviderId()); mLocalStorageProvider.setSummary(providers.get(mAccount.getLocalStorageProviderId())); mLocalStorageProvider.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { mLocalStorageProvider.setSummary(providers.get(newValue)); return true; } }); } // IMAP-specific preferences mSearchScreen = (PreferenceScreen) findPreference(PREFERENCE_SCREEN_SEARCH); mCloudSearchEnabled = (CheckBoxPreference) findPreference(PREFERENCE_CLOUD_SEARCH_ENABLED); mRemoteSearchNumResults = (ListPreference) findPreference(PREFERENCE_REMOTE_SEARCH_NUM_RESULTS); mRemoteSearchNumResults.setOnPreferenceChangeListener( new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference pref, Object newVal) { updateRemoteSearchLimit((String)newVal); return true; } } ); updateRemoteSearchLimit(mRemoteSearchNumResults.getValue()); //mRemoteSearchFullText = (CheckBoxPreference) findPreference(PREFERENCE_REMOTE_SEARCH_FULL_TEXT); mPushPollOnConnect = (CheckBoxPreference) findPreference(PREFERENCE_PUSH_POLL_ON_CONNECT); mIdleRefreshPeriod = (ListPreference) findPreference(PREFERENCE_IDLE_REFRESH_PERIOD); mMaxPushFolders = (ListPreference) findPreference(PREFERENCE_MAX_PUSH_FOLDERS); if (mIsPushCapable) { mPushPollOnConnect.setChecked(mAccount.isPushPollOnConnect()); mCloudSearchEnabled.setChecked(mAccount.allowRemoteSearch()); mRemoteSearchNumResults.setValue(Integer.toString(mAccount.getRemoteSearchNumResults())); //mRemoteSearchFullText.setChecked(mAccount.isRemoteSearchFullText()); mIdleRefreshPeriod.setValue(String.valueOf(mAccount.getIdleRefreshMinutes())); mIdleRefreshPeriod.setSummary(mIdleRefreshPeriod.getEntry()); mIdleRefreshPeriod.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mIdleRefreshPeriod.findIndexOfValue(summary); mIdleRefreshPeriod.setSummary(mIdleRefreshPeriod.getEntries()[index]); mIdleRefreshPeriod.setValue(summary); return false; } }); mMaxPushFolders.setValue(String.valueOf(mAccount.getMaxPushFolders())); mMaxPushFolders.setSummary(mMaxPushFolders.getEntry()); mMaxPushFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mMaxPushFolders.findIndexOfValue(summary); mMaxPushFolders.setSummary(mMaxPushFolders.getEntries()[index]); mMaxPushFolders.setValue(summary); return false; } }); mPushMode = (ListPreference) findPreference(PREFERENCE_PUSH_MODE); mPushMode.setValue(mAccount.getFolderPushMode().name()); mPushMode.setSummary(mPushMode.getEntry()); mPushMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mPushMode.findIndexOfValue(summary); mPushMode.setSummary(mPushMode.getEntries()[index]); mPushMode.setValue(summary); return false; } }); } else { PreferenceScreen incomingPrefs = (PreferenceScreen) findPreference(PREFERENCE_SCREEN_INCOMING); incomingPrefs.removePreference((PreferenceScreen) findPreference(PREFERENCE_SCREEN_PUSH_ADVANCED)); incomingPrefs.removePreference((ListPreference) findPreference(PREFERENCE_PUSH_MODE)); mMainScreen.removePreference(mSearchScreen); } mAccountNotify = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY); mAccountNotify.setChecked(mAccount.isNotifyNewMail()); mAccountNotifySelf = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY_SELF); mAccountNotifySelf.setChecked(mAccount.isNotifySelfNewMail()); mAccountNotifySync = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY_SYNC); mAccountNotifySync.setChecked(mAccount.isShowOngoing()); mAccountRingtone = (RingtonePreference) findPreference(PREFERENCE_RINGTONE); // XXX: The following two lines act as a workaround for the RingtonePreference // which does not let us set/get the value programmatically SharedPreferences prefs = mAccountRingtone.getPreferenceManager().getSharedPreferences(); String currentRingtone = (!mAccount.getNotificationSetting().shouldRing() ? null : mAccount.getNotificationSetting().getRingtone()); prefs.edit().putString(PREFERENCE_RINGTONE, currentRingtone).commit(); mAccountVibrate = (CheckBoxPreference) findPreference(PREFERENCE_VIBRATE); mAccountVibrate.setChecked(mAccount.getNotificationSetting().shouldVibrate()); mAccountVibratePattern = (ListPreference) findPreference(PREFERENCE_VIBRATE_PATTERN); mAccountVibratePattern.setValue(String.valueOf(mAccount.getNotificationSetting().getVibratePattern())); mAccountVibratePattern.setSummary(mAccountVibratePattern.getEntry()); mAccountVibratePattern.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mAccountVibratePattern.findIndexOfValue(summary); mAccountVibratePattern.setSummary(mAccountVibratePattern.getEntries()[index]); mAccountVibratePattern.setValue(summary); doVibrateTest(preference); return false; } }); mAccountVibrateTimes = (ListPreference) findPreference(PREFERENCE_VIBRATE_TIMES); mAccountVibrateTimes.setValue(String.valueOf(mAccount.getNotificationSetting().getVibrateTimes())); mAccountVibrateTimes.setSummary(String.valueOf(mAccount.getNotificationSetting().getVibrateTimes())); mAccountVibrateTimes.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { final String value = newValue.toString(); mAccountVibrateTimes.setSummary(value); mAccountVibrateTimes.setValue(value); doVibrateTest(preference); return false; } }); mAccountLed = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFICATION_LED); mAccountLed.setChecked(mAccount.getNotificationSetting().isLed()); mNotificationOpensUnread = (CheckBoxPreference)findPreference(PREFERENCE_NOTIFICATION_OPENS_UNREAD); mNotificationOpensUnread.setChecked(mAccount.goToUnreadMessageSearch()); CheckBoxPreference notificationUnreadCount = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFICATION_UNREAD_COUNT); /* * Honeycomb and newer don't show the notification number as overlay on the notification * icon in the status bar, so we hide the setting. * * See http://code.google.com/p/android/issues/detail?id=21477 */ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { PreferenceScreen notificationsPrefs = (PreferenceScreen) findPreference(PREFERENCE_SCREEN_NOTIFICATIONS); notificationsPrefs.removePreference(notificationUnreadCount); } else { notificationUnreadCount.setChecked(mAccount.isNotificationShowsUnreadCount()); mNotificationUnreadCount = notificationUnreadCount; } new PopulateFolderPrefsTask().execute(); mChipColor = findPreference(PREFERENCE_CHIP_COLOR); mChipColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { onChooseChipColor(); return false; } }); mLedColor = findPreference(PREFERENCE_LED_COLOR); mLedColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { onChooseLedColor(); return false; } }); findPreference(PREFERENCE_COMPOSITION).setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { onCompositionSettings(); return true; } }); findPreference(PREFERENCE_MANAGE_IDENTITIES).setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { onManageIdentities(); return true; } }); findPreference(PREFERENCE_INCOMING).setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { mIncomingChanged = true; onIncomingSettings(); return true; } }); findPreference(PREFERENCE_OUTGOING).setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { onOutgoingSettings(); return true; } }); mHasCrypto = new Apg().isAvailable(this); if (mHasCrypto) { mCryptoApp = (ListPreference) findPreference(PREFERENCE_CRYPTO_APP); mCryptoApp.setValue(String.valueOf(mAccount.getCryptoApp())); mCryptoApp.setSummary(mCryptoApp.getEntry()); mCryptoApp.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { String value = newValue.toString(); int index = mCryptoApp.findIndexOfValue(value); mCryptoApp.setSummary(mCryptoApp.getEntries()[index]); mCryptoApp.setValue(value); handleCryptoAppDependencies(); if (Apg.NAME.equals(value)) { Apg.createInstance(null).test(AccountSettings.this); } return false; } }); mCryptoAutoSignature = (CheckBoxPreference) findPreference(PREFERENCE_CRYPTO_AUTO_SIGNATURE); mCryptoAutoSignature.setChecked(mAccount.getCryptoAutoSignature()); mCryptoAutoEncrypt = (CheckBoxPreference) findPreference(PREFERENCE_CRYPTO_AUTO_ENCRYPT); mCryptoAutoEncrypt.setChecked(mAccount.isCryptoAutoEncrypt()); handleCryptoAppDependencies(); } else { final Preference mCryptoMenu = findPreference(PREFERENCE_CRYPTO); mCryptoMenu.setEnabled(false); mCryptoMenu.setSummary(R.string.account_settings_crypto_apg_not_installed); } }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String accountUuid = getIntent().getStringExtra(EXTRA_ACCOUNT); mAccount = Preferences.getPreferences(this).getAccount(accountUuid); try { final Store store = mAccount.getRemoteStore(); mIsMoveCapable = store.isMoveCapable(); mIsPushCapable = store.isPushCapable(); mIsExpungeCapable = store.isExpungeCapable(); mIsSeenFlagSupported = store.isSeenFlagSupported(); } catch (Exception e) { Log.e(K9.LOG_TAG, "Could not get remote store", e); } addPreferencesFromResource(R.xml.account_settings_preferences); mMainScreen = (PreferenceScreen) findPreference(PREFERENCE_SCREEN_MAIN); mAccountDescription = (EditTextPreference) findPreference(PREFERENCE_DESCRIPTION); mAccountDescription.setSummary(mAccount.getDescription()); mAccountDescription.setText(mAccount.getDescription()); mAccountDescription.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); mAccountDescription.setSummary(summary); mAccountDescription.setText(summary); return false; } }); mMarkMessageAsReadOnView = (CheckBoxPreference) findPreference(PREFERENCE_MARK_MESSAGE_AS_READ_ON_VIEW); mMarkMessageAsReadOnView.setChecked(mAccount.isMarkMessageAsReadOnView()); mMessageFormat = (ListPreference) findPreference(PREFERENCE_MESSAGE_FORMAT); mMessageFormat.setValue(mAccount.getMessageFormat().name()); mMessageFormat.setSummary(mMessageFormat.getEntry()); mMessageFormat.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mMessageFormat.findIndexOfValue(summary); mMessageFormat.setSummary(mMessageFormat.getEntries()[index]); mMessageFormat.setValue(summary); return false; } }); mAlwaysShowCcBcc = (CheckBoxPreference) findPreference(PREFERENCE_ALWAYS_SHOW_CC_BCC); mAlwaysShowCcBcc.setChecked(mAccount.isAlwaysShowCcBcc()); mMessageReadReceipt = (CheckBoxPreference) findPreference(PREFERENCE_MESSAGE_READ_RECEIPT); mMessageReadReceipt.setChecked(mAccount.isMessageReadReceiptAlways()); mAccountQuotePrefix = (EditTextPreference) findPreference(PREFERENCE_QUOTE_PREFIX); mAccountQuotePrefix.setSummary(mAccount.getQuotePrefix()); mAccountQuotePrefix.setText(mAccount.getQuotePrefix()); mAccountQuotePrefix.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { final String value = newValue.toString(); mAccountQuotePrefix.setSummary(value); mAccountQuotePrefix.setText(value); return false; } }); mAccountDefaultQuotedTextShown = (CheckBoxPreference) findPreference(PREFERENCE_DEFAULT_QUOTED_TEXT_SHOWN); mAccountDefaultQuotedTextShown.setChecked(mAccount.isDefaultQuotedTextShown()); mReplyAfterQuote = (CheckBoxPreference) findPreference(PREFERENCE_REPLY_AFTER_QUOTE); mReplyAfterQuote.setChecked(mAccount.isReplyAfterQuote()); mStripSignature = (CheckBoxPreference) findPreference(PREFERENCE_STRIP_SIGNATURE); mStripSignature.setChecked(mAccount.isStripSignature()); mComposingScreen = (PreferenceScreen) findPreference(PREFERENCE_SCREEN_COMPOSING); Preference.OnPreferenceChangeListener quoteStyleListener = new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { final QuoteStyle style = QuoteStyle.valueOf(newValue.toString()); int index = mQuoteStyle.findIndexOfValue(newValue.toString()); mQuoteStyle.setSummary(mQuoteStyle.getEntries()[index]); if (style == QuoteStyle.PREFIX) { mComposingScreen.addPreference(mAccountQuotePrefix); mComposingScreen.addPreference(mReplyAfterQuote); } else if (style == QuoteStyle.HEADER) { mComposingScreen.removePreference(mAccountQuotePrefix); mComposingScreen.removePreference(mReplyAfterQuote); } return true; } }; mQuoteStyle = (ListPreference) findPreference(PREFERENCE_QUOTE_STYLE); mQuoteStyle.setValue(mAccount.getQuoteStyle().name()); mQuoteStyle.setSummary(mQuoteStyle.getEntry()); mQuoteStyle.setOnPreferenceChangeListener(quoteStyleListener); // Call the onPreferenceChange() handler on startup to update the Preference dialogue based // upon the existing quote style setting. quoteStyleListener.onPreferenceChange(mQuoteStyle, mAccount.getQuoteStyle().name()); mCheckFrequency = (ListPreference) findPreference(PREFERENCE_FREQUENCY); mCheckFrequency.setValue(String.valueOf(mAccount.getAutomaticCheckIntervalMinutes())); mCheckFrequency.setSummary(mCheckFrequency.getEntry()); mCheckFrequency.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mCheckFrequency.findIndexOfValue(summary); mCheckFrequency.setSummary(mCheckFrequency.getEntries()[index]); mCheckFrequency.setValue(summary); return false; } }); mDisplayMode = (ListPreference) findPreference(PREFERENCE_DISPLAY_MODE); mDisplayMode.setValue(mAccount.getFolderDisplayMode().name()); mDisplayMode.setSummary(mDisplayMode.getEntry()); mDisplayMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mDisplayMode.findIndexOfValue(summary); mDisplayMode.setSummary(mDisplayMode.getEntries()[index]); mDisplayMode.setValue(summary); return false; } }); mSyncMode = (ListPreference) findPreference(PREFERENCE_SYNC_MODE); mSyncMode.setValue(mAccount.getFolderSyncMode().name()); mSyncMode.setSummary(mSyncMode.getEntry()); mSyncMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mSyncMode.findIndexOfValue(summary); mSyncMode.setSummary(mSyncMode.getEntries()[index]); mSyncMode.setValue(summary); return false; } }); mTargetMode = (ListPreference) findPreference(PREFERENCE_TARGET_MODE); mTargetMode.setValue(mAccount.getFolderTargetMode().name()); mTargetMode.setSummary(mTargetMode.getEntry()); mTargetMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mTargetMode.findIndexOfValue(summary); mTargetMode.setSummary(mTargetMode.getEntries()[index]); mTargetMode.setValue(summary); return false; } }); mDeletePolicy = (ListPreference) findPreference(PREFERENCE_DELETE_POLICY); if (!mIsSeenFlagSupported) { removeListEntry(mDeletePolicy, Integer.toString(Account.DELETE_POLICY_MARK_AS_READ)); } mDeletePolicy.setValue(Integer.toString(mAccount.getDeletePolicy())); mDeletePolicy.setSummary(mDeletePolicy.getEntry()); mDeletePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mDeletePolicy.findIndexOfValue(summary); mDeletePolicy.setSummary(mDeletePolicy.getEntries()[index]); mDeletePolicy.setValue(summary); return false; } }); mExpungePolicy = (ListPreference) findPreference(PREFERENCE_EXPUNGE_POLICY); if (mIsExpungeCapable) { mExpungePolicy.setValue(mAccount.getExpungePolicy()); mExpungePolicy.setSummary(mExpungePolicy.getEntry()); mExpungePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mExpungePolicy.findIndexOfValue(summary); mExpungePolicy.setSummary(mExpungePolicy.getEntries()[index]); mExpungePolicy.setValue(summary); return false; } }); } else { ((PreferenceScreen) findPreference(PREFERENCE_SCREEN_INCOMING)).removePreference(mExpungePolicy); } mSyncRemoteDeletions = (CheckBoxPreference) findPreference(PREFERENCE_SYNC_REMOTE_DELETIONS); mSyncRemoteDeletions.setChecked(mAccount.syncRemoteDeletions()); mSearchableFolders = (ListPreference) findPreference(PREFERENCE_SEARCHABLE_FOLDERS); mSearchableFolders.setValue(mAccount.getSearchableFolders().name()); mSearchableFolders.setSummary(mSearchableFolders.getEntry()); mSearchableFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mSearchableFolders.findIndexOfValue(summary); mSearchableFolders.setSummary(mSearchableFolders.getEntries()[index]); mSearchableFolders.setValue(summary); return false; } }); mDisplayCount = (ListPreference) findPreference(PREFERENCE_DISPLAY_COUNT); mDisplayCount.setValue(String.valueOf(mAccount.getDisplayCount())); mDisplayCount.setSummary(mDisplayCount.getEntry()); mDisplayCount.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mDisplayCount.findIndexOfValue(summary); mDisplayCount.setSummary(mDisplayCount.getEntries()[index]); mDisplayCount.setValue(summary); return false; } }); mMessageAge = (ListPreference) findPreference(PREFERENCE_MESSAGE_AGE); if (!mAccount.isSearchByDateCapable()) { ((PreferenceScreen) findPreference(PREFERENCE_SCREEN_INCOMING)).removePreference(mMessageAge); } else { mMessageAge.setValue(String.valueOf(mAccount.getMaximumPolledMessageAge())); mMessageAge.setSummary(mMessageAge.getEntry()); mMessageAge.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mMessageAge.findIndexOfValue(summary); mMessageAge.setSummary(mMessageAge.getEntries()[index]); mMessageAge.setValue(summary); return false; } }); } mMessageSize = (ListPreference) findPreference(PREFERENCE_MESSAGE_SIZE); mMessageSize.setValue(String.valueOf(mAccount.getMaximumAutoDownloadMessageSize())); mMessageSize.setSummary(mMessageSize.getEntry()); mMessageSize.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mMessageSize.findIndexOfValue(summary); mMessageSize.setSummary(mMessageSize.getEntries()[index]); mMessageSize.setValue(summary); return false; } }); mAccountDefault = (CheckBoxPreference) findPreference(PREFERENCE_DEFAULT); mAccountDefault.setChecked( mAccount.equals(Preferences.getPreferences(this).getDefaultAccount())); mAccountShowPictures = (ListPreference) findPreference(PREFERENCE_SHOW_PICTURES); mAccountShowPictures.setValue("" + mAccount.getShowPictures()); mAccountShowPictures.setSummary(mAccountShowPictures.getEntry()); mAccountShowPictures.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mAccountShowPictures.findIndexOfValue(summary); mAccountShowPictures.setSummary(mAccountShowPictures.getEntries()[index]); mAccountShowPictures.setValue(summary); return false; } }); mLocalStorageProvider = (ListPreference) findPreference(PREFERENCE_LOCAL_STORAGE_PROVIDER); { final Map<String, String> providers; providers = StorageManager.getInstance(K9.app).getAvailableProviders(); int i = 0; final String[] providerLabels = new String[providers.size()]; final String[] providerIds = new String[providers.size()]; for (final Map.Entry<String, String> entry : providers.entrySet()) { providerIds[i] = entry.getKey(); providerLabels[i] = entry.getValue(); i++; } mLocalStorageProvider.setEntryValues(providerIds); mLocalStorageProvider.setEntries(providerLabels); mLocalStorageProvider.setValue(mAccount.getLocalStorageProviderId()); mLocalStorageProvider.setSummary(providers.get(mAccount.getLocalStorageProviderId())); mLocalStorageProvider.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { mLocalStorageProvider.setSummary(providers.get(newValue)); return true; } }); } // IMAP-specific preferences mSearchScreen = (PreferenceScreen) findPreference(PREFERENCE_SCREEN_SEARCH); mCloudSearchEnabled = (CheckBoxPreference) findPreference(PREFERENCE_CLOUD_SEARCH_ENABLED); mRemoteSearchNumResults = (ListPreference) findPreference(PREFERENCE_REMOTE_SEARCH_NUM_RESULTS); mRemoteSearchNumResults.setOnPreferenceChangeListener( new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference pref, Object newVal) { updateRemoteSearchLimit((String)newVal); return true; } } ); //mRemoteSearchFullText = (CheckBoxPreference) findPreference(PREFERENCE_REMOTE_SEARCH_FULL_TEXT); mPushPollOnConnect = (CheckBoxPreference) findPreference(PREFERENCE_PUSH_POLL_ON_CONNECT); mIdleRefreshPeriod = (ListPreference) findPreference(PREFERENCE_IDLE_REFRESH_PERIOD); mMaxPushFolders = (ListPreference) findPreference(PREFERENCE_MAX_PUSH_FOLDERS); if (mIsPushCapable) { mPushPollOnConnect.setChecked(mAccount.isPushPollOnConnect()); mCloudSearchEnabled.setChecked(mAccount.allowRemoteSearch()); String searchNumResults = Integer.toString(mAccount.getRemoteSearchNumResults()); mRemoteSearchNumResults.setValue(searchNumResults); updateRemoteSearchLimit(searchNumResults); //mRemoteSearchFullText.setChecked(mAccount.isRemoteSearchFullText()); mIdleRefreshPeriod.setValue(String.valueOf(mAccount.getIdleRefreshMinutes())); mIdleRefreshPeriod.setSummary(mIdleRefreshPeriod.getEntry()); mIdleRefreshPeriod.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mIdleRefreshPeriod.findIndexOfValue(summary); mIdleRefreshPeriod.setSummary(mIdleRefreshPeriod.getEntries()[index]); mIdleRefreshPeriod.setValue(summary); return false; } }); mMaxPushFolders.setValue(String.valueOf(mAccount.getMaxPushFolders())); mMaxPushFolders.setSummary(mMaxPushFolders.getEntry()); mMaxPushFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mMaxPushFolders.findIndexOfValue(summary); mMaxPushFolders.setSummary(mMaxPushFolders.getEntries()[index]); mMaxPushFolders.setValue(summary); return false; } }); mPushMode = (ListPreference) findPreference(PREFERENCE_PUSH_MODE); mPushMode.setValue(mAccount.getFolderPushMode().name()); mPushMode.setSummary(mPushMode.getEntry()); mPushMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mPushMode.findIndexOfValue(summary); mPushMode.setSummary(mPushMode.getEntries()[index]); mPushMode.setValue(summary); return false; } }); } else { PreferenceScreen incomingPrefs = (PreferenceScreen) findPreference(PREFERENCE_SCREEN_INCOMING); incomingPrefs.removePreference((PreferenceScreen) findPreference(PREFERENCE_SCREEN_PUSH_ADVANCED)); incomingPrefs.removePreference((ListPreference) findPreference(PREFERENCE_PUSH_MODE)); mMainScreen.removePreference(mSearchScreen); } mAccountNotify = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY); mAccountNotify.setChecked(mAccount.isNotifyNewMail()); mAccountNotifySelf = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY_SELF); mAccountNotifySelf.setChecked(mAccount.isNotifySelfNewMail()); mAccountNotifySync = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY_SYNC); mAccountNotifySync.setChecked(mAccount.isShowOngoing()); mAccountRingtone = (RingtonePreference) findPreference(PREFERENCE_RINGTONE); // XXX: The following two lines act as a workaround for the RingtonePreference // which does not let us set/get the value programmatically SharedPreferences prefs = mAccountRingtone.getPreferenceManager().getSharedPreferences(); String currentRingtone = (!mAccount.getNotificationSetting().shouldRing() ? null : mAccount.getNotificationSetting().getRingtone()); prefs.edit().putString(PREFERENCE_RINGTONE, currentRingtone).commit(); mAccountVibrate = (CheckBoxPreference) findPreference(PREFERENCE_VIBRATE); mAccountVibrate.setChecked(mAccount.getNotificationSetting().shouldVibrate()); mAccountVibratePattern = (ListPreference) findPreference(PREFERENCE_VIBRATE_PATTERN); mAccountVibratePattern.setValue(String.valueOf(mAccount.getNotificationSetting().getVibratePattern())); mAccountVibratePattern.setSummary(mAccountVibratePattern.getEntry()); mAccountVibratePattern.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { final String summary = newValue.toString(); int index = mAccountVibratePattern.findIndexOfValue(summary); mAccountVibratePattern.setSummary(mAccountVibratePattern.getEntries()[index]); mAccountVibratePattern.setValue(summary); doVibrateTest(preference); return false; } }); mAccountVibrateTimes = (ListPreference) findPreference(PREFERENCE_VIBRATE_TIMES); mAccountVibrateTimes.setValue(String.valueOf(mAccount.getNotificationSetting().getVibrateTimes())); mAccountVibrateTimes.setSummary(String.valueOf(mAccount.getNotificationSetting().getVibrateTimes())); mAccountVibrateTimes.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { final String value = newValue.toString(); mAccountVibrateTimes.setSummary(value); mAccountVibrateTimes.setValue(value); doVibrateTest(preference); return false; } }); mAccountLed = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFICATION_LED); mAccountLed.setChecked(mAccount.getNotificationSetting().isLed()); mNotificationOpensUnread = (CheckBoxPreference)findPreference(PREFERENCE_NOTIFICATION_OPENS_UNREAD); mNotificationOpensUnread.setChecked(mAccount.goToUnreadMessageSearch()); CheckBoxPreference notificationUnreadCount = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFICATION_UNREAD_COUNT); /* * Honeycomb and newer don't show the notification number as overlay on the notification * icon in the status bar, so we hide the setting. * * See http://code.google.com/p/android/issues/detail?id=21477 */ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { PreferenceScreen notificationsPrefs = (PreferenceScreen) findPreference(PREFERENCE_SCREEN_NOTIFICATIONS); notificationsPrefs.removePreference(notificationUnreadCount); } else { notificationUnreadCount.setChecked(mAccount.isNotificationShowsUnreadCount()); mNotificationUnreadCount = notificationUnreadCount; } new PopulateFolderPrefsTask().execute(); mChipColor = findPreference(PREFERENCE_CHIP_COLOR); mChipColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { onChooseChipColor(); return false; } }); mLedColor = findPreference(PREFERENCE_LED_COLOR); mLedColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { onChooseLedColor(); return false; } }); findPreference(PREFERENCE_COMPOSITION).setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { onCompositionSettings(); return true; } }); findPreference(PREFERENCE_MANAGE_IDENTITIES).setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { onManageIdentities(); return true; } }); findPreference(PREFERENCE_INCOMING).setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { mIncomingChanged = true; onIncomingSettings(); return true; } }); findPreference(PREFERENCE_OUTGOING).setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { onOutgoingSettings(); return true; } }); mHasCrypto = new Apg().isAvailable(this); if (mHasCrypto) { mCryptoApp = (ListPreference) findPreference(PREFERENCE_CRYPTO_APP); mCryptoApp.setValue(String.valueOf(mAccount.getCryptoApp())); mCryptoApp.setSummary(mCryptoApp.getEntry()); mCryptoApp.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { String value = newValue.toString(); int index = mCryptoApp.findIndexOfValue(value); mCryptoApp.setSummary(mCryptoApp.getEntries()[index]); mCryptoApp.setValue(value); handleCryptoAppDependencies(); if (Apg.NAME.equals(value)) { Apg.createInstance(null).test(AccountSettings.this); } return false; } }); mCryptoAutoSignature = (CheckBoxPreference) findPreference(PREFERENCE_CRYPTO_AUTO_SIGNATURE); mCryptoAutoSignature.setChecked(mAccount.getCryptoAutoSignature()); mCryptoAutoEncrypt = (CheckBoxPreference) findPreference(PREFERENCE_CRYPTO_AUTO_ENCRYPT); mCryptoAutoEncrypt.setChecked(mAccount.isCryptoAutoEncrypt()); handleCryptoAppDependencies(); } else { final Preference mCryptoMenu = findPreference(PREFERENCE_CRYPTO); mCryptoMenu.setEnabled(false); mCryptoMenu.setSummary(R.string.account_settings_crypto_apg_not_installed); } }
diff --git a/jsglr-layout/src/org/spoofax/jsglr_layout/client/indentation/LayoutFilter.java b/jsglr-layout/src/org/spoofax/jsglr_layout/client/indentation/LayoutFilter.java index 330d4aa..d6424b1 100644 --- a/jsglr-layout/src/org/spoofax/jsglr_layout/client/indentation/LayoutFilter.java +++ b/jsglr-layout/src/org/spoofax/jsglr_layout/client/indentation/LayoutFilter.java @@ -1,329 +1,329 @@ package org.spoofax.jsglr_layout.client.indentation; import java.util.HashMap; import java.util.Map; import java.util.Stack; import org.spoofax.interpreter.terms.IStrategoAppl; import org.spoofax.interpreter.terms.IStrategoConstructor; import org.spoofax.interpreter.terms.IStrategoString; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.jsglr_layout.client.AbstractParseNode; import org.spoofax.jsglr_layout.client.ParseNode; import org.spoofax.jsglr_layout.client.ParseTable; import org.spoofax.jsglr_layout.client.imploder.ProductionAttributeReader; import org.spoofax.terms.Term; /** * @author Sebastian Erdweg <seba at informatik uni-marburg de> * */ public class LayoutFilter { private final Object NO_VALUE = null; private final boolean atParseTime; private ParseTable parseTable; private ProductionAttributeReader attrReader; private int disambiguationCount; private int filterCallCount = 0; /** * * @param parseTable * @param atParseTime if true, the filter is conservative: it only discards * trees whose parser state can be discarded in general. This is needed * when discarding trees at parse time, when a later join may represent * alternative trees by the same parser state. */ public LayoutFilter(ParseTable parseTable, boolean atParseTime) { this.parseTable = parseTable; this.attrReader = new ProductionAttributeReader(parseTable.getFactory()); this.atParseTime = atParseTime; } int error = 0; public int getFilterCallCount() { return filterCallCount; } public int getDisambiguationCount() { return disambiguationCount; } public boolean hasValidLayout(ParseNode t) { return hasValidLayout(t.getLabel(), t.getChildren()); } public boolean hasValidLayout(int label, AbstractParseNode[] kids) { IStrategoTerm layoutConstraint = parseTable.getLabel(label).getAttributes().getLayoutConstraint(); if (layoutConstraint == null) return true; disambiguationCount = 0; filterCallCount++; Boolean b = evalConstraint(layoutConstraint, kids, new HashMap<String, Object>(), Boolean.class); if (b == NO_VALUE) return true; return b; } @SuppressWarnings("unchecked") private <T> T evalConstraint(IStrategoTerm constraint, AbstractParseNode[] kids, Map<String, Object> env, Class<T> cl) { Object o = evalConstraint(constraint, kids, env); ensureType(o, cl, constraint); return (T) o; } private Object evalConstraint(IStrategoTerm constraint, AbstractParseNode[] kids, Map<String, Object> env) { switch (constraint.getTermType()) { case IStrategoTerm.INT: { int i = Term.asJavaInt(constraint); return getSubtree(i, kids); } case IStrategoTerm.STRING: String v = Term.asJavaString(constraint); Object o = env.get(v); if (o == null) throw new IllegalStateException("undefined variable " + v); return o; case IStrategoTerm.APPL: IStrategoConstructor cons = Term.tryGetConstructor(constraint); String consName = cons.getName(); if (consName.equals("num")) { - String num = Term.asJavaString(constraint); + String num = Term.asJavaString(constraint.getSubterm(0)); int i = Integer.parseInt(num); return getSubtree(i, kids); } if (consName.equals("eq") || consName.equals("gt") || consName.equals("ge") || consName.equals("lt") || consName.equals("le")) { ensureChildCount(constraint, 2, consName); Integer i1 = evalConstraint(constraint.getSubterm(0), kids, env, Integer.class); Integer i2 = evalConstraint(constraint.getSubterm(1), kids, env, Integer.class); return binArithComp(consName, i1, i2); } if (consName.equals("add") || consName.equals("sub") || consName.equals("mul") || consName.equals("div")) { ensureChildCount(constraint, 2, consName); Integer i1 = evalConstraint(constraint.getSubterm(0), kids, env, Integer.class); Integer i2 = evalConstraint(constraint.getSubterm(1), kids, env, Integer.class); return binArithOp(consName, i1, i2); } if (consName.equals("first") || consName.equals("left")) { ensureChildCount(constraint, 1, consName); AbstractParseNode n = evalConstraint(constraint.getSubterm(0), kids, env, AbstractParseNode.class); return nodeSelector(consName, n); } if (consName.equals("or")) { ensureChildCount(constraint, 2, consName); Boolean b1 = evalConstraint(constraint.getSubterm(0), kids, env, Boolean.class); if (b1 != NO_VALUE && b1) return true; Boolean b2 = evalConstraint(constraint.getSubterm(1), kids, env, Boolean.class); return b2; } if (consName.equals("and")) { ensureChildCount(constraint, 2, consName); Boolean b1 = evalConstraint(constraint.getSubterm(0), kids, env, Boolean.class); if (b1 != NO_VALUE && !b1) return false; Boolean b2 = evalConstraint(constraint.getSubterm(1), kids, env, Boolean.class); return b2; } if (consName.equals("not")) { ensureChildCount(constraint, 1, consName); Boolean b1 = evalConstraint(constraint.getSubterm(0), kids, env, Boolean.class); if (b1 == NO_VALUE) return NO_VALUE; return !b1; } if (consName.equals("all")) { ensureChildCount(constraint, 3, consName); ensureType(constraint.getSubterm(0), IStrategoString.class, constraint.getSubterm(0)); v = Term.asJavaString(constraint.getSubterm(0)); AbstractParseNode n = evalConstraint(constraint.getSubterm(1), kids, env, AbstractParseNode.class); return checkAll(n, v, constraint, kids, env); } if (consName.equals("col")) { ensureChildCount(constraint, 1, consName); AbstractParseNode n = evalConstraint(constraint.getSubterm(0), kids, env, AbstractParseNode.class); if (n == NO_VALUE) return NO_VALUE; return n.getColumn(); } if (consName.equals("line")) { ensureChildCount(constraint, 1, consName); AbstractParseNode n = evalConstraint(constraint.getSubterm(0), kids, env, AbstractParseNode.class); if (n == NO_VALUE) return NO_VALUE; return n.getLine(); } throw new IllegalStateException("unhandeled constructor " + consName); default: throw new IllegalStateException("unhandeled constraint " + constraint); } } private boolean checkAll(AbstractParseNode n, String v, IStrategoTerm constraint, AbstractParseNode[] kids, Map<String, Object> env) { Stack<AbstractParseNode> all = new Stack<AbstractParseNode>(); all.push(n); String sort = null; while (!all.isEmpty()) { AbstractParseNode next = all.pop(); if (sort == null && !next.isAmbNode() && !next.isParseProductionNode()) sort = sortOfNode(next); if (next.isAmbNode()) { boolean left = checkAll(next.getChildren()[0], v, constraint, kids, env); boolean right = checkAll(next.getChildren()[1], v, constraint, kids, env); if (!left && !right) return false; if (left && !right) { ((ParseNode) next).disambiguate(next.getChildren()[0]); disambiguationCount++; } if (!left && right) { ((ParseNode) next).disambiguate(next.getChildren()[1]); disambiguationCount++; } } else if (next.isParseProductionNode() || sort != null && !sort.equals(sortOfNode(next)) || !isListNode(next)){ Object old = env.get(v); env.put(v, next); try { Boolean b = evalConstraint(constraint.getSubterm(2), kids, env, Boolean.class); if (b != NO_VALUE && !b) return false; } finally { if (old == null) env.remove(v); else env.put(v, old); } } else for (int j = next.getChildren().length - 1; j >= 0; j--) { AbstractParseNode kid = next.getChildren()[j]; if (kid.isAmbNode() || sort.equals(sortOfNode(kid))) all.push(kid); } } return true; } private String sortOfNode(AbstractParseNode node) { return attrReader.getSort((IStrategoAppl) parseTable.getLabel(node.getLabel()).getProduction().getSubterm(1)); } private boolean isListNode(AbstractParseNode node) { IStrategoTerm prod = parseTable.getLabel(node.getLabel()).getProduction(); return attrReader.isList((IStrategoAppl) prod.getSubterm(1), (IStrategoAppl) prod.getSubterm(2)) && !attrReader.isFlatten((IStrategoAppl) prod.getSubterm(1), (IStrategoAppl) prod.getSubterm(2)); } private AbstractParseNode getSubtree(int i, AbstractParseNode[] kids) { i = i - 1; int elems = (kids.length + 1) / 2; if (i < 0 || i >= elems) throw new IllegalStateException("index out of bounds: " + "index is " + i + " but only " + elems + " children available"); return kids[2 * i]; } private Integer binArithOp(String op, Integer i1, Integer i2) { if (i1 == NO_VALUE || i2 == NO_VALUE) return noValue(); if (op.equals("add")) return i1 + i2; if (op.equals("sub")) return i1 - i2; if (op.equals("mult")) return i1 * i2; if (op.equals("div")) return i1 / i2; throw new IllegalStateException("unknown operator " + op); } private Boolean binArithComp(String comp, Integer i1, Integer i2) { if (i1 == NO_VALUE || i2 == NO_VALUE) return noValue(); if (comp.equals("eq")) return i1.equals(i2); if (comp.equals("gt")) return i1 > i2; if (comp.equals("ge")) return i1 >= i2; if (comp.equals("lt")) return i1 < i2; if (comp.equals("le")) return i1 <= i2; throw new IllegalStateException("unknown comparator " + comp); } private AbstractParseNode nodeSelector(String sel, AbstractParseNode t) { if (sel.equals("first")) if (isNothing(t)) return noValue(); else return t; if (sel.equals("left")) if (atParseTime) return noValue(); else return t.getLeft(); throw new IllegalStateException("unknown selector " + sel); } private void ensureType(Object o, Class<?> cl, IStrategoTerm term) { if (o != null && !cl.isInstance(o)) throw new IllegalStateException("ill-typed term " + term + ". Expected type " + cl.getName() + ", was " + o.getClass().getName()); } private void ensureChildCount(IStrategoTerm t, int count, String what) { if (t.getAllSubterms().length != count) throw new IllegalStateException("not enough arguments to " + what); } @SuppressWarnings("unchecked") private <T> T noValue() { return (T) NO_VALUE; } private boolean isNothing(AbstractParseNode n) { if (n.isAmbNode()) return isNothing(n.getChildren()[0]) && isNothing(n.getChildren()[1]); return n.isLayout() || n.isEmpty(); } }
true
true
private Object evalConstraint(IStrategoTerm constraint, AbstractParseNode[] kids, Map<String, Object> env) { switch (constraint.getTermType()) { case IStrategoTerm.INT: { int i = Term.asJavaInt(constraint); return getSubtree(i, kids); } case IStrategoTerm.STRING: String v = Term.asJavaString(constraint); Object o = env.get(v); if (o == null) throw new IllegalStateException("undefined variable " + v); return o; case IStrategoTerm.APPL: IStrategoConstructor cons = Term.tryGetConstructor(constraint); String consName = cons.getName(); if (consName.equals("num")) { String num = Term.asJavaString(constraint); int i = Integer.parseInt(num); return getSubtree(i, kids); } if (consName.equals("eq") || consName.equals("gt") || consName.equals("ge") || consName.equals("lt") || consName.equals("le")) { ensureChildCount(constraint, 2, consName); Integer i1 = evalConstraint(constraint.getSubterm(0), kids, env, Integer.class); Integer i2 = evalConstraint(constraint.getSubterm(1), kids, env, Integer.class); return binArithComp(consName, i1, i2); } if (consName.equals("add") || consName.equals("sub") || consName.equals("mul") || consName.equals("div")) { ensureChildCount(constraint, 2, consName); Integer i1 = evalConstraint(constraint.getSubterm(0), kids, env, Integer.class); Integer i2 = evalConstraint(constraint.getSubterm(1), kids, env, Integer.class); return binArithOp(consName, i1, i2); } if (consName.equals("first") || consName.equals("left")) { ensureChildCount(constraint, 1, consName); AbstractParseNode n = evalConstraint(constraint.getSubterm(0), kids, env, AbstractParseNode.class); return nodeSelector(consName, n); } if (consName.equals("or")) { ensureChildCount(constraint, 2, consName); Boolean b1 = evalConstraint(constraint.getSubterm(0), kids, env, Boolean.class); if (b1 != NO_VALUE && b1) return true; Boolean b2 = evalConstraint(constraint.getSubterm(1), kids, env, Boolean.class); return b2; } if (consName.equals("and")) { ensureChildCount(constraint, 2, consName); Boolean b1 = evalConstraint(constraint.getSubterm(0), kids, env, Boolean.class); if (b1 != NO_VALUE && !b1) return false; Boolean b2 = evalConstraint(constraint.getSubterm(1), kids, env, Boolean.class); return b2; } if (consName.equals("not")) { ensureChildCount(constraint, 1, consName); Boolean b1 = evalConstraint(constraint.getSubterm(0), kids, env, Boolean.class); if (b1 == NO_VALUE) return NO_VALUE; return !b1; } if (consName.equals("all")) { ensureChildCount(constraint, 3, consName); ensureType(constraint.getSubterm(0), IStrategoString.class, constraint.getSubterm(0)); v = Term.asJavaString(constraint.getSubterm(0)); AbstractParseNode n = evalConstraint(constraint.getSubterm(1), kids, env, AbstractParseNode.class); return checkAll(n, v, constraint, kids, env); } if (consName.equals("col")) { ensureChildCount(constraint, 1, consName); AbstractParseNode n = evalConstraint(constraint.getSubterm(0), kids, env, AbstractParseNode.class); if (n == NO_VALUE) return NO_VALUE; return n.getColumn(); } if (consName.equals("line")) { ensureChildCount(constraint, 1, consName); AbstractParseNode n = evalConstraint(constraint.getSubterm(0), kids, env, AbstractParseNode.class); if (n == NO_VALUE) return NO_VALUE; return n.getLine(); } throw new IllegalStateException("unhandeled constructor " + consName); default: throw new IllegalStateException("unhandeled constraint " + constraint); } }
private Object evalConstraint(IStrategoTerm constraint, AbstractParseNode[] kids, Map<String, Object> env) { switch (constraint.getTermType()) { case IStrategoTerm.INT: { int i = Term.asJavaInt(constraint); return getSubtree(i, kids); } case IStrategoTerm.STRING: String v = Term.asJavaString(constraint); Object o = env.get(v); if (o == null) throw new IllegalStateException("undefined variable " + v); return o; case IStrategoTerm.APPL: IStrategoConstructor cons = Term.tryGetConstructor(constraint); String consName = cons.getName(); if (consName.equals("num")) { String num = Term.asJavaString(constraint.getSubterm(0)); int i = Integer.parseInt(num); return getSubtree(i, kids); } if (consName.equals("eq") || consName.equals("gt") || consName.equals("ge") || consName.equals("lt") || consName.equals("le")) { ensureChildCount(constraint, 2, consName); Integer i1 = evalConstraint(constraint.getSubterm(0), kids, env, Integer.class); Integer i2 = evalConstraint(constraint.getSubterm(1), kids, env, Integer.class); return binArithComp(consName, i1, i2); } if (consName.equals("add") || consName.equals("sub") || consName.equals("mul") || consName.equals("div")) { ensureChildCount(constraint, 2, consName); Integer i1 = evalConstraint(constraint.getSubterm(0), kids, env, Integer.class); Integer i2 = evalConstraint(constraint.getSubterm(1), kids, env, Integer.class); return binArithOp(consName, i1, i2); } if (consName.equals("first") || consName.equals("left")) { ensureChildCount(constraint, 1, consName); AbstractParseNode n = evalConstraint(constraint.getSubterm(0), kids, env, AbstractParseNode.class); return nodeSelector(consName, n); } if (consName.equals("or")) { ensureChildCount(constraint, 2, consName); Boolean b1 = evalConstraint(constraint.getSubterm(0), kids, env, Boolean.class); if (b1 != NO_VALUE && b1) return true; Boolean b2 = evalConstraint(constraint.getSubterm(1), kids, env, Boolean.class); return b2; } if (consName.equals("and")) { ensureChildCount(constraint, 2, consName); Boolean b1 = evalConstraint(constraint.getSubterm(0), kids, env, Boolean.class); if (b1 != NO_VALUE && !b1) return false; Boolean b2 = evalConstraint(constraint.getSubterm(1), kids, env, Boolean.class); return b2; } if (consName.equals("not")) { ensureChildCount(constraint, 1, consName); Boolean b1 = evalConstraint(constraint.getSubterm(0), kids, env, Boolean.class); if (b1 == NO_VALUE) return NO_VALUE; return !b1; } if (consName.equals("all")) { ensureChildCount(constraint, 3, consName); ensureType(constraint.getSubterm(0), IStrategoString.class, constraint.getSubterm(0)); v = Term.asJavaString(constraint.getSubterm(0)); AbstractParseNode n = evalConstraint(constraint.getSubterm(1), kids, env, AbstractParseNode.class); return checkAll(n, v, constraint, kids, env); } if (consName.equals("col")) { ensureChildCount(constraint, 1, consName); AbstractParseNode n = evalConstraint(constraint.getSubterm(0), kids, env, AbstractParseNode.class); if (n == NO_VALUE) return NO_VALUE; return n.getColumn(); } if (consName.equals("line")) { ensureChildCount(constraint, 1, consName); AbstractParseNode n = evalConstraint(constraint.getSubterm(0), kids, env, AbstractParseNode.class); if (n == NO_VALUE) return NO_VALUE; return n.getLine(); } throw new IllegalStateException("unhandeled constructor " + consName); default: throw new IllegalStateException("unhandeled constraint " + constraint); } }
diff --git a/Ingest/src/org/sleuthkit/autopsy/ingest/IngestDialogPanel.java b/Ingest/src/org/sleuthkit/autopsy/ingest/IngestDialogPanel.java index 893a7f745..21f7cc630 100644 --- a/Ingest/src/org/sleuthkit/autopsy/ingest/IngestDialogPanel.java +++ b/Ingest/src/org/sleuthkit/autopsy/ingest/IngestDialogPanel.java @@ -1,565 +1,566 @@ /* * Autopsy Forensic Browser * * Copyright 2011 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * 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.sleuthkit.autopsy.ingest; import java.awt.Component; import org.sleuthkit.autopsy.corecomponents.AdvancedConfigurationDialog; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.ListSelectionModel; 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.DefaultTableCellRenderer; import javax.swing.table.TableColumn; import org.sleuthkit.autopsy.casemodule.IngestConfigurator; import org.sleuthkit.autopsy.ingest.IngestManager.UpdateFrequency; import org.sleuthkit.datamodel.Image; /** * main configuration panel for all ingest services, reusable JPanel component */ public class IngestDialogPanel extends javax.swing.JPanel implements IngestConfigurator { private IngestManager manager = null; private List<IngestServiceAbstract> services; private IngestServiceAbstract currentService; private Map<String, Boolean> serviceStates; private ServicesTableModel tableModel; private static final Logger logger = Logger.getLogger(IngestDialogPanel.class.getName()); // The image that's just been added to the database private Image image; private static IngestDialogPanel instance = null; /** Creates new form IngestDialogPanel */ private IngestDialogPanel() { tableModel = new ServicesTableModel(); services = new ArrayList<IngestServiceAbstract>(); serviceStates = new HashMap<String, Boolean>(); initComponents(); customizeComponents(); } synchronized static IngestDialogPanel getDefault() { if (instance == null) { instance = new IngestDialogPanel(); } return instance; } private void customizeComponents() { servicesTable.setModel(tableModel); this.manager = IngestManager.getDefault(); Collection<IngestServiceImage> imageServices = IngestManager.enumerateImageServices(); for (final IngestServiceImage service : imageServices) { addService(service); } Collection<IngestServiceAbstractFile> fsServices = IngestManager.enumerateAbstractFileServices(); for (final IngestServiceAbstractFile service : fsServices) { addService(service); } //time setting timeGroup.add(timeRadioButton1); timeGroup.add(timeRadioButton2); timeGroup.add(timeRadioButton3); if (manager.isIngestRunning()) { setTimeSettingEnabled(false); } else { setTimeSettingEnabled(true); } //set default final UpdateFrequency curFreq = manager.getUpdateFrequency(); switch (curFreq) { case FAST: timeRadioButton1.setSelected(true); break; case AVG: timeRadioButton2.setSelected(true); break; case SLOW: timeRadioButton3.setSelected(true); break; default: // } servicesTable.setTableHeader(null); servicesTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); //custom renderer for tooltips ServiceTableRenderer renderer = new ServiceTableRenderer(); //customize column witdhs final int width = servicesScrollPane.getPreferredSize().width; TableColumn column = null; for (int i = 0; i < servicesTable.getColumnCount(); i++) { column = servicesTable.getColumnModel().getColumn(i); if (i == 0) { column.setPreferredWidth(((int) (width * 0.15))); } else { column.setCellRenderer(renderer); column.setPreferredWidth(((int) (width * 0.84))); } } servicesTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { ListSelectionModel listSelectionModel = (ListSelectionModel) e.getSource(); if (!listSelectionModel.isSelectionEmpty()) { save(); int index = listSelectionModel.getMinSelectionIndex(); currentService = services.get(index); reloadSimpleConfiguration(); advancedButton.setEnabled(currentService.hasAdvancedConfiguration()); } else { currentService = null; } } }); processUnallocCheckbox.setSelected(manager.getProcessUnallocSpace()); } private void setTimeSettingEnabled(boolean enabled) { timeRadioButton1.setEnabled(enabled); timeRadioButton2.setEnabled(enabled); timeRadioButton3.setEnabled(enabled); } private void setProcessUnallocSpaceEnabled(boolean enabled) { processUnallocCheckbox.setEnabled(enabled); } @Override public void paint(Graphics g) { super.paint(g); if (manager.isIngestRunning()) { setTimeSettingEnabled(false); setProcessUnallocSpaceEnabled(false); } else { setTimeSettingEnabled(true); setProcessUnallocSpaceEnabled(true); } } private void addService(IngestServiceAbstract service) { final String serviceName = service.getName(); services.add(service); serviceStates.put(serviceName, true); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { timeGroup = new javax.swing.ButtonGroup(); servicesScrollPane = new javax.swing.JScrollPane(); servicesTable = new javax.swing.JTable(); jPanel1 = new javax.swing.JPanel(); advancedButton = new javax.swing.JButton(); jSeparator2 = new javax.swing.JSeparator(); jScrollPane1 = new javax.swing.JScrollPane(); simplePanel = new javax.swing.JPanel(); timePanel = new javax.swing.JPanel(); timeRadioButton3 = new javax.swing.JRadioButton(); timeRadioButton2 = new javax.swing.JRadioButton(); timeLabel = new javax.swing.JLabel(); timeRadioButton1 = new javax.swing.JRadioButton(); processUnallocPanel = new javax.swing.JPanel(); processUnallocCheckbox = new javax.swing.JCheckBox(); setPreferredSize(new java.awt.Dimension(522, 257)); servicesScrollPane.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160))); servicesScrollPane.setPreferredSize(new java.awt.Dimension(160, 160)); servicesTable.setBackground(new java.awt.Color(240, 240, 240)); servicesTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); servicesTable.setShowHorizontalLines(false); servicesTable.setShowVerticalLines(false); servicesScrollPane.setViewportView(servicesTable); jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160))); jPanel1.setPreferredSize(new java.awt.Dimension(338, 257)); advancedButton.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.advancedButton.text")); // NOI18N advancedButton.setEnabled(false); advancedButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { advancedButtonActionPerformed(evt); } }); jScrollPane1.setBorder(null); jScrollPane1.setPreferredSize(new java.awt.Dimension(250, 180)); simplePanel.setLayout(new javax.swing.BoxLayout(simplePanel, javax.swing.BoxLayout.PAGE_AXIS)); jScrollPane1.setViewportView(simplePanel); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE) .addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(245, Short.MAX_VALUE) .addComponent(advancedButton) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(advancedButton) .addContainerGap()) ); timePanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160))); timeRadioButton3.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton3.text")); // NOI18N timeRadioButton3.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton3.toolTipText")); // NOI18N timeRadioButton2.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton2.text")); // NOI18N timeRadioButton2.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton2.toolTipText")); // NOI18N timeLabel.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeLabel.text")); // NOI18N timeLabel.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeLabel.toolTipText")); // NOI18N timeRadioButton1.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton1.text")); // NOI18N timeRadioButton1.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton1.toolTipText")); // NOI18N timeRadioButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { timeRadioButton1ActionPerformed(evt); } }); javax.swing.GroupLayout timePanelLayout = new javax.swing.GroupLayout(timePanel); timePanel.setLayout(timePanelLayout); timePanelLayout.setHorizontalGroup( timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(timePanelLayout.createSequentialGroup() .addContainerGap() .addGroup(timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, timePanelLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(timeRadioButton1)) .addGroup(timePanelLayout.createSequentialGroup() .addGroup(timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(timeLabel) .addComponent(timeRadioButton2) .addComponent(timeRadioButton3)) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); timePanelLayout.setVerticalGroup( timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(timePanelLayout.createSequentialGroup() - .addGap(0, 0, Short.MAX_VALUE) + .addGap(0, 4, Short.MAX_VALUE) .addComponent(timeLabel) .addGap(0, 0, 0) .addComponent(timeRadioButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(timeRadioButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(timeRadioButton3) .addGap(2, 2, 2)) ); processUnallocPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160))); processUnallocCheckbox.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.processUnallocCheckbox.text")); // NOI18N + processUnallocCheckbox.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.processUnallocCheckbox.toolTipText")); // NOI18N processUnallocCheckbox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { processUnallocCheckboxActionPerformed(evt); } }); javax.swing.GroupLayout processUnallocPanelLayout = new javax.swing.GroupLayout(processUnallocPanel); processUnallocPanel.setLayout(processUnallocPanelLayout); processUnallocPanelLayout.setHorizontalGroup( processUnallocPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(processUnallocPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(processUnallocCheckbox) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); processUnallocPanelLayout.setVerticalGroup( processUnallocPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(processUnallocPanelLayout.createSequentialGroup() .addComponent(processUnallocCheckbox) .addGap(0, 2, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(servicesScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(timePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(processUnallocPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 235, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(servicesScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(processUnallocPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(timePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents private void advancedButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_advancedButtonActionPerformed final AdvancedConfigurationDialog dialog = new AdvancedConfigurationDialog(); dialog.addApplyButtonListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dialog.close(); currentService.saveAdvancedConfiguration(); reloadSimpleConfiguration(); } }); dialog.display(currentService.getAdvancedConfiguration()); }//GEN-LAST:event_advancedButtonActionPerformed private void timeRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_timeRadioButton1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_timeRadioButton1ActionPerformed private void processUnallocCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_processUnallocCheckboxActionPerformed // TODO add your handling code here: }//GEN-LAST:event_processUnallocCheckboxActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton advancedButton; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JSeparator jSeparator2; private javax.swing.JCheckBox processUnallocCheckbox; private javax.swing.JPanel processUnallocPanel; private javax.swing.JScrollPane servicesScrollPane; private javax.swing.JTable servicesTable; private javax.swing.JPanel simplePanel; private javax.swing.ButtonGroup timeGroup; private javax.swing.JLabel timeLabel; private javax.swing.JPanel timePanel; private javax.swing.JRadioButton timeRadioButton1; private javax.swing.JRadioButton timeRadioButton2; private javax.swing.JRadioButton timeRadioButton3; // End of variables declaration//GEN-END:variables private class ServicesTableModel extends AbstractTableModel { @Override public int getRowCount() { return services.size(); } @Override public int getColumnCount() { return 2; } @Override public Object getValueAt(int rowIndex, int columnIndex) { String name = services.get(rowIndex).getName(); if (columnIndex == 0) { return serviceStates.get(name); } else { return name; } } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return columnIndex == 0; } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { if (columnIndex == 0) { serviceStates.put((String) getValueAt(rowIndex, 1), (Boolean) aValue); } } @Override public Class<?> getColumnClass(int c) { return getValueAt(0, c).getClass(); } } List<IngestServiceAbstract> getServicesToStart() { List<IngestServiceAbstract> servicesToStart = new ArrayList<IngestServiceAbstract>(); for (IngestServiceAbstract service : services) { boolean serviceEnabled = serviceStates.get(service.getName()); if (serviceEnabled) { servicesToStart.add(service); } } return servicesToStart; } private boolean timeSelectionEnabled() { return timeRadioButton1.isEnabled() && timeRadioButton2.isEnabled() && timeRadioButton3.isEnabled(); } private boolean processUnallocSpaceEnabled() { return processUnallocCheckbox.isEnabled(); } private UpdateFrequency getSelectedTimeValue() { if (timeRadioButton1.isSelected()) { return UpdateFrequency.FAST; } else if (timeRadioButton2.isSelected()) { return UpdateFrequency.AVG; } else { return UpdateFrequency.SLOW; } } private void reloadSimpleConfiguration() { simplePanel.removeAll(); if (currentService.hasSimpleConfiguration()) { simplePanel.add(currentService.getSimpleConfiguration()); } simplePanel.revalidate(); simplePanel.repaint(); } /** * To be called whenever the next, close, or start buttons are pressed. * */ @Override public void save() { if (currentService != null && currentService.hasSimpleConfiguration()) { currentService.saveSimpleConfiguration(); } } @Override public JPanel getIngestConfigPanel() { return this; } @Override public void setImage(Image image) { this.image = image; } @Override public void start() { //pick the services List<IngestServiceAbstract> servicesToStart = getServicesToStart(); if (!servicesToStart.isEmpty()) { manager.execute(servicesToStart, image); } //update ingest freq. refresh if (timeSelectionEnabled()) { manager.setUpdateFrequency(getSelectedTimeValue()); } //update ingest proc. unalloc space if (processUnallocSpaceEnabled() ) { manager.setProcessUnallocSpace(processUnallocCheckbox.isSelected()); } } @Override public boolean isIngestRunning() { return manager.isIngestRunning(); } /** * Custom cell renderer for tooltips with service description */ private class ServiceTableRenderer extends DefaultTableCellRenderer { @Override public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (column == 1) { //String serviceName = (String) table.getModel().getValueAt(row, column); IngestServiceAbstract service = services.get(row); String serviceDescr = service.getDescription(); setToolTipText(serviceDescr); } return this; } } }
false
true
private void initComponents() { timeGroup = new javax.swing.ButtonGroup(); servicesScrollPane = new javax.swing.JScrollPane(); servicesTable = new javax.swing.JTable(); jPanel1 = new javax.swing.JPanel(); advancedButton = new javax.swing.JButton(); jSeparator2 = new javax.swing.JSeparator(); jScrollPane1 = new javax.swing.JScrollPane(); simplePanel = new javax.swing.JPanel(); timePanel = new javax.swing.JPanel(); timeRadioButton3 = new javax.swing.JRadioButton(); timeRadioButton2 = new javax.swing.JRadioButton(); timeLabel = new javax.swing.JLabel(); timeRadioButton1 = new javax.swing.JRadioButton(); processUnallocPanel = new javax.swing.JPanel(); processUnallocCheckbox = new javax.swing.JCheckBox(); setPreferredSize(new java.awt.Dimension(522, 257)); servicesScrollPane.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160))); servicesScrollPane.setPreferredSize(new java.awt.Dimension(160, 160)); servicesTable.setBackground(new java.awt.Color(240, 240, 240)); servicesTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); servicesTable.setShowHorizontalLines(false); servicesTable.setShowVerticalLines(false); servicesScrollPane.setViewportView(servicesTable); jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160))); jPanel1.setPreferredSize(new java.awt.Dimension(338, 257)); advancedButton.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.advancedButton.text")); // NOI18N advancedButton.setEnabled(false); advancedButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { advancedButtonActionPerformed(evt); } }); jScrollPane1.setBorder(null); jScrollPane1.setPreferredSize(new java.awt.Dimension(250, 180)); simplePanel.setLayout(new javax.swing.BoxLayout(simplePanel, javax.swing.BoxLayout.PAGE_AXIS)); jScrollPane1.setViewportView(simplePanel); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE) .addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(245, Short.MAX_VALUE) .addComponent(advancedButton) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(advancedButton) .addContainerGap()) ); timePanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160))); timeRadioButton3.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton3.text")); // NOI18N timeRadioButton3.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton3.toolTipText")); // NOI18N timeRadioButton2.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton2.text")); // NOI18N timeRadioButton2.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton2.toolTipText")); // NOI18N timeLabel.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeLabel.text")); // NOI18N timeLabel.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeLabel.toolTipText")); // NOI18N timeRadioButton1.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton1.text")); // NOI18N timeRadioButton1.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton1.toolTipText")); // NOI18N timeRadioButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { timeRadioButton1ActionPerformed(evt); } }); javax.swing.GroupLayout timePanelLayout = new javax.swing.GroupLayout(timePanel); timePanel.setLayout(timePanelLayout); timePanelLayout.setHorizontalGroup( timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(timePanelLayout.createSequentialGroup() .addContainerGap() .addGroup(timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, timePanelLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(timeRadioButton1)) .addGroup(timePanelLayout.createSequentialGroup() .addGroup(timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(timeLabel) .addComponent(timeRadioButton2) .addComponent(timeRadioButton3)) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); timePanelLayout.setVerticalGroup( timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(timePanelLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(timeLabel) .addGap(0, 0, 0) .addComponent(timeRadioButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(timeRadioButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(timeRadioButton3) .addGap(2, 2, 2)) ); processUnallocPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160))); processUnallocCheckbox.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.processUnallocCheckbox.text")); // NOI18N processUnallocCheckbox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { processUnallocCheckboxActionPerformed(evt); } }); javax.swing.GroupLayout processUnallocPanelLayout = new javax.swing.GroupLayout(processUnallocPanel); processUnallocPanel.setLayout(processUnallocPanelLayout); processUnallocPanelLayout.setHorizontalGroup( processUnallocPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(processUnallocPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(processUnallocCheckbox) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); processUnallocPanelLayout.setVerticalGroup( processUnallocPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(processUnallocPanelLayout.createSequentialGroup() .addComponent(processUnallocCheckbox) .addGap(0, 2, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(servicesScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(timePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(processUnallocPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 235, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(servicesScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(processUnallocPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(timePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { timeGroup = new javax.swing.ButtonGroup(); servicesScrollPane = new javax.swing.JScrollPane(); servicesTable = new javax.swing.JTable(); jPanel1 = new javax.swing.JPanel(); advancedButton = new javax.swing.JButton(); jSeparator2 = new javax.swing.JSeparator(); jScrollPane1 = new javax.swing.JScrollPane(); simplePanel = new javax.swing.JPanel(); timePanel = new javax.swing.JPanel(); timeRadioButton3 = new javax.swing.JRadioButton(); timeRadioButton2 = new javax.swing.JRadioButton(); timeLabel = new javax.swing.JLabel(); timeRadioButton1 = new javax.swing.JRadioButton(); processUnallocPanel = new javax.swing.JPanel(); processUnallocCheckbox = new javax.swing.JCheckBox(); setPreferredSize(new java.awt.Dimension(522, 257)); servicesScrollPane.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160))); servicesScrollPane.setPreferredSize(new java.awt.Dimension(160, 160)); servicesTable.setBackground(new java.awt.Color(240, 240, 240)); servicesTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); servicesTable.setShowHorizontalLines(false); servicesTable.setShowVerticalLines(false); servicesScrollPane.setViewportView(servicesTable); jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160))); jPanel1.setPreferredSize(new java.awt.Dimension(338, 257)); advancedButton.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.advancedButton.text")); // NOI18N advancedButton.setEnabled(false); advancedButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { advancedButtonActionPerformed(evt); } }); jScrollPane1.setBorder(null); jScrollPane1.setPreferredSize(new java.awt.Dimension(250, 180)); simplePanel.setLayout(new javax.swing.BoxLayout(simplePanel, javax.swing.BoxLayout.PAGE_AXIS)); jScrollPane1.setViewportView(simplePanel); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE) .addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(245, Short.MAX_VALUE) .addComponent(advancedButton) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(advancedButton) .addContainerGap()) ); timePanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160))); timeRadioButton3.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton3.text")); // NOI18N timeRadioButton3.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton3.toolTipText")); // NOI18N timeRadioButton2.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton2.text")); // NOI18N timeRadioButton2.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton2.toolTipText")); // NOI18N timeLabel.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeLabel.text")); // NOI18N timeLabel.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeLabel.toolTipText")); // NOI18N timeRadioButton1.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton1.text")); // NOI18N timeRadioButton1.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton1.toolTipText")); // NOI18N timeRadioButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { timeRadioButton1ActionPerformed(evt); } }); javax.swing.GroupLayout timePanelLayout = new javax.swing.GroupLayout(timePanel); timePanel.setLayout(timePanelLayout); timePanelLayout.setHorizontalGroup( timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(timePanelLayout.createSequentialGroup() .addContainerGap() .addGroup(timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, timePanelLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(timeRadioButton1)) .addGroup(timePanelLayout.createSequentialGroup() .addGroup(timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(timeLabel) .addComponent(timeRadioButton2) .addComponent(timeRadioButton3)) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); timePanelLayout.setVerticalGroup( timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(timePanelLayout.createSequentialGroup() .addGap(0, 4, Short.MAX_VALUE) .addComponent(timeLabel) .addGap(0, 0, 0) .addComponent(timeRadioButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(timeRadioButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(timeRadioButton3) .addGap(2, 2, 2)) ); processUnallocPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160))); processUnallocCheckbox.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.processUnallocCheckbox.text")); // NOI18N processUnallocCheckbox.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.processUnallocCheckbox.toolTipText")); // NOI18N processUnallocCheckbox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { processUnallocCheckboxActionPerformed(evt); } }); javax.swing.GroupLayout processUnallocPanelLayout = new javax.swing.GroupLayout(processUnallocPanel); processUnallocPanel.setLayout(processUnallocPanelLayout); processUnallocPanelLayout.setHorizontalGroup( processUnallocPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(processUnallocPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(processUnallocCheckbox) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); processUnallocPanelLayout.setVerticalGroup( processUnallocPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(processUnallocPanelLayout.createSequentialGroup() .addComponent(processUnallocCheckbox) .addGap(0, 2, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(servicesScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(timePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(processUnallocPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 235, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(servicesScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(processUnallocPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(timePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents
diff --git a/src/net/progval/android/andquote/QuoteActivity.java b/src/net/progval/android/andquote/QuoteActivity.java index d09d1c6..709db1d 100644 --- a/src/net/progval/android/andquote/QuoteActivity.java +++ b/src/net/progval/android/andquote/QuoteActivity.java @@ -1,141 +1,140 @@ package net.progval.android.andquote; import net.progval.android.andquote.utils.OpenQuoteApi; import android.app.Activity; import android.util.Log; import android.text.Html; import android.os.Bundle; import android.view.View; import android.widget.Toast; import android.webkit.WebView; import android.widget.TextView; import android.widget.ScrollView; import android.widget.LinearLayout; import android.content.SharedPreferences; import android.preference.PreferenceManager; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; public class QuoteActivity extends Activity { private static SharedPreferences settings; private LinearLayout layout; private OpenQuoteApi api; private SiteActivity.State state; private OpenQuoteApi.Quote quote; private TextView contentview, scoreview; private WebView imageview; private LinearLayout comments; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle extra = this.getIntent().getExtras(); QuoteActivity.settings = PreferenceManager.getDefaultSharedPreferences(this); this.state = new SiteActivity.State(); this.state.site_id = extra.getString("site_id"); this.state.site_name = extra.getString("site_name"); this.quote = OpenQuoteApi.Quote.unserialize(extra.getString("quote")); - Log.d("AndQuote", String.format("%d", this.quote.getId())); this.setTitle(this.state.site_name + " - " + this.quote.getId()); this.api = new OpenQuoteApi(this.settings.getString("api.url", "")); LinearLayout layout = new LinearLayout(this); - if (quote.getImageUrl() != null) { + if (!quote.getImageUrl().equals("null")) { this.layout = layout; this.setContentView(layout); } else { ScrollView scrollview = new ScrollView(this); layout.addView(scrollview); this.setContentView(layout); this.layout = new LinearLayout(this); scrollview.addView(this.layout); } this.layout.setOrientation(this.layout.VERTICAL); this.contentview = new TextView(this); this.contentview.setText(Html.fromHtml(this.quote.getContent())); this.layout.addView(this.contentview); this.scoreview = new TextView(this); this.scoreview.setText(this.quote.getScore()); this.layout.addView(this.scoreview); this.fetchExtraData(); } private void fetchExtraData() { class QuoteLoader implements OpenQuoteApi.ProgressListener { private OpenQuoteApi api; private TextView scoreview; public QuoteLoader(OpenQuoteApi api, TextView scoreview) { this.api = api; this.scoreview = scoreview; } public void onProgressUpdate(int progress) {} public void onFail(int status_message) { Toast.makeText(QuoteActivity.this, status_message, Toast.LENGTH_LONG).show(); } public void onSuccess(String file) { try { JSONObject object = (JSONObject) new JSONTokener(file).nextValue(); OpenQuoteApi.Quote quote = new OpenQuoteApi.Quote((JSONObject) object.get("quote")); QuoteActivity.this.setQuote(quote); if (quote.getAuthor() != null) this.scoreview.setText(quote.getScore() + " -- " + quote.getAuthor()); QuoteActivity.this.renderComments(OpenQuoteApi.Comment.parseComments((JSONArray) object.get("comments"))); if (quote.getImageUrl() != null) { QuoteActivity.this.setImage(quote.getImageUrl()); } } catch (JSONException e) { e.printStackTrace(); } } } this.api.safeGet(new QuoteLoader(this.api, this.scoreview), String.format("/%s/quotes/show/%d/", this.state.site_id, this.quote.getId())); } public void setQuote(OpenQuoteApi.Quote quote) { this.quote = quote; } public void setImage(String url) { this.imageview = new WebView(this); this.imageview.loadUrl(url); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT); this.imageview.setLayoutParams(params); this.imageview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); this.setContentView(this.layout); // Kick the scrollview out this.layout.addView(this.imageview); } public void renderComments(OpenQuoteApi.Comment[] comments) { this.comments = new LinearLayout(this); this.comments.setOrientation(this.comments.VERTICAL); this.layout.addView(this.comments); this.renderComments(comments, this.comments); } public void renderComments(OpenQuoteApi.Comment[] comments, LinearLayout layout) { for (int i=0; i<comments.length; i++) this.renderComment(comments[i], layout); } public void renderComment(OpenQuoteApi.Comment comment, LinearLayout layout) { TextView textview = new TextView(this); textview.setText(comment.getContent()); layout.addView(textview); LinearLayout repliesLayout = new LinearLayout(this); layout.setPadding(20, 0, 0, 0); layout.addView(repliesLayout); repliesLayout.setOrientation(this.layout.VERTICAL); this.renderComments(comment.getReplies(), repliesLayout); } }
false
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle extra = this.getIntent().getExtras(); QuoteActivity.settings = PreferenceManager.getDefaultSharedPreferences(this); this.state = new SiteActivity.State(); this.state.site_id = extra.getString("site_id"); this.state.site_name = extra.getString("site_name"); this.quote = OpenQuoteApi.Quote.unserialize(extra.getString("quote")); Log.d("AndQuote", String.format("%d", this.quote.getId())); this.setTitle(this.state.site_name + " - " + this.quote.getId()); this.api = new OpenQuoteApi(this.settings.getString("api.url", "")); LinearLayout layout = new LinearLayout(this); if (quote.getImageUrl() != null) { this.layout = layout; this.setContentView(layout); } else { ScrollView scrollview = new ScrollView(this); layout.addView(scrollview); this.setContentView(layout); this.layout = new LinearLayout(this); scrollview.addView(this.layout); } this.layout.setOrientation(this.layout.VERTICAL); this.contentview = new TextView(this); this.contentview.setText(Html.fromHtml(this.quote.getContent())); this.layout.addView(this.contentview); this.scoreview = new TextView(this); this.scoreview.setText(this.quote.getScore()); this.layout.addView(this.scoreview); this.fetchExtraData(); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle extra = this.getIntent().getExtras(); QuoteActivity.settings = PreferenceManager.getDefaultSharedPreferences(this); this.state = new SiteActivity.State(); this.state.site_id = extra.getString("site_id"); this.state.site_name = extra.getString("site_name"); this.quote = OpenQuoteApi.Quote.unserialize(extra.getString("quote")); this.setTitle(this.state.site_name + " - " + this.quote.getId()); this.api = new OpenQuoteApi(this.settings.getString("api.url", "")); LinearLayout layout = new LinearLayout(this); if (!quote.getImageUrl().equals("null")) { this.layout = layout; this.setContentView(layout); } else { ScrollView scrollview = new ScrollView(this); layout.addView(scrollview); this.setContentView(layout); this.layout = new LinearLayout(this); scrollview.addView(this.layout); } this.layout.setOrientation(this.layout.VERTICAL); this.contentview = new TextView(this); this.contentview.setText(Html.fromHtml(this.quote.getContent())); this.layout.addView(this.contentview); this.scoreview = new TextView(this); this.scoreview.setText(this.quote.getScore()); this.layout.addView(this.scoreview); this.fetchExtraData(); }
diff --git a/grib/src/main/java/ucar/nc2/grib/GribConverterUtility.java b/grib/src/main/java/ucar/nc2/grib/GribConverterUtility.java index 44fff72e8..3c025f9a4 100644 --- a/grib/src/main/java/ucar/nc2/grib/GribConverterUtility.java +++ b/grib/src/main/java/ucar/nc2/grib/GribConverterUtility.java @@ -1,78 +1,78 @@ package ucar.nc2.grib; /** * Created with IntelliJ IDEA. * User: madry * Date: 3/21/13 * Time: 2:37 PM * To change this template use File | Settings | File Templates. */ import ucar.nc2.dt.GridDataset; import ucar.nc2.grib.GribVariableRenamer; import java.io.IOException; import java.util.List; public class GribConverterUtility { public static void main(final String[] args) { String usage = "usage: ucar.nc2.dataset.GribConverterUtility -grib1|-grib2 <fileIn> <oldGribName> [-matchNCEP]"; String grbFile = null; // declare a grbFile filename String grbType = null; // declare a grbFile type - should be grib1 or grib2 String oldGribName = null; // declare the old Grib Variable Name Boolean matchNCEP = false; // don't default to matching NCEP if (args.length == 3 || args.length == 4) { String s = args[0]; if (s.equalsIgnoreCase("-grib1")) { grbType = "grib1"; } else if (s.equalsIgnoreCase("-grib2")) { grbType = "grib2"; } else { System.out.println(usage); System.exit(0); } grbFile = args[1]; oldGribName = args[2]; if (args.length == 4) { matchNCEP = true; // could be any fourth command line token, but assume this is what the user means } } else { System.out.println(usage); System.exit(0); } try { GribVariableRenamer r = null; GridDataset gds = ucar.nc2.dt.grid.GridDataset.open(grbFile); r = new GribVariableRenamer(); List result = null; if (grbType.equalsIgnoreCase("grib1")) { if (matchNCEP) { result = r.matchNcepNames(gds, oldGribName); } else { result = r.getMappedNamesGrib1(oldGribName); } } else { if (matchNCEP) { result = r.matchNcepNames(gds, oldGribName); } else { result = r.getMappedNamesGrib2(oldGribName); } } if (null == result) { System.out.println("Could not find \"" + oldGribName + "\" in " + grbFile); System.out.println("-Note that variable names are case sensitive"); } else { System.out.println(result); } } catch (IOException e) { System.out.println("oops..."); - System.out.println(e); +// System.out.println(e); System.out.println("Check filename " + grbFile); } catch (Exception e) { System.out.println("oops..."); System.out.println(e); } } }
true
true
public static void main(final String[] args) { String usage = "usage: ucar.nc2.dataset.GribConverterUtility -grib1|-grib2 <fileIn> <oldGribName> [-matchNCEP]"; String grbFile = null; // declare a grbFile filename String grbType = null; // declare a grbFile type - should be grib1 or grib2 String oldGribName = null; // declare the old Grib Variable Name Boolean matchNCEP = false; // don't default to matching NCEP if (args.length == 3 || args.length == 4) { String s = args[0]; if (s.equalsIgnoreCase("-grib1")) { grbType = "grib1"; } else if (s.equalsIgnoreCase("-grib2")) { grbType = "grib2"; } else { System.out.println(usage); System.exit(0); } grbFile = args[1]; oldGribName = args[2]; if (args.length == 4) { matchNCEP = true; // could be any fourth command line token, but assume this is what the user means } } else { System.out.println(usage); System.exit(0); } try { GribVariableRenamer r = null; GridDataset gds = ucar.nc2.dt.grid.GridDataset.open(grbFile); r = new GribVariableRenamer(); List result = null; if (grbType.equalsIgnoreCase("grib1")) { if (matchNCEP) { result = r.matchNcepNames(gds, oldGribName); } else { result = r.getMappedNamesGrib1(oldGribName); } } else { if (matchNCEP) { result = r.matchNcepNames(gds, oldGribName); } else { result = r.getMappedNamesGrib2(oldGribName); } } if (null == result) { System.out.println("Could not find \"" + oldGribName + "\" in " + grbFile); System.out.println("-Note that variable names are case sensitive"); } else { System.out.println(result); } } catch (IOException e) { System.out.println("oops..."); System.out.println(e); System.out.println("Check filename " + grbFile); } catch (Exception e) { System.out.println("oops..."); System.out.println(e); } }
public static void main(final String[] args) { String usage = "usage: ucar.nc2.dataset.GribConverterUtility -grib1|-grib2 <fileIn> <oldGribName> [-matchNCEP]"; String grbFile = null; // declare a grbFile filename String grbType = null; // declare a grbFile type - should be grib1 or grib2 String oldGribName = null; // declare the old Grib Variable Name Boolean matchNCEP = false; // don't default to matching NCEP if (args.length == 3 || args.length == 4) { String s = args[0]; if (s.equalsIgnoreCase("-grib1")) { grbType = "grib1"; } else if (s.equalsIgnoreCase("-grib2")) { grbType = "grib2"; } else { System.out.println(usage); System.exit(0); } grbFile = args[1]; oldGribName = args[2]; if (args.length == 4) { matchNCEP = true; // could be any fourth command line token, but assume this is what the user means } } else { System.out.println(usage); System.exit(0); } try { GribVariableRenamer r = null; GridDataset gds = ucar.nc2.dt.grid.GridDataset.open(grbFile); r = new GribVariableRenamer(); List result = null; if (grbType.equalsIgnoreCase("grib1")) { if (matchNCEP) { result = r.matchNcepNames(gds, oldGribName); } else { result = r.getMappedNamesGrib1(oldGribName); } } else { if (matchNCEP) { result = r.matchNcepNames(gds, oldGribName); } else { result = r.getMappedNamesGrib2(oldGribName); } } if (null == result) { System.out.println("Could not find \"" + oldGribName + "\" in " + grbFile); System.out.println("-Note that variable names are case sensitive"); } else { System.out.println(result); } } catch (IOException e) { System.out.println("oops..."); // System.out.println(e); System.out.println("Check filename " + grbFile); } catch (Exception e) { System.out.println("oops..."); System.out.println(e); } }
diff --git a/src/org/mozilla/javascript/Parser.java b/src/org/mozilla/javascript/Parser.java index 578197c1..da478a7a 100644 --- a/src/org/mozilla/javascript/Parser.java +++ b/src/org/mozilla/javascript/Parser.java @@ -1,3762 +1,3762 @@ /* -*- 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): * Mike Ang * Igor Bukanov * Yuh-Ruey Chen * Ethan Hugg * Bob Jervis * Terry Lucas * Mike McCabe * Milen Nankov * Norris Boyd * Steve Yegge * * 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 org.mozilla.javascript.ast.*; // we use basically every class import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.HashSet; /** * This class implements the JavaScript parser.<p> * * It is based on the SpiderMonkey C source files jsparse.c and jsparse.h in the * jsref package.<p> * * The parser generates an {@link AstRoot} parse tree representing the source * code. No tree rewriting is permitted at this stage, so that the parse tree * is a faithful representation of the source for frontend processing tools and * IDEs.<p> * * This parser implementation is not intended to be reused after a parse * finishes, and will throw an IllegalStateException() if invoked again.<p> * * @see TokenStream * * @author Mike McCabe * @author Brendan Eich */ public class Parser { /** * Maximum number of allowed function or constructor arguments, * to follow SpiderMonkey. */ public static final int ARGC_LIMIT = 1 << 16; // TokenInformation flags : currentFlaggedToken stores them together // with token type final static int CLEAR_TI_MASK = 0xFFFF, // mask to clear token information bits TI_AFTER_EOL = 1 << 16, // first token of the source line TI_CHECK_LABEL = 1 << 17; // indicates to check for label CompilerEnvirons compilerEnv; private ErrorReporter errorReporter; private IdeErrorReporter errorCollector; private String sourceURI; private char[] sourceChars; boolean calledByCompileFunction; // ugly - set directly by Context private boolean parseFinished; // set when finished to prevent reuse private TokenStream ts; private int currentFlaggedToken = Token.EOF; private int currentToken; private int syntaxErrorCount; private List<Comment> scannedComments; private String currentJsDocComment; protected int nestingOfFunction; private LabeledStatement currentLabel; private boolean inDestructuringAssignment; protected boolean inUseStrictDirective; // The following are per function variables and should be saved/restored // during function parsing. See PerFunctionVariables class below. ScriptNode currentScriptOrFn; Scope currentScope; int nestingOfWith; private int endFlags; private boolean inForInit; // bound temporarily during forStatement() private Map<String,LabeledStatement> labelSet; private List<Loop> loopSet; private List<Jump> loopAndSwitchSet; // end of per function variables // Lacking 2-token lookahead, labels become a problem. // These vars store the token info of the last matched name, // iff it wasn't the last matched token. private int prevNameTokenStart; private String prevNameTokenString = ""; private int prevNameTokenLineno; // Exception to unwind private static class ParserException extends RuntimeException { static final long serialVersionUID = 5882582646773765630L; } public Parser() { this(new CompilerEnvirons()); } public Parser(CompilerEnvirons compilerEnv) { this(compilerEnv, compilerEnv.getErrorReporter()); } public Parser(CompilerEnvirons compilerEnv, ErrorReporter errorReporter) { this.compilerEnv = compilerEnv; this.errorReporter = errorReporter; if (errorReporter instanceof IdeErrorReporter) { errorCollector = (IdeErrorReporter)errorReporter; } } // Add a strict warning on the last matched token. void addStrictWarning(String messageId, String messageArg) { int beg = -1, end = -1; if (ts != null) { beg = ts.tokenBeg; end = ts.tokenEnd - ts.tokenBeg; } addStrictWarning(messageId, messageArg, beg, end); } void addStrictWarning(String messageId, String messageArg, int position, int length) { if (compilerEnv.isStrictMode()) addWarning(messageId, messageArg, position, length); } void addWarning(String messageId, String messageArg) { int beg = -1, end = -1; if (ts != null) { beg = ts.tokenBeg; end = ts.tokenEnd - ts.tokenBeg; } addWarning(messageId, messageArg, beg, end); } void addWarning(String messageId, int position, int length) { addWarning(messageId, null, position, length); } void addWarning(String messageId, String messageArg, int position, int length) { String message = lookupMessage(messageId, messageArg); if (compilerEnv.reportWarningAsError()) { addError(messageId, messageArg, position, length); } else if (errorCollector != null) { errorCollector.warning(message, sourceURI, position, length); } else { errorReporter.warning(message, sourceURI, ts.getLineno(), ts.getLine(), ts.getOffset()); } } void addError(String messageId) { addError(messageId, ts.tokenBeg, ts.tokenEnd - ts.tokenBeg); } void addError(String messageId, int position, int length) { addError(messageId, null, position, length); } void addError(String messageId, String messageArg) { addError(messageId, messageArg, ts.tokenBeg, ts.tokenEnd - ts.tokenBeg); } void addError(String messageId, String messageArg, int position, int length) { ++syntaxErrorCount; String message = lookupMessage(messageId, messageArg); if (errorCollector != null) { errorCollector.error(message, sourceURI, position, length); } else { int lineno = 1, offset = 1; String line = ""; if (ts != null) { // happens in some regression tests lineno = ts.getLineno(); line = ts.getLine(); offset = ts.getOffset(); } errorReporter.error(message, sourceURI, lineno, line, offset); } } String lookupMessage(String messageId) { return lookupMessage(messageId, null); } String lookupMessage(String messageId, String messageArg) { return messageArg == null ? ScriptRuntime.getMessage0(messageId) : ScriptRuntime.getMessage1(messageId, messageArg); } void reportError(String messageId) { reportError(messageId, null); } void reportError(String messageId, String messageArg) { if (ts == null) { // happens in some regression tests reportError(messageId, messageArg, 1, 1); } else { reportError(messageId, messageArg, ts.tokenBeg, ts.tokenEnd - ts.tokenBeg); } } void reportError(String messageId, int position, int length) { reportError(messageId, null, position, length); } void reportError(String messageId, String messageArg, int position, int length) { addError(messageId, position, length); if (!compilerEnv.recoverFromErrors()) { throw new ParserException(); } } // Computes the absolute end offset of node N. // Use with caution! Assumes n.getPosition() is -absolute-, which // is only true before the node is added to its parent. private int getNodeEnd(AstNode n) { return n.getPosition() + n.getLength(); } private void recordComment(int lineno) { if (scannedComments == null) { scannedComments = new ArrayList<Comment>(); } String comment = ts.getAndResetCurrentComment(); if (ts.commentType == Token.CommentType.JSDOC && compilerEnv.isRecordingLocalJsDocComments()) { currentJsDocComment = comment; } Comment commentNode = new Comment(ts.tokenBeg, ts.getTokenLength(), ts.commentType, comment); commentNode.setLineno(lineno); scannedComments.add(commentNode); } private String getAndResetJsDoc() { String saved = currentJsDocComment; currentJsDocComment = null; return saved; } // Returns the next token without consuming it. // If previous token was consumed, calls scanner to get new token. // If previous token was -not- consumed, returns it (idempotent). // // This function will not return a newline (Token.EOL - instead, it // gobbles newlines until it finds a non-newline token, and flags // that token as appearing just after a newline. // // This function will also not return a Token.COMMENT. Instead, it // records comments in the scannedComments list. If the token // returned by this function immediately follows a jsdoc comment, // the token is flagged as such. // // Note that this function always returned the un-flagged token! // The flags, if any, are saved in currentFlaggedToken. private int peekToken() throws IOException { // By far the most common case: last token hasn't been consumed, // so return already-peeked token. if (currentFlaggedToken != Token.EOF) { return currentToken; } int lineno = ts.getLineno(); int tt = ts.getToken(); boolean sawEOL = false; // process comments and whitespace while (tt == Token.EOL || tt == Token.COMMENT) { if (tt == Token.EOL) { lineno++; sawEOL = true; } else { sawEOL = false; if (compilerEnv.isRecordingComments()) { recordComment(lineno); } } tt = ts.getToken(); } currentToken = tt; currentFlaggedToken = tt | (sawEOL ? TI_AFTER_EOL : 0); return currentToken; // return unflagged token } private int peekFlaggedToken() throws IOException { peekToken(); return currentFlaggedToken; } private void consumeToken() { currentFlaggedToken = Token.EOF; } private int nextToken() throws IOException { int tt = peekToken(); consumeToken(); return tt; } private int nextFlaggedToken() throws IOException { peekToken(); int ttFlagged = currentFlaggedToken; consumeToken(); return ttFlagged; } private boolean matchToken(int toMatch) throws IOException { if (peekToken() != toMatch) { return false; } consumeToken(); return true; } // Returns Token.EOL if the current token follows a newline, else returns // the current token. Used in situations where we don't consider certain // token types valid if they are preceded by a newline. One example is the // postfix ++ or -- operator, which has to be on the same line as its // operand. private int peekTokenOrEOL() throws IOException { int tt = peekToken(); // Check for last peeked token flags if ((currentFlaggedToken & TI_AFTER_EOL) != 0) { tt = Token.EOL; } return tt; } private boolean mustMatchToken(int toMatch, String messageId) throws IOException { return mustMatchToken(toMatch, messageId, ts.tokenBeg, ts.tokenEnd - ts.tokenBeg); } private boolean mustMatchToken(int toMatch, String msgId, int pos, int len) throws IOException { if (matchToken(toMatch)) { return true; } reportError(msgId, pos, len); return false; } private void mustHaveXML() { if (!compilerEnv.isXmlAvailable()) { reportError("msg.XML.not.available"); } } public boolean eof() { return ts.eof(); } boolean insideFunction() { return nestingOfFunction != 0; } void pushScope(Scope scope) { Scope parent = scope.getParentScope(); // During codegen, parent scope chain may already be initialized, // in which case we just need to set currentScope variable. if (parent != null) { if (parent != currentScope) codeBug(); } else { currentScope.addChildScope(scope); } currentScope = scope; } void popScope() { currentScope = currentScope.getParentScope(); } private void enterLoop(Loop loop) { if (loopSet == null) loopSet = new ArrayList<Loop>(); loopSet.add(loop); if (loopAndSwitchSet == null) loopAndSwitchSet = new ArrayList<Jump>(); loopAndSwitchSet.add(loop); pushScope(loop); if (currentLabel != null) { currentLabel.setStatement(loop); currentLabel.getFirstLabel().setLoop(loop); // This is the only time during parsing that we set a node's parent // before parsing the children. In order for the child node offsets // to be correct, we adjust the loop's reported position back to an // absolute source offset, and restore it when we call exitLoop(). loop.setRelative(-currentLabel.getPosition()); } } private void exitLoop() { Loop loop = loopSet.remove(loopSet.size() - 1); loopAndSwitchSet.remove(loopAndSwitchSet.size() - 1); if (loop.getParent() != null) { // see comment in enterLoop loop.setRelative(loop.getParent().getPosition()); } popScope(); } private void enterSwitch(SwitchStatement node) { if (loopAndSwitchSet == null) loopAndSwitchSet = new ArrayList<Jump>(); loopAndSwitchSet.add(node); } private void exitSwitch() { loopAndSwitchSet.remove(loopAndSwitchSet.size() - 1); } /** * Builds a parse tree from the given source string. * * @return an {@link AstRoot} object representing the parsed program. If * the parse fails, {@code null} will be returned. (The parse failure will * result in a call to the {@link ErrorReporter} from * {@link CompilerEnvirons}.) */ public AstRoot parse(String sourceString, String sourceURI, int lineno) { if (parseFinished) throw new IllegalStateException("parser reused"); this.sourceURI = sourceURI; if (compilerEnv.isIdeMode()) { this.sourceChars = sourceString.toCharArray(); } this.ts = new TokenStream(this, null, sourceString, lineno); try { return parse(); } catch (IOException iox) { // Should never happen throw new IllegalStateException(); } finally { parseFinished = true; } } /** * Builds a parse tree from the given sourcereader. * @see #parse(String,String,int) * @throws IOException if the {@link Reader} encounters an error */ public AstRoot parse(Reader sourceReader, String sourceURI, int lineno) throws IOException { if (parseFinished) throw new IllegalStateException("parser reused"); if (compilerEnv.isIdeMode()) { return parse(readFully(sourceReader), sourceURI, lineno); } try { this.sourceURI = sourceURI; ts = new TokenStream(this, sourceReader, null, lineno); return parse(); } finally { parseFinished = true; } } private AstRoot parse() throws IOException { int pos = 0; AstRoot root = new AstRoot(pos); currentScope = currentScriptOrFn = root; int baseLineno = ts.lineno; // line number where source starts int end = pos; // in case source is empty boolean inDirectivePrologue = true; boolean savedStrictMode = inUseStrictDirective; // TODO: eval code should get strict mode from invoking code inUseStrictDirective = false; try { for (;;) { int tt = peekToken(); if (tt <= Token.EOF) { break; } AstNode n; if (tt == Token.FUNCTION) { consumeToken(); try { n = function(calledByCompileFunction ? FunctionNode.FUNCTION_EXPRESSION : FunctionNode.FUNCTION_STATEMENT); } catch (ParserException e) { break; } } else { n = statement(); if (inDirectivePrologue) { String directive = getDirective(n); if (directive == null) { inDirectivePrologue = false; } else if (directive.equals("use strict")) { inUseStrictDirective = true; root.setInStrictMode(true); } } } end = getNodeEnd(n); root.addChildToBack(n); n.setParent(root); } } catch (StackOverflowError ex) { String msg = lookupMessage("msg.too.deep.parser.recursion"); if (!compilerEnv.isIdeMode()) throw Context.reportRuntimeError(msg, sourceURI, ts.lineno, null, 0); } finally { inUseStrictDirective = savedStrictMode; } if (this.syntaxErrorCount != 0) { String msg = String.valueOf(this.syntaxErrorCount); msg = lookupMessage("msg.got.syntax.errors", msg); if (!compilerEnv.isIdeMode()) throw errorReporter.runtimeError(msg, sourceURI, baseLineno, null, 0); } // add comments to root in lexical order if (scannedComments != null) { // If we find a comment beyond end of our last statement or // function, extend the root bounds to the end of that comment. int last = scannedComments.size() - 1; end = Math.max(end, getNodeEnd(scannedComments.get(last))); for (Comment c : scannedComments) { root.addComment(c); } } root.setLength(end - pos); root.setSourceName(sourceURI); root.setBaseLineno(baseLineno); root.setEndLineno(ts.lineno); return root; } private AstNode parseFunctionBody() throws IOException { if (!matchToken(Token.LC)) { if (compilerEnv.getLanguageVersion() < Context.VERSION_1_8) { reportError("msg.no.brace.body"); } return parseFunctionBodyExpr(); } ++nestingOfFunction; int pos = ts.tokenBeg; Block pn = new Block(pos); // starts at LC position boolean inDirectivePrologue = true; boolean savedStrictMode = inUseStrictDirective; // Don't set 'inUseStrictDirective' to false: inherit strict mode. pn.setLineno(ts.lineno); try { bodyLoop: for (;;) { AstNode n; int tt = peekToken(); switch (tt) { case Token.ERROR: case Token.EOF: case Token.RC: break bodyLoop; case Token.FUNCTION: consumeToken(); n = function(FunctionNode.FUNCTION_STATEMENT); break; default: n = statement(); if (inDirectivePrologue) { String directive = getDirective(n); if (directive == null) { inDirectivePrologue = false; } else if (directive.equals("use strict")) { inUseStrictDirective = true; } } break; } pn.addStatement(n); } } catch (ParserException e) { // Ignore it } finally { --nestingOfFunction; inUseStrictDirective = savedStrictMode; } int end = ts.tokenEnd; getAndResetJsDoc(); if (mustMatchToken(Token.RC, "msg.no.brace.after.body")) end = ts.tokenEnd; pn.setLength(end - pos); return pn; } private String getDirective(AstNode n) { if (n instanceof ExpressionStatement) { AstNode e = ((ExpressionStatement) n).getExpression(); if (e instanceof StringLiteral) { return ((StringLiteral) e).getValue(); } } return null; } private void parseFunctionParams(FunctionNode fnNode) throws IOException { if (matchToken(Token.RP)) { fnNode.setRp(ts.tokenBeg - fnNode.getPosition()); return; } // Would prefer not to call createDestructuringAssignment until codegen, // but the symbol definitions have to happen now, before body is parsed. Map<String, Node> destructuring = null; Set<String> paramNames = new HashSet<String>(); do { int tt = peekToken(); if (tt == Token.LB || tt == Token.LC) { AstNode expr = destructuringPrimaryExpr(); markDestructuring(expr); fnNode.addParam(expr); // Destructuring assignment for parameters: add a dummy // parameter name, and add a statement to the body to initialize // variables from the destructuring assignment if (destructuring == null) { destructuring = new HashMap<String, Node>(); } String pname = currentScriptOrFn.getNextTempName(); defineSymbol(Token.LP, pname, false); destructuring.put(pname, expr); } else { if (mustMatchToken(Token.NAME, "msg.no.parm")) { fnNode.addParam(createNameNode()); String paramName = ts.getString(); defineSymbol(Token.LP, paramName); if (this.inUseStrictDirective) { if ("eval".equals(paramName) || "arguments".equals(paramName)) { reportError("msg.bad.id.strict", paramName); } if (paramNames.contains(paramName)) addError("msg.dup.param.strict", paramName); paramNames.add(paramName); } } else { fnNode.addParam(makeErrorNode()); } } } while (matchToken(Token.COMMA)); if (destructuring != null) { Node destructuringNode = new Node(Token.COMMA); // Add assignment helper for each destructuring parameter for (Map.Entry<String, Node> param: destructuring.entrySet()) { Node assign = createDestructuringAssignment(Token.VAR, param.getValue(), createName(param.getKey())); destructuringNode.addChildToBack(assign); } fnNode.putProp(Node.DESTRUCTURING_PARAMS, destructuringNode); } if (mustMatchToken(Token.RP, "msg.no.paren.after.parms")) { fnNode.setRp(ts.tokenBeg - fnNode.getPosition()); } } private AstNode parseFunctionBodyExpr() throws IOException { ++nestingOfFunction; int lineno = ts.getLineno(); ReturnStatement n = new ReturnStatement(lineno); n.putProp(Node.EXPRESSION_CLOSURE_PROP, Boolean.TRUE); try { n.setReturnValue(assignExpr()); } finally { --nestingOfFunction; } return n; } private FunctionNode function(int type) throws IOException { int syntheticType = type; int baseLineno = ts.lineno; // line number where source starts int functionSourceStart = ts.tokenBeg; // start of "function" kwd Name name = null; AstNode memberExprNode = null; if (matchToken(Token.NAME)) { name = createNameNode(true, Token.NAME); if (inUseStrictDirective) { String id = name.getIdentifier(); if ("eval".equals(id)|| "arguments".equals(id)) { reportError("msg.bad.id.strict", id); } } if (!matchToken(Token.LP)) { if (compilerEnv.isAllowMemberExprAsFunctionName()) { AstNode memberExprHead = name; name = null; memberExprNode = memberExprTail(false, memberExprHead); } mustMatchToken(Token.LP, "msg.no.paren.parms"); } } else if (matchToken(Token.LP)) { // Anonymous function: leave name as null } else { if (compilerEnv.isAllowMemberExprAsFunctionName()) { // Note that memberExpr can not start with '(' like // in function (1+2).toString(), because 'function (' already // processed as anonymous function memberExprNode = memberExpr(false); } mustMatchToken(Token.LP, "msg.no.paren.parms"); } int lpPos = currentToken == Token.LP ? ts.tokenBeg : -1; if (memberExprNode != null) { syntheticType = FunctionNode.FUNCTION_EXPRESSION; } if (syntheticType != FunctionNode.FUNCTION_EXPRESSION && name != null && name.length() > 0) { // Function statements define a symbol in the enclosing scope defineSymbol(Token.FUNCTION, name.getIdentifier()); } FunctionNode fnNode = new FunctionNode(functionSourceStart, name); fnNode.setFunctionType(type); if (lpPos != -1) fnNode.setLp(lpPos - functionSourceStart); if (insideFunction() || nestingOfWith > 0) { // 1. Nested functions are not affected by the dynamic scope flag // as dynamic scope is already a parent of their scope. // 2. Functions defined under the with statement also immune to // this setup, in which case dynamic scope is ignored in favor // of the with object. fnNode.setIgnoreDynamicScope(); } fnNode.setJsDoc(getAndResetJsDoc()); PerFunctionVariables savedVars = new PerFunctionVariables(fnNode); try { parseFunctionParams(fnNode); fnNode.setBody(parseFunctionBody()); fnNode.setEncodedSourceBounds(functionSourceStart, ts.tokenEnd); fnNode.setLength(ts.tokenEnd - functionSourceStart); if (compilerEnv.isStrictMode() && !fnNode.getBody().hasConsistentReturnUsage()) { String msg = (name != null && name.length() > 0) ? "msg.no.return.value" : "msg.anon.no.return.value"; - addStrictWarning(msg, name.getIdentifier()); + addStrictWarning(msg, name == null ? "" : name.getIdentifier()); } // Function expressions define a name only in the body of the // function, and only if not hidden by a parameter name if (syntheticType == FunctionNode.FUNCTION_EXPRESSION && name != null && name.length() > 0 && currentScope.getSymbol(name.getIdentifier()) == null) { defineSymbol(Token.FUNCTION, name.getIdentifier()); } } finally { savedVars.restore(); } if (memberExprNode != null) { // TODO(stevey): fix missing functionality Kit.codeBug(); fnNode.setMemberExprNode(memberExprNode); // rewrite later /* old code: if (memberExprNode != null) { pn = nf.createAssignment(Token.ASSIGN, memberExprNode, pn); if (functionType != FunctionNode.FUNCTION_EXPRESSION) { // XXX check JScript behavior: should it be createExprStatement? pn = nf.createExprStatementNoReturn(pn, baseLineno); } } */ } fnNode.setSourceName(sourceURI); fnNode.setBaseLineno(baseLineno); fnNode.setEndLineno(ts.lineno); // Set the parent scope. Needed for finding undeclared vars. // Have to wait until after parsing the function to set its parent // scope, since defineSymbol needs the defining-scope check to stop // at the function boundary when checking for redeclarations. if (compilerEnv.isIdeMode()) { fnNode.setParentScope(currentScope); } return fnNode; } // This function does not match the closing RC: the caller matches // the RC so it can provide a suitable error message if not matched. // This means it's up to the caller to set the length of the node to // include the closing RC. The node start pos is set to the // absolute buffer start position, and the caller should fix it up // to be relative to the parent node. All children of this block // node are given relative start positions and correct lengths. private AstNode statements(AstNode parent) throws IOException { if (currentToken != Token.LC // assertion can be invalid in bad code && !compilerEnv.isIdeMode()) codeBug(); int pos = ts.tokenBeg; AstNode block = parent != null ? parent : new Block(pos); block.setLineno(ts.lineno); int tt; while ((tt = peekToken()) > Token.EOF && tt != Token.RC) { block.addChild(statement()); } block.setLength(ts.tokenBeg - pos); return block; } private AstNode statements() throws IOException { return statements(null); } private static class ConditionData { AstNode condition; int lp = -1; int rp = -1; } // parse and return a parenthesized expression private ConditionData condition() throws IOException { ConditionData data = new ConditionData(); if (mustMatchToken(Token.LP, "msg.no.paren.cond")) data.lp = ts.tokenBeg; data.condition = expr(); if (mustMatchToken(Token.RP, "msg.no.paren.after.cond")) data.rp = ts.tokenBeg; // Report strict warning on code like "if (a = 7) ...". Suppress the // warning if the condition is parenthesized, like "if ((a = 7)) ...". if (data.condition instanceof Assignment) { addStrictWarning("msg.equal.as.assign", "", data.condition.getPosition(), data.condition.getLength()); } return data; } private AstNode statement() throws IOException { int pos = ts.tokenBeg; try { AstNode pn = statementHelper(); if (pn != null) { if (compilerEnv.isStrictMode() && !pn.hasSideEffects()) { int beg = pn.getPosition(); beg = Math.max(beg, lineBeginningFor(beg)); addStrictWarning(pn instanceof EmptyExpression ? "msg.extra.trailing.semi" : "msg.no.side.effects", "", beg, nodeEnd(pn) - beg); } return pn; } } catch (ParserException e) { // an ErrorNode was added to the ErrorReporter } // error: skip ahead to a probable statement boundary guessingStatementEnd: for (;;) { int tt = peekTokenOrEOL(); consumeToken(); switch (tt) { case Token.ERROR: case Token.EOF: case Token.EOL: case Token.SEMI: break guessingStatementEnd; } } // We don't make error nodes explicitly part of the tree; // they get added to the ErrorReporter. May need to do // something different here. return new EmptyExpression(pos, ts.tokenBeg - pos); } private AstNode statementHelper() throws IOException { // If the statement is set, then it's been told its label by now. if (currentLabel != null && currentLabel.getStatement() != null) currentLabel = null; AstNode pn = null; int tt = peekToken(), pos = ts.tokenBeg; switch (tt) { case Token.IF: return ifStatement(); case Token.SWITCH: return switchStatement(); case Token.WHILE: return whileLoop(); case Token.DO: return doLoop(); case Token.FOR: return forLoop(); case Token.TRY: return tryStatement(); case Token.THROW: pn = throwStatement(); break; case Token.BREAK: pn = breakStatement(); break; case Token.CONTINUE: pn = continueStatement(); break; case Token.WITH: if (this.inUseStrictDirective) { reportError("msg.no.with.strict"); } return withStatement(); case Token.CONST: case Token.VAR: consumeToken(); int lineno = ts.lineno; pn = variables(currentToken, ts.tokenBeg); pn.setLineno(lineno); break; case Token.LET: pn = letStatement(); if (pn instanceof VariableDeclaration && peekToken() == Token.SEMI) break; return pn; case Token.RETURN: case Token.YIELD: pn = returnOrYield(tt, false); break; case Token.DEBUGGER: consumeToken(); pn = new KeywordLiteral(ts.tokenBeg, ts.tokenEnd - ts.tokenBeg, tt); pn.setLineno(ts.lineno); break; case Token.LC: return block(); case Token.ERROR: consumeToken(); return makeErrorNode(); case Token.SEMI: consumeToken(); pos = ts.tokenBeg; pn = new EmptyExpression(pos, ts.tokenEnd - pos); pn.setLineno(ts.lineno); return pn; case Token.FUNCTION: consumeToken(); return function(FunctionNode.FUNCTION_EXPRESSION_STATEMENT); case Token.DEFAULT : pn = defaultXmlNamespace(); break; case Token.NAME: pn = nameOrLabel(); if (pn instanceof ExpressionStatement) break; return pn; // LabeledStatement default: lineno = ts.lineno; pn = new ExpressionStatement(expr(), !insideFunction()); pn.setLineno(lineno); break; } autoInsertSemicolon(pn); return pn; } private void autoInsertSemicolon(AstNode pn) throws IOException { int ttFlagged = peekFlaggedToken(); int pos = pn.getPosition(); switch (ttFlagged & CLEAR_TI_MASK) { case Token.SEMI: // Consume ';' as a part of expression consumeToken(); // extend the node bounds to include the semicolon. pn.setLength(ts.tokenEnd - pos); break; case Token.ERROR: case Token.EOF: case Token.RC: // Autoinsert ; warnMissingSemi(pos, nodeEnd(pn)); break; default: if ((ttFlagged & TI_AFTER_EOL) == 0) { // Report error if no EOL or autoinsert ; otherwise reportError("msg.no.semi.stmt"); } else { warnMissingSemi(pos, nodeEnd(pn)); } break; } } private IfStatement ifStatement() throws IOException { if (currentToken != Token.IF) codeBug(); consumeToken(); int pos = ts.tokenBeg, lineno = ts.lineno, elsePos = -1; ConditionData data = condition(); AstNode ifTrue = statement(), ifFalse = null; if (matchToken(Token.ELSE)) { elsePos = ts.tokenBeg - pos; ifFalse = statement(); } int end = getNodeEnd(ifFalse != null ? ifFalse : ifTrue); IfStatement pn = new IfStatement(pos, end - pos); pn.setCondition(data.condition); pn.setParens(data.lp - pos, data.rp - pos); pn.setThenPart(ifTrue); pn.setElsePart(ifFalse); pn.setElsePosition(elsePos); pn.setLineno(lineno); return pn; } private SwitchStatement switchStatement() throws IOException { if (currentToken != Token.SWITCH) codeBug(); consumeToken(); int pos = ts.tokenBeg; SwitchStatement pn = new SwitchStatement(pos); if (mustMatchToken(Token.LP, "msg.no.paren.switch")) pn.setLp(ts.tokenBeg - pos); pn.setLineno(ts.lineno); AstNode discriminant = expr(); pn.setExpression(discriminant); enterSwitch(pn); try { if (mustMatchToken(Token.RP, "msg.no.paren.after.switch")) pn.setRp(ts.tokenBeg - pos); mustMatchToken(Token.LC, "msg.no.brace.switch"); boolean hasDefault = false; int tt; switchLoop: for (;;) { tt = nextToken(); int casePos = ts.tokenBeg; int caseLineno = ts.lineno; AstNode caseExpression = null; switch (tt) { case Token.RC: pn.setLength(ts.tokenEnd - pos); break switchLoop; case Token.CASE: caseExpression = expr(); mustMatchToken(Token.COLON, "msg.no.colon.case"); break; case Token.DEFAULT: if (hasDefault) { reportError("msg.double.switch.default"); } hasDefault = true; caseExpression = null; mustMatchToken(Token.COLON, "msg.no.colon.case"); break; default: reportError("msg.bad.switch"); break switchLoop; } SwitchCase caseNode = new SwitchCase(casePos); caseNode.setExpression(caseExpression); caseNode.setLength(ts.tokenEnd - pos); // include colon caseNode.setLineno(caseLineno); while ((tt = peekToken()) != Token.RC && tt != Token.CASE && tt != Token.DEFAULT && tt != Token.EOF) { caseNode.addStatement(statement()); // updates length } pn.addCase(caseNode); } } finally { exitSwitch(); } return pn; } private WhileLoop whileLoop() throws IOException { if (currentToken != Token.WHILE) codeBug(); consumeToken(); int pos = ts.tokenBeg; WhileLoop pn = new WhileLoop(pos); pn.setLineno(ts.lineno); enterLoop(pn); try { ConditionData data = condition(); pn.setCondition(data.condition); pn.setParens(data.lp - pos, data.rp - pos); AstNode body = statement(); pn.setLength(getNodeEnd(body) - pos); pn.setBody(body); } finally { exitLoop(); } return pn; } private DoLoop doLoop() throws IOException { if (currentToken != Token.DO) codeBug(); consumeToken(); int pos = ts.tokenBeg, end; DoLoop pn = new DoLoop(pos); pn.setLineno(ts.lineno); enterLoop(pn); try { AstNode body = statement(); mustMatchToken(Token.WHILE, "msg.no.while.do"); pn.setWhilePosition(ts.tokenBeg - pos); ConditionData data = condition(); pn.setCondition(data.condition); pn.setParens(data.lp - pos, data.rp - pos); end = getNodeEnd(body); pn.setBody(body); } finally { exitLoop(); } // Always auto-insert semicolon to follow SpiderMonkey: // It is required by ECMAScript but is ignored by the rest of // world, see bug 238945 if (matchToken(Token.SEMI)) { end = ts.tokenEnd; } pn.setLength(end - pos); return pn; } private Loop forLoop() throws IOException { if (currentToken != Token.FOR) codeBug(); consumeToken(); int forPos = ts.tokenBeg, lineno = ts.lineno; boolean isForEach = false, isForIn = false; int eachPos = -1, inPos = -1, lp = -1, rp = -1; AstNode init = null; // init is also foo in 'foo in object' AstNode cond = null; // cond is also object in 'foo in object' AstNode incr = null; Loop pn = null; Scope tempScope = new Scope(); pushScope(tempScope); // decide below what AST class to use try { // See if this is a for each () instead of just a for () if (matchToken(Token.NAME)) { if ("each".equals(ts.getString())) { isForEach = true; eachPos = ts.tokenBeg - forPos; } else { reportError("msg.no.paren.for"); } } if (mustMatchToken(Token.LP, "msg.no.paren.for")) lp = ts.tokenBeg - forPos; int tt = peekToken(); init = forLoopInit(tt); if (matchToken(Token.IN)) { isForIn = true; inPos = ts.tokenBeg - forPos; cond = expr(); // object over which we're iterating } else { // ordinary for-loop mustMatchToken(Token.SEMI, "msg.no.semi.for"); if (peekToken() == Token.SEMI) { // no loop condition cond = new EmptyExpression(ts.tokenBeg, 1); cond.setLineno(ts.lineno); } else { cond = expr(); } mustMatchToken(Token.SEMI, "msg.no.semi.for.cond"); int tmpPos = ts.tokenEnd; if (peekToken() == Token.RP) { incr = new EmptyExpression(tmpPos, 1); incr.setLineno(ts.lineno); } else { incr = expr(); } } if (mustMatchToken(Token.RP, "msg.no.paren.for.ctrl")) rp = ts.tokenBeg - forPos; if (isForIn) { ForInLoop fis = new ForInLoop(forPos); if (init instanceof VariableDeclaration) { // check that there was only one variable given if (((VariableDeclaration)init).getVariables().size() > 1) { reportError("msg.mult.index"); } } fis.setIterator(init); fis.setIteratedObject(cond); fis.setInPosition(inPos); fis.setIsForEach(isForEach); fis.setEachPosition(eachPos); pn = fis; } else { ForLoop fl = new ForLoop(forPos); fl.setInitializer(init); fl.setCondition(cond); fl.setIncrement(incr); pn = fl; } // replace temp scope with the new loop object currentScope.replaceWith(pn); popScope(); // We have to parse the body -after- creating the loop node, // so that the loop node appears in the loopSet, allowing // break/continue statements to find the enclosing loop. enterLoop(pn); try { AstNode body = statement(); pn.setLength(getNodeEnd(body) - forPos); pn.setBody(body); } finally { exitLoop(); } } finally { if (currentScope == tempScope) { popScope(); } } pn.setParens(lp, rp); pn.setLineno(lineno); return pn; } private AstNode forLoopInit(int tt) throws IOException { try { inForInit = true; // checked by variables() and relExpr() AstNode init = null; if (tt == Token.SEMI) { init = new EmptyExpression(ts.tokenBeg, 1); init.setLineno(ts.lineno); } else if (tt == Token.VAR || tt == Token.LET) { consumeToken(); init = variables(tt, ts.tokenBeg); } else { init = expr(); markDestructuring(init); } return init; } finally { inForInit = false; } } private TryStatement tryStatement() throws IOException { if (currentToken != Token.TRY) codeBug(); consumeToken(); // Pull out JSDoc info and reset it before recursing. String jsdoc = getAndResetJsDoc(); int tryPos = ts.tokenBeg, lineno = ts.lineno, finallyPos = -1; if (peekToken() != Token.LC) { reportError("msg.no.brace.try"); } AstNode tryBlock = statement(); int tryEnd = getNodeEnd(tryBlock); List<CatchClause> clauses = null; boolean sawDefaultCatch = false; int peek = peekToken(); if (peek == Token.CATCH) { while (matchToken(Token.CATCH)) { int catchLineNum = ts.lineno; if (sawDefaultCatch) { reportError("msg.catch.unreachable"); } int catchPos = ts.tokenBeg, lp = -1, rp = -1, guardPos = -1; if (mustMatchToken(Token.LP, "msg.no.paren.catch")) lp = ts.tokenBeg; mustMatchToken(Token.NAME, "msg.bad.catchcond"); Name varName = createNameNode(); String varNameString = varName.getIdentifier(); if (inUseStrictDirective) { if ("eval".equals(varNameString) || "arguments".equals(varNameString)) { reportError("msg.bad.id.strict", varNameString); } } AstNode catchCond = null; if (matchToken(Token.IF)) { guardPos = ts.tokenBeg; catchCond = expr(); } else { sawDefaultCatch = true; } if (mustMatchToken(Token.RP, "msg.bad.catchcond")) rp = ts.tokenBeg; mustMatchToken(Token.LC, "msg.no.brace.catchblock"); Block catchBlock = (Block)statements(); tryEnd = getNodeEnd(catchBlock); CatchClause catchNode = new CatchClause(catchPos); catchNode.setVarName(varName); catchNode.setCatchCondition(catchCond); catchNode.setBody(catchBlock); if (guardPos != -1) { catchNode.setIfPosition(guardPos - catchPos); } catchNode.setParens(lp, rp); catchNode.setLineno(catchLineNum); if (mustMatchToken(Token.RC, "msg.no.brace.after.body")) tryEnd = ts.tokenEnd; catchNode.setLength(tryEnd - catchPos); if (clauses == null) clauses = new ArrayList<CatchClause>(); clauses.add(catchNode); } } else if (peek != Token.FINALLY) { mustMatchToken(Token.FINALLY, "msg.try.no.catchfinally"); } AstNode finallyBlock = null; if (matchToken(Token.FINALLY)) { finallyPos = ts.tokenBeg; finallyBlock = statement(); tryEnd = getNodeEnd(finallyBlock); } TryStatement pn = new TryStatement(tryPos, tryEnd - tryPos); pn.setTryBlock(tryBlock); pn.setCatchClauses(clauses); pn.setFinallyBlock(finallyBlock); if (finallyPos != -1) { pn.setFinallyPosition(finallyPos - tryPos); } pn.setLineno(lineno); if (jsdoc != null) { pn.setJsDoc(jsdoc); } return pn; } private ThrowStatement throwStatement() throws IOException { if (currentToken != Token.THROW) codeBug(); consumeToken(); int pos = ts.tokenBeg, lineno = ts.lineno; if (peekTokenOrEOL() == Token.EOL) { // ECMAScript does not allow new lines before throw expression, // see bug 256617 reportError("msg.bad.throw.eol"); } AstNode expr = expr(); ThrowStatement pn = new ThrowStatement(pos, getNodeEnd(expr), expr); pn.setLineno(lineno); return pn; } // If we match a NAME, consume the token and return the statement // with that label. If the name does not match an existing label, // reports an error. Returns the labeled statement node, or null if // the peeked token was not a name. Side effect: sets scanner token // information for the label identifier (tokenBeg, tokenEnd, etc.) private LabeledStatement matchJumpLabelName() throws IOException { LabeledStatement label = null; if (peekTokenOrEOL() == Token.NAME) { consumeToken(); if (labelSet != null) { label = labelSet.get(ts.getString()); } if (label == null) { reportError("msg.undef.label"); } } return label; } private BreakStatement breakStatement() throws IOException { if (currentToken != Token.BREAK) codeBug(); consumeToken(); int lineno = ts.lineno, pos = ts.tokenBeg, end = ts.tokenEnd; Name breakLabel = null; if (peekTokenOrEOL() == Token.NAME) { breakLabel = createNameNode(); end = getNodeEnd(breakLabel); } // matchJumpLabelName only matches if there is one LabeledStatement labels = matchJumpLabelName(); // always use first label as target Jump breakTarget = labels == null ? null : labels.getFirstLabel(); if (breakTarget == null && breakLabel == null) { if (loopAndSwitchSet == null || loopAndSwitchSet.size() == 0) { if (breakLabel == null) { reportError("msg.bad.break", pos, end - pos); } } else { breakTarget = loopAndSwitchSet.get(loopAndSwitchSet.size() - 1); } } BreakStatement pn = new BreakStatement(pos, end - pos); pn.setBreakLabel(breakLabel); // can be null if it's a bad break in error-recovery mode if (breakTarget != null) pn.setBreakTarget(breakTarget); pn.setLineno(lineno); return pn; } private ContinueStatement continueStatement() throws IOException { if (currentToken != Token.CONTINUE) codeBug(); consumeToken(); int lineno = ts.lineno, pos = ts.tokenBeg, end = ts.tokenEnd; Name label = null; if (peekTokenOrEOL() == Token.NAME) { label = createNameNode(); end = getNodeEnd(label); } // matchJumpLabelName only matches if there is one LabeledStatement labels = matchJumpLabelName(); Loop target = null; if (labels == null && label == null) { if (loopSet == null || loopSet.size() == 0) { reportError("msg.continue.outside"); } else { target = loopSet.get(loopSet.size() - 1); } } else { if (labels == null || !(labels.getStatement() instanceof Loop)) { reportError("msg.continue.nonloop", pos, end - pos); } target = labels == null ? null : (Loop)labels.getStatement(); } ContinueStatement pn = new ContinueStatement(pos, end - pos); if (target != null) // can be null in error-recovery mode pn.setTarget(target); pn.setLabel(label); pn.setLineno(lineno); return pn; } private WithStatement withStatement() throws IOException { if (currentToken != Token.WITH) codeBug(); consumeToken(); int lineno = ts.lineno, pos = ts.tokenBeg, lp = -1, rp = -1; if (mustMatchToken(Token.LP, "msg.no.paren.with")) lp = ts.tokenBeg; AstNode obj = expr(); if (mustMatchToken(Token.RP, "msg.no.paren.after.with")) rp = ts.tokenBeg; ++nestingOfWith; AstNode body; try { body = statement(); } finally { --nestingOfWith; } WithStatement pn = new WithStatement(pos, getNodeEnd(body) - pos); pn.setJsDoc(getAndResetJsDoc()); pn.setExpression(obj); pn.setStatement(body); pn.setParens(lp, rp); pn.setLineno(lineno); return pn; } private AstNode letStatement() throws IOException { if (currentToken != Token.LET) codeBug(); consumeToken(); int lineno = ts.lineno, pos = ts.tokenBeg; AstNode pn; if (peekToken() == Token.LP) { pn = let(true, pos); } else { pn = variables(Token.LET, pos); // else, e.g.: let x=6, y=7; } pn.setLineno(lineno); return pn; } /** * Returns whether or not the bits in the mask have changed to all set. * @param before bits before change * @param after bits after change * @param mask mask for bits * @return {@code true} if all the bits in the mask are set in "after" * but not in "before" */ private static final boolean nowAllSet(int before, int after, int mask) { return ((before & mask) != mask) && ((after & mask) == mask); } private AstNode returnOrYield(int tt, boolean exprContext) throws IOException { if (!insideFunction()) { reportError(tt == Token.RETURN ? "msg.bad.return" : "msg.bad.yield"); } consumeToken(); int lineno = ts.lineno, pos = ts.tokenBeg, end = ts.tokenEnd; AstNode e = null; // This is ugly, but we don't want to require a semicolon. switch (peekTokenOrEOL()) { case Token.SEMI: case Token.RC: case Token.RB: case Token.RP: case Token.EOF: case Token.EOL: case Token.ERROR: case Token.YIELD: break; default: e = expr(); end = getNodeEnd(e); } int before = endFlags; AstNode ret; if (tt == Token.RETURN) { endFlags |= e == null ? Node.END_RETURNS : Node.END_RETURNS_VALUE; ret = new ReturnStatement(pos, end - pos, e); // see if we need a strict mode warning if (nowAllSet(before, endFlags, Node.END_RETURNS|Node.END_RETURNS_VALUE)) addStrictWarning("msg.return.inconsistent", "", pos, end - pos); } else { if (!insideFunction()) reportError("msg.bad.yield"); endFlags |= Node.END_YIELDS; ret = new Yield(pos, end - pos, e); setRequiresActivation(); setIsGenerator(); if (!exprContext) { ret = new ExpressionStatement(ret); } } // see if we are mixing yields and value returns. if (insideFunction() && nowAllSet(before, endFlags, Node.END_YIELDS|Node.END_RETURNS_VALUE)) { Name name = ((FunctionNode)currentScriptOrFn).getFunctionName(); if (name == null || name.length() == 0) addError("msg.anon.generator.returns", ""); else addError("msg.generator.returns", name.getIdentifier()); } ret.setLineno(lineno); return ret; } private AstNode block() throws IOException { if (currentToken != Token.LC) codeBug(); consumeToken(); int pos = ts.tokenBeg; Scope block = new Scope(pos); block.setLineno(ts.lineno); pushScope(block); try { statements(block); mustMatchToken(Token.RC, "msg.no.brace.block"); block.setLength(ts.tokenEnd - pos); return block; } finally { popScope(); } } private AstNode defaultXmlNamespace() throws IOException { if (currentToken != Token.DEFAULT) codeBug(); consumeToken(); mustHaveXML(); setRequiresActivation(); int lineno = ts.lineno, pos = ts.tokenBeg; if (!(matchToken(Token.NAME) && "xml".equals(ts.getString()))) { reportError("msg.bad.namespace"); } if (!(matchToken(Token.NAME) && "namespace".equals(ts.getString()))) { reportError("msg.bad.namespace"); } if (!matchToken(Token.ASSIGN)) { reportError("msg.bad.namespace"); } AstNode e = expr(); UnaryExpression dxmln = new UnaryExpression(pos, getNodeEnd(e) - pos); dxmln.setOperator(Token.DEFAULTNAMESPACE); dxmln.setOperand(e); dxmln.setLineno(lineno); ExpressionStatement es = new ExpressionStatement(dxmln, true); return es; } private void recordLabel(Label label, LabeledStatement bundle) throws IOException { // current token should be colon that primaryExpr left untouched if (peekToken() != Token.COLON) codeBug(); consumeToken(); String name = label.getName(); if (labelSet == null) { labelSet = new HashMap<String,LabeledStatement>(); } else { LabeledStatement ls = labelSet.get(name); if (ls != null) { if (compilerEnv.isIdeMode()) { Label dup = ls.getLabelByName(name); reportError("msg.dup.label", dup.getAbsolutePosition(), dup.getLength()); } reportError("msg.dup.label", label.getPosition(), label.getLength()); } } bundle.addLabel(label); labelSet.put(name, bundle); } /** * Found a name in a statement context. If it's a label, we gather * up any following labels and the next non-label statement into a * {@link LabeledStatement} "bundle" and return that. Otherwise we parse * an expression and return it wrapped in an {@link ExpressionStatement}. */ private AstNode nameOrLabel() throws IOException { if (currentToken != Token.NAME) throw codeBug(); int pos = ts.tokenBeg; // set check for label and call down to primaryExpr currentFlaggedToken |= TI_CHECK_LABEL; AstNode expr = expr(); if (expr.getType() != Token.LABEL) { AstNode n = new ExpressionStatement(expr, !insideFunction()); n.lineno = expr.lineno; return n; } LabeledStatement bundle = new LabeledStatement(pos); recordLabel((Label)expr, bundle); bundle.setLineno(ts.lineno); // look for more labels AstNode stmt = null; while (peekToken() == Token.NAME) { currentFlaggedToken |= TI_CHECK_LABEL; expr = expr(); if (expr.getType() != Token.LABEL) { stmt = new ExpressionStatement(expr, !insideFunction()); autoInsertSemicolon(stmt); break; } recordLabel((Label)expr, bundle); } // no more labels; now parse the labeled statement try { currentLabel = bundle; if (stmt == null) { stmt = statementHelper(); } } finally { currentLabel = null; // remove the labels for this statement from the global set for (Label lb : bundle.getLabels()) { labelSet.remove(lb.getName()); } } bundle.setLength(getNodeEnd(stmt) - pos); bundle.setStatement(stmt); return bundle; } /** * Parse a 'var' or 'const' statement, or a 'var' init list in a for * statement. * @param declType A token value: either VAR, CONST, or LET depending on * context. * @param pos the position where the node should start. It's sometimes * the var/const/let keyword, and other times the beginning of the first * token in the first variable declaration. * @return the parsed variable list */ private VariableDeclaration variables(int declType, int pos) throws IOException { int end; VariableDeclaration pn = new VariableDeclaration(pos); pn.setType(declType); pn.setLineno(ts.lineno); String varjsdoc = getAndResetJsDoc(); if (varjsdoc != null) { pn.setJsDoc(varjsdoc); } // Example: // var foo = {a: 1, b: 2}, bar = [3, 4]; // var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar; for (;;) { AstNode destructuring = null; Name name = null; int tt = peekToken(), kidPos = ts.tokenBeg; end = ts.tokenEnd; if (tt == Token.LB || tt == Token.LC) { // Destructuring assignment, e.g., var [a,b] = ... destructuring = destructuringPrimaryExpr(); end = getNodeEnd(destructuring); if (!(destructuring instanceof DestructuringForm)) reportError("msg.bad.assign.left", kidPos, end - kidPos); markDestructuring(destructuring); } else { // Simple variable name mustMatchToken(Token.NAME, "msg.bad.var"); name = createNameNode(); name.setLineno(ts.getLineno()); if (inUseStrictDirective) { String id = ts.getString(); if ("eval".equals(id) || "arguments".equals(ts.getString())) { reportError("msg.bad.id.strict", id); } } defineSymbol(declType, ts.getString(), inForInit); } int lineno = ts.lineno; String jsdoc = getAndResetJsDoc(); AstNode init = null; if (matchToken(Token.ASSIGN)) { init = assignExpr(); end = getNodeEnd(init); } VariableInitializer vi = new VariableInitializer(kidPos, end - kidPos); if (destructuring != null) { if (init == null && !inForInit) { reportError("msg.destruct.assign.no.init"); } vi.setTarget(destructuring); } else { vi.setTarget(name); } vi.setInitializer(init); vi.setType(declType); vi.setJsDoc(jsdoc); vi.setLineno(lineno); pn.addVariable(vi); if (!matchToken(Token.COMMA)) break; } pn.setLength(end - pos); return pn; } // have to pass in 'let' kwd position to compute kid offsets properly private AstNode let(boolean isStatement, int pos) throws IOException { LetNode pn = new LetNode(pos); pn.setLineno(ts.lineno); if (mustMatchToken(Token.LP, "msg.no.paren.after.let")) pn.setLp(ts.tokenBeg - pos); pushScope(pn); try { VariableDeclaration vars = variables(Token.LET, ts.tokenBeg); pn.setVariables(vars); if (mustMatchToken(Token.RP, "msg.no.paren.let")) { pn.setRp(ts.tokenBeg - pos); } if (isStatement && peekToken() == Token.LC) { // let statement consumeToken(); int beg = ts.tokenBeg; // position stmt at LC AstNode stmt = statements(); mustMatchToken(Token.RC, "msg.no.curly.let"); stmt.setLength(ts.tokenEnd - beg); pn.setLength(ts.tokenEnd - pos); pn.setBody(stmt); pn.setType(Token.LET); } else { // let expression AstNode expr = expr(); pn.setLength(getNodeEnd(expr) - pos); pn.setBody(expr); if (isStatement) { // let expression in statement context ExpressionStatement es = new ExpressionStatement(pn, !insideFunction()); es.setLineno(pn.getLineno()); return es; } } } finally { popScope(); } return pn; } void defineSymbol(int declType, String name) { defineSymbol(declType, name, false); } void defineSymbol(int declType, String name, boolean ignoreNotInBlock) { if (name == null) { if (compilerEnv.isIdeMode()) { // be robust in IDE-mode return; } else { codeBug(); } } Scope definingScope = currentScope.getDefiningScope(name); Symbol symbol = definingScope != null ? definingScope.getSymbol(name) : null; int symDeclType = symbol != null ? symbol.getDeclType() : -1; if (symbol != null && (symDeclType == Token.CONST || declType == Token.CONST || (definingScope == currentScope && symDeclType == Token.LET))) { addError(symDeclType == Token.CONST ? "msg.const.redecl" : symDeclType == Token.LET ? "msg.let.redecl" : symDeclType == Token.VAR ? "msg.var.redecl" : symDeclType == Token.FUNCTION ? "msg.fn.redecl" : "msg.parm.redecl", name); return; } switch (declType) { case Token.LET: if (!ignoreNotInBlock && ((currentScope.getType() == Token.IF) || currentScope instanceof Loop)) { addError("msg.let.decl.not.in.block"); return; } currentScope.putSymbol(new Symbol(declType, name)); return; case Token.VAR: case Token.CONST: case Token.FUNCTION: if (symbol != null) { if (symDeclType == Token.VAR) addStrictWarning("msg.var.redecl", name); else if (symDeclType == Token.LP) { addStrictWarning("msg.var.hides.arg", name); } } else { currentScriptOrFn.putSymbol(new Symbol(declType, name)); } return; case Token.LP: if (symbol != null) { // must be duplicate parameter. Second parameter hides the // first, so go ahead and add the second parameter addWarning("msg.dup.parms", name); } currentScriptOrFn.putSymbol(new Symbol(declType, name)); return; default: throw codeBug(); } } private AstNode expr() throws IOException { AstNode pn = assignExpr(); int pos = pn.getPosition(); while (matchToken(Token.COMMA)) { int lineno = ts.lineno; int opPos = ts.tokenBeg; if (compilerEnv.isStrictMode() && !pn.hasSideEffects()) addStrictWarning("msg.no.side.effects", "", pos, nodeEnd(pn) - pos); if (peekToken() == Token.YIELD) reportError("msg.yield.parenthesized"); pn = new InfixExpression(Token.COMMA, pn, assignExpr(), opPos); pn.setLineno(lineno); } return pn; } private AstNode assignExpr() throws IOException { int tt = peekToken(); if (tt == Token.YIELD) { return returnOrYield(tt, true); } AstNode pn = condExpr(); tt = peekToken(); if (Token.FIRST_ASSIGN <= tt && tt <= Token.LAST_ASSIGN) { consumeToken(); // Pull out JSDoc info and reset it before recursing. String jsdoc = getAndResetJsDoc(); markDestructuring(pn); int opPos = ts.tokenBeg; int opLineno = ts.getLineno(); pn = new Assignment(tt, pn, assignExpr(), opPos); pn.setLineno(opLineno); if (jsdoc != null) { pn.setJsDoc(jsdoc); } } else if (tt == Token.SEMI && pn.getType() == Token.GETPROP) { // This may be dead code added intentionally, for JSDoc purposes. // For example: /** @type Number */ C.prototype.x; if (currentJsDocComment != null) { pn.setJsDoc(getAndResetJsDoc()); } } return pn; } private AstNode condExpr() throws IOException { AstNode pn = orExpr(); if (matchToken(Token.HOOK)) { int line = ts.lineno; int qmarkPos = ts.tokenBeg, colonPos = -1; AstNode ifTrue = assignExpr(); if (mustMatchToken(Token.COLON, "msg.no.colon.cond")) colonPos = ts.tokenBeg; AstNode ifFalse = assignExpr(); int beg = pn.getPosition(), len = getNodeEnd(ifFalse) - beg; ConditionalExpression ce = new ConditionalExpression(beg, len); ce.setLineno(line); ce.setTestExpression(pn); ce.setTrueExpression(ifTrue); ce.setFalseExpression(ifFalse); ce.setQuestionMarkPosition(qmarkPos - beg); ce.setColonPosition(colonPos - beg); pn = ce; } return pn; } private AstNode orExpr() throws IOException { AstNode pn = andExpr(); if (matchToken(Token.OR)) { int opPos = ts.tokenBeg; int lineno = ts.lineno; pn = new InfixExpression(Token.OR, pn, orExpr(), opPos); pn.setLineno(lineno); } return pn; } private AstNode andExpr() throws IOException { AstNode pn = bitOrExpr(); if (matchToken(Token.AND)) { int opPos = ts.tokenBeg; int lineno = ts.lineno; pn = new InfixExpression(Token.AND, pn, andExpr(), opPos); pn.setLineno(lineno); } return pn; } private AstNode bitOrExpr() throws IOException { AstNode pn = bitXorExpr(); while (matchToken(Token.BITOR)) { int opPos = ts.tokenBeg; int lineno = ts.lineno; pn = new InfixExpression(Token.BITOR, pn, bitXorExpr(), opPos); pn.setLineno(lineno); } return pn; } private AstNode bitXorExpr() throws IOException { AstNode pn = bitAndExpr(); while (matchToken(Token.BITXOR)) { int opPos = ts.tokenBeg; int lineno = ts.lineno; pn = new InfixExpression(Token.BITXOR, pn, bitAndExpr(), opPos); pn.setLineno(lineno); } return pn; } private AstNode bitAndExpr() throws IOException { AstNode pn = eqExpr(); while (matchToken(Token.BITAND)) { int opPos = ts.tokenBeg; int lineno = ts.lineno; pn = new InfixExpression(Token.BITAND, pn, eqExpr(), opPos); pn.setLineno(lineno); } return pn; } private AstNode eqExpr() throws IOException { AstNode pn = relExpr(); for (;;) { int tt = peekToken(), opPos = ts.tokenBeg; int lineno = ts.lineno; switch (tt) { case Token.EQ: case Token.NE: case Token.SHEQ: case Token.SHNE: consumeToken(); int parseToken = tt; if (compilerEnv.getLanguageVersion() == Context.VERSION_1_2) { // JavaScript 1.2 uses shallow equality for == and != . if (tt == Token.EQ) parseToken = Token.SHEQ; else if (tt == Token.NE) parseToken = Token.SHNE; } pn = new InfixExpression(parseToken, pn, relExpr(), opPos); pn.setLineno(lineno); continue; } break; } return pn; } private AstNode relExpr() throws IOException { AstNode pn = shiftExpr(); for (;;) { int tt = peekToken(), opPos = ts.tokenBeg; int line = ts.lineno; switch (tt) { case Token.IN: if (inForInit) break; // fall through case Token.INSTANCEOF: case Token.LE: case Token.LT: case Token.GE: case Token.GT: consumeToken(); pn = new InfixExpression(tt, pn, shiftExpr(), opPos); pn.setLineno(line); continue; } break; } return pn; } private AstNode shiftExpr() throws IOException { AstNode pn = addExpr(); for (;;) { int tt = peekToken(), opPos = ts.tokenBeg; int lineno = ts.lineno; switch (tt) { case Token.LSH: case Token.URSH: case Token.RSH: consumeToken(); pn = new InfixExpression(tt, pn, addExpr(), opPos); pn.setLineno(lineno); continue; } break; } return pn; } private AstNode addExpr() throws IOException { AstNode pn = mulExpr(); for (;;) { int tt = peekToken(), opPos = ts.tokenBeg; if (tt == Token.ADD || tt == Token.SUB) { consumeToken(); int lineno = ts.lineno; pn = new InfixExpression(tt, pn, mulExpr(), opPos); pn.setLineno(lineno); continue; } break; } return pn; } private AstNode mulExpr() throws IOException { AstNode pn = unaryExpr(); for (;;) { int tt = peekToken(), opPos = ts.tokenBeg; switch (tt) { case Token.MUL: case Token.DIV: case Token.MOD: consumeToken(); int line = ts.lineno; pn = new InfixExpression(tt, pn, unaryExpr(), opPos); pn.setLineno(line); continue; } break; } return pn; } private AstNode unaryExpr() throws IOException { AstNode node; int tt = peekToken(); int line = ts.lineno; switch(tt) { case Token.VOID: case Token.NOT: case Token.BITNOT: case Token.TYPEOF: consumeToken(); node = new UnaryExpression(tt, ts.tokenBeg, unaryExpr()); node.setLineno(line); return node; case Token.ADD: consumeToken(); // Convert to special POS token in parse tree node = new UnaryExpression(Token.POS, ts.tokenBeg, unaryExpr()); node.setLineno(line); return node; case Token.SUB: consumeToken(); // Convert to special NEG token in parse tree node = new UnaryExpression(Token.NEG, ts.tokenBeg, unaryExpr()); node.setLineno(line); return node; case Token.INC: case Token.DEC: consumeToken(); UnaryExpression expr = new UnaryExpression(tt, ts.tokenBeg, memberExpr(true)); expr.setLineno(line); checkBadIncDec(expr); return expr; case Token.DELPROP: consumeToken(); node = new UnaryExpression(tt, ts.tokenBeg, unaryExpr()); node.setLineno(line); return node; case Token.ERROR: consumeToken(); return makeErrorNode(); case Token.LT: // XML stream encountered in expression. if (compilerEnv.isXmlAvailable()) { consumeToken(); return memberExprTail(true, xmlInitializer()); } // Fall thru to the default handling of RELOP default: AstNode pn = memberExpr(true); // Don't look across a newline boundary for a postfix incop. tt = peekTokenOrEOL(); if (!(tt == Token.INC || tt == Token.DEC)) { return pn; } consumeToken(); UnaryExpression uexpr = new UnaryExpression(tt, ts.tokenBeg, pn, true); uexpr.setLineno(line); checkBadIncDec(uexpr); return uexpr; } } private AstNode xmlInitializer() throws IOException { if (currentToken != Token.LT) codeBug(); int pos = ts.tokenBeg, tt = ts.getFirstXMLToken(); if (tt != Token.XML && tt != Token.XMLEND) { reportError("msg.syntax"); return makeErrorNode(); } XmlLiteral pn = new XmlLiteral(pos); pn.setLineno(ts.lineno); for (;;tt = ts.getNextXMLToken()) { switch (tt) { case Token.XML: pn.addFragment(new XmlString(ts.tokenBeg, ts.getString())); mustMatchToken(Token.LC, "msg.syntax"); int beg = ts.tokenBeg; AstNode expr = (peekToken() == Token.RC) ? new EmptyExpression(beg, ts.tokenEnd - beg) : expr(); mustMatchToken(Token.RC, "msg.syntax"); XmlExpression xexpr = new XmlExpression(beg, expr); xexpr.setIsXmlAttribute(ts.isXMLAttribute()); xexpr.setLength(ts.tokenEnd - beg); pn.addFragment(xexpr); break; case Token.XMLEND: pn.addFragment(new XmlString(ts.tokenBeg, ts.getString())); return pn; default: reportError("msg.syntax"); return makeErrorNode(); } } } private List<AstNode> argumentList() throws IOException { if (matchToken(Token.RP)) return null; List<AstNode> result = new ArrayList<AstNode>(); boolean wasInForInit = inForInit; inForInit = false; try { do { if (peekToken() == Token.YIELD) reportError("msg.yield.parenthesized"); result.add(assignExpr()); } while (matchToken(Token.COMMA)); } finally { inForInit = wasInForInit; } mustMatchToken(Token.RP, "msg.no.paren.arg"); return result; } /** * Parse a new-expression, or if next token isn't {@link Token#NEW}, * a primary expression. * @param allowCallSyntax passed down to {@link #memberExprTail} */ private AstNode memberExpr(boolean allowCallSyntax) throws IOException { int tt = peekToken(), lineno = ts.lineno; AstNode pn; if (tt != Token.NEW) { pn = primaryExpr(); } else { consumeToken(); int pos = ts.tokenBeg; NewExpression nx = new NewExpression(pos); AstNode target = memberExpr(false); int end = getNodeEnd(target); nx.setTarget(target); int lp = -1; if (matchToken(Token.LP)) { lp = ts.tokenBeg; List<AstNode> args = argumentList(); if (args != null && args.size() > ARGC_LIMIT) reportError("msg.too.many.constructor.args"); int rp = ts.tokenBeg; end = ts.tokenEnd; if (args != null) nx.setArguments(args); nx.setParens(lp - pos, rp - pos); } // Experimental syntax: allow an object literal to follow a new // expression, which will mean a kind of anonymous class built with // the JavaAdapter. the object literal will be passed as an // additional argument to the constructor. if (matchToken(Token.LC)) { ObjectLiteral initializer = objectLiteral(); end = getNodeEnd(initializer); nx.setInitializer(initializer); } nx.setLength(end - pos); pn = nx; } pn.setLineno(lineno); AstNode tail = memberExprTail(allowCallSyntax, pn); return tail; } /** * Parse any number of "(expr)", "[expr]" ".expr", "..expr", * or ".(expr)" constructs trailing the passed expression. * @param pn the non-null parent node * @return the outermost (lexically last occurring) expression, * which will have the passed parent node as a descendant */ private AstNode memberExprTail(boolean allowCallSyntax, AstNode pn) throws IOException { // we no longer return null for errors, so this won't be null if (pn == null) codeBug(); int pos = pn.getPosition(); int lineno; tailLoop: for (;;) { int tt = peekToken(); switch (tt) { case Token.DOT: case Token.DOTDOT: lineno = ts.lineno; pn = propertyAccess(tt, pn); pn.setLineno(lineno); break; case Token.DOTQUERY: consumeToken(); int opPos = ts.tokenBeg, rp = -1; lineno = ts.lineno; mustHaveXML(); setRequiresActivation(); AstNode filter = expr(); int end = getNodeEnd(filter); if (mustMatchToken(Token.RP, "msg.no.paren")) { rp = ts.tokenBeg; end = ts.tokenEnd; } XmlDotQuery q = new XmlDotQuery(pos, end - pos); q.setLeft(pn); q.setRight(filter); q.setOperatorPosition(opPos); q.setRp(rp - pos); q.setLineno(lineno); pn = q; break; case Token.LB: consumeToken(); int lb = ts.tokenBeg, rb = -1; lineno = ts.lineno; AstNode expr = expr(); end = getNodeEnd(expr); if (mustMatchToken(Token.RB, "msg.no.bracket.index")) { rb = ts.tokenBeg; end = ts.tokenEnd; } ElementGet g = new ElementGet(pos, end - pos); g.setTarget(pn); g.setElement(expr); g.setParens(lb, rb); g.setLineno(lineno); pn = g; break; case Token.LP: if (!allowCallSyntax) { break tailLoop; } lineno = ts.lineno; consumeToken(); checkCallRequiresActivation(pn); FunctionCall f = new FunctionCall(pos); f.setTarget(pn); // Assign the line number for the function call to where // the paren appeared, not where the name expression started. f.setLineno(lineno); f.setLp(ts.tokenBeg - pos); List<AstNode> args = argumentList(); if (args != null && args.size() > ARGC_LIMIT) reportError("msg.too.many.function.args"); f.setArguments(args); f.setRp(ts.tokenBeg - pos); f.setLength(ts.tokenEnd - pos); pn = f; break; default: break tailLoop; } } return pn; } /** * Handles any construct following a "." or ".." operator. * @param pn the left-hand side (target) of the operator. Never null. * @return a PropertyGet, XmlMemberGet, or ErrorNode */ private AstNode propertyAccess(int tt, AstNode pn) throws IOException { if (pn == null) codeBug(); int memberTypeFlags = 0, lineno = ts.lineno, dotPos = ts.tokenBeg; consumeToken(); if (tt == Token.DOTDOT) { mustHaveXML(); memberTypeFlags = Node.DESCENDANTS_FLAG; } if (!compilerEnv.isXmlAvailable()) { mustMatchToken(Token.NAME, "msg.no.name.after.dot"); Name name = createNameNode(true, Token.GETPROP); PropertyGet pg = new PropertyGet(pn, name, dotPos); pg.setLineno(lineno); return pg; } AstNode ref = null; // right side of . or .. operator switch (nextToken()) { case Token.THROW: // needed for generator.throw(); saveNameTokenData(ts.tokenBeg, "throw", ts.lineno); ref = propertyName(-1, "throw", memberTypeFlags); break; case Token.NAME: // handles: name, ns::name, ns::*, ns::[expr] ref = propertyName(-1, ts.getString(), memberTypeFlags); break; case Token.MUL: // handles: *, *::name, *::*, *::[expr] saveNameTokenData(ts.tokenBeg, "*", ts.lineno); ref = propertyName(-1, "*", memberTypeFlags); break; case Token.XMLATTR: // handles: '@attr', '@ns::attr', '@ns::*', '@ns::*', // '@::attr', '@::*', '@*', '@*::attr', '@*::*' ref = attributeAccess(); break; default: reportError("msg.no.name.after.dot"); return makeErrorNode(); } boolean xml = ref instanceof XmlRef; InfixExpression result = xml ? new XmlMemberGet() : new PropertyGet(); if (xml && tt == Token.DOT) result.setType(Token.DOT); int pos = pn.getPosition(); result.setPosition(pos); result.setLength(getNodeEnd(ref) - pos); result.setOperatorPosition(dotPos - pos); result.setLineno(lineno); result.setLeft(pn); // do this after setting position result.setRight(ref); return result; } /** * Xml attribute expression:<p> * {@code @attr}, {@code @ns::attr}, {@code @ns::*}, {@code @ns::*}, * {@code @*}, {@code @*::attr}, {@code @*::*}, {@code @ns::[expr]}, * {@code @*::[expr]}, {@code @[expr]} <p> * Called if we peeked an '@' token. */ private AstNode attributeAccess() throws IOException { int tt = nextToken(), atPos = ts.tokenBeg; switch (tt) { // handles: @name, @ns::name, @ns::*, @ns::[expr] case Token.NAME: return propertyName(atPos, ts.getString(), 0); // handles: @*, @*::name, @*::*, @*::[expr] case Token.MUL: saveNameTokenData(ts.tokenBeg, "*", ts.lineno); return propertyName(atPos, "*", 0); // handles @[expr] case Token.LB: return xmlElemRef(atPos, null, -1); default: reportError("msg.no.name.after.xmlAttr"); return makeErrorNode(); } } /** * Check if :: follows name in which case it becomes a qualified name. * * @param atPos a natural number if we just read an '@' token, else -1 * * @param s the name or string that was matched (an identifier, "throw" or * "*"). * * @param memberTypeFlags flags tracking whether we're a '.' or '..' child * * @return an XmlRef node if it's an attribute access, a child of a * '..' operator, or the name is followed by ::. For a plain name, * returns a Name node. Returns an ErrorNode for malformed XML * expressions. (For now - might change to return a partial XmlRef.) */ private AstNode propertyName(int atPos, String s, int memberTypeFlags) throws IOException { int pos = atPos != -1 ? atPos : ts.tokenBeg, lineno = ts.lineno; int colonPos = -1; Name name = createNameNode(true, currentToken); Name ns = null; if (matchToken(Token.COLONCOLON)) { ns = name; colonPos = ts.tokenBeg; switch (nextToken()) { // handles name::name case Token.NAME: name = createNameNode(); break; // handles name::* case Token.MUL: saveNameTokenData(ts.tokenBeg, "*", ts.lineno); name = createNameNode(false, -1); break; // handles name::[expr] or *::[expr] case Token.LB: return xmlElemRef(atPos, ns, colonPos); default: reportError("msg.no.name.after.coloncolon"); return makeErrorNode(); } } if (ns == null && memberTypeFlags == 0 && atPos == -1) { return name; } XmlPropRef ref = new XmlPropRef(pos, getNodeEnd(name) - pos); ref.setAtPos(atPos); ref.setNamespace(ns); ref.setColonPos(colonPos); ref.setPropName(name); ref.setLineno(lineno); return ref; } /** * Parse the [expr] portion of an xml element reference, e.g. * @[expr], @*::[expr], or ns::[expr]. */ private XmlElemRef xmlElemRef(int atPos, Name namespace, int colonPos) throws IOException { int lb = ts.tokenBeg, rb = -1, pos = atPos != -1 ? atPos : lb; AstNode expr = expr(); int end = getNodeEnd(expr); if (mustMatchToken(Token.RB, "msg.no.bracket.index")) { rb = ts.tokenBeg; end = ts.tokenEnd; } XmlElemRef ref = new XmlElemRef(pos, end - pos); ref.setNamespace(namespace); ref.setColonPos(colonPos); ref.setAtPos(atPos); ref.setExpression(expr); ref.setBrackets(lb, rb); return ref; } private AstNode destructuringPrimaryExpr() throws IOException, ParserException { try { inDestructuringAssignment = true; return primaryExpr(); } finally { inDestructuringAssignment = false; } } private AstNode primaryExpr() throws IOException { int ttFlagged = nextFlaggedToken(); int tt = ttFlagged & CLEAR_TI_MASK; switch(tt) { case Token.FUNCTION: return function(FunctionNode.FUNCTION_EXPRESSION); case Token.LB: return arrayLiteral(); case Token.LC: return objectLiteral(); case Token.LET: return let(false, ts.tokenBeg); case Token.LP: return parenExpr(); case Token.XMLATTR: mustHaveXML(); return attributeAccess(); case Token.NAME: return name(ttFlagged, tt); case Token.NUMBER: { String s = ts.getString(); if (this.inUseStrictDirective && ts.isNumberOctal()) { reportError("msg.no.octal.strict"); } return new NumberLiteral(ts.tokenBeg, s, ts.getNumber()); } case Token.STRING: return createStringLiteral(); case Token.DIV: case Token.ASSIGN_DIV: // Got / or /= which in this context means a regexp ts.readRegExp(tt); int pos = ts.tokenBeg, end = ts.tokenEnd; RegExpLiteral re = new RegExpLiteral(pos, end - pos); re.setValue(ts.getString()); re.setFlags(ts.readAndClearRegExpFlags()); return re; case Token.NULL: case Token.THIS: case Token.FALSE: case Token.TRUE: pos = ts.tokenBeg; end = ts.tokenEnd; return new KeywordLiteral(pos, end - pos, tt); case Token.RESERVED: reportError("msg.reserved.id"); break; case Token.ERROR: // the scanner or one of its subroutines reported the error. break; case Token.EOF: reportError("msg.unexpected.eof"); break; default: reportError("msg.syntax"); break; } // should only be reachable in IDE/error-recovery mode return makeErrorNode(); } private AstNode parenExpr() throws IOException { boolean wasInForInit = inForInit; inForInit = false; try { String jsdoc = getAndResetJsDoc(); int lineno = ts.lineno; AstNode e = expr(); ParenthesizedExpression pn = new ParenthesizedExpression(e); if (jsdoc == null) { jsdoc = getAndResetJsDoc(); } if (jsdoc != null) { pn.setJsDoc(jsdoc); } mustMatchToken(Token.RP, "msg.no.paren"); pn.setLength(ts.tokenEnd - pn.getPosition()); pn.setLineno(lineno); return pn; } finally { inForInit = wasInForInit; } } private AstNode name(int ttFlagged, int tt) throws IOException { String nameString = ts.getString(); int namePos = ts.tokenBeg, nameLineno = ts.lineno; if (0 != (ttFlagged & TI_CHECK_LABEL) && peekToken() == Token.COLON) { // Do not consume colon. It is used as an unwind indicator // to return to statementHelper. Label label = new Label(namePos, ts.tokenEnd - namePos); label.setName(nameString); label.setLineno(ts.lineno); return label; } // Not a label. Unfortunately peeking the next token to check for // a colon has biffed ts.tokenBeg, ts.tokenEnd. We store the name's // bounds in instance vars and createNameNode uses them. saveNameTokenData(namePos, nameString, nameLineno); if (compilerEnv.isXmlAvailable()) { return propertyName(-1, nameString, 0); } else { return createNameNode(true, Token.NAME); } } /** * May return an {@link ArrayLiteral} or {@link ArrayComprehension}. */ private AstNode arrayLiteral() throws IOException { if (currentToken != Token.LB) codeBug(); int pos = ts.tokenBeg, end = ts.tokenEnd; List<AstNode> elements = new ArrayList<AstNode>(); ArrayLiteral pn = new ArrayLiteral(pos); boolean after_lb_or_comma = true; int afterComma = -1; int skipCount = 0; for (;;) { int tt = peekToken(); if (tt == Token.COMMA) { consumeToken(); afterComma = ts.tokenEnd; if (!after_lb_or_comma) { after_lb_or_comma = true; } else { elements.add(new EmptyExpression(ts.tokenBeg, 1)); skipCount++; } } else if (tt == Token.RB) { consumeToken(); // for ([a,] in obj) is legal, but for ([a] in obj) is // not since we have both key and value supplied. The // trick is that [a,] and [a] are equivalent in other // array literal contexts. So we calculate a special // length value just for destructuring assignment. end = ts.tokenEnd; pn.setDestructuringLength(elements.size() + (after_lb_or_comma ? 1 : 0)); pn.setSkipCount(skipCount); if (afterComma != -1) warnTrailingComma("msg.array.trailing.comma", pos, elements, afterComma); break; } else if (tt == Token.FOR && !after_lb_or_comma && elements.size() == 1) { return arrayComprehension(elements.get(0), pos); } else if (tt == Token.EOF) { end = ts.tokenBeg; break; } else { if (!after_lb_or_comma) { reportError("msg.no.bracket.arg"); } elements.add(assignExpr()); after_lb_or_comma = false; afterComma = -1; } } for (AstNode e : elements) { pn.addElement(e); } pn.setLength(end - pos); return pn; } /** * Parse a JavaScript 1.7 Array comprehension. * @param result the first expression after the opening left-bracket * @param pos start of LB token that begins the array comprehension * @return the array comprehension or an error node */ private AstNode arrayComprehension(AstNode result, int pos) throws IOException { List<ArrayComprehensionLoop> loops = new ArrayList<ArrayComprehensionLoop>(); while (peekToken() == Token.FOR) { loops.add(arrayComprehensionLoop()); } int ifPos = -1; ConditionData data = null; if (peekToken() == Token.IF) { consumeToken(); ifPos = ts.tokenBeg - pos; data = condition(); } mustMatchToken(Token.RB, "msg.no.bracket.arg"); ArrayComprehension pn = new ArrayComprehension(pos, ts.tokenEnd - pos); pn.setResult(result); pn.setLoops(loops); if (data != null) { pn.setIfPosition(ifPos); pn.setFilter(data.condition); pn.setFilterLp(data.lp - pos); pn.setFilterRp(data.rp - pos); } return pn; } private ArrayComprehensionLoop arrayComprehensionLoop() throws IOException { if (nextToken() != Token.FOR) codeBug(); int pos = ts.tokenBeg; int eachPos = -1, lp = -1, rp = -1, inPos = -1; ArrayComprehensionLoop pn = new ArrayComprehensionLoop(pos); pushScope(pn); try { if (matchToken(Token.NAME)) { if (ts.getString().equals("each")) { eachPos = ts.tokenBeg - pos; } else { reportError("msg.no.paren.for"); } } if (mustMatchToken(Token.LP, "msg.no.paren.for")) { lp = ts.tokenBeg - pos; } AstNode iter = null; switch (peekToken()) { case Token.LB: case Token.LC: // handle destructuring assignment iter = destructuringPrimaryExpr(); markDestructuring(iter); break; case Token.NAME: consumeToken(); iter = createNameNode(); break; default: reportError("msg.bad.var"); } // Define as a let since we want the scope of the variable to // be restricted to the array comprehension if (iter.getType() == Token.NAME) { defineSymbol(Token.LET, ts.getString(), true); } if (mustMatchToken(Token.IN, "msg.in.after.for.name")) inPos = ts.tokenBeg - pos; AstNode obj = expr(); if (mustMatchToken(Token.RP, "msg.no.paren.for.ctrl")) rp = ts.tokenBeg - pos; pn.setLength(ts.tokenEnd - pos); pn.setIterator(iter); pn.setIteratedObject(obj); pn.setInPosition(inPos); pn.setEachPosition(eachPos); pn.setIsForEach(eachPos != -1); pn.setParens(lp, rp); return pn; } finally { popScope(); } } private ObjectLiteral objectLiteral() throws IOException { int pos = ts.tokenBeg, lineno = ts.lineno; int afterComma = -1; List<ObjectProperty> elems = new ArrayList<ObjectProperty>(); Set<String> propertyNames = new HashSet<String>(); commaLoop: for (;;) { String propertyName = null; int tt = peekToken(); String jsdoc = getAndResetJsDoc(); switch(tt) { case Token.NAME: case Token.STRING: afterComma = -1; saveNameTokenData(ts.tokenBeg, ts.getString(), ts.lineno); consumeToken(); StringLiteral stringProp = null; if (tt == Token.STRING) { stringProp = createStringLiteral(); } Name name = createNameNode(); propertyName = ts.getString(); int ppos = ts.tokenBeg; if ((tt == Token.NAME && peekToken() == Token.NAME && ("get".equals(propertyName) || "set".equals(propertyName)))) { consumeToken(); name = createNameNode(); name.setJsDoc(jsdoc); ObjectProperty objectProp = getterSetterProperty(ppos, name, "get".equals(propertyName)); elems.add(objectProp); propertyName = objectProp.getLeft().getString(); } else { AstNode pname = stringProp != null ? stringProp : name; pname.setJsDoc(jsdoc); elems.add(plainProperty(pname, tt)); } break; case Token.NUMBER: consumeToken(); afterComma = -1; AstNode nl = new NumberLiteral(ts.tokenBeg, ts.getString(), ts.getNumber()); nl.setJsDoc(jsdoc); propertyName = ts.getString(); elems.add(plainProperty(nl, tt)); break; case Token.RC: if (afterComma != -1 && compilerEnv.getWarnTrailingComma()) warnTrailingComma("msg.extra.trailing.comma", pos, elems, afterComma); break commaLoop; default: reportError("msg.bad.prop"); break; } if (this.inUseStrictDirective) { if (propertyNames.contains(propertyName)) { addError("msg.dup.obj.lit.prop.strict", propertyName); } propertyNames.add(propertyName); } // Eat any dangling jsdoc in the property. getAndResetJsDoc(); jsdoc = null; if (matchToken(Token.COMMA)) { afterComma = ts.tokenEnd; } else { break commaLoop; } } mustMatchToken(Token.RC, "msg.no.brace.prop"); ObjectLiteral pn = new ObjectLiteral(pos, ts.tokenEnd - pos); pn.setElements(elems); pn.setLineno(lineno); return pn; } private ObjectProperty plainProperty(AstNode property, int ptt) throws IOException { // Support, e.g., |var {x, y} = o| as destructuring shorthand // for |var {x: x, y: y} = o|, as implemented in spidermonkey JS 1.8. int tt = peekToken(); if ((tt == Token.COMMA || tt == Token.RC) && ptt == Token.NAME && compilerEnv.getLanguageVersion() >= Context.VERSION_1_8) { if (!inDestructuringAssignment) { reportError("msg.bad.object.init"); } AstNode nn = new Name(property.getPosition(), property.getString()); ObjectProperty pn = new ObjectProperty(); pn.putProp(Node.DESTRUCTURING_SHORTHAND, Boolean.TRUE); pn.setLeftAndRight(property, nn); return pn; } mustMatchToken(Token.COLON, "msg.no.colon.prop"); ObjectProperty pn = new ObjectProperty(); pn.setOperatorPosition(ts.tokenBeg); pn.setLeftAndRight(property, assignExpr()); return pn; } private ObjectProperty getterSetterProperty(int pos, AstNode propName, boolean isGetter) throws IOException { FunctionNode fn = function(FunctionNode.FUNCTION_EXPRESSION); // We've already parsed the function name, so fn should be anonymous. Name name = fn.getFunctionName(); if (name != null && name.length() != 0) { reportError("msg.bad.prop"); } ObjectProperty pn = new ObjectProperty(pos); if (isGetter) { pn.setIsGetter(); } else { pn.setIsSetter(); } int end = getNodeEnd(fn); pn.setLeft(propName); pn.setRight(fn); pn.setLength(end - pos); return pn; } private Name createNameNode() { return createNameNode(false, Token.NAME); } /** * Create a {@code Name} node using the token info from the * last scanned name. In some cases we need to either synthesize * a name node, or we lost the name token information by peeking. * If the {@code token} parameter is not {@link Token#NAME}, then * we use token info saved in instance vars. */ private Name createNameNode(boolean checkActivation, int token) { int beg = ts.tokenBeg; String s = ts.getString(); int lineno = ts.lineno; if (currentToken != Token.NAME) { beg = prevNameTokenStart; s = prevNameTokenString; lineno = prevNameTokenLineno; prevNameTokenStart = 0; prevNameTokenString = ""; prevNameTokenLineno = 0; } if (s == null) { if (compilerEnv.isIdeMode()) { s = ""; } else { codeBug(); } } Name name = new Name(beg, s); name.setLineno(lineno); if (checkActivation) { checkActivationName(s, token); } return name; } private StringLiteral createStringLiteral() { int pos = ts.tokenBeg, end = ts.tokenEnd; StringLiteral s = new StringLiteral(pos, end - pos); s.setLineno(ts.lineno); s.setValue(ts.getString()); s.setQuoteCharacter(ts.getQuoteChar()); return s; } protected void checkActivationName(String name, int token) { if (!insideFunction()) { return; } boolean activation = false; if ("arguments".equals(name) || (compilerEnv.getActivationNames() != null && compilerEnv.getActivationNames().contains(name))) { activation = true; } else if ("length".equals(name)) { if (token == Token.GETPROP && compilerEnv.getLanguageVersion() == Context.VERSION_1_2) { // Use of "length" in 1.2 requires an activation object. activation = true; } } if (activation) { setRequiresActivation(); } } protected void setRequiresActivation() { if (insideFunction()) { ((FunctionNode)currentScriptOrFn).setRequiresActivation(); } } private void checkCallRequiresActivation(AstNode pn) { if ((pn.getType() == Token.NAME && "eval".equals(((Name)pn).getIdentifier())) || (pn.getType() == Token.GETPROP && "eval".equals(((PropertyGet)pn).getProperty().getIdentifier()))) setRequiresActivation(); } protected void setIsGenerator() { if (insideFunction()) { ((FunctionNode)currentScriptOrFn).setIsGenerator(); } } private void checkBadIncDec(UnaryExpression expr) { AstNode op = removeParens(expr.getOperand()); int tt = op.getType(); if (!(tt == Token.NAME || tt == Token.GETPROP || tt == Token.GETELEM || tt == Token.GET_REF || tt == Token.CALL)) reportError(expr.getType() == Token.INC ? "msg.bad.incr" : "msg.bad.decr"); } private ErrorNode makeErrorNode() { ErrorNode pn = new ErrorNode(ts.tokenBeg, ts.tokenEnd - ts.tokenBeg); pn.setLineno(ts.lineno); return pn; } // Return end of node. Assumes node does NOT have a parent yet. private int nodeEnd(AstNode node) { return node.getPosition() + node.getLength(); } private void saveNameTokenData(int pos, String name, int lineno) { prevNameTokenStart = pos; prevNameTokenString = name; prevNameTokenLineno = lineno; } /** * Return the file offset of the beginning of the input source line * containing the passed position. * * @param pos an offset into the input source stream. If the offset * is negative, it's converted to 0, and if it's beyond the end of * the source buffer, the last source position is used. * * @return the offset of the beginning of the line containing pos * (i.e. 1+ the offset of the first preceding newline). Returns -1 * if the {@link CompilerEnvirons} is not set to ide-mode, * and {@link #parse(java.io.Reader,String,int)} was used. */ private int lineBeginningFor(int pos) { if (sourceChars == null) { return -1; } if (pos <= 0) { return 0; } char[] buf = sourceChars; if (pos >= buf.length) { pos = buf.length - 1; } while (--pos >= 0) { char c = buf[pos]; if (c == '\n' || c == '\r') { return pos + 1; // want position after the newline } } return 0; } private void warnMissingSemi(int pos, int end) { // Should probably change this to be a CompilerEnvirons setting, // with an enum Never, Always, Permissive, where Permissive means // don't warn for 1-line functions like function (s) {return x+2} if (compilerEnv.isStrictMode()) { int beg = Math.max(pos, lineBeginningFor(end)); if (end == -1) end = ts.cursor; addStrictWarning("msg.missing.semi", "", beg, end - beg); } } private void warnTrailingComma(String messageId, int pos, List<?> elems, int commaPos) { if (compilerEnv.getWarnTrailingComma()) { // back up from comma to beginning of line or array/objlit if (!elems.isEmpty()) { pos = ((AstNode)elems.get(0)).getPosition(); } pos = Math.max(pos, lineBeginningFor(commaPos)); addWarning("msg.extra.trailing.comma", pos, commaPos - pos); } } private String readFully(Reader reader) throws IOException { BufferedReader in = new BufferedReader(reader); try { char[] cbuf = new char[1024]; StringBuilder sb = new StringBuilder(1024); int bytes_read; while ((bytes_read = in.read(cbuf, 0, 1024)) != -1) { sb.append(cbuf, 0, bytes_read); } return sb.toString(); } finally { in.close(); } } // helps reduce clutter in the already-large function() method protected class PerFunctionVariables { private ScriptNode savedCurrentScriptOrFn; private Scope savedCurrentScope; private int savedNestingOfWith; private int savedEndFlags; private boolean savedInForInit; private Map<String,LabeledStatement> savedLabelSet; private List<Loop> savedLoopSet; private List<Jump> savedLoopAndSwitchSet; PerFunctionVariables(FunctionNode fnNode) { savedCurrentScriptOrFn = Parser.this.currentScriptOrFn; Parser.this.currentScriptOrFn = fnNode; savedCurrentScope = Parser.this.currentScope; Parser.this.currentScope = fnNode; savedNestingOfWith = Parser.this.nestingOfWith; Parser.this.nestingOfWith = 0; savedLabelSet = Parser.this.labelSet; Parser.this.labelSet = null; savedLoopSet = Parser.this.loopSet; Parser.this.loopSet = null; savedLoopAndSwitchSet = Parser.this.loopAndSwitchSet; Parser.this.loopAndSwitchSet = null; savedEndFlags = Parser.this.endFlags; Parser.this.endFlags = 0; savedInForInit = Parser.this.inForInit; Parser.this.inForInit = false; } void restore() { Parser.this.currentScriptOrFn = savedCurrentScriptOrFn; Parser.this.currentScope = savedCurrentScope; Parser.this.nestingOfWith = savedNestingOfWith; Parser.this.labelSet = savedLabelSet; Parser.this.loopSet = savedLoopSet; Parser.this.loopAndSwitchSet = savedLoopAndSwitchSet; Parser.this.endFlags = savedEndFlags; Parser.this.inForInit = savedInForInit; } } /** * Given a destructuring assignment with a left hand side parsed * as an array or object literal and a right hand side expression, * rewrite as a series of assignments to the variables defined in * left from property accesses to the expression on the right. * @param type declaration type: Token.VAR or Token.LET or -1 * @param left array or object literal containing NAME nodes for * variables to assign * @param right expression to assign from * @return expression that performs a series of assignments to * the variables defined in left */ Node createDestructuringAssignment(int type, Node left, Node right) { String tempName = currentScriptOrFn.getNextTempName(); Node result = destructuringAssignmentHelper(type, left, right, tempName); Node comma = result.getLastChild(); comma.addChildToBack(createName(tempName)); return result; } Node destructuringAssignmentHelper(int variableType, Node left, Node right, String tempName) { Scope result = createScopeNode(Token.LETEXPR, left.getLineno()); result.addChildToFront(new Node(Token.LET, createName(Token.NAME, tempName, right))); try { pushScope(result); defineSymbol(Token.LET, tempName, true); } finally { popScope(); } Node comma = new Node(Token.COMMA); result.addChildToBack(comma); List<String> destructuringNames = new ArrayList<String>(); boolean empty = true; switch (left.getType()) { case Token.ARRAYLIT: empty = destructuringArray((ArrayLiteral)left, variableType, tempName, comma, destructuringNames); break; case Token.OBJECTLIT: empty = destructuringObject((ObjectLiteral)left, variableType, tempName, comma, destructuringNames); break; case Token.GETPROP: case Token.GETELEM: comma.addChildToBack(simpleAssignment(left, createName(tempName))); break; default: reportError("msg.bad.assign.left"); } if (empty) { // Don't want a COMMA node with no children. Just add a zero. comma.addChildToBack(createNumber(0)); } result.putProp(Node.DESTRUCTURING_NAMES, destructuringNames); return result; } boolean destructuringArray(ArrayLiteral array, int variableType, String tempName, Node parent, List<String> destructuringNames) { boolean empty = true; int setOp = variableType == Token.CONST ? Token.SETCONST : Token.SETNAME; int index = 0; for (AstNode n : array.getElements()) { if (n.getType() == Token.EMPTY) { index++; continue; } Node rightElem = new Node(Token.GETELEM, createName(tempName), createNumber(index)); if (n.getType() == Token.NAME) { String name = n.getString(); parent.addChildToBack(new Node(setOp, createName(Token.BINDNAME, name, null), rightElem)); if (variableType != -1) { defineSymbol(variableType, name, true); destructuringNames.add(name); } } else { parent.addChildToBack (destructuringAssignmentHelper (variableType, n, rightElem, currentScriptOrFn.getNextTempName())); } index++; empty = false; } return empty; } boolean destructuringObject(ObjectLiteral node, int variableType, String tempName, Node parent, List<String> destructuringNames) { boolean empty = true; int setOp = variableType == Token.CONST ? Token.SETCONST : Token.SETNAME; for (ObjectProperty prop : node.getElements()) { int lineno = 0; // This function is sometimes called from the IRFactory when // when executing regression tests, and in those cases the // tokenStream isn't set. Deal with it. if (ts != null) { lineno = ts.lineno; } AstNode id = prop.getLeft(); Node rightElem = null; if (id instanceof Name) { Node s = Node.newString(((Name)id).getIdentifier()); rightElem = new Node(Token.GETPROP, createName(tempName), s); } else if (id instanceof StringLiteral) { Node s = Node.newString(((StringLiteral)id).getValue()); rightElem = new Node(Token.GETPROP, createName(tempName), s); } else if (id instanceof NumberLiteral) { Node s = createNumber((int)((NumberLiteral)id).getNumber()); rightElem = new Node(Token.GETELEM, createName(tempName), s); } else { throw codeBug(); } rightElem.setLineno(lineno); AstNode value = prop.getRight(); if (value.getType() == Token.NAME) { String name = ((Name)value).getIdentifier(); parent.addChildToBack(new Node(setOp, createName(Token.BINDNAME, name, null), rightElem)); if (variableType != -1) { defineSymbol(variableType, name, true); destructuringNames.add(name); } } else { parent.addChildToBack (destructuringAssignmentHelper (variableType, value, rightElem, currentScriptOrFn.getNextTempName())); } empty = false; } return empty; } protected Node createName(String name) { checkActivationName(name, Token.NAME); return Node.newString(Token.NAME, name); } protected Node createName(int type, String name, Node child) { Node result = createName(name); result.setType(type); if (child != null) result.addChildToBack(child); return result; } protected Node createNumber(double number) { return Node.newNumber(number); } /** * Create a node that can be used to hold lexically scoped variable * definitions (via let declarations). * * @param token the token of the node to create * @param lineno line number of source * @return the created node */ protected Scope createScopeNode(int token, int lineno) { Scope scope =new Scope(); scope.setType(token); scope.setLineno(lineno); return scope; } // Quickie tutorial for some of the interpreter bytecodes. // // GETPROP - for normal foo.bar prop access; right side is a name // GETELEM - for normal foo[bar] element access; rhs is an expr // SETPROP - for assignment when left side is a GETPROP // SETELEM - for assignment when left side is a GETELEM // DELPROP - used for delete foo.bar or foo[bar] // // GET_REF, SET_REF, DEL_REF - in general, these mean you're using // get/set/delete on a right-hand side expression (possibly with no // explicit left-hand side) that doesn't use the normal JavaScript // Object (i.e. ScriptableObject) get/set/delete functions, but wants // to provide its own versions instead. It will ultimately implement // Ref, and currently SpecialRef (for __proto__ etc.) and XmlName // (for E4X XML objects) are the only implementations. The runtime // notices these bytecodes and delegates get/set/delete to the object. // // BINDNAME: used in assignments. LHS is evaluated first to get a // specific object containing the property ("binding" the property // to the object) so that it's always the same object, regardless of // side effects in the RHS. protected Node simpleAssignment(Node left, Node right) { int nodeType = left.getType(); switch (nodeType) { case Token.NAME: if (inUseStrictDirective && "eval".equals(((Name) left).getIdentifier())) { reportError("msg.bad.id.strict", ((Name) left).getIdentifier()); } left.setType(Token.BINDNAME); return new Node(Token.SETNAME, left, right); case Token.GETPROP: case Token.GETELEM: { Node obj, id; // If it's a PropertyGet or ElementGet, we're in the parse pass. // We could alternately have PropertyGet and ElementGet // override getFirstChild/getLastChild and return the appropriate // field, but that seems just as ugly as this casting. if (left instanceof PropertyGet) { obj = ((PropertyGet)left).getTarget(); id = ((PropertyGet)left).getProperty(); } else if (left instanceof ElementGet) { obj = ((ElementGet)left).getTarget(); id = ((ElementGet)left).getElement(); } else { // This branch is called during IRFactory transform pass. obj = left.getFirstChild(); id = left.getLastChild(); } int type; if (nodeType == Token.GETPROP) { type = Token.SETPROP; // TODO(stevey) - see https://bugzilla.mozilla.org/show_bug.cgi?id=492036 // The new AST code generates NAME tokens for GETPROP ids where the old parser // generated STRING nodes. If we don't set the type to STRING below, this will // cause java.lang.VerifyError in codegen for code like // "var obj={p:3};[obj.p]=[9];" id.setType(Token.STRING); } else { type = Token.SETELEM; } return new Node(type, obj, id, right); } case Token.GET_REF: { Node ref = left.getFirstChild(); checkMutableReference(ref); return new Node(Token.SET_REF, ref, right); } } throw codeBug(); } protected void checkMutableReference(Node n) { int memberTypeFlags = n.getIntProp(Node.MEMBER_TYPE_PROP, 0); if ((memberTypeFlags & Node.DESCENDANTS_FLAG) != 0) { reportError("msg.bad.assign.left"); } } // remove any ParenthesizedExpression wrappers protected AstNode removeParens(AstNode node) { while (node instanceof ParenthesizedExpression) { node = ((ParenthesizedExpression)node).getExpression(); } return node; } void markDestructuring(AstNode node) { if (node instanceof DestructuringForm) { ((DestructuringForm)node).setIsDestructuring(true); } else if (node instanceof ParenthesizedExpression) { markDestructuring(((ParenthesizedExpression)node).getExpression()); } } // throw a failed-assertion with some helpful debugging info private RuntimeException codeBug() throws RuntimeException { throw Kit.codeBug("ts.cursor=" + ts.cursor + ", ts.tokenBeg=" + ts.tokenBeg + ", currentToken=" + currentToken); } }
true
true
private FunctionNode function(int type) throws IOException { int syntheticType = type; int baseLineno = ts.lineno; // line number where source starts int functionSourceStart = ts.tokenBeg; // start of "function" kwd Name name = null; AstNode memberExprNode = null; if (matchToken(Token.NAME)) { name = createNameNode(true, Token.NAME); if (inUseStrictDirective) { String id = name.getIdentifier(); if ("eval".equals(id)|| "arguments".equals(id)) { reportError("msg.bad.id.strict", id); } } if (!matchToken(Token.LP)) { if (compilerEnv.isAllowMemberExprAsFunctionName()) { AstNode memberExprHead = name; name = null; memberExprNode = memberExprTail(false, memberExprHead); } mustMatchToken(Token.LP, "msg.no.paren.parms"); } } else if (matchToken(Token.LP)) { // Anonymous function: leave name as null } else { if (compilerEnv.isAllowMemberExprAsFunctionName()) { // Note that memberExpr can not start with '(' like // in function (1+2).toString(), because 'function (' already // processed as anonymous function memberExprNode = memberExpr(false); } mustMatchToken(Token.LP, "msg.no.paren.parms"); } int lpPos = currentToken == Token.LP ? ts.tokenBeg : -1; if (memberExprNode != null) { syntheticType = FunctionNode.FUNCTION_EXPRESSION; } if (syntheticType != FunctionNode.FUNCTION_EXPRESSION && name != null && name.length() > 0) { // Function statements define a symbol in the enclosing scope defineSymbol(Token.FUNCTION, name.getIdentifier()); } FunctionNode fnNode = new FunctionNode(functionSourceStart, name); fnNode.setFunctionType(type); if (lpPos != -1) fnNode.setLp(lpPos - functionSourceStart); if (insideFunction() || nestingOfWith > 0) { // 1. Nested functions are not affected by the dynamic scope flag // as dynamic scope is already a parent of their scope. // 2. Functions defined under the with statement also immune to // this setup, in which case dynamic scope is ignored in favor // of the with object. fnNode.setIgnoreDynamicScope(); } fnNode.setJsDoc(getAndResetJsDoc()); PerFunctionVariables savedVars = new PerFunctionVariables(fnNode); try { parseFunctionParams(fnNode); fnNode.setBody(parseFunctionBody()); fnNode.setEncodedSourceBounds(functionSourceStart, ts.tokenEnd); fnNode.setLength(ts.tokenEnd - functionSourceStart); if (compilerEnv.isStrictMode() && !fnNode.getBody().hasConsistentReturnUsage()) { String msg = (name != null && name.length() > 0) ? "msg.no.return.value" : "msg.anon.no.return.value"; addStrictWarning(msg, name.getIdentifier()); } // Function expressions define a name only in the body of the // function, and only if not hidden by a parameter name if (syntheticType == FunctionNode.FUNCTION_EXPRESSION && name != null && name.length() > 0 && currentScope.getSymbol(name.getIdentifier()) == null) { defineSymbol(Token.FUNCTION, name.getIdentifier()); } } finally { savedVars.restore(); } if (memberExprNode != null) { // TODO(stevey): fix missing functionality Kit.codeBug(); fnNode.setMemberExprNode(memberExprNode); // rewrite later /* old code: if (memberExprNode != null) { pn = nf.createAssignment(Token.ASSIGN, memberExprNode, pn); if (functionType != FunctionNode.FUNCTION_EXPRESSION) { // XXX check JScript behavior: should it be createExprStatement? pn = nf.createExprStatementNoReturn(pn, baseLineno); } } */ } fnNode.setSourceName(sourceURI); fnNode.setBaseLineno(baseLineno); fnNode.setEndLineno(ts.lineno); // Set the parent scope. Needed for finding undeclared vars. // Have to wait until after parsing the function to set its parent // scope, since defineSymbol needs the defining-scope check to stop // at the function boundary when checking for redeclarations. if (compilerEnv.isIdeMode()) { fnNode.setParentScope(currentScope); } return fnNode; }
private FunctionNode function(int type) throws IOException { int syntheticType = type; int baseLineno = ts.lineno; // line number where source starts int functionSourceStart = ts.tokenBeg; // start of "function" kwd Name name = null; AstNode memberExprNode = null; if (matchToken(Token.NAME)) { name = createNameNode(true, Token.NAME); if (inUseStrictDirective) { String id = name.getIdentifier(); if ("eval".equals(id)|| "arguments".equals(id)) { reportError("msg.bad.id.strict", id); } } if (!matchToken(Token.LP)) { if (compilerEnv.isAllowMemberExprAsFunctionName()) { AstNode memberExprHead = name; name = null; memberExprNode = memberExprTail(false, memberExprHead); } mustMatchToken(Token.LP, "msg.no.paren.parms"); } } else if (matchToken(Token.LP)) { // Anonymous function: leave name as null } else { if (compilerEnv.isAllowMemberExprAsFunctionName()) { // Note that memberExpr can not start with '(' like // in function (1+2).toString(), because 'function (' already // processed as anonymous function memberExprNode = memberExpr(false); } mustMatchToken(Token.LP, "msg.no.paren.parms"); } int lpPos = currentToken == Token.LP ? ts.tokenBeg : -1; if (memberExprNode != null) { syntheticType = FunctionNode.FUNCTION_EXPRESSION; } if (syntheticType != FunctionNode.FUNCTION_EXPRESSION && name != null && name.length() > 0) { // Function statements define a symbol in the enclosing scope defineSymbol(Token.FUNCTION, name.getIdentifier()); } FunctionNode fnNode = new FunctionNode(functionSourceStart, name); fnNode.setFunctionType(type); if (lpPos != -1) fnNode.setLp(lpPos - functionSourceStart); if (insideFunction() || nestingOfWith > 0) { // 1. Nested functions are not affected by the dynamic scope flag // as dynamic scope is already a parent of their scope. // 2. Functions defined under the with statement also immune to // this setup, in which case dynamic scope is ignored in favor // of the with object. fnNode.setIgnoreDynamicScope(); } fnNode.setJsDoc(getAndResetJsDoc()); PerFunctionVariables savedVars = new PerFunctionVariables(fnNode); try { parseFunctionParams(fnNode); fnNode.setBody(parseFunctionBody()); fnNode.setEncodedSourceBounds(functionSourceStart, ts.tokenEnd); fnNode.setLength(ts.tokenEnd - functionSourceStart); if (compilerEnv.isStrictMode() && !fnNode.getBody().hasConsistentReturnUsage()) { String msg = (name != null && name.length() > 0) ? "msg.no.return.value" : "msg.anon.no.return.value"; addStrictWarning(msg, name == null ? "" : name.getIdentifier()); } // Function expressions define a name only in the body of the // function, and only if not hidden by a parameter name if (syntheticType == FunctionNode.FUNCTION_EXPRESSION && name != null && name.length() > 0 && currentScope.getSymbol(name.getIdentifier()) == null) { defineSymbol(Token.FUNCTION, name.getIdentifier()); } } finally { savedVars.restore(); } if (memberExprNode != null) { // TODO(stevey): fix missing functionality Kit.codeBug(); fnNode.setMemberExprNode(memberExprNode); // rewrite later /* old code: if (memberExprNode != null) { pn = nf.createAssignment(Token.ASSIGN, memberExprNode, pn); if (functionType != FunctionNode.FUNCTION_EXPRESSION) { // XXX check JScript behavior: should it be createExprStatement? pn = nf.createExprStatementNoReturn(pn, baseLineno); } } */ } fnNode.setSourceName(sourceURI); fnNode.setBaseLineno(baseLineno); fnNode.setEndLineno(ts.lineno); // Set the parent scope. Needed for finding undeclared vars. // Have to wait until after parsing the function to set its parent // scope, since defineSymbol needs the defining-scope check to stop // at the function boundary when checking for redeclarations. if (compilerEnv.isIdeMode()) { fnNode.setParentScope(currentScope); } return fnNode; }
diff --git a/src/main/java/com/tomslabs/grid/avro/AvroAsTextTypedBytesInputFormat.java b/src/main/java/com/tomslabs/grid/avro/AvroAsTextTypedBytesInputFormat.java index 00836fa..9642372 100644 --- a/src/main/java/com/tomslabs/grid/avro/AvroAsTextTypedBytesInputFormat.java +++ b/src/main/java/com/tomslabs/grid/avro/AvroAsTextTypedBytesInputFormat.java @@ -1,105 +1,110 @@ /* * Copyright 2011, Bestofmedia, Inc. * * Bestofmedia licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.tomslabs.grid.avro; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.avro.file.DataFileReader; import org.apache.avro.file.FileReader; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericRecord; import org.apache.avro.mapred.AvroOutputFormat; import org.apache.avro.mapred.FsInput; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.mapred.FileInputFormat; import org.apache.hadoop.mapred.FileSplit; import org.apache.hadoop.mapred.InputSplit; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.RecordReader; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.typedbytes.TypedBytesWritable; public class AvroAsTextTypedBytesInputFormat extends FileInputFormat<TypedBytesWritable, TypedBytesWritable> { @Override protected FileStatus[] listStatus(JobConf job) throws IOException { List<FileStatus> result = new ArrayList<FileStatus>(); for (FileStatus file : super.listStatus(job)) if (file.getPath().getName().endsWith(AvroOutputFormat.EXT)) result.add(file); return result.toArray(new FileStatus[0]); } @Override public RecordReader<TypedBytesWritable, TypedBytesWritable> getRecordReader(InputSplit split, JobConf job, Reporter reporter) throws IOException { reporter.setStatus(split.toString()); return new AvroTypedBytesRecordReader<GenericRecord>(job, (FileSplit) split); } static class AvroTypedBytesRecordReader<T> implements RecordReader<TypedBytesWritable, TypedBytesWritable> { private FileReader<T> reader; private long start; private long end; public AvroTypedBytesRecordReader(JobConf job, FileSplit split) throws IOException { this(new DataFileReader<T>(new FsInput(split.getPath(), job), new GenericDatumReader<T>()), split); } protected AvroTypedBytesRecordReader(FileReader<T> reader, FileSplit split) throws IOException { this.reader = reader; reader.sync(split.getStart()); // sync to start this.start = reader.tell(); this.end = split.getStart() + split.getLength(); } public TypedBytesWritable createKey() { return new TypedBytesWritable(); } public TypedBytesWritable createValue() { return new TypedBytesWritable(); } public boolean next(TypedBytesWritable key, TypedBytesWritable value) throws IOException { if (!reader.hasNext() || reader.pastSync(end)) { return false; } key.setValue(""); - value.setValue(reader.next().toString()); + // until https://github.com/apache/avro/pull/2/ is fixed, we can not rely + // on toString() to provide a correct JSON string with unicode. + //value.setValue(reader.next().toString()); + StringBuilder buf = new StringBuilder(); + JSONUtils.writeJSON(reader.next(), buf); + value.setValue(buf.toString()); return true; } public float getProgress() throws IOException { if (end == start) { return 0.0f; } else { return Math.min(1.0f, (getPos() - start) / (float) (end - start)); } } public long getPos() throws IOException { return reader.tell(); } public void close() throws IOException { reader.close(); } } }
true
true
public boolean next(TypedBytesWritable key, TypedBytesWritable value) throws IOException { if (!reader.hasNext() || reader.pastSync(end)) { return false; } key.setValue(""); value.setValue(reader.next().toString()); return true; }
public boolean next(TypedBytesWritable key, TypedBytesWritable value) throws IOException { if (!reader.hasNext() || reader.pastSync(end)) { return false; } key.setValue(""); // until https://github.com/apache/avro/pull/2/ is fixed, we can not rely // on toString() to provide a correct JSON string with unicode. //value.setValue(reader.next().toString()); StringBuilder buf = new StringBuilder(); JSONUtils.writeJSON(reader.next(), buf); value.setValue(buf.toString()); return true; }
diff --git a/src/org/rascalmpl/interpreter/env/ModuleEnvironment.java b/src/org/rascalmpl/interpreter/env/ModuleEnvironment.java index f47ea0f718..4fb0de71f2 100644 --- a/src/org/rascalmpl/interpreter/env/ModuleEnvironment.java +++ b/src/org/rascalmpl/interpreter/env/ModuleEnvironment.java @@ -1,704 +1,704 @@ /******************************************************************************* * Copyright (c) 2009-2011 CWI * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * * Jurgen J. Vinju - [email protected] - CWI * * Tijs van der Storm - [email protected] * * Emilie Balland - (CWI) * * Paul Klint - [email protected] - CWI * * Mark Hills - [email protected] (CWI) * * Arnold Lankamp - [email protected] *******************************************************************************/ package org.rascalmpl.interpreter.env; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.imp.pdb.facts.IConstructor; import org.eclipse.imp.pdb.facts.IMap; import org.eclipse.imp.pdb.facts.IMapWriter; import org.eclipse.imp.pdb.facts.ISetWriter; import org.eclipse.imp.pdb.facts.ITuple; import org.eclipse.imp.pdb.facts.IValue; import org.eclipse.imp.pdb.facts.IValueFactory; import org.eclipse.imp.pdb.facts.exceptions.FactTypeUseException; import org.eclipse.imp.pdb.facts.type.Type; import org.eclipse.imp.pdb.facts.type.TypeFactory; import org.eclipse.imp.pdb.facts.type.TypeStore; import org.rascalmpl.ast.AbstractAST; import org.rascalmpl.ast.Name; import org.rascalmpl.ast.QualifiedName; import org.rascalmpl.ast.SyntaxDefinition; import org.rascalmpl.interpreter.Evaluator; import org.rascalmpl.interpreter.result.AbstractFunction; import org.rascalmpl.interpreter.result.ConstructorFunction; import org.rascalmpl.interpreter.result.OverloadedFunctionResult; import org.rascalmpl.interpreter.result.Result; import org.rascalmpl.interpreter.staticErrors.UndeclaredModuleError; import org.rascalmpl.interpreter.types.NonTerminalType; import org.rascalmpl.interpreter.types.RascalTypeFactory; import org.rascalmpl.interpreter.utils.Names; import org.rascalmpl.values.ValueFactoryFactory; import org.rascalmpl.values.uptr.Factory; /** * A module environment represents a module object (i.e. a running module). * It manages imported modules and visibility of the * functions and variables it declares. * * TODO: add management of locally declared types and constructors * */ public class ModuleEnvironment extends Environment { protected final GlobalEnvironment heap; protected Map<String, ModuleEnvironment> importedModules; protected Set<String> extended; protected Map<Type, List<Type>> extensions; protected TypeStore typeStore; protected Set<IValue> productions; protected Map<String, NonTerminalType> concreteSyntaxTypes; private boolean initialized; private boolean syntaxDefined; private boolean bootstrap; private String cachedParser; protected static final TypeFactory TF = TypeFactory.getInstance(); public ModuleEnvironment(String name, GlobalEnvironment heap) { super(name); this.heap = heap; this.importedModules = new HashMap<String, ModuleEnvironment>(); this.extensions = new HashMap<Type, List<Type>>(); this.concreteSyntaxTypes = new HashMap<String, NonTerminalType>(); this.productions = new HashSet<IValue>(); this.typeStore = new TypeStore(); this.initialized = false; this.syntaxDefined = false; this.bootstrap = false; } public void reset() { super.reset(); this.importedModules = new HashMap<String, ModuleEnvironment>(); this.extensions = new HashMap<Type, List<Type>>(); this.concreteSyntaxTypes = new HashMap<String, NonTerminalType>(); this.typeStore = new TypeStore(); this.productions = new HashSet<IValue>(); this.initialized = false; this.syntaxDefined = false; this.bootstrap = false; } @Override public GlobalEnvironment getHeap() { return heap; } public boolean isSyntaxDefined() { return syntaxDefined; } public void setSyntaxDefined(boolean val) { this.syntaxDefined = val; } @Override public void declareProduction(SyntaxDefinition x) { productions.add(x.getTree()); } /** * Builds a map to communicate all relevant syntax definitions to the parser generator. * See lang::rascal::grammar::definition::Modules.modules2grammar() */ public IMap getSyntaxDefinition() { List<String> todo = new LinkedList<String>(); Set<String> done = new HashSet<String>(); todo.add(getName()); IValueFactory VF = ValueFactoryFactory.getValueFactory(); Type DefSort = RascalTypeFactory.getInstance().nonTerminalType((IConstructor) Factory.Symbol_Sort.make(VF, "SyntaxDefinition")); IMapWriter result = VF.mapWriter(TF.stringType(), TF.tupleType(TF.setType(TF.stringType()), TF.setType(TF.stringType()), TF.setType(DefSort))); while(!todo.isEmpty()){ String m = todo.get(0); todo.remove(0); if(done.contains(m)) continue; done.add(m); ModuleEnvironment env = heap.getModule(m); if(env != null){ ISetWriter importWriter = VF.setWriter(TF.stringType()); for(String impname : env.getImports()){ if(!done.contains(impname)) todo.add(impname); importWriter.insert(VF.string(impname)); } ISetWriter extendWriter = VF.setWriter(TF.stringType()); for(String impname : env.getExtends()){ if(!done.contains(impname)) todo.add(impname); extendWriter.insert(VF.string(impname)); } ISetWriter defWriter = VF.setWriter(DefSort); for(IValue def : env.productions){ defWriter.insert(def); } ITuple t = VF.tuple(importWriter.done(), extendWriter.done(), defWriter.done()); result.put(VF.string(m), t); }else if(m == getName()){ // This is the root scope. ISetWriter importWriter = VF.setWriter(TF.stringType()); for(String impname : importedModules.keySet()){ if(!done.contains(impname)) todo.add(impname); importWriter.insert(VF.string(impname)); } ISetWriter extendWriter = VF.setWriter(TF.stringType()); - for(String impname : env.getExtends()){ + for(String impname : getExtends()){ if(!done.contains(impname)) todo.add(impname); extendWriter.insert(VF.string(impname)); } ISetWriter defWriter = VF.setWriter(DefSort); for(IValue def : productions){ defWriter.insert(def); } ITuple t = VF.tuple(importWriter.done(), extendWriter.done(), defWriter.done()); result.put(VF.string(m), t); } } return result.done(); } public boolean isModuleEnvironment() { return true; } public void addImport(String name, ModuleEnvironment env) { importedModules.put(name, env); typeStore.importStore(env.typeStore); } public void addExtend(String name) { if (extended == null) { extended = new HashSet<String>(); } extended.add(name); } public List<AbstractFunction> getTests() { List<AbstractFunction> result = new LinkedList<AbstractFunction>(); if (functionEnvironment != null) { for (OverloadedFunctionResult f : functionEnvironment.values()) { result.addAll(f.getTests()); } } return result; } @Override public Set<String> getImports() { return importedModules.keySet(); } public void unImport(String moduleName) { importedModules.remove(moduleName); } public String getName() { return name; } @Override public TypeStore getStore() { return typeStore; } @Override public Result<IValue> getVariable(QualifiedName name) { String modulename = Names.moduleName(name); String cons = Names.name(Names.lastName(name)); Type adt = getAbstractDataType(modulename); if (adt != null) { OverloadedFunctionResult result = null; OverloadedFunctionResult candidates = getAllFunctions(cons); if(candidates != null){ for(AbstractFunction candidate : candidates.iterable()){ if (candidate.getReturnType() == adt) { result = result == null ? new OverloadedFunctionResult(candidate) : result.add(candidate); } } } return result; } if (modulename != null) { if (modulename.equals(getName())) { return getVariable(cons); } ModuleEnvironment imported = getImport(modulename); if (imported == null) { throw new UndeclaredModuleError(modulename, name); } // TODO: will this not do a transitive closure? This should not happen... return imported.getVariable(name); } return getVariable(cons); } @Override public void storeVariable(String name, Result<IValue> value) { if (value instanceof AbstractFunction) { storeFunction(name, (AbstractFunction) value); return; } Result<IValue> result = super.getVariable(name); if (result != null) { super.storeVariable(name, value); } else { for (String i : getImports()) { ModuleEnvironment module = importedModules.get(i); result = module.getLocalPublicVariable(name); if (result != null) { module.storeVariable(name, value); return; } } super.storeVariable(name, value); } } protected org.rascalmpl.interpreter.result.Result<IValue> getSimpleVariable(String name) { Result<IValue> var = super.getSimpleVariable(name); if (var != null) { return var; } for (String moduleName : getImports()) { ModuleEnvironment mod = getImport(moduleName); var = mod.getLocalPublicVariable(name); if (var != null) { return var; } } return null; } /** * Search for the environment that declared a variable. */ protected Map<String,Result<IValue>> getVariableDefiningEnvironment(String name) { if (variableEnvironment != null) { Result<IValue> r = variableEnvironment.get(name); if (r != null) { return variableEnvironment; } } for (String moduleName : getImports()) { ModuleEnvironment mod = getImport(moduleName); Result<IValue> r = null; if (mod.variableEnvironment != null) r = mod.variableEnvironment.get(name); if (r != null && r.isPublic()) { return mod.variableEnvironment; } } return null; } @Override protected OverloadedFunctionResult getAllFunctions(String name) { OverloadedFunctionResult funs = super.getAllFunctions(name); for (String moduleName : getImports()) { ModuleEnvironment mod = getImport(moduleName); OverloadedFunctionResult locals = mod.getLocalPublicFunctions(name); if (locals != null && funs != null) { funs = locals.join(funs); } else if (funs == null && locals != null) { funs = locals; } } return funs; } private Result<IValue> getLocalPublicVariable(String name) { Result<IValue> var = null; if (variableEnvironment != null) { var = variableEnvironment.get(name); } if (var != null && var.isPublic()) { return var; } return null; } private OverloadedFunctionResult getLocalPublicFunctions(String name) { OverloadedFunctionResult all = null; if (functionEnvironment != null) { all = functionEnvironment.get(name); } OverloadedFunctionResult result = null; if (all == null) { return null; } for (AbstractFunction l : all.iterable()) { if (l.isPublic()) { result = result == null ? new OverloadedFunctionResult(l) : result.add(l); } } return result; } @Override public Type abstractDataType(String name, Type... parameters) { return TF.abstractDataType(typeStore, name, parameters); } public Type concreteSyntaxType(String name, IConstructor symbol) { NonTerminalType sort = (NonTerminalType) RascalTypeFactory.getInstance().nonTerminalType(symbol); concreteSyntaxTypes.put(name, sort); return sort; } @Override public ConstructorFunction constructorFromTuple(AbstractAST ast, Evaluator eval, Type adt, String name, Type tupleType) { Type cons = TF.constructorFromTuple(typeStore, adt, name, tupleType); ConstructorFunction function = new ConstructorFunction(ast, eval, this, cons); storeFunction(name, function); markNameFinal(name); markNameOverloadable(name); return function; } @Override public ConstructorFunction constructor(AbstractAST ast, Evaluator eval, Type nodeType, String name, Object... childrenAndLabels) { Type cons = TF.constructor(typeStore, nodeType, name, childrenAndLabels); ConstructorFunction function = new ConstructorFunction(ast, eval, this, cons); storeFunction(name, function); markNameFinal(name); markNameOverloadable(name); return function; } @Override public ConstructorFunction constructor(AbstractAST ast, Evaluator eval, Type nodeType, String name, Type... children) { Type cons = TF.constructor(typeStore, nodeType, name, children); ConstructorFunction function = new ConstructorFunction(ast, eval, this, cons); storeFunction(name, function); markNameFinal(name); markNameOverloadable(name); return function; } @Override public Type aliasType(String name, Type aliased, Type... parameters) { return TF.aliasType(typeStore, name, aliased, parameters); } @Override public void declareAnnotation(Type onType, String label, Type valueType) { typeStore.declareAnnotation(onType, label, valueType); } @Override public Type getAnnotationType(Type type, String label) { Type anno = typeStore.getAnnotationType(type, label); if (anno == null && type instanceof NonTerminalType) { return typeStore.getAnnotationType(Factory.Tree, label); } return anno; } @Override public Type getAbstractDataType(String sort) { return typeStore.lookupAbstractDataType(sort); } @Override public Type getConstructor(String cons, Type args) { return typeStore.lookupFirstConstructor(cons, args); } @Override public Type getConstructor(Type sort, String cons, Type args) { return typeStore.lookupConstructor(sort, cons, args); } @Override public boolean isTreeConstructorName(QualifiedName name, Type signature) { java.util.List<Name> names = name.getNames(); if (names.size() > 1) { String sort = Names.sortName(name); Type sortType = getAbstractDataType(sort); if (sortType != null) { String cons = Names.consName(name); if (getConstructor(sortType, cons, signature) != null) { return true; } } } else { String cons = Names.consName(name); if (getConstructor(cons, signature) != null) { return true; } } return false; } @Override public String toString() { return "Environment [ " + getName() + ", imports: " + ((importedModules != null) ? importedModules : "") + ", extends: " + ((extended != null) ? extended : "") + "]"; } @Override public ModuleEnvironment getImport(String moduleName) { return importedModules.get(moduleName); } @Override public void storeVariable(QualifiedName name, Result<IValue> result) { String modulename = Names.moduleName(name); if (modulename != null) { if (modulename.equals(getName())) { storeVariable(Names.name(Names.lastName(name)), result); return; } ModuleEnvironment imported = getImport(modulename); if (imported == null) { throw new UndeclaredModuleError(modulename, name); } imported.storeVariable(name, result); return; } super.storeVariable(name, result); } @Override public boolean declaresAnnotation(Type type, String label) { return typeStore.getAnnotationType(type, label) != null; } @Override public Type lookupAbstractDataType(String name) { return typeStore.lookupAbstractDataType(name); } @Override public Type lookupConcreteSyntaxType(String name) { Type type = concreteSyntaxTypes.get(name); if (type == null) { for (String i : getImports()) { ModuleEnvironment mod = getImport(i); // don't recurse here (cyclic imports!) type = mod.concreteSyntaxTypes.get(name); if (type != null) { return type; } } } return type; } @Override public Type lookupAlias(String name) { return typeStore.lookupAlias(name); } @Override public Set<Type> lookupAlternatives(Type adt) { return typeStore.lookupAlternatives(adt); } @Override public Type lookupConstructor(Type adt, String cons, Type args) { return typeStore.lookupConstructor(adt, cons, args); } @Override public Set<Type> lookupConstructor(Type adt, String constructorName) throws FactTypeUseException { return typeStore.lookupConstructor(adt, constructorName); } @Override public Set<Type> lookupConstructors(String constructorName) { return typeStore.lookupConstructors(constructorName); } @Override public Type lookupFirstConstructor(String cons, Type args) { return typeStore.lookupFirstConstructor(cons, args); } public boolean isInitialized() { return initialized; } public void setInitialized() { this.initialized = true; } public void setInitialized(boolean init) { this.initialized = init; } public void setBootstrap(boolean needBootstrapParser) { this.bootstrap = needBootstrapParser; } public boolean getBootstrap() { return bootstrap; } // todo: bootstrap must go and use this public void setCachedParser(String cachedParser) { this.cachedParser = cachedParser; } public String getCachedParser() { return cachedParser; } public boolean hasCachedParser() { return cachedParser != null; } @Override protected boolean isNameFlagged(QualifiedName name, int flags) { String modulename = Names.moduleName(name); String cons = Names.name(Names.lastName(name)); if (modulename != null) { if (modulename.equals(getName())) { return isNameFlagged(cons, flags); } ModuleEnvironment imported = getImport(modulename); if (imported == null) { throw new UndeclaredModuleError(modulename, name); } return imported.isNameFlagged(cons, flags); } return isNameFlagged(cons, flags); } @Override protected void flagName(QualifiedName name, int flags) { String modulename = Names.moduleName(name); String cons = Names.name(Names.lastName(name)); if (modulename != null) { if (modulename.equals(getName())) { flagName(cons, flags); } ModuleEnvironment imported = getImport(modulename); if (imported == null) { throw new UndeclaredModuleError(modulename, name); } imported.flagName(cons, flags); } flagName(cons, flags); } @Override protected Environment getFlagsEnvironment(String name) { Environment env = super.getFlagsEnvironment(name); if (env != null) { return env; } for (String moduleName : getImports()) { ModuleEnvironment mod = getImport(moduleName); env = mod.getLocalFlagsEnvironment(name); if (env != null) { return env; } } return null; } private Environment getLocalFlagsEnvironment(String name) { if (this.nameFlags != null && nameFlags.get(name) != null) return this; return null; } public Set<String> getExtends() { if (extended != null) { return Collections.unmodifiableSet(extended); } return Collections.<String>emptySet(); } }
true
true
public IMap getSyntaxDefinition() { List<String> todo = new LinkedList<String>(); Set<String> done = new HashSet<String>(); todo.add(getName()); IValueFactory VF = ValueFactoryFactory.getValueFactory(); Type DefSort = RascalTypeFactory.getInstance().nonTerminalType((IConstructor) Factory.Symbol_Sort.make(VF, "SyntaxDefinition")); IMapWriter result = VF.mapWriter(TF.stringType(), TF.tupleType(TF.setType(TF.stringType()), TF.setType(TF.stringType()), TF.setType(DefSort))); while(!todo.isEmpty()){ String m = todo.get(0); todo.remove(0); if(done.contains(m)) continue; done.add(m); ModuleEnvironment env = heap.getModule(m); if(env != null){ ISetWriter importWriter = VF.setWriter(TF.stringType()); for(String impname : env.getImports()){ if(!done.contains(impname)) todo.add(impname); importWriter.insert(VF.string(impname)); } ISetWriter extendWriter = VF.setWriter(TF.stringType()); for(String impname : env.getExtends()){ if(!done.contains(impname)) todo.add(impname); extendWriter.insert(VF.string(impname)); } ISetWriter defWriter = VF.setWriter(DefSort); for(IValue def : env.productions){ defWriter.insert(def); } ITuple t = VF.tuple(importWriter.done(), extendWriter.done(), defWriter.done()); result.put(VF.string(m), t); }else if(m == getName()){ // This is the root scope. ISetWriter importWriter = VF.setWriter(TF.stringType()); for(String impname : importedModules.keySet()){ if(!done.contains(impname)) todo.add(impname); importWriter.insert(VF.string(impname)); } ISetWriter extendWriter = VF.setWriter(TF.stringType()); for(String impname : env.getExtends()){ if(!done.contains(impname)) todo.add(impname); extendWriter.insert(VF.string(impname)); } ISetWriter defWriter = VF.setWriter(DefSort); for(IValue def : productions){ defWriter.insert(def); } ITuple t = VF.tuple(importWriter.done(), extendWriter.done(), defWriter.done()); result.put(VF.string(m), t); } } return result.done(); }
public IMap getSyntaxDefinition() { List<String> todo = new LinkedList<String>(); Set<String> done = new HashSet<String>(); todo.add(getName()); IValueFactory VF = ValueFactoryFactory.getValueFactory(); Type DefSort = RascalTypeFactory.getInstance().nonTerminalType((IConstructor) Factory.Symbol_Sort.make(VF, "SyntaxDefinition")); IMapWriter result = VF.mapWriter(TF.stringType(), TF.tupleType(TF.setType(TF.stringType()), TF.setType(TF.stringType()), TF.setType(DefSort))); while(!todo.isEmpty()){ String m = todo.get(0); todo.remove(0); if(done.contains(m)) continue; done.add(m); ModuleEnvironment env = heap.getModule(m); if(env != null){ ISetWriter importWriter = VF.setWriter(TF.stringType()); for(String impname : env.getImports()){ if(!done.contains(impname)) todo.add(impname); importWriter.insert(VF.string(impname)); } ISetWriter extendWriter = VF.setWriter(TF.stringType()); for(String impname : env.getExtends()){ if(!done.contains(impname)) todo.add(impname); extendWriter.insert(VF.string(impname)); } ISetWriter defWriter = VF.setWriter(DefSort); for(IValue def : env.productions){ defWriter.insert(def); } ITuple t = VF.tuple(importWriter.done(), extendWriter.done(), defWriter.done()); result.put(VF.string(m), t); }else if(m == getName()){ // This is the root scope. ISetWriter importWriter = VF.setWriter(TF.stringType()); for(String impname : importedModules.keySet()){ if(!done.contains(impname)) todo.add(impname); importWriter.insert(VF.string(impname)); } ISetWriter extendWriter = VF.setWriter(TF.stringType()); for(String impname : getExtends()){ if(!done.contains(impname)) todo.add(impname); extendWriter.insert(VF.string(impname)); } ISetWriter defWriter = VF.setWriter(DefSort); for(IValue def : productions){ defWriter.insert(def); } ITuple t = VF.tuple(importWriter.done(), extendWriter.done(), defWriter.done()); result.put(VF.string(m), t); } } return result.done(); }
diff --git a/src/test/ed/util/ScriptTestInstanceBase.java b/src/test/ed/util/ScriptTestInstanceBase.java index cfb20997f..2d23262fa 100644 --- a/src/test/ed/util/ScriptTestInstanceBase.java +++ b/src/test/ed/util/ScriptTestInstanceBase.java @@ -1,95 +1,96 @@ /** * Copyright (C) 2008 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ed.util; import java.io.File; import org.testng.annotations.Test; import ed.js.JSFunction; import ed.js.func.JSFunctionCalls0; import ed.util.ScriptTestInstance; import ed.js.engine.Scope; import ed.js.Shell; import ed.MyAsserts; /** * Dynamic test instance for testing any 10genPlatform script * * Code stolen lock, stock and barrel from ConvertTest. Uses exact same convention * and scheme for comparing output */ public abstract class ScriptTestInstanceBase extends MyAsserts implements ScriptTestInstance{ File _file; public ScriptTestInstanceBase() { } public void setTestScriptFile(File f) { _file = f; } public File getTestScriptFile() { return _file; } /** * Test method for running a script * * @throws Exception in case of failure */ @Test public void test() throws Exception { // System.out.println("ScriptTestInstanceBase : running " + _file); JSFunction f = convert(); Scope scope = Scope.newGlobal().child(new File("/tmp")); scope.setGlobal( true ); scope.makeThreadLocal(); /* * augment the scope */ preTest(scope); Shell.addNiceShellStuff(scope); scope.put( "exit" , new JSFunctionCalls0(){ public Object call( Scope s , Object crap[] ){ System.err.println("JSTestInstance : exit() called from " + _file.toString() + " Ignoring."); return null; } } , true ); + ed.appserver.JSFileLibrary.addPath( f , new ed.appserver.JSFileLibrary( _file.getParentFile() , "asd" , scope ) ); try { f.call(scope); validateOutput(scope); } catch (RuntimeException re) { throw new Exception("For file " + _file.toString(), re); } finally { scope.kill(); } } }
true
true
public void test() throws Exception { // System.out.println("ScriptTestInstanceBase : running " + _file); JSFunction f = convert(); Scope scope = Scope.newGlobal().child(new File("/tmp")); scope.setGlobal( true ); scope.makeThreadLocal(); /* * augment the scope */ preTest(scope); Shell.addNiceShellStuff(scope); scope.put( "exit" , new JSFunctionCalls0(){ public Object call( Scope s , Object crap[] ){ System.err.println("JSTestInstance : exit() called from " + _file.toString() + " Ignoring."); return null; } } , true ); try { f.call(scope); validateOutput(scope); } catch (RuntimeException re) { throw new Exception("For file " + _file.toString(), re); } finally { scope.kill(); } }
public void test() throws Exception { // System.out.println("ScriptTestInstanceBase : running " + _file); JSFunction f = convert(); Scope scope = Scope.newGlobal().child(new File("/tmp")); scope.setGlobal( true ); scope.makeThreadLocal(); /* * augment the scope */ preTest(scope); Shell.addNiceShellStuff(scope); scope.put( "exit" , new JSFunctionCalls0(){ public Object call( Scope s , Object crap[] ){ System.err.println("JSTestInstance : exit() called from " + _file.toString() + " Ignoring."); return null; } } , true ); ed.appserver.JSFileLibrary.addPath( f , new ed.appserver.JSFileLibrary( _file.getParentFile() , "asd" , scope ) ); try { f.call(scope); validateOutput(scope); } catch (RuntimeException re) { throw new Exception("For file " + _file.toString(), re); } finally { scope.kill(); } }
diff --git a/freeplane/src/org/freeplane/core/ui/components/BitmapImagePreview.java b/freeplane/src/org/freeplane/core/ui/components/BitmapImagePreview.java index 033c05eb0..228ac2b06 100644 --- a/freeplane/src/org/freeplane/core/ui/components/BitmapImagePreview.java +++ b/freeplane/src/org/freeplane/core/ui/components/BitmapImagePreview.java @@ -1,107 +1,107 @@ /* * Freeplane - mind map editor * Copyright (C) 2009 Dimitry * * This file author is Dimitry * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.freeplane.core.ui.components; /** * @author Dimitry Polivaev * 22.08.2009 */ import java.awt.Color; import java.awt.Dimension; import java.awt.Image; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.border.MatteBorder; import org.freeplane.core.resources.ResourceController; import org.freeplane.core.util.LogTool; public class BitmapImagePreview extends JComponent implements PropertyChangeListener { /** * */ private static final long serialVersionUID = 1L; protected static final int BORDER_WIDTH = 2; protected final JFileChooser fc; public BitmapImagePreview(final JFileChooser fc) { super(); this.fc = fc; setBorder(new MatteBorder(BORDER_WIDTH, BORDER_WIDTH, BORDER_WIDTH, BORDER_WIDTH, Color.BLACK)); final int previewSize = ResourceController.getResourceController().getIntProperty("image_preview_size", 300); setPreferredSize(new Dimension(previewSize, previewSize)); fc.addPropertyChangeListener(this); } public void propertyChange(final PropertyChangeEvent e) { final String prop = e.getPropertyName(); //If the directory changed, don't show an image. final File file; if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop)) { file = null; //If a file became selected, find out which one. } else if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) { file = (File) e.getNewValue(); } else { return; } - if(! file.exists()){ + if(file == null || ! file.exists()){ return; } if (getComponentCount() == 1) { remove(0); } repaint(); if (file == null) { return; } try { updateView(file); } catch (final MalformedURLException e1) { LogTool.warn(e1); } catch (final IOException e1) { LogTool.warn(e1); } } protected void updateView(final File file) throws MalformedURLException, IOException { final BitmapViewerComponent viewer = new BitmapViewerComponent(file.toURI()); viewer.setHint(Image.SCALE_FAST); final Dimension size = getSize(); size.width -= 2 * BORDER_WIDTH; size.height -= 2 * BORDER_WIDTH; viewer.setPreferredSize(size); viewer.setSize(size); viewer.setLocation(BORDER_WIDTH, BORDER_WIDTH); add(viewer); viewer.revalidate(); viewer.repaint(); } }
true
true
public void propertyChange(final PropertyChangeEvent e) { final String prop = e.getPropertyName(); //If the directory changed, don't show an image. final File file; if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop)) { file = null; //If a file became selected, find out which one. } else if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) { file = (File) e.getNewValue(); } else { return; } if(! file.exists()){ return; } if (getComponentCount() == 1) { remove(0); } repaint(); if (file == null) { return; } try { updateView(file); } catch (final MalformedURLException e1) { LogTool.warn(e1); } catch (final IOException e1) { LogTool.warn(e1); } }
public void propertyChange(final PropertyChangeEvent e) { final String prop = e.getPropertyName(); //If the directory changed, don't show an image. final File file; if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop)) { file = null; //If a file became selected, find out which one. } else if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) { file = (File) e.getNewValue(); } else { return; } if(file == null || ! file.exists()){ return; } if (getComponentCount() == 1) { remove(0); } repaint(); if (file == null) { return; } try { updateView(file); } catch (final MalformedURLException e1) { LogTool.warn(e1); } catch (final IOException e1) { LogTool.warn(e1); } }
diff --git a/src/main/java/lamprey/seprphase3/GUI/Screens/GameplayScreen.java b/src/main/java/lamprey/seprphase3/GUI/Screens/GameplayScreen.java index 30c88a6..317d3db 100644 --- a/src/main/java/lamprey/seprphase3/GUI/Screens/GameplayScreen.java +++ b/src/main/java/lamprey/seprphase3/GUI/Screens/GameplayScreen.java @@ -1,182 +1,182 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package lamprey.seprphase3.GUI.Screens; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.scenes.scene2d.ui.Image; import eel.seprphase2.Simulator.GameManager; import eel.seprphase2.Simulator.PlantController; import eel.seprphase2.Simulator.PlantStatus; import lamprey.seprphase3.GUI.BackyardReactor; import lamprey.seprphase3.GUI.GameplayListeners; import lamprey.seprphase3.GUI.Images.HoverButton; import lamprey.seprphase3.GUI.Images.MechanicImage; import lamprey.seprphase3.GUI.Images.TurbineImage; /** * * @author Simeon */ public class GameplayScreen extends AbstractScreen { GameplayListeners listeners; Texture gamebgTexture; Texture borderTexture; Texture condenserTexture; Texture coolerTexture; Texture pipesTexture; Texture poweroutTexture; Texture reactorbackTexture; Texture pauseTexture; Texture consolebackTexture; Texture crUpTexture; Texture crDownTexture; Texture pump1Texture; Texture pump2Texture; Texture valve1Texture; Texture valve2Texture; Texture sErrorTexture; Image gamebgImage; Image borderImage; HoverButton condenserImage; Image coolerImage; Image pipesImage; Image poweroutImage; HoverButton reactorImage; TurbineImage turbineImage; MechanicImage mechanicImage; HoverButton pauseImage; Image consolebackImage; HoverButton crUpImage; HoverButton crDownImage; HoverButton pump1Image; HoverButton pump2Image; HoverButton valve1Image; HoverButton valve2Image; Image sErrorImage; public GameplayScreen(BackyardReactor game, PlantController controller, PlantStatus status, GameManager manager) { super(game, controller, status, manager); listeners = new GameplayListeners(this, controller, status, manager); gamebgTexture = new Texture(Gdx.files.internal("assets\\game\\bg.png")); borderTexture = new Texture(Gdx.files.internal("assets\\game\\border.png")); condenserTexture = new Texture(Gdx.files.internal("assets\\game\\condenser.png")); coolerTexture = new Texture(Gdx.files.internal("assets\\game\\cooler.png")); pipesTexture = new Texture(Gdx.files.internal("assets\\game\\pipes.png")); poweroutTexture = new Texture(Gdx.files.internal("assets\\game\\powerout.png")); reactorbackTexture = new Texture(Gdx.files.internal("assets\\game\\reactor_back.png")); pauseTexture = new Texture(Gdx.files.internal("assets\\game\\pause.png")); consolebackTexture = new Texture(Gdx.files.internal("assets\\game\\consoleback.png")); crUpTexture = new Texture(Gdx.files.internal("assets\\game\\controlrodup.png")); crDownTexture = new Texture(Gdx.files.internal("assets\\game\\controlroddown.png")); pump1Texture = new Texture(Gdx.files.internal("assets\\game\\pump1.png")); pump2Texture = new Texture(Gdx.files.internal("assets\\game\\pump2.png")); valve1Texture = new Texture(Gdx.files.internal("assets\\game\\valve1.png")); valve2Texture = new Texture(Gdx.files.internal("assets\\game\\valve2.png")); - sErrorTexture = new Texture(Gdx.files.internal("assets\\game\\softwareError.png")); + sErrorTexture = new Texture(Gdx.files.internal("assets\\game\\softwareerror.png")); gamebgImage = new Image(gamebgTexture); borderImage = new Image(borderTexture); condenserImage = new HoverButton(condenserTexture, false); coolerImage = new HoverButton(coolerTexture, false); pipesImage = new Image(pipesTexture); poweroutImage = new Image(poweroutTexture); reactorImage = new HoverButton(reactorbackTexture, false); turbineImage = new TurbineImage(this.getPlantStatus()); mechanicImage = new MechanicImage(); pauseImage = new HoverButton(pauseTexture, true); consolebackImage = new Image(consolebackTexture); crUpImage = new HoverButton(crUpTexture, false); crDownImage = new HoverButton(crDownTexture, false); pump1Image = new HoverButton(pump1Texture, false); pump2Image = new HoverButton(pump2Texture, false); valve1Image = new HoverButton(valve1Texture, false); valve2Image = new HoverButton(valve2Texture, false); sErrorImage = new Image(sErrorTexture); gamebgImage.setPosition(0, 0); borderImage.setPosition(0, 0); condenserImage.setPosition(523, 110); coolerImage.setPosition(803, 122); pipesImage.setPosition(132, 149); poweroutImage.setPosition(703, 405); reactorImage.setPosition(33, 113); turbineImage.setPosition(436, 404); mechanicImage.setPosition(630, 75); mechanicImage.moveMechanicTo(630f); //ensures the mechanic is initially not moving pauseImage.setPosition(17, 15); consolebackImage.setPosition(260, 0); crUpImage.setPosition(545, 75); crDownImage.setPosition(560, 21); pump1Image.setPosition(323, 71); pump2Image.setPosition(373, 76); valve1Image.setPosition(300, 22); valve2Image.setPosition(353, 22); sErrorImage.setPosition(433, 18); condenserImage.addListener(listeners.getCondenserListener()); // coolerImage.addListener(listeners.getCoolerListener()); reactorImage.addListener(listeners.getReactorListener()); pauseImage.addListener(listeners.getPauseListener()); crUpImage.addListener(listeners.getConrolRodsUpListener()); crDownImage.addListener(listeners.getConrolRodsDownListener()); valve1Image.addListener(listeners.getValve1Listener()); valve2Image.addListener(listeners.getValve2Listener()); pump1Image.addListener(listeners.getPump1Listener()); pump2Image.addListener(listeners.getPump2Listener()); } @Override public void show() { super.show(); stage.addActor(gamebgImage); stage.addActor(borderImage); stage.addActor(pipesImage); stage.addActor(coolerImage); stage.addActor(poweroutImage); stage.addActor(reactorImage); stage.addActor(turbineImage); stage.addActor(condenserImage); stage.addActor(mechanicImage); stage.addActor(pauseImage); stage.addActor(consolebackImage); stage.addActor(crUpImage); stage.addActor(crDownImage); stage.addActor(pump1Image); stage.addActor(pump2Image); stage.addActor(valve1Image); stage.addActor(valve2Image); stage.addActor(sErrorImage); } @Override public void resize(int width, int height) { super.resize(width, height); } @Override public void render(float delta) { super.render(delta); } @Override public void hide() { stage.clear(); } public void moveMechanicTo(float destination) { mechanicImage.moveMechanicTo(destination); } public BackyardReactor getGame() { return this.game; } }
true
true
public GameplayScreen(BackyardReactor game, PlantController controller, PlantStatus status, GameManager manager) { super(game, controller, status, manager); listeners = new GameplayListeners(this, controller, status, manager); gamebgTexture = new Texture(Gdx.files.internal("assets\\game\\bg.png")); borderTexture = new Texture(Gdx.files.internal("assets\\game\\border.png")); condenserTexture = new Texture(Gdx.files.internal("assets\\game\\condenser.png")); coolerTexture = new Texture(Gdx.files.internal("assets\\game\\cooler.png")); pipesTexture = new Texture(Gdx.files.internal("assets\\game\\pipes.png")); poweroutTexture = new Texture(Gdx.files.internal("assets\\game\\powerout.png")); reactorbackTexture = new Texture(Gdx.files.internal("assets\\game\\reactor_back.png")); pauseTexture = new Texture(Gdx.files.internal("assets\\game\\pause.png")); consolebackTexture = new Texture(Gdx.files.internal("assets\\game\\consoleback.png")); crUpTexture = new Texture(Gdx.files.internal("assets\\game\\controlrodup.png")); crDownTexture = new Texture(Gdx.files.internal("assets\\game\\controlroddown.png")); pump1Texture = new Texture(Gdx.files.internal("assets\\game\\pump1.png")); pump2Texture = new Texture(Gdx.files.internal("assets\\game\\pump2.png")); valve1Texture = new Texture(Gdx.files.internal("assets\\game\\valve1.png")); valve2Texture = new Texture(Gdx.files.internal("assets\\game\\valve2.png")); sErrorTexture = new Texture(Gdx.files.internal("assets\\game\\softwareError.png")); gamebgImage = new Image(gamebgTexture); borderImage = new Image(borderTexture); condenserImage = new HoverButton(condenserTexture, false); coolerImage = new HoverButton(coolerTexture, false); pipesImage = new Image(pipesTexture); poweroutImage = new Image(poweroutTexture); reactorImage = new HoverButton(reactorbackTexture, false); turbineImage = new TurbineImage(this.getPlantStatus()); mechanicImage = new MechanicImage(); pauseImage = new HoverButton(pauseTexture, true); consolebackImage = new Image(consolebackTexture); crUpImage = new HoverButton(crUpTexture, false); crDownImage = new HoverButton(crDownTexture, false); pump1Image = new HoverButton(pump1Texture, false); pump2Image = new HoverButton(pump2Texture, false); valve1Image = new HoverButton(valve1Texture, false); valve2Image = new HoverButton(valve2Texture, false); sErrorImage = new Image(sErrorTexture); gamebgImage.setPosition(0, 0); borderImage.setPosition(0, 0); condenserImage.setPosition(523, 110); coolerImage.setPosition(803, 122); pipesImage.setPosition(132, 149); poweroutImage.setPosition(703, 405); reactorImage.setPosition(33, 113); turbineImage.setPosition(436, 404); mechanicImage.setPosition(630, 75); mechanicImage.moveMechanicTo(630f); //ensures the mechanic is initially not moving pauseImage.setPosition(17, 15); consolebackImage.setPosition(260, 0); crUpImage.setPosition(545, 75); crDownImage.setPosition(560, 21); pump1Image.setPosition(323, 71); pump2Image.setPosition(373, 76); valve1Image.setPosition(300, 22); valve2Image.setPosition(353, 22); sErrorImage.setPosition(433, 18); condenserImage.addListener(listeners.getCondenserListener()); // coolerImage.addListener(listeners.getCoolerListener()); reactorImage.addListener(listeners.getReactorListener()); pauseImage.addListener(listeners.getPauseListener()); crUpImage.addListener(listeners.getConrolRodsUpListener()); crDownImage.addListener(listeners.getConrolRodsDownListener()); valve1Image.addListener(listeners.getValve1Listener()); valve2Image.addListener(listeners.getValve2Listener()); pump1Image.addListener(listeners.getPump1Listener()); pump2Image.addListener(listeners.getPump2Listener()); }
public GameplayScreen(BackyardReactor game, PlantController controller, PlantStatus status, GameManager manager) { super(game, controller, status, manager); listeners = new GameplayListeners(this, controller, status, manager); gamebgTexture = new Texture(Gdx.files.internal("assets\\game\\bg.png")); borderTexture = new Texture(Gdx.files.internal("assets\\game\\border.png")); condenserTexture = new Texture(Gdx.files.internal("assets\\game\\condenser.png")); coolerTexture = new Texture(Gdx.files.internal("assets\\game\\cooler.png")); pipesTexture = new Texture(Gdx.files.internal("assets\\game\\pipes.png")); poweroutTexture = new Texture(Gdx.files.internal("assets\\game\\powerout.png")); reactorbackTexture = new Texture(Gdx.files.internal("assets\\game\\reactor_back.png")); pauseTexture = new Texture(Gdx.files.internal("assets\\game\\pause.png")); consolebackTexture = new Texture(Gdx.files.internal("assets\\game\\consoleback.png")); crUpTexture = new Texture(Gdx.files.internal("assets\\game\\controlrodup.png")); crDownTexture = new Texture(Gdx.files.internal("assets\\game\\controlroddown.png")); pump1Texture = new Texture(Gdx.files.internal("assets\\game\\pump1.png")); pump2Texture = new Texture(Gdx.files.internal("assets\\game\\pump2.png")); valve1Texture = new Texture(Gdx.files.internal("assets\\game\\valve1.png")); valve2Texture = new Texture(Gdx.files.internal("assets\\game\\valve2.png")); sErrorTexture = new Texture(Gdx.files.internal("assets\\game\\softwareerror.png")); gamebgImage = new Image(gamebgTexture); borderImage = new Image(borderTexture); condenserImage = new HoverButton(condenserTexture, false); coolerImage = new HoverButton(coolerTexture, false); pipesImage = new Image(pipesTexture); poweroutImage = new Image(poweroutTexture); reactorImage = new HoverButton(reactorbackTexture, false); turbineImage = new TurbineImage(this.getPlantStatus()); mechanicImage = new MechanicImage(); pauseImage = new HoverButton(pauseTexture, true); consolebackImage = new Image(consolebackTexture); crUpImage = new HoverButton(crUpTexture, false); crDownImage = new HoverButton(crDownTexture, false); pump1Image = new HoverButton(pump1Texture, false); pump2Image = new HoverButton(pump2Texture, false); valve1Image = new HoverButton(valve1Texture, false); valve2Image = new HoverButton(valve2Texture, false); sErrorImage = new Image(sErrorTexture); gamebgImage.setPosition(0, 0); borderImage.setPosition(0, 0); condenserImage.setPosition(523, 110); coolerImage.setPosition(803, 122); pipesImage.setPosition(132, 149); poweroutImage.setPosition(703, 405); reactorImage.setPosition(33, 113); turbineImage.setPosition(436, 404); mechanicImage.setPosition(630, 75); mechanicImage.moveMechanicTo(630f); //ensures the mechanic is initially not moving pauseImage.setPosition(17, 15); consolebackImage.setPosition(260, 0); crUpImage.setPosition(545, 75); crDownImage.setPosition(560, 21); pump1Image.setPosition(323, 71); pump2Image.setPosition(373, 76); valve1Image.setPosition(300, 22); valve2Image.setPosition(353, 22); sErrorImage.setPosition(433, 18); condenserImage.addListener(listeners.getCondenserListener()); // coolerImage.addListener(listeners.getCoolerListener()); reactorImage.addListener(listeners.getReactorListener()); pauseImage.addListener(listeners.getPauseListener()); crUpImage.addListener(listeners.getConrolRodsUpListener()); crDownImage.addListener(listeners.getConrolRodsDownListener()); valve1Image.addListener(listeners.getValve1Listener()); valve2Image.addListener(listeners.getValve2Listener()); pump1Image.addListener(listeners.getPump1Listener()); pump2Image.addListener(listeners.getPump2Listener()); }
diff --git a/nuxeo-platform-replication-importer/nuxeo-platform-replication-importer-core/src/test/java/org/nuxeo/ecm/platform/TestImport.java b/nuxeo-platform-replication-importer/nuxeo-platform-replication-importer-core/src/test/java/org/nuxeo/ecm/platform/TestImport.java index 730d7af..474f9eb 100644 --- a/nuxeo-platform-replication-importer/nuxeo-platform-replication-importer-core/src/test/java/org/nuxeo/ecm/platform/TestImport.java +++ b/nuxeo-platform-replication-importer/nuxeo-platform-replication-importer-core/src/test/java/org/nuxeo/ecm/platform/TestImport.java @@ -1,168 +1,171 @@ /* * (C) Copyright 2009 Nuxeo SAS (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * Nuxeo - initial API and implementation * */ package org.nuxeo.ecm.platform; import java.io.File; 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 org.nuxeo.common.utils.FileUtils; import org.nuxeo.common.utils.Path; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.DocumentModelList; import org.nuxeo.ecm.core.api.IdRef; import org.nuxeo.ecm.core.storage.sql.SQLRepositoryTestCase; import org.nuxeo.ecm.platform.replication.importer.DocumentaryBaseImporterService; import org.nuxeo.runtime.api.Framework; public class TestImport extends SQLRepositoryTestCase { public TestImport(String name) { super(name); } @Override public void setUp() throws Exception { super.setUp(); deployBundle("org.nuxeo.ecm.core.api"); deployBundle("org.nuxeo.ecm.core"); deployBundle("org.nuxeo.ecm.core.schema"); deployBundle("org.nuxeo.ecm.platform.picture.core"); deployBundle("org.nuxeo.ecm.platform.forum.core"); deployBundle("org.nuxeo.ecm.platform.replication.importer.api"); deployContrib("org.nuxeo.ecm.platform.replication.importer.core", "OSGI-INF/ImporterService.xml"); deployContrib("org.nuxeo.ecm.platform.replication.importer.core", "OSGI-INF/default-document-xml-transformer-contrib.xml"); openSession(); } @SuppressWarnings("unchecked") private File getArchiveFile() throws ZipException, IOException { File zip = new File( FileUtils.getResourcePathFromContext("DocumentaryBase.zip")); ZipFile arch = new ZipFile(zip); Path basePath = new Path(System.getProperty("java.io.tmpdir")).append( "TestImport").append(System.currentTimeMillis() + ""); new File(basePath.toString()).mkdirs(); Enumeration entries = arch.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); InputStream in = arch.getInputStream(entry); File out = new File(basePath.append(entry.getName()).toString()); if (entry.isDirectory()) { out.mkdirs(); } else { out.createNewFile(); FileUtils.copyToFile(in, out); } in.close(); } return new File(basePath.toString()); } public void testImport() throws Exception { DocumentModel root = session.getRootDocument(); assertNotNull(root); DocumentModelList children = session.getChildren(root.getRef()); assertEquals(0, children.size()); DocumentaryBaseImporterService importer = Framework.getLocalService(DocumentaryBaseImporterService.class); assertNotNull(importer); File archiveDir = getArchiveFile(); assertTrue(archiveDir.exists()); assertTrue(archiveDir.list().length > 0); importer.importDocuments(null, archiveDir, false, true, true, false, false); root = session.getRootDocument(); assertNotNull(root); // check a top directory IdRef ref = new IdRef("b293d80e-9357-484f-9713-ff5bc12a4ac6"); assertTrue(session.exists(ref)); DocumentModel doc = session.getDocument(ref); assertEquals("WorkspaceRoot", doc.getType()); assertEquals("Workspaces", doc.getTitle()); // check default domain ref = new IdRef("6c0f811c-d13b-4461-8376-3664274a7ba4"); assertTrue(session.exists(ref)); doc = session.getDocument(ref); assertEquals("Domain", doc.getType()); assertEquals("Default domain", doc.getTitle()); // check an usual document ref = new IdRef("a55ff4f7-556a-4a4b-bd5b-1eabb47b57fb"); assertTrue(session.exists(ref)); doc = session.getDocument(ref); assertEquals("File", doc.getType()); assertEquals("file 1", doc.getTitle()); + // testing lock. Document should be unlocked + assertFalse(doc.isLocked()); + assertNull(doc.getLockInfo()); // check usual document: note ref = new IdRef("69803adb-1b6e-4658-a95d-52ed706f0548"); assertTrue(session.exists(ref)); doc = session.getDocument(ref); assertEquals("Note", doc.getType()); assertEquals("domanu", doc.getTitle()); assertEquals("<p>Do the dew</p><p>Second dew </p>", doc.getProperty("note", "note")); // check a version ref = new IdRef("e1e9b1fe-9f48-4408-afc1-f8f167524f4b"); assertTrue(session.exists(ref)); doc = session.getDocument(ref); assertEquals("Note", doc.getType()); assertEquals("domanu", doc.getTitle()); assertTrue(doc.isVersion()); assertEquals("2", doc.getVersionLabel()); // check a proxy ref = new IdRef("23080819-2a78-410f-9323-d3938d52c044"); assertTrue(session.exists(ref)); doc = session.getDocument(ref); assertEquals("Note", doc.getType()); assertEquals("domanu", doc.getTitle()); assertTrue(doc.isProxy()); } public void testDoubleImport() throws Exception { testImport(); DocumentaryBaseImporterService importer = Framework.getLocalService(DocumentaryBaseImporterService.class); assertNotNull(importer); File archiveDir = getArchiveFile(); assertTrue(archiveDir.exists()); assertTrue(archiveDir.list().length > 0); importer.importDocuments(null, archiveDir, false, true, true, false, false); session.getRootDocument(); } }
true
true
public void testImport() throws Exception { DocumentModel root = session.getRootDocument(); assertNotNull(root); DocumentModelList children = session.getChildren(root.getRef()); assertEquals(0, children.size()); DocumentaryBaseImporterService importer = Framework.getLocalService(DocumentaryBaseImporterService.class); assertNotNull(importer); File archiveDir = getArchiveFile(); assertTrue(archiveDir.exists()); assertTrue(archiveDir.list().length > 0); importer.importDocuments(null, archiveDir, false, true, true, false, false); root = session.getRootDocument(); assertNotNull(root); // check a top directory IdRef ref = new IdRef("b293d80e-9357-484f-9713-ff5bc12a4ac6"); assertTrue(session.exists(ref)); DocumentModel doc = session.getDocument(ref); assertEquals("WorkspaceRoot", doc.getType()); assertEquals("Workspaces", doc.getTitle()); // check default domain ref = new IdRef("6c0f811c-d13b-4461-8376-3664274a7ba4"); assertTrue(session.exists(ref)); doc = session.getDocument(ref); assertEquals("Domain", doc.getType()); assertEquals("Default domain", doc.getTitle()); // check an usual document ref = new IdRef("a55ff4f7-556a-4a4b-bd5b-1eabb47b57fb"); assertTrue(session.exists(ref)); doc = session.getDocument(ref); assertEquals("File", doc.getType()); assertEquals("file 1", doc.getTitle()); // check usual document: note ref = new IdRef("69803adb-1b6e-4658-a95d-52ed706f0548"); assertTrue(session.exists(ref)); doc = session.getDocument(ref); assertEquals("Note", doc.getType()); assertEquals("domanu", doc.getTitle()); assertEquals("<p>Do the dew</p><p>Second dew </p>", doc.getProperty("note", "note")); // check a version ref = new IdRef("e1e9b1fe-9f48-4408-afc1-f8f167524f4b"); assertTrue(session.exists(ref)); doc = session.getDocument(ref); assertEquals("Note", doc.getType()); assertEquals("domanu", doc.getTitle()); assertTrue(doc.isVersion()); assertEquals("2", doc.getVersionLabel()); // check a proxy ref = new IdRef("23080819-2a78-410f-9323-d3938d52c044"); assertTrue(session.exists(ref)); doc = session.getDocument(ref); assertEquals("Note", doc.getType()); assertEquals("domanu", doc.getTitle()); assertTrue(doc.isProxy()); }
public void testImport() throws Exception { DocumentModel root = session.getRootDocument(); assertNotNull(root); DocumentModelList children = session.getChildren(root.getRef()); assertEquals(0, children.size()); DocumentaryBaseImporterService importer = Framework.getLocalService(DocumentaryBaseImporterService.class); assertNotNull(importer); File archiveDir = getArchiveFile(); assertTrue(archiveDir.exists()); assertTrue(archiveDir.list().length > 0); importer.importDocuments(null, archiveDir, false, true, true, false, false); root = session.getRootDocument(); assertNotNull(root); // check a top directory IdRef ref = new IdRef("b293d80e-9357-484f-9713-ff5bc12a4ac6"); assertTrue(session.exists(ref)); DocumentModel doc = session.getDocument(ref); assertEquals("WorkspaceRoot", doc.getType()); assertEquals("Workspaces", doc.getTitle()); // check default domain ref = new IdRef("6c0f811c-d13b-4461-8376-3664274a7ba4"); assertTrue(session.exists(ref)); doc = session.getDocument(ref); assertEquals("Domain", doc.getType()); assertEquals("Default domain", doc.getTitle()); // check an usual document ref = new IdRef("a55ff4f7-556a-4a4b-bd5b-1eabb47b57fb"); assertTrue(session.exists(ref)); doc = session.getDocument(ref); assertEquals("File", doc.getType()); assertEquals("file 1", doc.getTitle()); // testing lock. Document should be unlocked assertFalse(doc.isLocked()); assertNull(doc.getLockInfo()); // check usual document: note ref = new IdRef("69803adb-1b6e-4658-a95d-52ed706f0548"); assertTrue(session.exists(ref)); doc = session.getDocument(ref); assertEquals("Note", doc.getType()); assertEquals("domanu", doc.getTitle()); assertEquals("<p>Do the dew</p><p>Second dew </p>", doc.getProperty("note", "note")); // check a version ref = new IdRef("e1e9b1fe-9f48-4408-afc1-f8f167524f4b"); assertTrue(session.exists(ref)); doc = session.getDocument(ref); assertEquals("Note", doc.getType()); assertEquals("domanu", doc.getTitle()); assertTrue(doc.isVersion()); assertEquals("2", doc.getVersionLabel()); // check a proxy ref = new IdRef("23080819-2a78-410f-9323-d3938d52c044"); assertTrue(session.exists(ref)); doc = session.getDocument(ref); assertEquals("Note", doc.getType()); assertEquals("domanu", doc.getTitle()); assertTrue(doc.isProxy()); }
diff --git a/src/main/java/net/aufdemrand/denizen/objects/Element.java b/src/main/java/net/aufdemrand/denizen/objects/Element.java index 36bb819b4..241288574 100644 --- a/src/main/java/net/aufdemrand/denizen/objects/Element.java +++ b/src/main/java/net/aufdemrand/denizen/objects/Element.java @@ -1,783 +1,785 @@ package net.aufdemrand.denizen.objects; import java.text.DecimalFormat; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.aufdemrand.denizen.objects.aH.Argument; import net.aufdemrand.denizen.scripts.commands.core.*; import net.aufdemrand.denizen.scripts.commands.core.Comparable; import net.aufdemrand.denizen.tags.Attribute; import net.aufdemrand.denizen.utilities.debugging.dB; import org.apache.commons.lang.StringUtils; import org.bukkit.ChatColor; // <--[language] // @name Element // @group Object System // @description // Elements are simple objects that contain either a boolean (true/false), // string, or number value. Their main usage is within the replaceable tag // system, often times returned from the use of another tag that isn't returning // a specific object type, such as a location or entity. For example, // <player.name> or <li@item|item2|item3.as_cslist> will both return Elements. // // Pluses to the Element system is the ability to utilize its attributes that // can provide a range of functionality that should be familiar from any other // programming language, such as 'to_uppercase', 'split', 'replace', 'contains', // as_int, any many more. See 'element' tags for more information. // // While information fetched from other tags resulting in an Element is often // times automatically handled, it may be desirable to utilize element // attributes from strings/numbers/etc. that aren't already an element object. // To accomplish this, the object fetcher can be used to create a new element. // Element has a constructor, el@val[element_value], that will allow the // creation of a new element. For example: <el@val[This_is_a_test.].to_uppercase> // will result in the value 'THIS_IS_A_TEST.' Note that while other objects often // return their object identifier (el@, li@, e@, etc.), elements do not. // --> public class Element implements dObject { public final static Element TRUE = new Element(Boolean.TRUE); public final static Element FALSE = new Element(Boolean.FALSE); public final static Element SERVER = new Element("server"); public final static Element NULL = new Element("null"); final static Pattern VALUE_PATTERN = Pattern.compile("el@val(?:ue)?\\[([^\\[\\]]+)\\].*", Pattern.CASE_INSENSITIVE); /** * * @param string the string or dScript argument String * @return a dScript dList * */ @Fetchable("el") public static Element valueOf(String string) { if (string == null) return null; Matcher m = VALUE_PATTERN.matcher(string); // Allow construction of elements with el@val[<value>] if (m.matches()) { String value = m.group(1); Argument arg = Argument.valueOf(value); if (arg.matchesPrimitive(aH.PrimitiveType.Integer)) return new Element(aH.getIntegerFrom(value)); else if (arg.matchesPrimitive(aH.PrimitiveType.Double)) return new Element(aH.getDoubleFrom(value)); else return new Element(value); } return new Element(string); } public static boolean matches(String string) { return string != null; } private final String element; public Element(String string) { this.prefix = "element"; this.element = string; } public Element(Boolean bool) { this.prefix = "boolean"; this.element = String.valueOf(bool); } public Element(Integer integer) { this.prefix = "integer"; this.element = String.valueOf(integer); } public Element(Byte byt) { this.prefix = "byte"; this.element = String.valueOf(byt); } public Element(Short shrt) { this.prefix = "short"; this.element = String.valueOf(shrt); } public Element(Long lng) { this.prefix = "long"; this.element = String.valueOf(lng); } public Element(Double dbl) { this.prefix = "double"; this.element = String.valueOf(dbl); } public Element(Float flt) { this.prefix = "float"; this.element = String.valueOf(flt); } public Element(String prefix, String string) { if (prefix == null) this.prefix = "element"; else this.prefix = prefix; this.element = string; } public double asDouble() { return Double.valueOf(element.replaceAll("(el@)|%", "")); } public float asFloat() { return Float.valueOf(element.replaceAll("(el@)|%", "")); } public int asInt() { return Integer.valueOf(element.replaceAll("(el@)|%", "")); } public boolean asBoolean() { return Boolean.valueOf(element.replaceAll("el@", "")); } public String asString() { return element; } private String prefix; @Override public String getObjectType() { return "Element"; } @Override public String getPrefix() { return prefix; } @Override public dObject setPrefix(String prefix) { this.prefix = prefix; return this; } @Override public String debug() { return (prefix + "='<A>" + identify() + "<G>' "); } @Override public String identify() { return element; } @Override public String toString() { return identify(); } @Override public boolean isUnique() { return false; } @Override public String getAttribute(Attribute attribute) { if (attribute == null) return null; //////////////////// // COMPARABLE ATTRIBUTES //////////////// // <--[tag] // @attribute <[email protected][<operator>].to[<element>]> // @returns Element(Boolean) // @description // Takes an operator, and compares the value of the element to the supplied // element. Returns the outcome of the comparable, either true or false. For // information on operators, see <@link language operator>. // --> // <--[tag] // @attribute <[email protected][<operator>].than[<element>]> // @returns Element(Boolean) // @description // Takes an operator, and compares the value of the element to the supplied // element. Returns the outcome of the comparable, either true or false. For // information on operators, see <@link language operator>. // --> if (attribute.startsWith("is") && attribute.hasContext(1) && (attribute.startsWith("to", 2) || attribute.startsWith("than", 2)) && attribute.hasContext(2)) { // Use the Comparable object as implemented for the IF command. First, a new Comparable! Comparable com = new net.aufdemrand.denizen.scripts.commands.core.Comparable(); // Comparable is the value of this element com.setComparable(element); // Compared_to is the value of the .to[] context. com.setComparedto(attribute.getContext(2)); // Check for negative logic String operator; if (attribute.getContext(1).startsWith("!")) { operator = attribute.getContext(1).substring(1); com.setNegativeLogic(); } else operator = attribute.getContext(1); // Operator is the value of the .is[] context. Valid are Comparable.Operators, same // as used by the IF command. com.setOperator(Comparable.Operator.valueOf(operator .replace("==", "EQUALS").replace(">=", "OR_MORE").replace("<=", "OR_LESS") .replace("<", "LESS").replace(">", "MORE").replace("=", "EQUALS"))); return new Element(com.determineOutcome()).getAttribute(attribute.fulfill(2)); } ///////////////////// // CONVERSION ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_boolean> // @returns Element(Boolean) // @description // Returns the element as true/false. // --> if (attribute.startsWith("asboolean") || attribute.startsWith("as_boolean")) return new Element(Boolean.valueOf(element).toString()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_double> // @returns Element(Decimal) // @description // Returns the element as a number with a decimal. // --> if (attribute.startsWith("asdouble") || attribute.startsWith("as_double")) try { return new Element(Double.valueOf(element)) .getAttribute(attribute.fulfill(1)); } catch (NumberFormatException e) { dB.echoError("'" + element + "' is not a valid Double."); return new Element("null").getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_duration> // @returns Duration // @description // Returns the element as a duration. // --> if (attribute.startsWith("asduration") || attribute.startsWith("as_duration")) return Duration.valueOf(element).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_entity> // @returns dEntity // @description // Returns the element as an entity. Note: the value must be a valid entity. // --> if (attribute.startsWith("asentity") || attribute.startsWith("as_entity")) return dEntity.valueOf(element).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_up> // @returns Element(Number) // @description // Rounds a decimal upward. // --> if (attribute.startsWith("round_up")) try { return new Element((int)Math.ceil(Double.valueOf(element))) .getAttribute(attribute.fulfill(1)); } catch (NumberFormatException e) { dB.echoError("'" + element + "' is not a valid Integer."); return new Element("null").getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_down> // @returns Element(Number) // @description // Rounds a decimal downward. // --> if (attribute.startsWith("round_down")) try { return new Element((int)Math.floor(Double.valueOf(element))) .getAttribute(attribute.fulfill(1)); } catch (NumberFormatException e) { dB.echoError("'" + element + "' is not a valid Integer."); return new Element("null").getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_int> // @returns Element(Number) // @description // Returns the element as a number without a decimal. Rounds double values. // --> if (attribute.startsWith("asint") || attribute.startsWith("as_int")) try { // Round the Double instead of just getting its // value as an Integer (which would incorrectly // turn 2.9 into 2) return new Element(Math.round(Double.valueOf(element))) .getAttribute(attribute.fulfill(1)); } catch (NumberFormatException e) { dB.echoError("'" + element + "' is not a valid Integer."); return new Element("null").getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_item> // @returns dItem // @description // Returns the element as an item. Additional attributes can be accessed by dItem. // Note: the value must be a valid item. // --> if (attribute.startsWith("asitem") || attribute.startsWith("as_item")) return dItem.valueOf(element).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_list> // @returns dList // @description // Returns the element as a list. // --> if (attribute.startsWith("aslist") || attribute.startsWith("as_list")) return dList.valueOf(element).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_location> // @returns dLocation // @description // Returns the element as a location. Note: the value must be a valid location. // --> if (attribute.startsWith("aslocation") || attribute.startsWith("as_location")) return dLocation.valueOf(element).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_money> // @returns Element(Decimal) // @description // Returns the element as a number with two decimal places. // --> if (attribute.startsWith("asmoney") || attribute.startsWith("as_money")) { try { DecimalFormat d = new DecimalFormat("0.00"); return new Element(d.format(Double.valueOf(element))) .getAttribute(attribute.fulfill(1)); } catch (NumberFormatException e) { dB.echoError("'" + element + "' is not a valid Money format."); return new Element("null").getAttribute(attribute.fulfill(1)); } } // <--[tag] // @attribute <[email protected]_npc> // @returns dNPC // @description // Returns the element as an NPC. Note: the value must be a valid NPC. // --> if (attribute.startsWith("asnpc") || attribute.startsWith("as_npc")) return dNPC.valueOf(element).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_player> // @returns dPlayer // @description // Returns the element as a player. Note: the value must be a valid player. Can be online or offline. // --> if (attribute.startsWith("asplayer") || attribute.startsWith("as_player")) return dPlayer.valueOf(element).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_script> // @returns dScript // @description // Returns the element as a script. Note: the value must be a valid script. // --> if (attribute.startsWith("asscript") || attribute.startsWith("as_script")) return dScript.valueOf(element).getAttribute(attribute.fulfill(1)); ///////////////////// // DEBUG ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Prints the Element's debug representation in the console and returns true. // --> if (attribute.startsWith("debug.log")) { dB.log(debug()); return new Element(Boolean.TRUE) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]_color> // @returns Element // @description // Returns a standard debug representation of the Element with colors stripped. // --> if (attribute.startsWith("debug.no_color")) { return new Element(ChatColor.stripColor(debug())) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns a standard debug representation of the Element. // --> if (attribute.startsWith("debug")) { return new Element(debug()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the prefix of the element. // --> if (attribute.startsWith("prefix")) return new Element(prefix) .getAttribute(attribute.fulfill(1)); ///////////////////// // STRING CHECKING ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected][<string>]> // @returns Element(Boolean) // @description // Returns whether the element contains a specified string, case insensitive. Can use // regular expression by prefixing the string with regex: // --> if (attribute.startsWith("contains")) { String contains = attribute.getContext(1); if (contains.toLowerCase().startsWith("regex:")) { if (Pattern.compile(contains.substring(("regex:").length()), Pattern.CASE_INSENSITIVE).matcher(element).matches()) return new Element("true").getAttribute(attribute.fulfill(1)); else return new Element("false").getAttribute(attribute.fulfill(1)); } else if (element.toLowerCase().contains(contains.toLowerCase())) return new Element("true").getAttribute(attribute.fulfill(1)); else return new Element("false").getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_with[<string>]> // @returns Element(Boolean) // @description // Returns whether the element ends with a specified string. // --> if (attribute.startsWith("ends_with") || attribute.startsWith("endswith")) return new Element(element.endsWith(attribute.getContext(1))).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_color> // @returns Element // @description // Returns the ChatColors used at the end of a string. // --> if (attribute.startsWith("last_color")) return new Element(ChatColor.getLastColors(element)).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the length of the element. // --> if (attribute.startsWith("length")) { return new Element(element.length()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_with[<string>]> // @returns Element(Boolean) // @description // Returns whether the element starts with a specified string. // --> if (attribute.startsWith("starts_with") || attribute.startsWith("startswith")) return new Element(element.startsWith(attribute.getContext(1))).getAttribute(attribute.fulfill(1)); ///////////////////// // STRING MANIPULATION ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected][<string>]> // @returns Element // @description // Returns the portion of an element after a specified string. ie. <[email protected][hello]> returns 'World'. // --> if (attribute.startsWith("after")) { String delimiter = attribute.getContext(1); if (element.contains(delimiter)) return new Element(element.substring (element.indexOf(delimiter) + delimiter.length())) .getAttribute(attribute.fulfill(1)); else return new Element(element) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<string>]> // @returns Element // @description // Returns the portion of an element before a specified string. // --> if (attribute.startsWith("before")) { String delimiter = attribute.getContext(1); if (element.contains(delimiter)) return new Element(element.substring (0, element.indexOf(delimiter))) .getAttribute(attribute.fulfill(1)); else return new Element(element) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<string>]> // @returns Element // @description // Returns the element with all instances of a string removed. // --> // <--[tag] // @attribute <[email protected][<string>].with[<string>]> // @returns Element // @description // Returns the element with all instances of a string replaced with another. // --> if (attribute.startsWith("replace") && attribute.hasContext(1)) { String replace = attribute.getContext(1); String replacement = ""; attribute.fulfill(1); if (attribute.startsWith("with")) { if (attribute.hasContext(1)) { replacement = attribute.getContext(1); + if (replacement == null) + replacement = ""; attribute.fulfill(1); } } return new Element(element.replace(replace, replacement)) .getAttribute(attribute); } // <--[tag] // @attribute <[email protected][<string>].limit[<#>]> // @returns dList // @description // Returns a list of portions of this element, split by the specified string, // and capped at the specified number of max list items. // --> if (attribute.startsWith("split") && attribute.startsWith("limit", 2)) { String split_string = (attribute.hasContext(1) ? attribute.getContext(1) : " "); Integer limit = (attribute.hasContext(2) ? attribute.getIntContext(2) : 1); if (split_string.toLowerCase().startsWith("regex:")) return new dList(Arrays.asList(element.split(split_string.split(":", 2)[1], limit))) .getAttribute(attribute.fulfill(1)); else return new dList(Arrays.asList(StringUtils.split(element, split_string, limit))) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<string>]> // @returns dList // @description // Returns a list of portions of this element, split by the specified string. // --> if (attribute.startsWith("split")) { String split_string = (attribute.hasContext(1) ? attribute.getContext(1) : " "); if (split_string.toLowerCase().startsWith("regex:")) return new dList(Arrays.asList(element.split(split_string.split(":", 2)[1]))) .getAttribute(attribute.fulfill(1)); else return new dList(Arrays.asList(StringUtils.split(element, split_string))) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_color> // @returns Element // @description // Returns the element with all color encoding stripped. // --> if (attribute.startsWith("strip_color")) return new Element(ChatColor.stripColor(element)).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the value of an element minus any leading or trailing whitespace. // --> if (attribute.startsWith("trim")) return new Element(element.trim()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected][<#>(,<#>)]> // @returns Element // @description // Returns the portion of an element between two string indices. // If no second index is specified, it will return the portion of an // element after the specified index. // --> if (attribute.startsWith("substring")||attribute.startsWith("substr")) { // substring[2,8] int beginning_index = Integer.valueOf(attribute.getContext(1).split(",")[0]) - 1; int ending_index; if (attribute.getContext(1).split(",").length > 1) ending_index = Integer.valueOf(attribute.getContext(1).split(",")[1]) - 1; else ending_index = element.length(); if (beginning_index < 0) beginning_index = 0; if (ending_index > element.length()) ending_index = element.length(); return new Element(element.substring(beginning_index, ending_index)) .getAttribute(attribute.fulfill(1)); } ///////////////////// // MATH ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns Element(Decimal) // @description // Returns the absolute value of the element. // --> if (attribute.startsWith("abs")) { return new Element(Math.abs(asDouble())) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<#>]> // @returns Element(Decimal) // @description // Returns the element plus a number. // --> if (attribute.startsWith("add") && attribute.hasContext(1)) { return new Element(asDouble() + aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<#>]> // @returns Element(Decimal) // @description // Returns the element divided by a number. // --> if (attribute.startsWith("div") && attribute.hasContext(1)) { return new Element(asDouble() / aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<#>]> // @returns Element(Decimal) // @description // Returns the remainder of the element divided by a number. // --> if (attribute.startsWith("mod") && attribute.hasContext(1)) { return new Element(asDouble() % aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<#>]> // @returns Element(Decimal) // @description // Returns the element multiplied by a number. // --> if (attribute.startsWith("mul") && attribute.hasContext(1)) { return new Element(asDouble() * aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Decimal) // @description // Returns the square root of the element. // --> if (attribute.startsWith("sqrt")) { return new Element(Math.sqrt(asDouble())) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<#>]> // @returns Element(Decimal) // @description // Returns the element minus a number. // --> if (attribute.startsWith("sub") && attribute.hasContext(1)) { return new Element(asDouble() - aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // Unfilled attributes past this point probably means the tag is spelled // incorrectly. So instead of just passing through what's been resolved - // so far, 'null' shall be returned with an error message. + // so far, 'null' shall be returned with a debug message. if (attribute.attributes.size() > 0) { - dB.echoError("Unfilled attributes '" + attribute.attributes.toString() + "'" + + dB.echoDebug(attribute.getScriptEntry(), "Unfilled attributes '" + attribute.attributes.toString() + "'" + "for tag <" + attribute.getOrigin() + ">!"); return "null"; } else { dB.echoDebug(attribute.getScriptEntry(), "Filled tag <" + attribute.getOrigin() + "> with '" + element + "'."); return element; } } }
false
true
public String getAttribute(Attribute attribute) { if (attribute == null) return null; //////////////////// // COMPARABLE ATTRIBUTES //////////////// // <--[tag] // @attribute <[email protected][<operator>].to[<element>]> // @returns Element(Boolean) // @description // Takes an operator, and compares the value of the element to the supplied // element. Returns the outcome of the comparable, either true or false. For // information on operators, see <@link language operator>. // --> // <--[tag] // @attribute <[email protected][<operator>].than[<element>]> // @returns Element(Boolean) // @description // Takes an operator, and compares the value of the element to the supplied // element. Returns the outcome of the comparable, either true or false. For // information on operators, see <@link language operator>. // --> if (attribute.startsWith("is") && attribute.hasContext(1) && (attribute.startsWith("to", 2) || attribute.startsWith("than", 2)) && attribute.hasContext(2)) { // Use the Comparable object as implemented for the IF command. First, a new Comparable! Comparable com = new net.aufdemrand.denizen.scripts.commands.core.Comparable(); // Comparable is the value of this element com.setComparable(element); // Compared_to is the value of the .to[] context. com.setComparedto(attribute.getContext(2)); // Check for negative logic String operator; if (attribute.getContext(1).startsWith("!")) { operator = attribute.getContext(1).substring(1); com.setNegativeLogic(); } else operator = attribute.getContext(1); // Operator is the value of the .is[] context. Valid are Comparable.Operators, same // as used by the IF command. com.setOperator(Comparable.Operator.valueOf(operator .replace("==", "EQUALS").replace(">=", "OR_MORE").replace("<=", "OR_LESS") .replace("<", "LESS").replace(">", "MORE").replace("=", "EQUALS"))); return new Element(com.determineOutcome()).getAttribute(attribute.fulfill(2)); } ///////////////////// // CONVERSION ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_boolean> // @returns Element(Boolean) // @description // Returns the element as true/false. // --> if (attribute.startsWith("asboolean") || attribute.startsWith("as_boolean")) return new Element(Boolean.valueOf(element).toString()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_double> // @returns Element(Decimal) // @description // Returns the element as a number with a decimal. // --> if (attribute.startsWith("asdouble") || attribute.startsWith("as_double")) try { return new Element(Double.valueOf(element)) .getAttribute(attribute.fulfill(1)); } catch (NumberFormatException e) { dB.echoError("'" + element + "' is not a valid Double."); return new Element("null").getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_duration> // @returns Duration // @description // Returns the element as a duration. // --> if (attribute.startsWith("asduration") || attribute.startsWith("as_duration")) return Duration.valueOf(element).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_entity> // @returns dEntity // @description // Returns the element as an entity. Note: the value must be a valid entity. // --> if (attribute.startsWith("asentity") || attribute.startsWith("as_entity")) return dEntity.valueOf(element).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_up> // @returns Element(Number) // @description // Rounds a decimal upward. // --> if (attribute.startsWith("round_up")) try { return new Element((int)Math.ceil(Double.valueOf(element))) .getAttribute(attribute.fulfill(1)); } catch (NumberFormatException e) { dB.echoError("'" + element + "' is not a valid Integer."); return new Element("null").getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_down> // @returns Element(Number) // @description // Rounds a decimal downward. // --> if (attribute.startsWith("round_down")) try { return new Element((int)Math.floor(Double.valueOf(element))) .getAttribute(attribute.fulfill(1)); } catch (NumberFormatException e) { dB.echoError("'" + element + "' is not a valid Integer."); return new Element("null").getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_int> // @returns Element(Number) // @description // Returns the element as a number without a decimal. Rounds double values. // --> if (attribute.startsWith("asint") || attribute.startsWith("as_int")) try { // Round the Double instead of just getting its // value as an Integer (which would incorrectly // turn 2.9 into 2) return new Element(Math.round(Double.valueOf(element))) .getAttribute(attribute.fulfill(1)); } catch (NumberFormatException e) { dB.echoError("'" + element + "' is not a valid Integer."); return new Element("null").getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_item> // @returns dItem // @description // Returns the element as an item. Additional attributes can be accessed by dItem. // Note: the value must be a valid item. // --> if (attribute.startsWith("asitem") || attribute.startsWith("as_item")) return dItem.valueOf(element).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_list> // @returns dList // @description // Returns the element as a list. // --> if (attribute.startsWith("aslist") || attribute.startsWith("as_list")) return dList.valueOf(element).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_location> // @returns dLocation // @description // Returns the element as a location. Note: the value must be a valid location. // --> if (attribute.startsWith("aslocation") || attribute.startsWith("as_location")) return dLocation.valueOf(element).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_money> // @returns Element(Decimal) // @description // Returns the element as a number with two decimal places. // --> if (attribute.startsWith("asmoney") || attribute.startsWith("as_money")) { try { DecimalFormat d = new DecimalFormat("0.00"); return new Element(d.format(Double.valueOf(element))) .getAttribute(attribute.fulfill(1)); } catch (NumberFormatException e) { dB.echoError("'" + element + "' is not a valid Money format."); return new Element("null").getAttribute(attribute.fulfill(1)); } } // <--[tag] // @attribute <[email protected]_npc> // @returns dNPC // @description // Returns the element as an NPC. Note: the value must be a valid NPC. // --> if (attribute.startsWith("asnpc") || attribute.startsWith("as_npc")) return dNPC.valueOf(element).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_player> // @returns dPlayer // @description // Returns the element as a player. Note: the value must be a valid player. Can be online or offline. // --> if (attribute.startsWith("asplayer") || attribute.startsWith("as_player")) return dPlayer.valueOf(element).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_script> // @returns dScript // @description // Returns the element as a script. Note: the value must be a valid script. // --> if (attribute.startsWith("asscript") || attribute.startsWith("as_script")) return dScript.valueOf(element).getAttribute(attribute.fulfill(1)); ///////////////////// // DEBUG ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Prints the Element's debug representation in the console and returns true. // --> if (attribute.startsWith("debug.log")) { dB.log(debug()); return new Element(Boolean.TRUE) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]_color> // @returns Element // @description // Returns a standard debug representation of the Element with colors stripped. // --> if (attribute.startsWith("debug.no_color")) { return new Element(ChatColor.stripColor(debug())) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns a standard debug representation of the Element. // --> if (attribute.startsWith("debug")) { return new Element(debug()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the prefix of the element. // --> if (attribute.startsWith("prefix")) return new Element(prefix) .getAttribute(attribute.fulfill(1)); ///////////////////// // STRING CHECKING ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected][<string>]> // @returns Element(Boolean) // @description // Returns whether the element contains a specified string, case insensitive. Can use // regular expression by prefixing the string with regex: // --> if (attribute.startsWith("contains")) { String contains = attribute.getContext(1); if (contains.toLowerCase().startsWith("regex:")) { if (Pattern.compile(contains.substring(("regex:").length()), Pattern.CASE_INSENSITIVE).matcher(element).matches()) return new Element("true").getAttribute(attribute.fulfill(1)); else return new Element("false").getAttribute(attribute.fulfill(1)); } else if (element.toLowerCase().contains(contains.toLowerCase())) return new Element("true").getAttribute(attribute.fulfill(1)); else return new Element("false").getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_with[<string>]> // @returns Element(Boolean) // @description // Returns whether the element ends with a specified string. // --> if (attribute.startsWith("ends_with") || attribute.startsWith("endswith")) return new Element(element.endsWith(attribute.getContext(1))).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_color> // @returns Element // @description // Returns the ChatColors used at the end of a string. // --> if (attribute.startsWith("last_color")) return new Element(ChatColor.getLastColors(element)).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the length of the element. // --> if (attribute.startsWith("length")) { return new Element(element.length()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_with[<string>]> // @returns Element(Boolean) // @description // Returns whether the element starts with a specified string. // --> if (attribute.startsWith("starts_with") || attribute.startsWith("startswith")) return new Element(element.startsWith(attribute.getContext(1))).getAttribute(attribute.fulfill(1)); ///////////////////// // STRING MANIPULATION ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected][<string>]> // @returns Element // @description // Returns the portion of an element after a specified string. ie. <[email protected][hello]> returns 'World'. // --> if (attribute.startsWith("after")) { String delimiter = attribute.getContext(1); if (element.contains(delimiter)) return new Element(element.substring (element.indexOf(delimiter) + delimiter.length())) .getAttribute(attribute.fulfill(1)); else return new Element(element) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<string>]> // @returns Element // @description // Returns the portion of an element before a specified string. // --> if (attribute.startsWith("before")) { String delimiter = attribute.getContext(1); if (element.contains(delimiter)) return new Element(element.substring (0, element.indexOf(delimiter))) .getAttribute(attribute.fulfill(1)); else return new Element(element) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<string>]> // @returns Element // @description // Returns the element with all instances of a string removed. // --> // <--[tag] // @attribute <[email protected][<string>].with[<string>]> // @returns Element // @description // Returns the element with all instances of a string replaced with another. // --> if (attribute.startsWith("replace") && attribute.hasContext(1)) { String replace = attribute.getContext(1); String replacement = ""; attribute.fulfill(1); if (attribute.startsWith("with")) { if (attribute.hasContext(1)) { replacement = attribute.getContext(1); attribute.fulfill(1); } } return new Element(element.replace(replace, replacement)) .getAttribute(attribute); } // <--[tag] // @attribute <[email protected][<string>].limit[<#>]> // @returns dList // @description // Returns a list of portions of this element, split by the specified string, // and capped at the specified number of max list items. // --> if (attribute.startsWith("split") && attribute.startsWith("limit", 2)) { String split_string = (attribute.hasContext(1) ? attribute.getContext(1) : " "); Integer limit = (attribute.hasContext(2) ? attribute.getIntContext(2) : 1); if (split_string.toLowerCase().startsWith("regex:")) return new dList(Arrays.asList(element.split(split_string.split(":", 2)[1], limit))) .getAttribute(attribute.fulfill(1)); else return new dList(Arrays.asList(StringUtils.split(element, split_string, limit))) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<string>]> // @returns dList // @description // Returns a list of portions of this element, split by the specified string. // --> if (attribute.startsWith("split")) { String split_string = (attribute.hasContext(1) ? attribute.getContext(1) : " "); if (split_string.toLowerCase().startsWith("regex:")) return new dList(Arrays.asList(element.split(split_string.split(":", 2)[1]))) .getAttribute(attribute.fulfill(1)); else return new dList(Arrays.asList(StringUtils.split(element, split_string))) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_color> // @returns Element // @description // Returns the element with all color encoding stripped. // --> if (attribute.startsWith("strip_color")) return new Element(ChatColor.stripColor(element)).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the value of an element minus any leading or trailing whitespace. // --> if (attribute.startsWith("trim")) return new Element(element.trim()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected][<#>(,<#>)]> // @returns Element // @description // Returns the portion of an element between two string indices. // If no second index is specified, it will return the portion of an // element after the specified index. // --> if (attribute.startsWith("substring")||attribute.startsWith("substr")) { // substring[2,8] int beginning_index = Integer.valueOf(attribute.getContext(1).split(",")[0]) - 1; int ending_index; if (attribute.getContext(1).split(",").length > 1) ending_index = Integer.valueOf(attribute.getContext(1).split(",")[1]) - 1; else ending_index = element.length(); if (beginning_index < 0) beginning_index = 0; if (ending_index > element.length()) ending_index = element.length(); return new Element(element.substring(beginning_index, ending_index)) .getAttribute(attribute.fulfill(1)); } ///////////////////// // MATH ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns Element(Decimal) // @description // Returns the absolute value of the element. // --> if (attribute.startsWith("abs")) { return new Element(Math.abs(asDouble())) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<#>]> // @returns Element(Decimal) // @description // Returns the element plus a number. // --> if (attribute.startsWith("add") && attribute.hasContext(1)) { return new Element(asDouble() + aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<#>]> // @returns Element(Decimal) // @description // Returns the element divided by a number. // --> if (attribute.startsWith("div") && attribute.hasContext(1)) { return new Element(asDouble() / aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<#>]> // @returns Element(Decimal) // @description // Returns the remainder of the element divided by a number. // --> if (attribute.startsWith("mod") && attribute.hasContext(1)) { return new Element(asDouble() % aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<#>]> // @returns Element(Decimal) // @description // Returns the element multiplied by a number. // --> if (attribute.startsWith("mul") && attribute.hasContext(1)) { return new Element(asDouble() * aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Decimal) // @description // Returns the square root of the element. // --> if (attribute.startsWith("sqrt")) { return new Element(Math.sqrt(asDouble())) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<#>]> // @returns Element(Decimal) // @description // Returns the element minus a number. // --> if (attribute.startsWith("sub") && attribute.hasContext(1)) { return new Element(asDouble() - aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // Unfilled attributes past this point probably means the tag is spelled // incorrectly. So instead of just passing through what's been resolved // so far, 'null' shall be returned with an error message. if (attribute.attributes.size() > 0) { dB.echoError("Unfilled attributes '" + attribute.attributes.toString() + "'" + "for tag <" + attribute.getOrigin() + ">!"); return "null"; } else { dB.echoDebug(attribute.getScriptEntry(), "Filled tag <" + attribute.getOrigin() + "> with '" + element + "'."); return element; } }
public String getAttribute(Attribute attribute) { if (attribute == null) return null; //////////////////// // COMPARABLE ATTRIBUTES //////////////// // <--[tag] // @attribute <[email protected][<operator>].to[<element>]> // @returns Element(Boolean) // @description // Takes an operator, and compares the value of the element to the supplied // element. Returns the outcome of the comparable, either true or false. For // information on operators, see <@link language operator>. // --> // <--[tag] // @attribute <[email protected][<operator>].than[<element>]> // @returns Element(Boolean) // @description // Takes an operator, and compares the value of the element to the supplied // element. Returns the outcome of the comparable, either true or false. For // information on operators, see <@link language operator>. // --> if (attribute.startsWith("is") && attribute.hasContext(1) && (attribute.startsWith("to", 2) || attribute.startsWith("than", 2)) && attribute.hasContext(2)) { // Use the Comparable object as implemented for the IF command. First, a new Comparable! Comparable com = new net.aufdemrand.denizen.scripts.commands.core.Comparable(); // Comparable is the value of this element com.setComparable(element); // Compared_to is the value of the .to[] context. com.setComparedto(attribute.getContext(2)); // Check for negative logic String operator; if (attribute.getContext(1).startsWith("!")) { operator = attribute.getContext(1).substring(1); com.setNegativeLogic(); } else operator = attribute.getContext(1); // Operator is the value of the .is[] context. Valid are Comparable.Operators, same // as used by the IF command. com.setOperator(Comparable.Operator.valueOf(operator .replace("==", "EQUALS").replace(">=", "OR_MORE").replace("<=", "OR_LESS") .replace("<", "LESS").replace(">", "MORE").replace("=", "EQUALS"))); return new Element(com.determineOutcome()).getAttribute(attribute.fulfill(2)); } ///////////////////// // CONVERSION ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_boolean> // @returns Element(Boolean) // @description // Returns the element as true/false. // --> if (attribute.startsWith("asboolean") || attribute.startsWith("as_boolean")) return new Element(Boolean.valueOf(element).toString()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_double> // @returns Element(Decimal) // @description // Returns the element as a number with a decimal. // --> if (attribute.startsWith("asdouble") || attribute.startsWith("as_double")) try { return new Element(Double.valueOf(element)) .getAttribute(attribute.fulfill(1)); } catch (NumberFormatException e) { dB.echoError("'" + element + "' is not a valid Double."); return new Element("null").getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_duration> // @returns Duration // @description // Returns the element as a duration. // --> if (attribute.startsWith("asduration") || attribute.startsWith("as_duration")) return Duration.valueOf(element).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_entity> // @returns dEntity // @description // Returns the element as an entity. Note: the value must be a valid entity. // --> if (attribute.startsWith("asentity") || attribute.startsWith("as_entity")) return dEntity.valueOf(element).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_up> // @returns Element(Number) // @description // Rounds a decimal upward. // --> if (attribute.startsWith("round_up")) try { return new Element((int)Math.ceil(Double.valueOf(element))) .getAttribute(attribute.fulfill(1)); } catch (NumberFormatException e) { dB.echoError("'" + element + "' is not a valid Integer."); return new Element("null").getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_down> // @returns Element(Number) // @description // Rounds a decimal downward. // --> if (attribute.startsWith("round_down")) try { return new Element((int)Math.floor(Double.valueOf(element))) .getAttribute(attribute.fulfill(1)); } catch (NumberFormatException e) { dB.echoError("'" + element + "' is not a valid Integer."); return new Element("null").getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_int> // @returns Element(Number) // @description // Returns the element as a number without a decimal. Rounds double values. // --> if (attribute.startsWith("asint") || attribute.startsWith("as_int")) try { // Round the Double instead of just getting its // value as an Integer (which would incorrectly // turn 2.9 into 2) return new Element(Math.round(Double.valueOf(element))) .getAttribute(attribute.fulfill(1)); } catch (NumberFormatException e) { dB.echoError("'" + element + "' is not a valid Integer."); return new Element("null").getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_item> // @returns dItem // @description // Returns the element as an item. Additional attributes can be accessed by dItem. // Note: the value must be a valid item. // --> if (attribute.startsWith("asitem") || attribute.startsWith("as_item")) return dItem.valueOf(element).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_list> // @returns dList // @description // Returns the element as a list. // --> if (attribute.startsWith("aslist") || attribute.startsWith("as_list")) return dList.valueOf(element).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_location> // @returns dLocation // @description // Returns the element as a location. Note: the value must be a valid location. // --> if (attribute.startsWith("aslocation") || attribute.startsWith("as_location")) return dLocation.valueOf(element).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_money> // @returns Element(Decimal) // @description // Returns the element as a number with two decimal places. // --> if (attribute.startsWith("asmoney") || attribute.startsWith("as_money")) { try { DecimalFormat d = new DecimalFormat("0.00"); return new Element(d.format(Double.valueOf(element))) .getAttribute(attribute.fulfill(1)); } catch (NumberFormatException e) { dB.echoError("'" + element + "' is not a valid Money format."); return new Element("null").getAttribute(attribute.fulfill(1)); } } // <--[tag] // @attribute <[email protected]_npc> // @returns dNPC // @description // Returns the element as an NPC. Note: the value must be a valid NPC. // --> if (attribute.startsWith("asnpc") || attribute.startsWith("as_npc")) return dNPC.valueOf(element).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_player> // @returns dPlayer // @description // Returns the element as a player. Note: the value must be a valid player. Can be online or offline. // --> if (attribute.startsWith("asplayer") || attribute.startsWith("as_player")) return dPlayer.valueOf(element).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_script> // @returns dScript // @description // Returns the element as a script. Note: the value must be a valid script. // --> if (attribute.startsWith("asscript") || attribute.startsWith("as_script")) return dScript.valueOf(element).getAttribute(attribute.fulfill(1)); ///////////////////// // DEBUG ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Prints the Element's debug representation in the console and returns true. // --> if (attribute.startsWith("debug.log")) { dB.log(debug()); return new Element(Boolean.TRUE) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]_color> // @returns Element // @description // Returns a standard debug representation of the Element with colors stripped. // --> if (attribute.startsWith("debug.no_color")) { return new Element(ChatColor.stripColor(debug())) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns a standard debug representation of the Element. // --> if (attribute.startsWith("debug")) { return new Element(debug()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the prefix of the element. // --> if (attribute.startsWith("prefix")) return new Element(prefix) .getAttribute(attribute.fulfill(1)); ///////////////////// // STRING CHECKING ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected][<string>]> // @returns Element(Boolean) // @description // Returns whether the element contains a specified string, case insensitive. Can use // regular expression by prefixing the string with regex: // --> if (attribute.startsWith("contains")) { String contains = attribute.getContext(1); if (contains.toLowerCase().startsWith("regex:")) { if (Pattern.compile(contains.substring(("regex:").length()), Pattern.CASE_INSENSITIVE).matcher(element).matches()) return new Element("true").getAttribute(attribute.fulfill(1)); else return new Element("false").getAttribute(attribute.fulfill(1)); } else if (element.toLowerCase().contains(contains.toLowerCase())) return new Element("true").getAttribute(attribute.fulfill(1)); else return new Element("false").getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_with[<string>]> // @returns Element(Boolean) // @description // Returns whether the element ends with a specified string. // --> if (attribute.startsWith("ends_with") || attribute.startsWith("endswith")) return new Element(element.endsWith(attribute.getContext(1))).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_color> // @returns Element // @description // Returns the ChatColors used at the end of a string. // --> if (attribute.startsWith("last_color")) return new Element(ChatColor.getLastColors(element)).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the length of the element. // --> if (attribute.startsWith("length")) { return new Element(element.length()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_with[<string>]> // @returns Element(Boolean) // @description // Returns whether the element starts with a specified string. // --> if (attribute.startsWith("starts_with") || attribute.startsWith("startswith")) return new Element(element.startsWith(attribute.getContext(1))).getAttribute(attribute.fulfill(1)); ///////////////////// // STRING MANIPULATION ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected][<string>]> // @returns Element // @description // Returns the portion of an element after a specified string. ie. <[email protected][hello]> returns 'World'. // --> if (attribute.startsWith("after")) { String delimiter = attribute.getContext(1); if (element.contains(delimiter)) return new Element(element.substring (element.indexOf(delimiter) + delimiter.length())) .getAttribute(attribute.fulfill(1)); else return new Element(element) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<string>]> // @returns Element // @description // Returns the portion of an element before a specified string. // --> if (attribute.startsWith("before")) { String delimiter = attribute.getContext(1); if (element.contains(delimiter)) return new Element(element.substring (0, element.indexOf(delimiter))) .getAttribute(attribute.fulfill(1)); else return new Element(element) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<string>]> // @returns Element // @description // Returns the element with all instances of a string removed. // --> // <--[tag] // @attribute <[email protected][<string>].with[<string>]> // @returns Element // @description // Returns the element with all instances of a string replaced with another. // --> if (attribute.startsWith("replace") && attribute.hasContext(1)) { String replace = attribute.getContext(1); String replacement = ""; attribute.fulfill(1); if (attribute.startsWith("with")) { if (attribute.hasContext(1)) { replacement = attribute.getContext(1); if (replacement == null) replacement = ""; attribute.fulfill(1); } } return new Element(element.replace(replace, replacement)) .getAttribute(attribute); } // <--[tag] // @attribute <[email protected][<string>].limit[<#>]> // @returns dList // @description // Returns a list of portions of this element, split by the specified string, // and capped at the specified number of max list items. // --> if (attribute.startsWith("split") && attribute.startsWith("limit", 2)) { String split_string = (attribute.hasContext(1) ? attribute.getContext(1) : " "); Integer limit = (attribute.hasContext(2) ? attribute.getIntContext(2) : 1); if (split_string.toLowerCase().startsWith("regex:")) return new dList(Arrays.asList(element.split(split_string.split(":", 2)[1], limit))) .getAttribute(attribute.fulfill(1)); else return new dList(Arrays.asList(StringUtils.split(element, split_string, limit))) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<string>]> // @returns dList // @description // Returns a list of portions of this element, split by the specified string. // --> if (attribute.startsWith("split")) { String split_string = (attribute.hasContext(1) ? attribute.getContext(1) : " "); if (split_string.toLowerCase().startsWith("regex:")) return new dList(Arrays.asList(element.split(split_string.split(":", 2)[1]))) .getAttribute(attribute.fulfill(1)); else return new dList(Arrays.asList(StringUtils.split(element, split_string))) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_color> // @returns Element // @description // Returns the element with all color encoding stripped. // --> if (attribute.startsWith("strip_color")) return new Element(ChatColor.stripColor(element)).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the value of an element minus any leading or trailing whitespace. // --> if (attribute.startsWith("trim")) return new Element(element.trim()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected][<#>(,<#>)]> // @returns Element // @description // Returns the portion of an element between two string indices. // If no second index is specified, it will return the portion of an // element after the specified index. // --> if (attribute.startsWith("substring")||attribute.startsWith("substr")) { // substring[2,8] int beginning_index = Integer.valueOf(attribute.getContext(1).split(",")[0]) - 1; int ending_index; if (attribute.getContext(1).split(",").length > 1) ending_index = Integer.valueOf(attribute.getContext(1).split(",")[1]) - 1; else ending_index = element.length(); if (beginning_index < 0) beginning_index = 0; if (ending_index > element.length()) ending_index = element.length(); return new Element(element.substring(beginning_index, ending_index)) .getAttribute(attribute.fulfill(1)); } ///////////////////// // MATH ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns Element(Decimal) // @description // Returns the absolute value of the element. // --> if (attribute.startsWith("abs")) { return new Element(Math.abs(asDouble())) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<#>]> // @returns Element(Decimal) // @description // Returns the element plus a number. // --> if (attribute.startsWith("add") && attribute.hasContext(1)) { return new Element(asDouble() + aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<#>]> // @returns Element(Decimal) // @description // Returns the element divided by a number. // --> if (attribute.startsWith("div") && attribute.hasContext(1)) { return new Element(asDouble() / aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<#>]> // @returns Element(Decimal) // @description // Returns the remainder of the element divided by a number. // --> if (attribute.startsWith("mod") && attribute.hasContext(1)) { return new Element(asDouble() % aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<#>]> // @returns Element(Decimal) // @description // Returns the element multiplied by a number. // --> if (attribute.startsWith("mul") && attribute.hasContext(1)) { return new Element(asDouble() * aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Decimal) // @description // Returns the square root of the element. // --> if (attribute.startsWith("sqrt")) { return new Element(Math.sqrt(asDouble())) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][<#>]> // @returns Element(Decimal) // @description // Returns the element minus a number. // --> if (attribute.startsWith("sub") && attribute.hasContext(1)) { return new Element(asDouble() - aH.getDoubleFrom(attribute.getContext(1))) .getAttribute(attribute.fulfill(1)); } // Unfilled attributes past this point probably means the tag is spelled // incorrectly. So instead of just passing through what's been resolved // so far, 'null' shall be returned with a debug message. if (attribute.attributes.size() > 0) { dB.echoDebug(attribute.getScriptEntry(), "Unfilled attributes '" + attribute.attributes.toString() + "'" + "for tag <" + attribute.getOrigin() + ">!"); return "null"; } else { dB.echoDebug(attribute.getScriptEntry(), "Filled tag <" + attribute.getOrigin() + "> with '" + element + "'."); return element; } }
diff --git a/src/main/java/com/lorepo/icplayer/client/PlayerEntryPoint.java b/src/main/java/com/lorepo/icplayer/client/PlayerEntryPoint.java index aa4d6fdf..09cd7b07 100644 --- a/src/main/java/com/lorepo/icplayer/client/PlayerEntryPoint.java +++ b/src/main/java/com/lorepo/icplayer/client/PlayerEntryPoint.java @@ -1,135 +1,138 @@ package com.lorepo.icplayer.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.JavaScriptObject; /** * Entry point classes define <code>onModuleLoad()</code>. */ public class PlayerEntryPoint implements EntryPoint { private PlayerApp theApplication; private JavaScriptObject pageLoadedListener; /** * This is the entry point method. */ public void onModuleLoad() { initJavaScriptAPI(this); } /** * Init Javascript API */ private static native void initJavaScriptAPI(PlayerEntryPoint x) /*-{ // CreatePlayer $wnd.icCreatePlayer = function(id) { var player = [email protected]::createAppPlayer(Ljava/lang/String;)(id); player.load = function(url, index){ index = index || 0; [email protected]::load(Ljava/lang/String;I)(url, index); } player.setApiUrl = function(url){ [email protected]::setApiUrl(Ljava/lang/String;)(url); } player.setAnalyticsUrl = function(url){ [email protected]::setAnalyticsUrl(Ljava/lang/String;)(url); } player.setTestMode = function(){ [email protected]::setTestMode()(); } player.getState = function(){ return [email protected]::getState()(); } player.setState = function(state){ [email protected]::setState(Ljava/lang/String;)(state); } player.getPlayerServices = function(){ return [email protected]::getPlayerServices()(); } player.onPageLoaded = function(listener){ [email protected]::pageLoadedListener = listener; } return player; } // Call App loaded function - if(typeof $wnd.qpOnAppLoaded == 'function') { + if(typeof $wnd.icOnAppLoaded == 'function') { + $wnd.icOnAppLoaded(); + } + else if(typeof $wnd.qpOnAppLoaded == 'function') { $wnd.qpOnAppLoaded(); } }-*/; /** * createPlayer js interface * * @param node_id * wrap this node */ private JavaScriptObject createAppPlayer(String node_id) { theApplication = new PlayerApp(node_id, this); return JavaScriptObject.createFunction(); } private void load(String url, int pageIndex) { if(pageIndex < 0){ pageIndex = 0; } theApplication.load(url, pageIndex); } private void setApiUrl(String url) { theApplication.setApiUrl(url); } private void setAnalyticsUrl(String url) { theApplication.setAnalyticsUrl(url); } private void setTestMode() { theApplication.setTestMode(); } private void setState(String state) { theApplication.getState().loadFromString(state); } private String getState() { return theApplication.getState().getAsString(); } private JavaScriptObject getPlayerServices() { return theApplication.getPlayerServices().getAsJSObject(); } private static native void firePageLoaded(JavaScriptObject callback) /*-{ if(callback != null){ callback(); } }-*/; public void onPageLoaded() { firePageLoaded(pageLoadedListener); } }
true
true
private static native void initJavaScriptAPI(PlayerEntryPoint x) /*-{ // CreatePlayer $wnd.icCreatePlayer = function(id) { var player = [email protected]::createAppPlayer(Ljava/lang/String;)(id); player.load = function(url, index){ index = index || 0; [email protected]::load(Ljava/lang/String;I)(url, index); } player.setApiUrl = function(url){ [email protected]::setApiUrl(Ljava/lang/String;)(url); } player.setAnalyticsUrl = function(url){ [email protected]::setAnalyticsUrl(Ljava/lang/String;)(url); } player.setTestMode = function(){ [email protected]::setTestMode()(); } player.getState = function(){ return [email protected]::getState()(); } player.setState = function(state){ [email protected]::setState(Ljava/lang/String;)(state); } player.getPlayerServices = function(){ return [email protected]::getPlayerServices()(); } player.onPageLoaded = function(listener){ [email protected]::pageLoadedListener = listener; } return player; } // Call App loaded function if(typeof $wnd.qpOnAppLoaded == 'function') { $wnd.qpOnAppLoaded(); } }-*/;
private static native void initJavaScriptAPI(PlayerEntryPoint x) /*-{ // CreatePlayer $wnd.icCreatePlayer = function(id) { var player = [email protected]::createAppPlayer(Ljava/lang/String;)(id); player.load = function(url, index){ index = index || 0; [email protected]::load(Ljava/lang/String;I)(url, index); } player.setApiUrl = function(url){ [email protected]::setApiUrl(Ljava/lang/String;)(url); } player.setAnalyticsUrl = function(url){ [email protected]::setAnalyticsUrl(Ljava/lang/String;)(url); } player.setTestMode = function(){ [email protected]::setTestMode()(); } player.getState = function(){ return [email protected]::getState()(); } player.setState = function(state){ [email protected]::setState(Ljava/lang/String;)(state); } player.getPlayerServices = function(){ return [email protected]::getPlayerServices()(); } player.onPageLoaded = function(listener){ [email protected]::pageLoadedListener = listener; } return player; } // Call App loaded function if(typeof $wnd.icOnAppLoaded == 'function') { $wnd.icOnAppLoaded(); } else if(typeof $wnd.qpOnAppLoaded == 'function') { $wnd.qpOnAppLoaded(); } }-*/;
diff --git a/org.eclipse.mylyn.context.tests/src/org/eclipse/mylyn/context/tests/AbstractContextTest.java b/org.eclipse.mylyn.context.tests/src/org/eclipse/mylyn/context/tests/AbstractContextTest.java index df70a5deb..d0d01240e 100644 --- a/org.eclipse.mylyn.context.tests/src/org/eclipse/mylyn/context/tests/AbstractContextTest.java +++ b/org.eclipse.mylyn.context.tests/src/org/eclipse/mylyn/context/tests/AbstractContextTest.java @@ -1,92 +1,93 @@ /******************************************************************************* * Copyright (c) 2004, 2008 Tasktop Technologies and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Tasktop Technologies - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.context.tests; import junit.framework.TestCase; import org.eclipse.mylyn.context.core.ContextCore; import org.eclipse.mylyn.context.core.IInteractionContext; import org.eclipse.mylyn.internal.context.core.InteractionContextManager; import org.eclipse.mylyn.monitor.core.InteractionEvent; import org.eclipse.ui.IViewPart; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; /** * @author Mik Kersten */ public abstract class AbstractContextTest extends TestCase { protected static final String MOCK_HANDLE = "<mock-handle>"; private static final String MOCK_PROVIDER = "<mock-provider>"; protected static final String MOCK_ORIGIN = "<mock-origin>"; protected static final String MOCK_KIND = "java"; @Override protected void setUp() throws Exception { super.setUp(); if (ContextCore.getContextManager() != null) { - assertFalse("" + ((InteractionContextManager) ContextCore.getContextManager()).getActiveContexts(), + assertFalse("Unexpected context active: " + + ((InteractionContextManager) ContextCore.getContextManager()).getActiveContexts(), ContextCore.getContextManager().isContextActive()); } } @Override protected void tearDown() throws Exception { super.tearDown(); if (ContextCore.getContextManager() != null) { assertFalse("" + ((InteractionContextManager) ContextCore.getContextManager()).getActiveContexts(), ContextCore.getContextManager().isContextActive()); } } protected InteractionEvent mockSelection(String handle) { return new InteractionEvent(InteractionEvent.Kind.SELECTION, MOCK_KIND, handle, MOCK_ORIGIN); } protected InteractionEvent mockPropagation(String handle) { return new InteractionEvent(InteractionEvent.Kind.PROPAGATION, MOCK_KIND, handle, MOCK_ORIGIN); } protected InteractionEvent mockSelection() { return mockSelection(MOCK_HANDLE); } protected InteractionEvent mockNavigation(String toHandle) { return new InteractionEvent(InteractionEvent.Kind.SELECTION, MOCK_KIND, toHandle, MOCK_ORIGIN, MOCK_PROVIDER); } protected InteractionEvent mockInterestContribution(String handle, String kind, float value) { InteractionEvent event = new InteractionEvent(InteractionEvent.Kind.MANIPULATION, kind, handle, MOCK_ORIGIN, value); return event; } protected InteractionEvent mockInterestContribution(String handle, float value) { return mockInterestContribution(handle, MOCK_KIND, value); } protected InteractionEvent mockPreferenceChange(String handle) { return new InteractionEvent(InteractionEvent.Kind.PREFERENCE, MOCK_KIND, handle, MOCK_ORIGIN); } protected boolean compareTaskscapeEquality(IInteractionContext t1, IInteractionContext t2) { return false; } protected IViewPart openView(String id) throws PartInitException { return PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(id); } }
true
true
protected void setUp() throws Exception { super.setUp(); if (ContextCore.getContextManager() != null) { assertFalse("" + ((InteractionContextManager) ContextCore.getContextManager()).getActiveContexts(), ContextCore.getContextManager().isContextActive()); } }
protected void setUp() throws Exception { super.setUp(); if (ContextCore.getContextManager() != null) { assertFalse("Unexpected context active: " + ((InteractionContextManager) ContextCore.getContextManager()).getActiveContexts(), ContextCore.getContextManager().isContextActive()); } }
diff --git a/hazelcast/src/main/java/com/hazelcast/transaction/impl/TransactionContextImpl.java b/hazelcast/src/main/java/com/hazelcast/transaction/impl/TransactionContextImpl.java index f68e1f1f97..8a72fb3949 100644 --- a/hazelcast/src/main/java/com/hazelcast/transaction/impl/TransactionContextImpl.java +++ b/hazelcast/src/main/java/com/hazelcast/transaction/impl/TransactionContextImpl.java @@ -1,146 +1,147 @@ /* * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.transaction.impl; import com.hazelcast.collection.CollectionProxyId; import com.hazelcast.collection.CollectionProxyType; import com.hazelcast.collection.CollectionService; import com.hazelcast.collection.list.ObjectListProxy; import com.hazelcast.collection.set.ObjectSetProxy; import com.hazelcast.core.*; import com.hazelcast.map.MapService; import com.hazelcast.queue.QueueService; import com.hazelcast.spi.TransactionalService; import com.hazelcast.spi.impl.NodeEngineImpl; import com.hazelcast.transaction.*; import java.util.HashMap; import java.util.Map; /** * @author mdogan 2/26/13 */ final class TransactionContextImpl implements TransactionContext { private final NodeEngineImpl nodeEngine; private final TransactionImpl transaction; private final Map<TransactionalObjectKey, TransactionalObject> txnObjectMap = new HashMap<TransactionalObjectKey, TransactionalObject>(2); TransactionContextImpl(TransactionManagerServiceImpl transactionManagerService, NodeEngineImpl nodeEngine, TransactionOptions options, String ownerUuid) { this.nodeEngine = nodeEngine; this.transaction = new TransactionImpl(transactionManagerService, nodeEngine, options, ownerUuid); } public String getTxnId() { return transaction.getTxnId(); } public void beginTransaction() { transaction.begin(); } public void commitTransaction() throws TransactionException { if (transaction.getTransactionType().equals(TransactionOptions.TransactionType.TWO_PHASE)) { transaction.prepare(); } transaction.commit(); } public void rollbackTransaction() { transaction.rollback(); } @SuppressWarnings("unchecked") public <K, V> TransactionalMap<K, V> getMap(String name) { return (TransactionalMap<K, V>) getTransactionalObject(MapService.SERVICE_NAME, name); } @SuppressWarnings("unchecked") public <E> TransactionalQueue<E> getQueue(String name) { return (TransactionalQueue<E>) getTransactionalObject(QueueService.SERVICE_NAME, name); } @SuppressWarnings("unchecked") public <K, V> TransactionalMultiMap<K, V> getMultiMap(String name) { return (TransactionalMultiMap<K, V>) getTransactionalObject(CollectionService.SERVICE_NAME, new CollectionProxyId(name, null, CollectionProxyType.MULTI_MAP)); } @SuppressWarnings("unchecked") public <E> TransactionalList<E> getList(String name) { return (TransactionalList<E>) getTransactionalObject(CollectionService.SERVICE_NAME, new CollectionProxyId(ObjectListProxy.COLLECTION_LIST_NAME, name, CollectionProxyType.LIST)); } @SuppressWarnings("unchecked") public <E> TransactionalSet<E> getSet(String name) { return (TransactionalSet<E>) getTransactionalObject(CollectionService.SERVICE_NAME, new CollectionProxyId(ObjectSetProxy.COLLECTION_SET_NAME, name, CollectionProxyType.SET)); } @SuppressWarnings("unchecked") public TransactionalObject getTransactionalObject(String serviceName, Object id) { if (transaction.getState() != Transaction.State.ACTIVE) { throw new TransactionNotActiveException("No transaction is found while accessing " + "transactional object -> " + serviceName + "[" + id + "]!"); } TransactionalObjectKey key = new TransactionalObjectKey(serviceName, id); TransactionalObject obj = txnObjectMap.get(key); if (obj == null) { final Object service = nodeEngine.getService(serviceName); if (service instanceof TransactionalService) { + nodeEngine.getProxyService().initializeDistributedObject(serviceName, id); obj = ((TransactionalService) service).createTransactionalObject(id, transaction); txnObjectMap.put(key, obj); } else { throw new IllegalArgumentException("Service[" + serviceName + "] is not transactional!"); } } return obj; } Transaction getTransaction() { return transaction; } private class TransactionalObjectKey { private final String serviceName; private final Object id; TransactionalObjectKey(String serviceName, Object id) { this.serviceName = serviceName; this.id = id; } public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof TransactionalObjectKey)) return false; TransactionalObjectKey that = (TransactionalObjectKey) o; if (!id.equals(that.id)) return false; if (!serviceName.equals(that.serviceName)) return false; return true; } public int hashCode() { int result = serviceName.hashCode(); result = 31 * result + id.hashCode(); return result; } } }
true
true
public TransactionalObject getTransactionalObject(String serviceName, Object id) { if (transaction.getState() != Transaction.State.ACTIVE) { throw new TransactionNotActiveException("No transaction is found while accessing " + "transactional object -> " + serviceName + "[" + id + "]!"); } TransactionalObjectKey key = new TransactionalObjectKey(serviceName, id); TransactionalObject obj = txnObjectMap.get(key); if (obj == null) { final Object service = nodeEngine.getService(serviceName); if (service instanceof TransactionalService) { obj = ((TransactionalService) service).createTransactionalObject(id, transaction); txnObjectMap.put(key, obj); } else { throw new IllegalArgumentException("Service[" + serviceName + "] is not transactional!"); } } return obj; }
public TransactionalObject getTransactionalObject(String serviceName, Object id) { if (transaction.getState() != Transaction.State.ACTIVE) { throw new TransactionNotActiveException("No transaction is found while accessing " + "transactional object -> " + serviceName + "[" + id + "]!"); } TransactionalObjectKey key = new TransactionalObjectKey(serviceName, id); TransactionalObject obj = txnObjectMap.get(key); if (obj == null) { final Object service = nodeEngine.getService(serviceName); if (service instanceof TransactionalService) { nodeEngine.getProxyService().initializeDistributedObject(serviceName, id); obj = ((TransactionalService) service).createTransactionalObject(id, transaction); txnObjectMap.put(key, obj); } else { throw new IllegalArgumentException("Service[" + serviceName + "] is not transactional!"); } } return obj; }
diff --git a/src/blur-store/src/main/java/com/nearinfinity/blur/store/blockcache/BlockDirectory.java b/src/blur-store/src/main/java/com/nearinfinity/blur/store/blockcache/BlockDirectory.java index 9d21fb05..46165fc4 100644 --- a/src/blur-store/src/main/java/com/nearinfinity/blur/store/blockcache/BlockDirectory.java +++ b/src/blur-store/src/main/java/com/nearinfinity/blur/store/blockcache/BlockDirectory.java @@ -1,276 +1,276 @@ package com.nearinfinity.blur.store.blockcache; import java.io.IOException; import java.util.Collection; import java.util.Set; import org.apache.lucene.store.Directory; import org.apache.lucene.store.IndexInput; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.store.Lock; import org.apache.lucene.store.LockFactory; import com.nearinfinity.blur.index.DirectIODirectory; import com.nearinfinity.blur.store.BufferStore; import com.nearinfinity.blur.store.CustomBufferedIndexInput; public class BlockDirectory extends DirectIODirectory { public static final long BLOCK_SHIFT = 13; // 2^13 = 8,192 bytes per block public static final long BLOCK_MOD = 0x1FFF; public static final int BLOCK_SIZE = 1 << BLOCK_SHIFT; public static long getBlock(long pos) { return pos >>> BLOCK_SHIFT; } public static long getPosition(long pos) { return pos & BLOCK_MOD; } public static long getRealPosition(long block, long positionInBlock) { return (block << BLOCK_SHIFT) + positionInBlock; } public static Cache NO_CACHE = new Cache() { @Override public void update(String name, long blockId, byte[] buffer) { } @Override public boolean fetch(String name, long blockId, int blockOffset, byte[] b, int off, int lengthToReadInBlock) { return false; } @Override public void delete(String name) { } @Override public long size() { return 0; } }; private DirectIODirectory _directory; private int _blockSize; private String _dirName; private Cache _cache; private Set<String> _blockCacheFileTypes; public BlockDirectory(String dirName, DirectIODirectory directory) throws IOException { this(dirName, directory, NO_CACHE); } public BlockDirectory(String dirName, DirectIODirectory directory, Cache cache) throws IOException { this(dirName, directory, cache, null); } public BlockDirectory(String dirName, DirectIODirectory directory, Cache cache, Set<String> blockCacheFileTypes) throws IOException { _dirName = dirName; _directory = directory; _blockSize = BLOCK_SIZE; _cache = cache; - if (_blockCacheFileTypes == null || _blockCacheFileTypes.isEmpty()) { + if (blockCacheFileTypes == null || blockCacheFileTypes.isEmpty()) { _blockCacheFileTypes = null; } else { _blockCacheFileTypes = blockCacheFileTypes; } setLockFactory(directory.getLockFactory()); } public IndexInput openInput(String name, int bufferSize) throws IOException { final IndexInput source = _directory.openInput(name, _blockSize); if (_blockCacheFileTypes == null || isCachableFile(name)) { return new CachedIndexInput(source, _blockSize, name, getFileCacheName(name), _cache, bufferSize); } return source; } private boolean isCachableFile(String name) { for (String ext : _blockCacheFileTypes) { if (name.endsWith(ext)) { return true; } } return false; } @Override public IndexInput openInput(final String name) throws IOException { return openInput(name, _blockSize); } static class CachedIndexInput extends CustomBufferedIndexInput { private IndexInput _source; private int _blockSize; private long _fileLength; private String _cacheName; private Cache _cache; public CachedIndexInput(IndexInput source, int blockSize, String name, String cacheName, Cache cache, int bufferSize) { super(name, bufferSize); _source = source; _blockSize = blockSize; _fileLength = source.length(); _cacheName = cacheName; _cache = cache; } @Override public Object clone() { CachedIndexInput clone = (CachedIndexInput) super.clone(); clone._source = (IndexInput) _source.clone(); return clone; } @Override public long length() { return _source.length(); } @Override protected void seekInternal(long pos) throws IOException { } @Override protected void readInternal(byte[] b, int off, int len) throws IOException { long position = getFilePointer(); while (len > 0) { int length = fetchBlock(position, b, off, len); position += length; len -= length; off += length; } } private int fetchBlock(long position, byte[] b, int off, int len) throws IOException { // read whole block into cache and then provide needed data long blockId = getBlock(position); int blockOffset = (int) getPosition(position); int lengthToReadInBlock = Math.min(len, _blockSize - blockOffset); if (checkCache(blockId, blockOffset, b, off, lengthToReadInBlock)) { return lengthToReadInBlock; } else { readIntoCacheAndResult(blockId, blockOffset, b, off, lengthToReadInBlock); } return lengthToReadInBlock; } private void readIntoCacheAndResult(long blockId, int blockOffset, byte[] b, int off, int lengthToReadInBlock) throws IOException { long position = getRealPosition(blockId, 0); int length = (int) Math.min(_blockSize, _fileLength - position); _source.seek(position); byte[] buf = BufferStore.takeBuffer(_blockSize); _source.readBytes(buf, 0, length); System.arraycopy(buf, blockOffset, b, off, lengthToReadInBlock); _cache.update(_cacheName, blockId, buf); BufferStore.putBuffer(buf); } private boolean checkCache(long blockId, int blockOffset, byte[] b, int off, int lengthToReadInBlock) { return _cache.fetch(_cacheName, blockId, blockOffset, b, off, lengthToReadInBlock); } @Override protected void closeInternal() throws IOException { _source.close(); } } @Override public void close() throws IOException { String[] files = listAll(); for (String file : files) { _cache.delete(getFileCacheName(file)); } _directory.close(); } private String getFileCacheName(String name) throws IOException { return _dirName + "/" + name + ":" + fileModified(name); } public void clearLock(String name) throws IOException { _directory.clearLock(name); } public void copy(Directory to, String src, String dest) throws IOException { _directory.copy(to, src, dest); } public LockFactory getLockFactory() { return _directory.getLockFactory(); } public String getLockID() { return _directory.getLockID(); } public Lock makeLock(String name) { return _directory.makeLock(name); } public void setLockFactory(LockFactory lockFactory) throws IOException { _directory.setLockFactory(lockFactory); } public void sync(Collection<String> names) throws IOException { _directory.sync(names); } @SuppressWarnings("deprecation") public void sync(String name) throws IOException { _directory.sync(name); } public String toString() { return _directory.toString(); } public IndexOutput createOutput(String name) throws IOException { return _directory.createOutput(name); } public void deleteFile(String name) throws IOException { _cache.delete(getFileCacheName(name)); _directory.deleteFile(name); } public boolean fileExists(String name) throws IOException { return _directory.fileExists(name); } public long fileLength(String name) throws IOException { return _directory.fileLength(name); } public long fileModified(String name) throws IOException { return _directory.fileModified(name); } public String[] listAll() throws IOException { return _directory.listAll(); } @SuppressWarnings("deprecation") public void touchFile(String name) throws IOException { _directory.touchFile(name); } @Override public IndexOutput createOutputDirectIO(String name) throws IOException { return _directory.createOutputDirectIO(name); } @Override public IndexInput openInputDirectIO(String name) throws IOException { return _directory.openInputDirectIO(name); } }
true
true
public BlockDirectory(String dirName, DirectIODirectory directory, Cache cache, Set<String> blockCacheFileTypes) throws IOException { _dirName = dirName; _directory = directory; _blockSize = BLOCK_SIZE; _cache = cache; if (_blockCacheFileTypes == null || _blockCacheFileTypes.isEmpty()) { _blockCacheFileTypes = null; } else { _blockCacheFileTypes = blockCacheFileTypes; } setLockFactory(directory.getLockFactory()); }
public BlockDirectory(String dirName, DirectIODirectory directory, Cache cache, Set<String> blockCacheFileTypes) throws IOException { _dirName = dirName; _directory = directory; _blockSize = BLOCK_SIZE; _cache = cache; if (blockCacheFileTypes == null || blockCacheFileTypes.isEmpty()) { _blockCacheFileTypes = null; } else { _blockCacheFileTypes = blockCacheFileTypes; } setLockFactory(directory.getLockFactory()); }
diff --git a/src/cz/vutbr/fit/gja/gjaddr/gui/DetailPanel.java b/src/cz/vutbr/fit/gja/gjaddr/gui/DetailPanel.java index 3f13b1f..24976ce 100644 --- a/src/cz/vutbr/fit/gja/gjaddr/gui/DetailPanel.java +++ b/src/cz/vutbr/fit/gja/gjaddr/gui/DetailPanel.java @@ -1,347 +1,347 @@ package cz.vutbr.fit.gja.gjaddr.gui; import cz.vutbr.fit.gja.gjaddr.persistancelayer.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLEncoder; import java.text.DateFormat; import javax.swing.*; /** * Panel with contact detail * * @author Bc. Jan Kaláb <[email protected],vutbr.cz> */ class DetailPanel extends JPanel { static final long serialVersionUID = 0; private final Database db = Database.getInstance(); private final JLabel name = new JLabel(); private final JLabel nickname = new JLabel(); private final JPanel address = new JPanel(); private final JPanel emails = new JPanel(); private final JLabel phones = new JLabel(); private final JPanel webs = new JPanel(); private final JLabel birthday = new JLabel(); private final JLabel nameday = new JLabel(); private final JLabel celebration = new JLabel(); private final JLabel note = new JLabel(); private final JLabel bdayIcon = new JLabel(); private final JLabel namedayIcon = new JLabel(); private final JLabel celebrationIcon = new JLabel(); private final PhotoButton photo = new PhotoButton(); private final JLabel groups = new JLabel(); private final JLabel nicknameLabel = new JLabel("<html><b>Nickname: </b></html>"); private final JLabel addressLabel = new JLabel("<html><b>Address: </b></html>"); private final JLabel emailLabel = new JLabel("<html><b>Email: </b></html>"); private final JLabel phoneLabel = new JLabel("<html><b>Phone: </b></html>"); private final JLabel websLabel = new JLabel("<html><b>Webs: </b></html>"); private final JLabel birthdayLabel = new JLabel("<html><b>Birthday: </b></html>"); private final JLabel namedayLabel = new JLabel("<html><b>Nameday: </b></html>"); private final JLabel celebrationLabel = new JLabel("<html><b>Celebration: </b></html>"); private final JLabel noteLabel = new JLabel("<html><b>Note: </b></html>"); private final JLabel groupsLabel = new JLabel("<html><b>Groups: </b></html>"); private JScrollPane detailScrollPane; /** * Constructor */ public DetailPanel() { setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10)); final JLabel label = new JLabel("Detail"); label.setAlignmentX(CENTER_ALIGNMENT); add(label); // create panel with name and with birthday icon final JPanel namePanel = new JPanel(); namePanel.setLayout(new BoxLayout(namePanel, BoxLayout.LINE_AXIS)); bdayIcon.setIcon(new ImageIcon(getClass().getResource("/res/present.png"))); bdayIcon.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10)); bdayIcon.setVisible(false); namedayIcon.setIcon(new ImageIcon(getClass().getResource("/res/nameday.png"))); namedayIcon.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10)); namedayIcon.setVisible(false); celebrationIcon.setIcon(new ImageIcon(getClass().getResource("/res/celebration.png"))); celebrationIcon.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10)); celebrationIcon.setVisible(false); namePanel.add(bdayIcon); namePanel.add(namedayIcon); namePanel.add(celebrationIcon); namePanel.add(name); photo.setVisible(false); namePanel.add(photo); /* namePanel.setAlignmentX(Component.CENTER_ALIGNMENT); namePanel.setAlignmentY(Component.TOP_ALIGNMENT); */ add(namePanel); final JPanel detailPanel = new JPanel(new GridBagLayout()); final GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1; c.anchor = GridBagConstraints.PAGE_START; c.gridx = 0; c.gridy = 0; detailPanel.add(nicknameLabel, c); c.gridx = 1; nickname.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0)); detailPanel.add(nickname, c); c.gridx = 0; c.gridy++; detailPanel.add(addressLabel, c); c.gridx = 1; address.setLayout(new BoxLayout(address, BoxLayout.PAGE_AXIS)); address.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0)); detailPanel.add(address, c); c.gridx = 0; c.gridy++; detailPanel.add(emailLabel, c); c.gridx = 1; emails.setLayout(new BoxLayout(emails, BoxLayout.PAGE_AXIS)); emails.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0)); detailPanel.add(emails, c); c.gridx = 0; c.gridy++; detailPanel.add(phoneLabel, c); c.gridx = 1; phones.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0)); detailPanel.add(phones, c); c.gridx = 0; c.gridy++; detailPanel.add(websLabel, c); c.gridx = 1; webs.setLayout(new BoxLayout(webs, BoxLayout.PAGE_AXIS)); webs.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0)); detailPanel.add(webs, c); c.gridx = 0; c.gridy++; detailPanel.add(birthdayLabel, c); c.gridx = 1; birthday.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0)); detailPanel.add(birthday, c); c.gridx = 0; c.gridy++; detailPanel.add(namedayLabel, c); c.gridx = 1; birthday.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0)); detailPanel.add(nameday, c); c.gridx = 0; c.gridy++; detailPanel.add(celebrationLabel, c); c.gridx = 1; birthday.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0)); detailPanel.add(celebration, c); c.gridx = 0; c.gridy++; detailPanel.add(noteLabel, c); c.gridx = 1; note.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0)); detailPanel.add(note, c); c.gridx = 0; c.gridy++; detailPanel.add(groupsLabel, c); c.gridx = 1; //groups.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0)); //Last without margin detailPanel.add(groups, c); c.gridy++; c.weighty = 1; detailPanel.add(Box.createVerticalGlue(), c); detailScrollPane = new JScrollPane(detailPanel); detailScrollPane.setBorder(BorderFactory.createEmptyBorder()); detailScrollPane.setVisible(false); add(detailScrollPane); } void show(Contact contact) { if (contact != null) { if (contact.hasBirthday()) { bdayIcon.setVisible(true); } else { bdayIcon.setVisible(false); } if (contact.hasNameDay()) { namedayIcon.setVisible(true); } else { namedayIcon.setVisible(false); } if (contact.hasCelebration()) { celebrationIcon.setVisible(true); } else { celebrationIcon.setVisible(false); } photo.setContact(contact); photo.setVisible(true); name.setText(String.format("<html><h1>" + contact.getFullName() + "</h1></html>")); if (contact.getNickName() != null && !contact.getNickName().isEmpty()) { nicknameLabel.setVisible(true); nickname.setVisible(true); nickname.setText(contact.getNickName()); } else { nicknameLabel.setVisible(false); nickname.setVisible(false); } address.removeAll(); addressLabel.setVisible(false); for (Address a : contact.getAdresses()) { if (!a.getAddress().isEmpty()) { addressLabel.setVisible(true); JLabelButton l = new JLabelButton(); l.setVerticalTextPosition(JLabel.TOP); l.setHorizontalTextPosition(JLabel.CENTER); l.setAlignmentX(Component.LEFT_ALIGNMENT); l.setCursor(new Cursor(Cursor.HAND_CURSOR)); l.setText(a.getAddress()); try { l.setIcon(new ImageIcon(new URL("http://maps.google.com/maps/api/staticmap?size=128x128&sensor=false&markers=" + URLEncoder.encode(l.getText(), "utf8")))); } catch (IOException e) { System.err.println(e); } l.addActionListener(new MapListener()); address.add(l); } } emails.removeAll(); emailLabel.setVisible(false); for (Email e : contact.getEmails()) { if (!e.getEmail().isEmpty()) { emailLabel.setVisible(true); JLabelButton lb = new JLabelButton(e.getEmail()); lb.setCursor(new Cursor(Cursor.HAND_CURSOR)); lb.addActionListener(new EmailListener()); emails.add(lb); } } webs.removeAll(); websLabel.setVisible(false); for (Url u : contact.getUrls()) { if (u.getValue() != null) { websLabel.setVisible(true); JLabelButton lb = new JLabelButton(u.getValue().toString()); lb.setCursor(new Cursor(Cursor.HAND_CURSOR)); lb.addActionListener(new WebListener()); - emails.add(lb); + webs.add(lb); } } if (!contact.getPhoneNumbers().isEmpty()) { phoneLabel.setVisible(true); phones.setVisible(true); phones.setText("<html>" + contact.getAllPhones().replaceAll(", ", "<br>") + "</html>"); } else { phoneLabel.setVisible(false); phones.setVisible(false); } if (contact.getBirthday() != null && contact.getBirthday().getDate() != null) { birthday.setVisible(true); birthdayLabel.setVisible(true); birthday.setText(DateFormat.getDateInstance().format(contact.getBirthday().getDate())); } else { birthday.setVisible(false); birthdayLabel.setVisible(false); } if (contact.getNameDay() != null && contact.getNameDay().getDate() != null) { nameday.setVisible(true); namedayLabel.setVisible(true); nameday.setText(DateFormat.getDateInstance().format(contact.getNameDay().getDate())); } else { nameday.setVisible(false); namedayLabel.setVisible(false); } if (contact.getCelebration() != null && contact.getCelebration().getDate() != null) { celebration.setVisible(true); celebrationLabel.setVisible(true); celebration.setText(DateFormat.getDateInstance().format(contact.getCelebration().getDate())); } else { celebration.setVisible(false); celebrationLabel.setVisible(false); } if (contact.getNote() != null && !contact.getNote().isEmpty()) { note.setVisible(true); noteLabel.setVisible(true); note.setText("<html>" + contact.getNote().replaceAll("\n", "<br>") + "</html>"); } else { note.setVisible(false); noteLabel.setVisible(false); } String separator = ""; final StringBuilder groupstring = new StringBuilder(); groups.setVisible(false); groupsLabel.setVisible(false); for (Group g : db.getAllGroupsForContact(contact)) { groups.setVisible(true); groupsLabel.setVisible(true); groupstring.append(separator); groupstring.append(g.getName()); separator = ", "; } groups.setText(groupstring.toString()); detailScrollPane.setVisible(true); } } /** * Action for opening mail client */ private class EmailListener implements ActionListener { @Override public void actionPerformed(ActionEvent ev) { final JButton b = (JButton) ev.getSource(); try { Desktop.getDesktop().mail(new URI("mailto", b.getText(), null)); } catch (URISyntaxException ex) { System.err.println(ex); } catch (IOException ex) { System.err.println(ex); } } } /** * Action for opening browser with maps */ private class MapListener implements ActionListener { @Override public void actionPerformed(ActionEvent ev) { final JButton b = (JButton) ev.getSource(); try { Desktop.getDesktop().browse(new URI("http://maps.google.com/maps?q=" + URLEncoder.encode(b.getText(), "utf8"))); } catch (URISyntaxException ex) { System.err.println(ex); } catch (IOException ex) { System.err.println(ex); } } } /** * Action for opening browser with web */ private class WebListener implements ActionListener { @Override public void actionPerformed(ActionEvent ev) { final JButton b = (JButton) ev.getSource(); try { Desktop.getDesktop().browse(new URI(b.getText())); } catch (URISyntaxException ex) { System.err.println(ex); } catch (IOException ex) { System.err.println(ex); } } } }
true
true
void show(Contact contact) { if (contact != null) { if (contact.hasBirthday()) { bdayIcon.setVisible(true); } else { bdayIcon.setVisible(false); } if (contact.hasNameDay()) { namedayIcon.setVisible(true); } else { namedayIcon.setVisible(false); } if (contact.hasCelebration()) { celebrationIcon.setVisible(true); } else { celebrationIcon.setVisible(false); } photo.setContact(contact); photo.setVisible(true); name.setText(String.format("<html><h1>" + contact.getFullName() + "</h1></html>")); if (contact.getNickName() != null && !contact.getNickName().isEmpty()) { nicknameLabel.setVisible(true); nickname.setVisible(true); nickname.setText(contact.getNickName()); } else { nicknameLabel.setVisible(false); nickname.setVisible(false); } address.removeAll(); addressLabel.setVisible(false); for (Address a : contact.getAdresses()) { if (!a.getAddress().isEmpty()) { addressLabel.setVisible(true); JLabelButton l = new JLabelButton(); l.setVerticalTextPosition(JLabel.TOP); l.setHorizontalTextPosition(JLabel.CENTER); l.setAlignmentX(Component.LEFT_ALIGNMENT); l.setCursor(new Cursor(Cursor.HAND_CURSOR)); l.setText(a.getAddress()); try { l.setIcon(new ImageIcon(new URL("http://maps.google.com/maps/api/staticmap?size=128x128&sensor=false&markers=" + URLEncoder.encode(l.getText(), "utf8")))); } catch (IOException e) { System.err.println(e); } l.addActionListener(new MapListener()); address.add(l); } } emails.removeAll(); emailLabel.setVisible(false); for (Email e : contact.getEmails()) { if (!e.getEmail().isEmpty()) { emailLabel.setVisible(true); JLabelButton lb = new JLabelButton(e.getEmail()); lb.setCursor(new Cursor(Cursor.HAND_CURSOR)); lb.addActionListener(new EmailListener()); emails.add(lb); } } webs.removeAll(); websLabel.setVisible(false); for (Url u : contact.getUrls()) { if (u.getValue() != null) { websLabel.setVisible(true); JLabelButton lb = new JLabelButton(u.getValue().toString()); lb.setCursor(new Cursor(Cursor.HAND_CURSOR)); lb.addActionListener(new WebListener()); emails.add(lb); } } if (!contact.getPhoneNumbers().isEmpty()) { phoneLabel.setVisible(true); phones.setVisible(true); phones.setText("<html>" + contact.getAllPhones().replaceAll(", ", "<br>") + "</html>"); } else { phoneLabel.setVisible(false); phones.setVisible(false); } if (contact.getBirthday() != null && contact.getBirthday().getDate() != null) { birthday.setVisible(true); birthdayLabel.setVisible(true); birthday.setText(DateFormat.getDateInstance().format(contact.getBirthday().getDate())); } else { birthday.setVisible(false); birthdayLabel.setVisible(false); } if (contact.getNameDay() != null && contact.getNameDay().getDate() != null) { nameday.setVisible(true); namedayLabel.setVisible(true); nameday.setText(DateFormat.getDateInstance().format(contact.getNameDay().getDate())); } else { nameday.setVisible(false); namedayLabel.setVisible(false); } if (contact.getCelebration() != null && contact.getCelebration().getDate() != null) { celebration.setVisible(true); celebrationLabel.setVisible(true); celebration.setText(DateFormat.getDateInstance().format(contact.getCelebration().getDate())); } else { celebration.setVisible(false); celebrationLabel.setVisible(false); } if (contact.getNote() != null && !contact.getNote().isEmpty()) { note.setVisible(true); noteLabel.setVisible(true); note.setText("<html>" + contact.getNote().replaceAll("\n", "<br>") + "</html>"); } else { note.setVisible(false); noteLabel.setVisible(false); } String separator = ""; final StringBuilder groupstring = new StringBuilder(); groups.setVisible(false); groupsLabel.setVisible(false); for (Group g : db.getAllGroupsForContact(contact)) { groups.setVisible(true); groupsLabel.setVisible(true); groupstring.append(separator); groupstring.append(g.getName()); separator = ", "; } groups.setText(groupstring.toString()); detailScrollPane.setVisible(true); } }
void show(Contact contact) { if (contact != null) { if (contact.hasBirthday()) { bdayIcon.setVisible(true); } else { bdayIcon.setVisible(false); } if (contact.hasNameDay()) { namedayIcon.setVisible(true); } else { namedayIcon.setVisible(false); } if (contact.hasCelebration()) { celebrationIcon.setVisible(true); } else { celebrationIcon.setVisible(false); } photo.setContact(contact); photo.setVisible(true); name.setText(String.format("<html><h1>" + contact.getFullName() + "</h1></html>")); if (contact.getNickName() != null && !contact.getNickName().isEmpty()) { nicknameLabel.setVisible(true); nickname.setVisible(true); nickname.setText(contact.getNickName()); } else { nicknameLabel.setVisible(false); nickname.setVisible(false); } address.removeAll(); addressLabel.setVisible(false); for (Address a : contact.getAdresses()) { if (!a.getAddress().isEmpty()) { addressLabel.setVisible(true); JLabelButton l = new JLabelButton(); l.setVerticalTextPosition(JLabel.TOP); l.setHorizontalTextPosition(JLabel.CENTER); l.setAlignmentX(Component.LEFT_ALIGNMENT); l.setCursor(new Cursor(Cursor.HAND_CURSOR)); l.setText(a.getAddress()); try { l.setIcon(new ImageIcon(new URL("http://maps.google.com/maps/api/staticmap?size=128x128&sensor=false&markers=" + URLEncoder.encode(l.getText(), "utf8")))); } catch (IOException e) { System.err.println(e); } l.addActionListener(new MapListener()); address.add(l); } } emails.removeAll(); emailLabel.setVisible(false); for (Email e : contact.getEmails()) { if (!e.getEmail().isEmpty()) { emailLabel.setVisible(true); JLabelButton lb = new JLabelButton(e.getEmail()); lb.setCursor(new Cursor(Cursor.HAND_CURSOR)); lb.addActionListener(new EmailListener()); emails.add(lb); } } webs.removeAll(); websLabel.setVisible(false); for (Url u : contact.getUrls()) { if (u.getValue() != null) { websLabel.setVisible(true); JLabelButton lb = new JLabelButton(u.getValue().toString()); lb.setCursor(new Cursor(Cursor.HAND_CURSOR)); lb.addActionListener(new WebListener()); webs.add(lb); } } if (!contact.getPhoneNumbers().isEmpty()) { phoneLabel.setVisible(true); phones.setVisible(true); phones.setText("<html>" + contact.getAllPhones().replaceAll(", ", "<br>") + "</html>"); } else { phoneLabel.setVisible(false); phones.setVisible(false); } if (contact.getBirthday() != null && contact.getBirthday().getDate() != null) { birthday.setVisible(true); birthdayLabel.setVisible(true); birthday.setText(DateFormat.getDateInstance().format(contact.getBirthday().getDate())); } else { birthday.setVisible(false); birthdayLabel.setVisible(false); } if (contact.getNameDay() != null && contact.getNameDay().getDate() != null) { nameday.setVisible(true); namedayLabel.setVisible(true); nameday.setText(DateFormat.getDateInstance().format(contact.getNameDay().getDate())); } else { nameday.setVisible(false); namedayLabel.setVisible(false); } if (contact.getCelebration() != null && contact.getCelebration().getDate() != null) { celebration.setVisible(true); celebrationLabel.setVisible(true); celebration.setText(DateFormat.getDateInstance().format(contact.getCelebration().getDate())); } else { celebration.setVisible(false); celebrationLabel.setVisible(false); } if (contact.getNote() != null && !contact.getNote().isEmpty()) { note.setVisible(true); noteLabel.setVisible(true); note.setText("<html>" + contact.getNote().replaceAll("\n", "<br>") + "</html>"); } else { note.setVisible(false); noteLabel.setVisible(false); } String separator = ""; final StringBuilder groupstring = new StringBuilder(); groups.setVisible(false); groupsLabel.setVisible(false); for (Group g : db.getAllGroupsForContact(contact)) { groups.setVisible(true); groupsLabel.setVisible(true); groupstring.append(separator); groupstring.append(g.getName()); separator = ", "; } groups.setText(groupstring.toString()); detailScrollPane.setVisible(true); } }
diff --git a/BruinLyfe/src/main/java/com/bruinlyfe/bruinlyfe/MenuDisplayActivity.java b/BruinLyfe/src/main/java/com/bruinlyfe/bruinlyfe/MenuDisplayActivity.java index 649eccd..e6b3442 100644 --- a/BruinLyfe/src/main/java/com/bruinlyfe/bruinlyfe/MenuDisplayActivity.java +++ b/BruinLyfe/src/main/java/com/bruinlyfe/bruinlyfe/MenuDisplayActivity.java @@ -1,46 +1,47 @@ package com.bruinlyfe.bruinlyfe; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.widget.ListView; import java.util.ArrayList; import java.util.List; /** * Created by chris on 10/10/13. */ public class MenuDisplayActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_menu_display); Intent intent = this.getIntent(); List<String> meal = intent.getExtras().getStringArrayList("menuData"); String hallMeal = intent.getExtras().getString("hallMeal"); setTitle(hallMeal); List<Item> items = new ArrayList<Item>(); for(int i=0;i<meal.size();i++) { //Check to see if the item is a section header + meal.set(i, meal.get(i).replace("&amp;", "&")); //fix ampersand issues if(meal.get(i).toString().contains("\"title\"")) { StringBuilder sb = new StringBuilder(meal.get(i).toString()); //Remove some JSON stuff sb.delete(0, 10); sb.delete(sb.length()-2, sb.length()); items.add(new Header(getLayoutInflater(), sb.toString())); } else { items.add(new ListItem(getLayoutInflater(), meal.get(i).toString())); } } ListView lv = (ListView)findViewById(R.id.listViewMenu); TwoTextArrayAdapter adapter = new TwoTextArrayAdapter(this, items); lv.setAdapter(adapter); } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_menu_display); Intent intent = this.getIntent(); List<String> meal = intent.getExtras().getStringArrayList("menuData"); String hallMeal = intent.getExtras().getString("hallMeal"); setTitle(hallMeal); List<Item> items = new ArrayList<Item>(); for(int i=0;i<meal.size();i++) { //Check to see if the item is a section header if(meal.get(i).toString().contains("\"title\"")) { StringBuilder sb = new StringBuilder(meal.get(i).toString()); //Remove some JSON stuff sb.delete(0, 10); sb.delete(sb.length()-2, sb.length()); items.add(new Header(getLayoutInflater(), sb.toString())); } else { items.add(new ListItem(getLayoutInflater(), meal.get(i).toString())); } } ListView lv = (ListView)findViewById(R.id.listViewMenu); TwoTextArrayAdapter adapter = new TwoTextArrayAdapter(this, items); lv.setAdapter(adapter); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_menu_display); Intent intent = this.getIntent(); List<String> meal = intent.getExtras().getStringArrayList("menuData"); String hallMeal = intent.getExtras().getString("hallMeal"); setTitle(hallMeal); List<Item> items = new ArrayList<Item>(); for(int i=0;i<meal.size();i++) { //Check to see if the item is a section header meal.set(i, meal.get(i).replace("&amp;", "&")); //fix ampersand issues if(meal.get(i).toString().contains("\"title\"")) { StringBuilder sb = new StringBuilder(meal.get(i).toString()); //Remove some JSON stuff sb.delete(0, 10); sb.delete(sb.length()-2, sb.length()); items.add(new Header(getLayoutInflater(), sb.toString())); } else { items.add(new ListItem(getLayoutInflater(), meal.get(i).toString())); } } ListView lv = (ListView)findViewById(R.id.listViewMenu); TwoTextArrayAdapter adapter = new TwoTextArrayAdapter(this, items); lv.setAdapter(adapter); }
diff --git a/cucumber/src/org/jetbrains/plugins/cucumber/inspections/GherkinBrokenTableInspection.java b/cucumber/src/org/jetbrains/plugins/cucumber/inspections/GherkinBrokenTableInspection.java index aff41194df..e0079af603 100644 --- a/cucumber/src/org/jetbrains/plugins/cucumber/inspections/GherkinBrokenTableInspection.java +++ b/cucumber/src/org/jetbrains/plugins/cucumber/inspections/GherkinBrokenTableInspection.java @@ -1,64 +1,66 @@ package org.jetbrains.plugins.cucumber.inspections; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.cucumber.CucumberBundle; import org.jetbrains.plugins.cucumber.psi.*; import java.util.List; /** * User: Andrey.Vokin * Date: 10/29/13 */ public class GherkinBrokenTableInspection extends GherkinInspection { @NotNull @Override public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) { return new GherkinElementVisitor() { @Override public void visitScenarioOutline(GherkinScenarioOutline outline) { final List<GherkinExamplesBlock> examples = outline.getExamplesBlocks(); for (GherkinExamplesBlock block : examples) { - checkTable(block.getTable(), holder); + if (block.getTable() != null) { + checkTable(block.getTable(), holder); + } } } @Override public void visitStep(GherkinStep step) { final GherkinTable table = PsiTreeUtil.getChildOfType(step, GherkinTable.class); if (table != null) { checkTable(table, holder); } } }; } private static void checkTable(@NotNull final GherkinTable table, @NotNull final ProblemsHolder holder) { GherkinTableRow header = table.getHeaderRow(); for (GherkinTableRow row : table.getDataRows()) { if (header == null) { header = row; } if (row.getPsiCells().size() != header.getPsiCells().size()) { holder.registerProblem(row, CucumberBundle.message("inspection.gherkin.table.is.broken.row.error.message")); } } } @Nls @NotNull @Override public String getDisplayName() { return CucumberBundle.message("inspection.gherkin.table.is.broken.name"); } @NotNull @Override public String getShortName() { return "GherkinBrokenTableInspection"; } }
true
true
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) { return new GherkinElementVisitor() { @Override public void visitScenarioOutline(GherkinScenarioOutline outline) { final List<GherkinExamplesBlock> examples = outline.getExamplesBlocks(); for (GherkinExamplesBlock block : examples) { checkTable(block.getTable(), holder); } } @Override public void visitStep(GherkinStep step) { final GherkinTable table = PsiTreeUtil.getChildOfType(step, GherkinTable.class); if (table != null) { checkTable(table, holder); } } }; }
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) { return new GherkinElementVisitor() { @Override public void visitScenarioOutline(GherkinScenarioOutline outline) { final List<GherkinExamplesBlock> examples = outline.getExamplesBlocks(); for (GherkinExamplesBlock block : examples) { if (block.getTable() != null) { checkTable(block.getTable(), holder); } } } @Override public void visitStep(GherkinStep step) { final GherkinTable table = PsiTreeUtil.getChildOfType(step, GherkinTable.class); if (table != null) { checkTable(table, holder); } } }; }
diff --git a/bundles/org.eclipse.orion.server.hosting/src/org/eclipse/orion/internal/server/hosting/RemoteURLProxyServlet.java b/bundles/org.eclipse.orion.server.hosting/src/org/eclipse/orion/internal/server/hosting/RemoteURLProxyServlet.java index 44283693..a01ed992 100644 --- a/bundles/org.eclipse.orion.server.hosting/src/org/eclipse/orion/internal/server/hosting/RemoteURLProxyServlet.java +++ b/bundles/org.eclipse.orion.server.hosting/src/org/eclipse/orion/internal/server/hosting/RemoteURLProxyServlet.java @@ -1,225 +1,227 @@ /******************************************************************************* * Copyright (c) 2011 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.orion.internal.server.hosting; import java.io.IOException; import java.io.InputStream; import java.net.*; import java.util.Enumeration; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.http.HttpURI; import org.eclipse.jetty.servlets.ProxyServlet; import org.eclipse.jetty.util.IO; /** * Override the Jetty ProxyServlet implementation. Do this to tolerate some unusual * HTTP practices that Ajax libraries are using (see NOTE: below.) */ public class RemoteURLProxyServlet extends ProxyServlet { { // Bug 346139 _DontProxyHeaders.add("host"); } private HttpURI url; private final boolean failEarlyOn404; public RemoteURLProxyServlet(URL url, boolean failEarlyOn404) { try { this.url = new HttpURI(url.toURI()); this.failEarlyOn404 = failEarlyOn404; } catch (URISyntaxException e) { //should be well formed throw new RuntimeException(e); } } @Override protected HttpURI proxyHttpURI(final String scheme, final String serverName, int serverPort, final String uri) throws MalformedURLException { return url; } /* (non-Javadoc) * @see javax.servlet.Servlet#service(javax.servlet.ServletRequest, javax.servlet.ServletResponse) */ public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; if ("CONNECT".equalsIgnoreCase(request.getMethod())) { handleConnect(request, response); } else { String uri = request.getRequestURI(); if (request.getQueryString() != null) uri += "?" + request.getQueryString(); HttpURI url = proxyHttpURI(request.getScheme(), request.getServerName(), request.getServerPort(), uri); URL rawURL = new URL(url.toString()); URLConnection connection = rawURL.openConnection(); connection.setAllowUserInteraction(false); // Set method HttpURLConnection http = null; if (connection instanceof HttpURLConnection) { http = (HttpURLConnection) connection; http.setRequestMethod(request.getMethod()); http.setInstanceFollowRedirects(false); // NOTE } // check connection header String connectionHdr = request.getHeader("Connection"); if (connectionHdr != null) { connectionHdr = connectionHdr.toLowerCase(); if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close")) connectionHdr = null; } // copy headers boolean xForwardedFor = false; boolean hasContent = false; Enumeration enm = request.getHeaderNames(); while (enm.hasMoreElements()) { // TODO could be better than this! String hdr = (String) enm.nextElement(); String lhdr = hdr.toLowerCase(); if ("host".equals(lhdr)) { // Bug 346139: set Host based on the destination URL being proxied int port = url.getPort(); String realHost; if (port == -1 || port == rawURL.getDefaultPort()) realHost = url.getHost(); else realHost = url.getHost() + ":" + port; connection.addRequestProperty("Host", realHost); } if (_DontProxyHeaders.contains(lhdr)) continue; if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0) continue; if ("content-type".equals(lhdr)) hasContent = true; Enumeration vals = request.getHeaders(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { connection.addRequestProperty(hdr, val); xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr); } } } // Proxy headers connection.setRequestProperty("Via", "1.1 (jetty)"); if (!xForwardedFor) connection.addRequestProperty("X-Forwarded-For", request.getRemoteAddr()); // Bug 346139: prevent an infinite proxy loop by decrementing the Max-Forwards header Enumeration maxForwardsHeaders = request.getHeaders("Max-Forwards"); String maxForwardsHeader = null; while (maxForwardsHeaders.hasMoreElements()) { maxForwardsHeader = (String) maxForwardsHeaders.nextElement(); } int maxForwards = 5; try { maxForwards = Math.max(0, Integer.parseInt(maxForwardsHeader)); } catch (NumberFormatException e) { // Use default } if (maxForwards-- < 1) { response.sendError(HttpURLConnection.HTTP_BAD_GATEWAY, "Max-Forwards exceeded"); return; } connection.addRequestProperty("Max-Forwards", "" + maxForwards); // a little bit of cache control String cache_control = request.getHeader("Cache-Control"); if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0)) connection.setUseCaches(false); // customize Connection try { connection.setDoInput(true); // do input thang! InputStream in = request.getInputStream(); if (hasContent && isOutputSupported(request)) { connection.setDoOutput(true); IO.copy(in, connection.getOutputStream()); } // Connect connection.connect(); } catch (Exception e) { - _context.log("proxy", e); + if (!(e instanceof UnknownHostException)) + _context.log("proxy", e); } InputStream proxy_in = null; // handler status codes etc. int code = 500; if (http != null) { proxy_in = http.getErrorStream(); code = http.getResponseCode(); if (failEarlyOn404 && code == 404) { // make sure this is thrown only in the "fail early on 404" case throw new NotFoundException(); } response.setStatus(code, http.getResponseMessage()); } if (proxy_in == null) { try { proxy_in = connection.getInputStream(); } catch (Exception e) { - _context.log("stream", e); + if (!(e instanceof IOException)) + _context.log("stream", e); proxy_in = http.getErrorStream(); } } // clear response defaults. response.setHeader("Date", null); response.setHeader("Server", null); // set response headers int h = 0; String hdr = connection.getHeaderFieldKey(h); String val = connection.getHeaderField(h); while (hdr != null || val != null) { String lhdr = hdr != null ? hdr.toLowerCase() : null; if (hdr != null && val != null && !_DontProxyHeaders.contains(lhdr)) response.addHeader(hdr, val); h++; hdr = connection.getHeaderFieldKey(h); val = connection.getHeaderField(h); } response.addHeader("Via", "1.1 (jetty)"); // Handle if (proxy_in != null) IO.copy(proxy_in, response.getOutputStream()); } } private static boolean isOutputSupported(HttpServletRequest req) { String method = req.getMethod(); return "POST".equals(method) || "PUT".equals(method); } }
false
true
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; if ("CONNECT".equalsIgnoreCase(request.getMethod())) { handleConnect(request, response); } else { String uri = request.getRequestURI(); if (request.getQueryString() != null) uri += "?" + request.getQueryString(); HttpURI url = proxyHttpURI(request.getScheme(), request.getServerName(), request.getServerPort(), uri); URL rawURL = new URL(url.toString()); URLConnection connection = rawURL.openConnection(); connection.setAllowUserInteraction(false); // Set method HttpURLConnection http = null; if (connection instanceof HttpURLConnection) { http = (HttpURLConnection) connection; http.setRequestMethod(request.getMethod()); http.setInstanceFollowRedirects(false); // NOTE } // check connection header String connectionHdr = request.getHeader("Connection"); if (connectionHdr != null) { connectionHdr = connectionHdr.toLowerCase(); if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close")) connectionHdr = null; } // copy headers boolean xForwardedFor = false; boolean hasContent = false; Enumeration enm = request.getHeaderNames(); while (enm.hasMoreElements()) { // TODO could be better than this! String hdr = (String) enm.nextElement(); String lhdr = hdr.toLowerCase(); if ("host".equals(lhdr)) { // Bug 346139: set Host based on the destination URL being proxied int port = url.getPort(); String realHost; if (port == -1 || port == rawURL.getDefaultPort()) realHost = url.getHost(); else realHost = url.getHost() + ":" + port; connection.addRequestProperty("Host", realHost); } if (_DontProxyHeaders.contains(lhdr)) continue; if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0) continue; if ("content-type".equals(lhdr)) hasContent = true; Enumeration vals = request.getHeaders(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { connection.addRequestProperty(hdr, val); xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr); } } } // Proxy headers connection.setRequestProperty("Via", "1.1 (jetty)"); if (!xForwardedFor) connection.addRequestProperty("X-Forwarded-For", request.getRemoteAddr()); // Bug 346139: prevent an infinite proxy loop by decrementing the Max-Forwards header Enumeration maxForwardsHeaders = request.getHeaders("Max-Forwards"); String maxForwardsHeader = null; while (maxForwardsHeaders.hasMoreElements()) { maxForwardsHeader = (String) maxForwardsHeaders.nextElement(); } int maxForwards = 5; try { maxForwards = Math.max(0, Integer.parseInt(maxForwardsHeader)); } catch (NumberFormatException e) { // Use default } if (maxForwards-- < 1) { response.sendError(HttpURLConnection.HTTP_BAD_GATEWAY, "Max-Forwards exceeded"); return; } connection.addRequestProperty("Max-Forwards", "" + maxForwards); // a little bit of cache control String cache_control = request.getHeader("Cache-Control"); if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0)) connection.setUseCaches(false); // customize Connection try { connection.setDoInput(true); // do input thang! InputStream in = request.getInputStream(); if (hasContent && isOutputSupported(request)) { connection.setDoOutput(true); IO.copy(in, connection.getOutputStream()); } // Connect connection.connect(); } catch (Exception e) { _context.log("proxy", e); } InputStream proxy_in = null; // handler status codes etc. int code = 500; if (http != null) { proxy_in = http.getErrorStream(); code = http.getResponseCode(); if (failEarlyOn404 && code == 404) { // make sure this is thrown only in the "fail early on 404" case throw new NotFoundException(); } response.setStatus(code, http.getResponseMessage()); } if (proxy_in == null) { try { proxy_in = connection.getInputStream(); } catch (Exception e) { _context.log("stream", e); proxy_in = http.getErrorStream(); } } // clear response defaults. response.setHeader("Date", null); response.setHeader("Server", null); // set response headers int h = 0; String hdr = connection.getHeaderFieldKey(h); String val = connection.getHeaderField(h); while (hdr != null || val != null) { String lhdr = hdr != null ? hdr.toLowerCase() : null; if (hdr != null && val != null && !_DontProxyHeaders.contains(lhdr)) response.addHeader(hdr, val); h++; hdr = connection.getHeaderFieldKey(h); val = connection.getHeaderField(h); } response.addHeader("Via", "1.1 (jetty)"); // Handle if (proxy_in != null) IO.copy(proxy_in, response.getOutputStream()); } }
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; if ("CONNECT".equalsIgnoreCase(request.getMethod())) { handleConnect(request, response); } else { String uri = request.getRequestURI(); if (request.getQueryString() != null) uri += "?" + request.getQueryString(); HttpURI url = proxyHttpURI(request.getScheme(), request.getServerName(), request.getServerPort(), uri); URL rawURL = new URL(url.toString()); URLConnection connection = rawURL.openConnection(); connection.setAllowUserInteraction(false); // Set method HttpURLConnection http = null; if (connection instanceof HttpURLConnection) { http = (HttpURLConnection) connection; http.setRequestMethod(request.getMethod()); http.setInstanceFollowRedirects(false); // NOTE } // check connection header String connectionHdr = request.getHeader("Connection"); if (connectionHdr != null) { connectionHdr = connectionHdr.toLowerCase(); if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close")) connectionHdr = null; } // copy headers boolean xForwardedFor = false; boolean hasContent = false; Enumeration enm = request.getHeaderNames(); while (enm.hasMoreElements()) { // TODO could be better than this! String hdr = (String) enm.nextElement(); String lhdr = hdr.toLowerCase(); if ("host".equals(lhdr)) { // Bug 346139: set Host based on the destination URL being proxied int port = url.getPort(); String realHost; if (port == -1 || port == rawURL.getDefaultPort()) realHost = url.getHost(); else realHost = url.getHost() + ":" + port; connection.addRequestProperty("Host", realHost); } if (_DontProxyHeaders.contains(lhdr)) continue; if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0) continue; if ("content-type".equals(lhdr)) hasContent = true; Enumeration vals = request.getHeaders(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { connection.addRequestProperty(hdr, val); xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr); } } } // Proxy headers connection.setRequestProperty("Via", "1.1 (jetty)"); if (!xForwardedFor) connection.addRequestProperty("X-Forwarded-For", request.getRemoteAddr()); // Bug 346139: prevent an infinite proxy loop by decrementing the Max-Forwards header Enumeration maxForwardsHeaders = request.getHeaders("Max-Forwards"); String maxForwardsHeader = null; while (maxForwardsHeaders.hasMoreElements()) { maxForwardsHeader = (String) maxForwardsHeaders.nextElement(); } int maxForwards = 5; try { maxForwards = Math.max(0, Integer.parseInt(maxForwardsHeader)); } catch (NumberFormatException e) { // Use default } if (maxForwards-- < 1) { response.sendError(HttpURLConnection.HTTP_BAD_GATEWAY, "Max-Forwards exceeded"); return; } connection.addRequestProperty("Max-Forwards", "" + maxForwards); // a little bit of cache control String cache_control = request.getHeader("Cache-Control"); if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0)) connection.setUseCaches(false); // customize Connection try { connection.setDoInput(true); // do input thang! InputStream in = request.getInputStream(); if (hasContent && isOutputSupported(request)) { connection.setDoOutput(true); IO.copy(in, connection.getOutputStream()); } // Connect connection.connect(); } catch (Exception e) { if (!(e instanceof UnknownHostException)) _context.log("proxy", e); } InputStream proxy_in = null; // handler status codes etc. int code = 500; if (http != null) { proxy_in = http.getErrorStream(); code = http.getResponseCode(); if (failEarlyOn404 && code == 404) { // make sure this is thrown only in the "fail early on 404" case throw new NotFoundException(); } response.setStatus(code, http.getResponseMessage()); } if (proxy_in == null) { try { proxy_in = connection.getInputStream(); } catch (Exception e) { if (!(e instanceof IOException)) _context.log("stream", e); proxy_in = http.getErrorStream(); } } // clear response defaults. response.setHeader("Date", null); response.setHeader("Server", null); // set response headers int h = 0; String hdr = connection.getHeaderFieldKey(h); String val = connection.getHeaderField(h); while (hdr != null || val != null) { String lhdr = hdr != null ? hdr.toLowerCase() : null; if (hdr != null && val != null && !_DontProxyHeaders.contains(lhdr)) response.addHeader(hdr, val); h++; hdr = connection.getHeaderFieldKey(h); val = connection.getHeaderField(h); } response.addHeader("Via", "1.1 (jetty)"); // Handle if (proxy_in != null) IO.copy(proxy_in, response.getOutputStream()); } }
diff --git a/src/edu/vu/vuse/cs278/g3/gui/MainWindow.java b/src/edu/vu/vuse/cs278/g3/gui/MainWindow.java index 5b8c56f..d00a592 100755 --- a/src/edu/vu/vuse/cs278/g3/gui/MainWindow.java +++ b/src/edu/vu/vuse/cs278/g3/gui/MainWindow.java @@ -1,390 +1,390 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * MainWindow.java * * Created on Nov 29, 2011, 1:13:19 AM */ package edu.vu.vuse.cs278.g3.gui; import org.nlogo.lite.InterfaceComponent; /** * * @author Amber Maria */ public class MainWindow extends javax.swing.JFrame { /** Creates new form MainWindow */ public MainWindow() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { addObject = new javax.swing.JButton(); editObject = new javax.swing.JButton(); runSimulation = new javax.swing.JButton(); stopSimulation = new javax.swing.JButton(); pauseSimulation = new javax.swing.JButton(); busAcceleration = new javax.swing.JSlider(); busDeceleration = new javax.swing.JSlider(); busAccelerationLabel = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); sillyNetLogo = new javax.swing.JInternalFrame(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); busAccelerationLabelValue = new javax.swing.JLabel(); busDecelerationLabelValue = new javax.swing.JLabel(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenu3 = new javax.swing.JMenu(); jMenu4 = new javax.swing.JMenu(); jMenu5 = new javax.swing.JMenu(); jMenu6 = new javax.swing.JMenu(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); addObject.setText("Add Object"); addObject.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addObjectActionPerformed(evt); } }); editObject.setText("Edit Object"); editObject.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { editObjectActionPerformed(evt); } }); runSimulation.setText("Run Simulation"); runSimulation.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { runSimulationActionPerformed(evt); } }); stopSimulation.setText("Stop Simulation"); pauseSimulation.setText("Pause Simulation"); pauseSimulation.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pauseSimulationActionPerformed(evt); } }); busAcceleration.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { busAccelerationStateChanged(evt); } }); busDeceleration.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { busDecelerationStateChanged(evt); } }); busAccelerationLabel.setText("Bus Acceleration"); jLabel2.setText("Bus Deceleration"); sillyNetLogo.setVisible(true); sillyNetLogo.addInternalFrameListener(new javax.swing.event.InternalFrameListener() { public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) { //sillyNetLogoInternalFrameActivated(evt); } public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) { } }); javax.swing.GroupLayout sillyNetLogoLayout = new javax.swing.GroupLayout(sillyNetLogo.getContentPane()); sillyNetLogo.getContentPane().setLayout(sillyNetLogoLayout); sillyNetLogoLayout.setHorizontalGroup( sillyNetLogoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 316, Short.MAX_VALUE) ); sillyNetLogoLayout.setVerticalGroup( sillyNetLogoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 360, Short.MAX_VALUE) ); new Thread() { public void run() { try { //final javax.swing.JFrame frame = new javax.swing.JFrame(); - final InterfaceComponent comp = new InterfaceComponent(this); + final InterfaceComponent comp = new InterfaceComponent(MainWindow.this); java.awt.EventQueue.invokeAndWait //breaks here ( new Runnable() { public void run() { add(comp); try { comp.open("./CS278.nlogo"); } catch(Exception ex) { ex.printStackTrace(); } } } ) ; } catch(Exception ex) { ex.printStackTrace(); } } }.start(); jLabel3.setText("0"); jLabel4.setText("100"); jLabel5.setText("0"); jLabel6.setText("100"); busAccelerationLabelValue.setText("50"); busDecelerationLabelValue.setText("50"); jMenu1.setText("File"); jMenu1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenu1ActionPerformed(evt); } }); jMenu3.setText("New"); jMenu1.add(jMenu3); jMenu4.setText("Open"); jMenu1.add(jMenu4); jMenu5.setText("Save"); jMenu1.add(jMenu5); jMenu6.setText("Exit"); jMenu1.add(jMenu6); jMenuBar1.add(jMenu1); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(16, 16, 16) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(busAcceleration, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel4)) .addGroup(layout.createSequentialGroup() .addComponent(busDeceleration, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel6)))) .addComponent(stopSimulation, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(runSimulation, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(editObject, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(addObject, javax.swing.GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE) .addComponent(pauseSimulation, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(layout.createSequentialGroup() .addGap(53, 53, 53) .addComponent(busAccelerationLabel) .addGap(18, 18, 18) .addComponent(busAccelerationLabelValue, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(52, 52, 52) .addComponent(jLabel2) .addGap(18, 18, 18) .addComponent(busDecelerationLabelValue, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addComponent(sillyNetLogo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(63, 63, 63) .addComponent(addObject) .addGap(18, 18, 18) .addComponent(editObject) .addGap(18, 18, 18) .addComponent(runSimulation) .addGap(18, 18, 18) .addComponent(stopSimulation) .addGap(18, 18, 18) .addComponent(pauseSimulation) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(busAcceleration, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(busAccelerationLabel) .addComponent(busAccelerationLabelValue)) .addGap(13, 13, 13) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel6) .addComponent(busDeceleration, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(busDecelerationLabelValue))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(19, 19, 19) .addComponent(sillyNetLogo))) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void addObjectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addObjectActionPerformed // TODO add your handling code here: new ObjectUI().setVisible(true); }//GEN-LAST:event_addObjectActionPerformed private void editObjectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editObjectActionPerformed // TODO add your handling code here: new EditObjectUI().setVisible(true); }//GEN-LAST:event_editObjectActionPerformed private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu1ActionPerformed // TODO add your handling code here: System.exit(0); }//GEN-LAST:event_jMenu1ActionPerformed private void jInternalFrame1InternalFrameActivated(javax.swing.event.InternalFrameEvent evt) { //GEN-FIRST:event_jInternalFrame1InternalFrameActivated } //GEN-LAST:event_jInternalFrame1InternalFrameActivated private void runSimulationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_runSimulationActionPerformed // TODO add your handling code here: int busAccel = busAcceleration.getValue(); int busDecel = busDeceleration.getValue(); }//GEN-LAST:event_runSimulationActionPerformed private void pauseSimulationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pauseSimulationActionPerformed // TODO add your handling code here: }//GEN-LAST:event_pauseSimulationActionPerformed private void busAccelerationStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_busAccelerationStateChanged // TODO add your handling code here: int tmp = busAcceleration.getValue(); String tmpBusAccel = Integer.toString(tmp); busAccelerationLabelValue.setText(tmpBusAccel); }//GEN-LAST:event_busAccelerationStateChanged private void busDecelerationStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_busDecelerationStateChanged // TODO add your handling code here: int tmp = busDeceleration.getValue(); String tmpBusDecel = Integer.toString(tmp); busDecelerationLabelValue.setText(tmpBusDecel); busDecelerationLabelValue.setEnabled(true); }//GEN-LAST:event_busDecelerationStateChanged /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MainWindow().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton addObject; private javax.swing.JSlider busAcceleration; private javax.swing.JLabel busAccelerationLabel; private javax.swing.JLabel busAccelerationLabelValue; private javax.swing.JSlider busDeceleration; private javax.swing.JLabel busDecelerationLabelValue; private javax.swing.JButton editObject; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu3; private javax.swing.JMenu jMenu4; private javax.swing.JMenu jMenu5; private javax.swing.JMenu jMenu6; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JButton pauseSimulation; private javax.swing.JButton runSimulation; private javax.swing.JInternalFrame sillyNetLogo; private javax.swing.JButton stopSimulation; // End of variables declaration//GEN-END:variables }
true
true
private void initComponents() { addObject = new javax.swing.JButton(); editObject = new javax.swing.JButton(); runSimulation = new javax.swing.JButton(); stopSimulation = new javax.swing.JButton(); pauseSimulation = new javax.swing.JButton(); busAcceleration = new javax.swing.JSlider(); busDeceleration = new javax.swing.JSlider(); busAccelerationLabel = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); sillyNetLogo = new javax.swing.JInternalFrame(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); busAccelerationLabelValue = new javax.swing.JLabel(); busDecelerationLabelValue = new javax.swing.JLabel(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenu3 = new javax.swing.JMenu(); jMenu4 = new javax.swing.JMenu(); jMenu5 = new javax.swing.JMenu(); jMenu6 = new javax.swing.JMenu(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); addObject.setText("Add Object"); addObject.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addObjectActionPerformed(evt); } }); editObject.setText("Edit Object"); editObject.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { editObjectActionPerformed(evt); } }); runSimulation.setText("Run Simulation"); runSimulation.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { runSimulationActionPerformed(evt); } }); stopSimulation.setText("Stop Simulation"); pauseSimulation.setText("Pause Simulation"); pauseSimulation.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pauseSimulationActionPerformed(evt); } }); busAcceleration.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { busAccelerationStateChanged(evt); } }); busDeceleration.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { busDecelerationStateChanged(evt); } }); busAccelerationLabel.setText("Bus Acceleration"); jLabel2.setText("Bus Deceleration"); sillyNetLogo.setVisible(true); sillyNetLogo.addInternalFrameListener(new javax.swing.event.InternalFrameListener() { public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) { //sillyNetLogoInternalFrameActivated(evt); } public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) { } }); javax.swing.GroupLayout sillyNetLogoLayout = new javax.swing.GroupLayout(sillyNetLogo.getContentPane()); sillyNetLogo.getContentPane().setLayout(sillyNetLogoLayout); sillyNetLogoLayout.setHorizontalGroup( sillyNetLogoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 316, Short.MAX_VALUE) ); sillyNetLogoLayout.setVerticalGroup( sillyNetLogoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 360, Short.MAX_VALUE) ); new Thread() { public void run() { try { //final javax.swing.JFrame frame = new javax.swing.JFrame(); final InterfaceComponent comp = new InterfaceComponent(this); java.awt.EventQueue.invokeAndWait //breaks here ( new Runnable() { public void run() { add(comp); try { comp.open("./CS278.nlogo"); } catch(Exception ex) { ex.printStackTrace(); } } } ) ; } catch(Exception ex) { ex.printStackTrace(); } } }.start(); jLabel3.setText("0"); jLabel4.setText("100"); jLabel5.setText("0"); jLabel6.setText("100"); busAccelerationLabelValue.setText("50"); busDecelerationLabelValue.setText("50"); jMenu1.setText("File"); jMenu1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenu1ActionPerformed(evt); } }); jMenu3.setText("New"); jMenu1.add(jMenu3); jMenu4.setText("Open"); jMenu1.add(jMenu4); jMenu5.setText("Save"); jMenu1.add(jMenu5); jMenu6.setText("Exit"); jMenu1.add(jMenu6); jMenuBar1.add(jMenu1); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(16, 16, 16) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(busAcceleration, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel4)) .addGroup(layout.createSequentialGroup() .addComponent(busDeceleration, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel6)))) .addComponent(stopSimulation, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(runSimulation, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(editObject, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(addObject, javax.swing.GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE) .addComponent(pauseSimulation, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(layout.createSequentialGroup() .addGap(53, 53, 53) .addComponent(busAccelerationLabel) .addGap(18, 18, 18) .addComponent(busAccelerationLabelValue, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(52, 52, 52) .addComponent(jLabel2) .addGap(18, 18, 18) .addComponent(busDecelerationLabelValue, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addComponent(sillyNetLogo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(63, 63, 63) .addComponent(addObject) .addGap(18, 18, 18) .addComponent(editObject) .addGap(18, 18, 18) .addComponent(runSimulation) .addGap(18, 18, 18) .addComponent(stopSimulation) .addGap(18, 18, 18) .addComponent(pauseSimulation) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(busAcceleration, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(busAccelerationLabel) .addComponent(busAccelerationLabelValue)) .addGap(13, 13, 13) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel6) .addComponent(busDeceleration, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(busDecelerationLabelValue))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(19, 19, 19) .addComponent(sillyNetLogo))) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { addObject = new javax.swing.JButton(); editObject = new javax.swing.JButton(); runSimulation = new javax.swing.JButton(); stopSimulation = new javax.swing.JButton(); pauseSimulation = new javax.swing.JButton(); busAcceleration = new javax.swing.JSlider(); busDeceleration = new javax.swing.JSlider(); busAccelerationLabel = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); sillyNetLogo = new javax.swing.JInternalFrame(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); busAccelerationLabelValue = new javax.swing.JLabel(); busDecelerationLabelValue = new javax.swing.JLabel(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenu3 = new javax.swing.JMenu(); jMenu4 = new javax.swing.JMenu(); jMenu5 = new javax.swing.JMenu(); jMenu6 = new javax.swing.JMenu(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); addObject.setText("Add Object"); addObject.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addObjectActionPerformed(evt); } }); editObject.setText("Edit Object"); editObject.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { editObjectActionPerformed(evt); } }); runSimulation.setText("Run Simulation"); runSimulation.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { runSimulationActionPerformed(evt); } }); stopSimulation.setText("Stop Simulation"); pauseSimulation.setText("Pause Simulation"); pauseSimulation.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pauseSimulationActionPerformed(evt); } }); busAcceleration.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { busAccelerationStateChanged(evt); } }); busDeceleration.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { busDecelerationStateChanged(evt); } }); busAccelerationLabel.setText("Bus Acceleration"); jLabel2.setText("Bus Deceleration"); sillyNetLogo.setVisible(true); sillyNetLogo.addInternalFrameListener(new javax.swing.event.InternalFrameListener() { public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) { //sillyNetLogoInternalFrameActivated(evt); } public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) { } public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) { } }); javax.swing.GroupLayout sillyNetLogoLayout = new javax.swing.GroupLayout(sillyNetLogo.getContentPane()); sillyNetLogo.getContentPane().setLayout(sillyNetLogoLayout); sillyNetLogoLayout.setHorizontalGroup( sillyNetLogoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 316, Short.MAX_VALUE) ); sillyNetLogoLayout.setVerticalGroup( sillyNetLogoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 360, Short.MAX_VALUE) ); new Thread() { public void run() { try { //final javax.swing.JFrame frame = new javax.swing.JFrame(); final InterfaceComponent comp = new InterfaceComponent(MainWindow.this); java.awt.EventQueue.invokeAndWait //breaks here ( new Runnable() { public void run() { add(comp); try { comp.open("./CS278.nlogo"); } catch(Exception ex) { ex.printStackTrace(); } } } ) ; } catch(Exception ex) { ex.printStackTrace(); } } }.start(); jLabel3.setText("0"); jLabel4.setText("100"); jLabel5.setText("0"); jLabel6.setText("100"); busAccelerationLabelValue.setText("50"); busDecelerationLabelValue.setText("50"); jMenu1.setText("File"); jMenu1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenu1ActionPerformed(evt); } }); jMenu3.setText("New"); jMenu1.add(jMenu3); jMenu4.setText("Open"); jMenu1.add(jMenu4); jMenu5.setText("Save"); jMenu1.add(jMenu5); jMenu6.setText("Exit"); jMenu1.add(jMenu6); jMenuBar1.add(jMenu1); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(16, 16, 16) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(busAcceleration, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel4)) .addGroup(layout.createSequentialGroup() .addComponent(busDeceleration, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel6)))) .addComponent(stopSimulation, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(runSimulation, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(editObject, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(addObject, javax.swing.GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE) .addComponent(pauseSimulation, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(layout.createSequentialGroup() .addGap(53, 53, 53) .addComponent(busAccelerationLabel) .addGap(18, 18, 18) .addComponent(busAccelerationLabelValue, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(52, 52, 52) .addComponent(jLabel2) .addGap(18, 18, 18) .addComponent(busDecelerationLabelValue, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addComponent(sillyNetLogo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(63, 63, 63) .addComponent(addObject) .addGap(18, 18, 18) .addComponent(editObject) .addGap(18, 18, 18) .addComponent(runSimulation) .addGap(18, 18, 18) .addComponent(stopSimulation) .addGap(18, 18, 18) .addComponent(pauseSimulation) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(busAcceleration, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(busAccelerationLabel) .addComponent(busAccelerationLabelValue)) .addGap(13, 13, 13) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel6) .addComponent(busDeceleration, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(busDecelerationLabelValue))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(19, 19, 19) .addComponent(sillyNetLogo))) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents
diff --git a/deployables/bindingcomponents/servicemix-mail/src/main/java/org/apache/servicemix/mail/MailPollerEndpoint.java b/deployables/bindingcomponents/servicemix-mail/src/main/java/org/apache/servicemix/mail/MailPollerEndpoint.java index a5fe7641e..9decd9d55 100644 --- a/deployables/bindingcomponents/servicemix-mail/src/main/java/org/apache/servicemix/mail/MailPollerEndpoint.java +++ b/deployables/bindingcomponents/servicemix-mail/src/main/java/org/apache/servicemix/mail/MailPollerEndpoint.java @@ -1,310 +1,310 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.servicemix.mail; import java.util.Properties; import javax.jbi.JBIException; import javax.jbi.messaging.ExchangeStatus; import javax.jbi.messaging.InOnly; import javax.jbi.messaging.MessageExchange; import javax.jbi.messaging.NormalizedMessage; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.Message; import javax.mail.Session; import javax.mail.Store; import javax.mail.internet.MimeMessage; import javax.mail.internet.ParseException; import javax.mail.search.FlagTerm; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.servicemix.common.endpoints.PollingEndpoint; import org.apache.servicemix.mail.marshaler.AbstractMailMarshaler; import org.apache.servicemix.mail.marshaler.DefaultMailMarshaler; import org.apache.servicemix.mail.utils.MailConnectionConfiguration; import org.apache.servicemix.mail.utils.MailUtils; /** * This is the polling endpoint for the mail component. * * @org.apache.xbean.XBean element="poller" * @author lhein */ public class MailPollerEndpoint extends PollingEndpoint implements MailEndpointType { private static final transient Log LOG = LogFactory.getLog(MailPollerEndpoint.class); private AbstractMailMarshaler marshaler = new DefaultMailMarshaler(); private String customTrustManagers; private MailConnectionConfiguration config; private String connection; private int maxFetchSize = 5; private boolean processOnlyUnseenMessages; private boolean deleteProcessedMessages; private boolean debugMode; /** * default constructor */ public MailPollerEndpoint() { this.processOnlyUnseenMessages = true; this.deleteProcessedMessages = false; this.debugMode = false; } /* * (non-Javadoc) * * @see org.apache.servicemix.common.endpoints.ConsumerEndpoint#getLocationURI() */ @Override public String getLocationURI() { // return a URI that unique identify this endpoint return getService() + "#" + getEndpoint(); } /* * (non-Javadoc) * * @see org.apache.servicemix.common.ExchangeProcessor#process(javax.jbi.messaging.MessageExchange) */ public void process(MessageExchange arg0) throws Exception { // Do nothing. In our case, this method should never be called // as we only send synchronous InOnly exchange } /* * (non-Javadoc) * * @see org.apache.servicemix.components.util.PollingComponentSupport#poll() */ public void poll() throws Exception { LOG.debug("Polling mailfolder " + config.getFolderName() + " at host " + config.getHost() + "..."); if (maxFetchSize == 0) { LOG.debug("The configuration is set to poll no new messages at all...skipping."); return; } Store store = null; Folder folder = null; Session session = null; try { Properties props = MailUtils.getPropertiesForProtocol(this.config, this.customTrustManagers); props.put("mail.debug", isDebugMode() ? "true" : "false"); // Get session session = Session.getInstance(props, config.getAuthenticator()); // debug the session session.setDebug(this.debugMode); store = session.getStore(config.getProtocol()); store.connect(config.getHost(), config.getUsername(), config.getPassword()); folder = store.getFolder(config.getFolderName()); if (folder == null || !folder.exists()) { throw new Exception("Folder not found or invalid: " + config.getFolderName()); } folder.open(Folder.READ_WRITE); Message[] messages = null; if (isProcessOnlyUnseenMessages()) { messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); } else { messages = folder.getMessages(); } int fetchSize = getMaxFetchSize() == -1 ? messages.length : Math.min(getMaxFetchSize(), messages.length); for (int cnt = 0; cnt < fetchSize; cnt++) { // get the message MimeMessage mailMsg = (MimeMessage)messages[cnt]; // create a inOnly exchange InOnly io = getExchangeFactory().createInOnlyExchange(); // configure the exchange target configureExchangeTarget(io); // create the in message NormalizedMessage normalizedMessage = io.createMessage(); // now let the marshaller convert the mail into a normalized // message to send to jbi bus marshaler.convertMailToJBI(io, normalizedMessage, mailMsg); // then put the in message into the inOnly exchange io.setInMessage(normalizedMessage); // and use sendSync to deliver it sendSync(io); // now check if delivery succeeded or went wrong if (io.getStatus() == ExchangeStatus.ERROR) { Exception e = io.getError(); if (e == null) { - e = new JBIException("Unexpected error: " + e.getMessage()); + e = new JBIException("Unexpected error occured..."); } throw e; } else { // then mark the mail as processed (only if no errors) if (deleteProcessedMessages) { // processed messages have to be marked as deleted mailMsg.setFlag(Flags.Flag.DELETED, true); } else { // processed messages have to be marked as seen mailMsg.setFlag(Flags.Flag.SEEN, true); } } } } finally { // finally clean up and close the folder and store try { if (folder != null) { folder.close(true); } if (store != null) { store.close(); } } catch (Exception ignored) { logger.debug(ignored); } } } /** * @return the deleteProcessedMessages */ public boolean isDeleteProcessedMessages() { return this.deleteProcessedMessages; } /** * @param deleteProcessedMessages * the deleteProcessedMessages to set */ public void setDeleteProcessedMessages(boolean deleteProcessedMessages) { this.deleteProcessedMessages = deleteProcessedMessages; } /** * @return the marshaler */ public AbstractMailMarshaler getMarshaler() { return this.marshaler; } /** * @param marshaler * the marshaler to set */ public void setMarshaler(AbstractMailMarshaler marshaler) { this.marshaler = marshaler; } /** * @return the maxFetchSize */ public int getMaxFetchSize() { return this.maxFetchSize; } /** * @param maxFetchSize * the maxFetchSize to set */ public void setMaxFetchSize(int maxFetchSize) { this.maxFetchSize = maxFetchSize; } /** * @return the processOnlyUnseenMessages */ public boolean isProcessOnlyUnseenMessages() { return this.processOnlyUnseenMessages; } /** * @param processOnlyUnseenMessages * the processOnlyUnseenMessages to set */ public void setProcessOnlyUnseenMessages(boolean processOnlyUnseenMessages) { this.processOnlyUnseenMessages = processOnlyUnseenMessages; } /** * returns the connection uri used for this poller endpoint * * @return Returns the connection. */ public String getConnection() { return this.connection; } /** * sets the connection uri * * @param connection * The connection to set. */ public void setConnection(String connection) { this.connection = connection; try { this.config = MailUtils.configure(this.connection); } catch (ParseException ex) { LOG.error("The configured connection uri is invalid", ex); } } /** * @return the debugMode */ public boolean isDebugMode() { return this.debugMode; } /** * @param debugMode * the debugMode to set */ public void setDebugMode(boolean debugMode) { this.debugMode = debugMode; } /** * @return the customTrustManagers */ public String getCustomTrustManagers() { return this.customTrustManagers; } /** * @param customTrustManagers * the customTrustManagers to set */ public void setCustomTrustManagers(String customTrustManagers) { this.customTrustManagers = customTrustManagers; } }
true
true
public void poll() throws Exception { LOG.debug("Polling mailfolder " + config.getFolderName() + " at host " + config.getHost() + "..."); if (maxFetchSize == 0) { LOG.debug("The configuration is set to poll no new messages at all...skipping."); return; } Store store = null; Folder folder = null; Session session = null; try { Properties props = MailUtils.getPropertiesForProtocol(this.config, this.customTrustManagers); props.put("mail.debug", isDebugMode() ? "true" : "false"); // Get session session = Session.getInstance(props, config.getAuthenticator()); // debug the session session.setDebug(this.debugMode); store = session.getStore(config.getProtocol()); store.connect(config.getHost(), config.getUsername(), config.getPassword()); folder = store.getFolder(config.getFolderName()); if (folder == null || !folder.exists()) { throw new Exception("Folder not found or invalid: " + config.getFolderName()); } folder.open(Folder.READ_WRITE); Message[] messages = null; if (isProcessOnlyUnseenMessages()) { messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); } else { messages = folder.getMessages(); } int fetchSize = getMaxFetchSize() == -1 ? messages.length : Math.min(getMaxFetchSize(), messages.length); for (int cnt = 0; cnt < fetchSize; cnt++) { // get the message MimeMessage mailMsg = (MimeMessage)messages[cnt]; // create a inOnly exchange InOnly io = getExchangeFactory().createInOnlyExchange(); // configure the exchange target configureExchangeTarget(io); // create the in message NormalizedMessage normalizedMessage = io.createMessage(); // now let the marshaller convert the mail into a normalized // message to send to jbi bus marshaler.convertMailToJBI(io, normalizedMessage, mailMsg); // then put the in message into the inOnly exchange io.setInMessage(normalizedMessage); // and use sendSync to deliver it sendSync(io); // now check if delivery succeeded or went wrong if (io.getStatus() == ExchangeStatus.ERROR) { Exception e = io.getError(); if (e == null) { e = new JBIException("Unexpected error: " + e.getMessage()); } throw e; } else { // then mark the mail as processed (only if no errors) if (deleteProcessedMessages) { // processed messages have to be marked as deleted mailMsg.setFlag(Flags.Flag.DELETED, true); } else { // processed messages have to be marked as seen mailMsg.setFlag(Flags.Flag.SEEN, true); } } } } finally { // finally clean up and close the folder and store try { if (folder != null) { folder.close(true); } if (store != null) { store.close(); } } catch (Exception ignored) { logger.debug(ignored); } } }
public void poll() throws Exception { LOG.debug("Polling mailfolder " + config.getFolderName() + " at host " + config.getHost() + "..."); if (maxFetchSize == 0) { LOG.debug("The configuration is set to poll no new messages at all...skipping."); return; } Store store = null; Folder folder = null; Session session = null; try { Properties props = MailUtils.getPropertiesForProtocol(this.config, this.customTrustManagers); props.put("mail.debug", isDebugMode() ? "true" : "false"); // Get session session = Session.getInstance(props, config.getAuthenticator()); // debug the session session.setDebug(this.debugMode); store = session.getStore(config.getProtocol()); store.connect(config.getHost(), config.getUsername(), config.getPassword()); folder = store.getFolder(config.getFolderName()); if (folder == null || !folder.exists()) { throw new Exception("Folder not found or invalid: " + config.getFolderName()); } folder.open(Folder.READ_WRITE); Message[] messages = null; if (isProcessOnlyUnseenMessages()) { messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); } else { messages = folder.getMessages(); } int fetchSize = getMaxFetchSize() == -1 ? messages.length : Math.min(getMaxFetchSize(), messages.length); for (int cnt = 0; cnt < fetchSize; cnt++) { // get the message MimeMessage mailMsg = (MimeMessage)messages[cnt]; // create a inOnly exchange InOnly io = getExchangeFactory().createInOnlyExchange(); // configure the exchange target configureExchangeTarget(io); // create the in message NormalizedMessage normalizedMessage = io.createMessage(); // now let the marshaller convert the mail into a normalized // message to send to jbi bus marshaler.convertMailToJBI(io, normalizedMessage, mailMsg); // then put the in message into the inOnly exchange io.setInMessage(normalizedMessage); // and use sendSync to deliver it sendSync(io); // now check if delivery succeeded or went wrong if (io.getStatus() == ExchangeStatus.ERROR) { Exception e = io.getError(); if (e == null) { e = new JBIException("Unexpected error occured..."); } throw e; } else { // then mark the mail as processed (only if no errors) if (deleteProcessedMessages) { // processed messages have to be marked as deleted mailMsg.setFlag(Flags.Flag.DELETED, true); } else { // processed messages have to be marked as seen mailMsg.setFlag(Flags.Flag.SEEN, true); } } } } finally { // finally clean up and close the folder and store try { if (folder != null) { folder.close(true); } if (store != null) { store.close(); } } catch (Exception ignored) { logger.debug(ignored); } } }
diff --git a/src/java/org/apache/hadoop/filecache/DistributedCache.java b/src/java/org/apache/hadoop/filecache/DistributedCache.java index 0c050cc31..b93e7c528 100644 --- a/src/java/org/apache/hadoop/filecache/DistributedCache.java +++ b/src/java/org/apache/hadoop/filecache/DistributedCache.java @@ -1,810 +1,813 @@ /** * 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.hadoop.filecache; import org.apache.commons.logging.*; import java.io.*; import java.util.*; import org.apache.hadoop.conf.*; import org.apache.hadoop.util.*; import org.apache.hadoop.fs.*; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.Reducer; import java.net.URI; /** * Distribute application-specific large, read-only files efficiently. * * <p><code>DistributedCache</code> is a facility provided by the Map-Reduce * framework to cache files (text, archives, jars etc.) needed by applications. * </p> * * <p>Applications specify the files, via urls (hdfs:// or http://) to be cached * via the {@link JobConf}. The <code>DistributedCache</code> assumes that the * files specified via hdfs:// urls are already present on the * {@link FileSystem} at the path specified by the url.</p> * * <p>The framework will copy the necessary files on to the slave node before * any tasks for the job are executed on that node. Its efficiency stems from * the fact that the files are only copied once per job and the ability to * cache archives which are un-archived on the slaves.</p> * * <p><code>DistributedCache</code> can be used to distribute simple, read-only * data/text files and/or more complex types such as archives, jars etc. * Archives (zip, tar and tgz/tar.gz files) are un-archived at the slave nodes. * Jars may be optionally added to the classpath of the tasks, a rudimentary * software distribution mechanism. Files have execution permissions. * Optionally users can also direct it to symlink the distributed cache file(s) * into the working directory of the task.</p> * * <p><code>DistributedCache</code> tracks modification timestamps of the cache * files. Clearly the cache files should not be modified by the application * or externally while the job is executing.</p> * * <p>Here is an illustrative example on how to use the * <code>DistributedCache</code>:</p> * <p><blockquote><pre> * // Setting up the cache for the application * * 1. Copy the requisite files to the <code>FileSystem</code>: * * $ bin/hadoop fs -copyFromLocal lookup.dat /myapp/lookup.dat * $ bin/hadoop fs -copyFromLocal map.zip /myapp/map.zip * $ bin/hadoop fs -copyFromLocal mylib.jar /myapp/mylib.jar * $ bin/hadoop fs -copyFromLocal mytar.tar /myapp/mytar.tar * $ bin/hadoop fs -copyFromLocal mytgz.tgz /myapp/mytgz.tgz * $ bin/hadoop fs -copyFromLocal mytargz.tar.gz /myapp/mytargz.tar.gz * * 2. Setup the application's <code>JobConf</code>: * * JobConf job = new JobConf(); * DistributedCache.addCacheFile(new URI("/myapp/lookup.dat#lookup.dat"), * job); * DistributedCache.addCacheArchive(new URI("/myapp/map.zip", job); * DistributedCache.addFileToClassPath(new Path("/myapp/mylib.jar"), job); * DistributedCache.addCacheArchive(new URI("/myapp/mytar.tar", job); * DistributedCache.addCacheArchive(new URI("/myapp/mytgz.tgz", job); * DistributedCache.addCacheArchive(new URI("/myapp/mytargz.tar.gz", job); * * 3. Use the cached files in the {@link Mapper} or {@link Reducer}: * * public static class MapClass extends MapReduceBase * implements Mapper&lt;K, V, K, V&gt; { * * private Path[] localArchives; * private Path[] localFiles; * * public void configure(JobConf job) { * // Get the cached archives/files * localArchives = DistributedCache.getLocalCacheArchives(job); * localFiles = DistributedCache.getLocalCacheFiles(job); * } * * public void map(K key, V value, * OutputCollector&lt;K, V&gt; output, Reporter reporter) * throws IOException { * // Use data from the cached archives/files here * // ... * // ... * output.collect(k, v); * } * } * * </pre></blockquote></p> * * @see JobConf * @see JobClient */ public class DistributedCache { // cacheID to cacheStatus mapping private static TreeMap<String, CacheStatus> cachedArchives = new TreeMap<String, CacheStatus>(); // default total cache size private static final long DEFAULT_CACHE_SIZE = 1048576L; private static final Log LOG = LogFactory.getLog(DistributedCache.class); /** * Get the locally cached file or archive; it could either be * previously cached (and valid) or copy it from the {@link FileSystem} now. * * @param cache the cache to be localized, this should be specified as * new URI(hdfs://hostname:port/absolute_path_to_file#LINKNAME). If no schema * or hostname:port is provided the file is assumed to be in the filesystem * being used in the Configuration * @param conf The Confguration file which contains the filesystem * @param baseDir The base cache Dir where you wnat to localize the files/archives * @param fileStatus The file status on the dfs. * @param isArchive if the cache is an archive or a file. In case it is an * archive with a .zip or .jar or .tar or .tgz or .tar.gz extension it will * be unzipped/unjarred/untarred automatically * and the directory where the archive is unzipped/unjarred/untarred is * returned as the Path. * In case of a file, the path to the file is returned * @param confFileStamp this is the hdfs file modification timestamp to verify that the * file to be cached hasn't changed since the job started * @param currentWorkDir this is the directory where you would want to create symlinks * for the locally cached files/archives * @return the path to directory where the archives are unjarred in case of archives, * the path to the file where the file is copied locally * @throws IOException */ public static Path getLocalCache(URI cache, Configuration conf, Path baseDir, FileStatus fileStatus, boolean isArchive, long confFileStamp, Path currentWorkDir) throws IOException { String cacheId = makeRelative(cache, conf); CacheStatus lcacheStatus; Path localizedPath; synchronized (cachedArchives) { lcacheStatus = cachedArchives.get(cacheId); if (lcacheStatus == null) { // was never localized lcacheStatus = new CacheStatus(new Path(baseDir, new Path(cacheId))); cachedArchives.put(cacheId, lcacheStatus); } synchronized (lcacheStatus) { localizedPath = localizeCache(conf, cache, confFileStamp, lcacheStatus, fileStatus, isArchive, currentWorkDir); lcacheStatus.refcount++; } } // try deleting stuff if you can long size = FileUtil.getDU(new File(baseDir.toString())); // setting the cache size to a default of 1MB long allowedSize = conf.getLong("local.cache.size", DEFAULT_CACHE_SIZE); if (allowedSize < size) { // try some cache deletions deleteCache(conf); } return localizedPath; } /** * Get the locally cached file or archive; it could either be * previously cached (and valid) or copy it from the {@link FileSystem} now. * * @param cache the cache to be localized, this should be specified as * new URI(hdfs://hostname:port/absolute_path_to_file#LINKNAME). If no schema * or hostname:port is provided the file is assumed to be in the filesystem * being used in the Configuration * @param conf The Confguration file which contains the filesystem * @param baseDir The base cache Dir where you wnat to localize the files/archives * @param isArchive if the cache is an archive or a file. In case it is an * archive with a .zip or .jar or .tar or .tgz or .tar.gz extension it will * be unzipped/unjarred/untarred automatically * and the directory where the archive is unzipped/unjarred/untarred * is returned as the Path. * In case of a file, the path to the file is returned * @param confFileStamp this is the hdfs file modification timestamp to verify that the * file to be cached hasn't changed since the job started * @param currentWorkDir this is the directory where you would want to create symlinks * for the locally cached files/archives * @return the path to directory where the archives are unjarred in case of archives, * the path to the file where the file is copied locally * @throws IOException */ public static Path getLocalCache(URI cache, Configuration conf, Path baseDir, boolean isArchive, long confFileStamp, Path currentWorkDir) throws IOException { return getLocalCache(cache, conf, baseDir, null, isArchive, confFileStamp, currentWorkDir); } /** * This is the opposite of getlocalcache. When you are done with * using the cache, you need to release the cache * @param cache The cache URI to be released * @param conf configuration which contains the filesystem the cache * is contained in. * @throws IOException */ public static void releaseCache(URI cache, Configuration conf) throws IOException { String cacheId = makeRelative(cache, conf); synchronized (cachedArchives) { CacheStatus lcacheStatus = cachedArchives.get(cacheId); if (lcacheStatus == null) return; synchronized (lcacheStatus) { lcacheStatus.refcount--; } } } // To delete the caches which have a refcount of zero private static void deleteCache(Configuration conf) throws IOException { // try deleting cache Status with refcount of zero synchronized (cachedArchives) { for (Iterator it = cachedArchives.keySet().iterator(); it.hasNext();) { String cacheId = (String) it.next(); CacheStatus lcacheStatus = cachedArchives.get(cacheId); synchronized (lcacheStatus) { if (lcacheStatus.refcount == 0) { // delete this cache entry FileSystem.getLocal(conf).delete(lcacheStatus.localLoadPath, true); it.remove(); } } } } } /* * Returns the relative path of the dir this cache will be localized in * relative path that this cache will be localized in. For * hdfs://hostname:port/absolute_path -- the relative path is * hostname/absolute path -- if it is just /absolute_path -- then the * relative path is hostname of DFS this mapred cluster is running * on/absolute_path */ public static String makeRelative(URI cache, Configuration conf) throws IOException { String host = cache.getHost(); if (host == null) { host = cache.getScheme(); } if (host == null) { URI defaultUri = FileSystem.get(conf).getUri(); host = defaultUri.getHost(); if (host == null) { host = defaultUri.getScheme(); } } String path = host + cache.getPath(); path = path.replace(":/","/"); // remove windows device colon return path; } private static Path cacheFilePath(Path p) { return new Path(p, p.getName()); } // the method which actually copies the caches locally and unjars/unzips them // and does chmod for the files private static Path localizeCache(Configuration conf, URI cache, long confFileStamp, CacheStatus cacheStatus, FileStatus fileStatus, boolean isArchive, Path currentWorkDir) throws IOException { boolean doSymlink = getSymlink(conf); + if(cache.getFragment() == null) { + doSymlink = false; + } FileSystem fs = getFileSystem(cache, conf); String link = currentWorkDir.toString() + Path.SEPARATOR + cache.getFragment(); File flink = new File(link); if (ifExistsAndFresh(conf, fs, cache, confFileStamp, cacheStatus, fileStatus)) { if (isArchive) { if (doSymlink){ if (!flink.exists()) FileUtil.symLink(cacheStatus.localLoadPath.toString(), link); } return cacheStatus.localLoadPath; } else { if (doSymlink){ if (!flink.exists()) FileUtil.symLink(cacheFilePath(cacheStatus.localLoadPath).toString(), link); } return cacheFilePath(cacheStatus.localLoadPath); } } else { // remove the old archive // if the old archive cannot be removed since it is being used by another // job // return null if (cacheStatus.refcount > 1 && (cacheStatus.currentStatus == true)) throw new IOException("Cache " + cacheStatus.localLoadPath.toString() + " is in use and cannot be refreshed"); FileSystem localFs = FileSystem.getLocal(conf); localFs.delete(cacheStatus.localLoadPath, true); Path parchive = new Path(cacheStatus.localLoadPath, new Path(cacheStatus.localLoadPath.getName())); if (!localFs.mkdirs(cacheStatus.localLoadPath)) { throw new IOException("Mkdirs failed to create directory " + cacheStatus.localLoadPath.toString()); } String cacheId = cache.getPath(); fs.copyToLocalFile(new Path(cacheId), parchive); if (isArchive) { String tmpArchive = parchive.toString().toLowerCase(); File srcFile = new File(parchive.toString()); File destDir = new File(parchive.getParent().toString()); if (tmpArchive.endsWith(".jar")) { RunJar.unJar(srcFile, destDir); } else if (tmpArchive.endsWith(".zip")) { FileUtil.unZip(srcFile, destDir); } else if (isTarFile(tmpArchive)) { FileUtil.unTar(srcFile, destDir); } // else will not do anyhting // and copy the file into the dir as it is } // do chmod here try { FileUtil.chmod(parchive.toString(), "+x"); } catch(InterruptedException e) { LOG.warn("Exception in chmod" + e.toString()); } // update cacheStatus to reflect the newly cached file cacheStatus.currentStatus = true; cacheStatus.mtime = getTimestamp(conf, cache); } if (isArchive){ if (doSymlink){ if (!flink.exists()) FileUtil.symLink(cacheStatus.localLoadPath.toString(), link); } return cacheStatus.localLoadPath; } else { if (doSymlink){ if (!flink.exists()) FileUtil.symLink(cacheFilePath(cacheStatus.localLoadPath).toString(), link); } return cacheFilePath(cacheStatus.localLoadPath); } } private static boolean isTarFile(String filename) { return (filename.endsWith(".tgz") || filename.endsWith(".tar.gz") || filename.endsWith(".tar")); } // Checks if the cache has already been localized and is fresh private static boolean ifExistsAndFresh(Configuration conf, FileSystem fs, URI cache, long confFileStamp, CacheStatus lcacheStatus, FileStatus fileStatus) throws IOException { // check for existence of the cache if (lcacheStatus.currentStatus == false) { return false; } else { long dfsFileStamp; if (fileStatus != null) { dfsFileStamp = fileStatus.getModificationTime(); } else { dfsFileStamp = getTimestamp(conf, cache); } // ensure that the file on hdfs hasn't been modified since the job started if (dfsFileStamp != confFileStamp) { LOG.fatal("File: " + cache + " has changed on HDFS since job started"); throw new IOException("File: " + cache + " has changed on HDFS since job started"); } if (dfsFileStamp != lcacheStatus.mtime) { // needs refreshing return false; } } return true; } /** * Returns mtime of a given cache file on hdfs. * @param conf configuration * @param cache cache file * @return mtime of a given cache file on hdfs * @throws IOException */ public static long getTimestamp(Configuration conf, URI cache) throws IOException { FileSystem fileSystem = FileSystem.get(cache, conf); Path filePath = new Path(cache.getPath()); return fileSystem.getFileStatus(filePath).getModificationTime(); } /** * This method create symlinks for all files in a given dir in another directory * @param conf the configuration * @param jobCacheDir the target directory for creating symlinks * @param workDir the directory in which the symlinks are created * @throws IOException */ public static void createAllSymlink(Configuration conf, File jobCacheDir, File workDir) throws IOException{ if ((jobCacheDir == null || !jobCacheDir.isDirectory()) || workDir == null || (!workDir.isDirectory())) { return; } boolean createSymlink = getSymlink(conf); if (createSymlink){ File[] list = jobCacheDir.listFiles(); for (int i=0; i < list.length; i++){ FileUtil.symLink(list[i].getAbsolutePath(), new File(workDir, list[i].getName()).toString()); } } } private static String getFileSysName(URI url) { String fsname = url.getScheme(); if ("hdfs".equals(fsname)) { String host = url.getHost(); int port = url.getPort(); return (port == (-1)) ? host : (host + ":" + port); } else { return null; } } private static FileSystem getFileSystem(URI cache, Configuration conf) throws IOException { String fileSysName = getFileSysName(cache); if (fileSysName != null) return FileSystem.getNamed(fileSysName, conf); else return FileSystem.get(conf); } /** * Set the configuration with the given set of archives * @param archives The list of archives that need to be localized * @param conf Configuration which will be changed */ public static void setCacheArchives(URI[] archives, Configuration conf) { String sarchives = StringUtils.uriToString(archives); conf.set("mapred.cache.archives", sarchives); } /** * Set the configuration with the given set of files * @param files The list of files that need to be localized * @param conf Configuration which will be changed */ public static void setCacheFiles(URI[] files, Configuration conf) { String sfiles = StringUtils.uriToString(files); conf.set("mapred.cache.files", sfiles); } /** * Get cache archives set in the Configuration * @param conf The configuration which contains the archives * @return A URI array of the caches set in the Configuration * @throws IOException */ public static URI[] getCacheArchives(Configuration conf) throws IOException { return StringUtils.stringToURI(conf.getStrings("mapred.cache.archives")); } /** * Get cache files set in the Configuration * @param conf The configuration which contains the files * @return A URI array of the files set in the Configuration * @throws IOException */ public static URI[] getCacheFiles(Configuration conf) throws IOException { return StringUtils.stringToURI(conf.getStrings("mapred.cache.files")); } /** * Return the path array of the localized caches * @param conf Configuration that contains the localized archives * @return A path array of localized caches * @throws IOException */ public static Path[] getLocalCacheArchives(Configuration conf) throws IOException { return StringUtils.stringToPath(conf .getStrings("mapred.cache.localArchives")); } /** * Return the path array of the localized files * @param conf Configuration that contains the localized files * @return A path array of localized files * @throws IOException */ public static Path[] getLocalCacheFiles(Configuration conf) throws IOException { return StringUtils.stringToPath(conf.getStrings("mapred.cache.localFiles")); } /** * Get the timestamps of the archives * @param conf The configuration which stored the timestamps * @return a string array of timestamps * @throws IOException */ public static String[] getArchiveTimestamps(Configuration conf) { return conf.getStrings("mapred.cache.archives.timestamps"); } /** * Get the timestamps of the files * @param conf The configuration which stored the timestamps * @return a string array of timestamps * @throws IOException */ public static String[] getFileTimestamps(Configuration conf) { return conf.getStrings("mapred.cache.files.timestamps"); } /** * This is to check the timestamp of the archives to be localized * @param conf Configuration which stores the timestamp's * @param timestamps comma separated list of timestamps of archives. * The order should be the same as the order in which the archives are added. */ public static void setArchiveTimestamps(Configuration conf, String timestamps) { conf.set("mapred.cache.archives.timestamps", timestamps); } /** * This is to check the timestamp of the files to be localized * @param conf Configuration which stores the timestamp's * @param timestamps comma separated list of timestamps of files. * The order should be the same as the order in which the files are added. */ public static void setFileTimestamps(Configuration conf, String timestamps) { conf.set("mapred.cache.files.timestamps", timestamps); } /** * Set the conf to contain the location for localized archives * @param conf The conf to modify to contain the localized caches * @param str a comma separated list of local archives */ public static void setLocalArchives(Configuration conf, String str) { conf.set("mapred.cache.localArchives", str); } /** * Set the conf to contain the location for localized files * @param conf The conf to modify to contain the localized caches * @param str a comma separated list of local files */ public static void setLocalFiles(Configuration conf, String str) { conf.set("mapred.cache.localFiles", str); } /** * Add a archives to be localized to the conf * @param uri The uri of the cache to be localized * @param conf Configuration to add the cache to */ public static void addCacheArchive(URI uri, Configuration conf) { String archives = conf.get("mapred.cache.archives"); conf.set("mapred.cache.archives", archives == null ? uri.toString() : archives + "," + uri.toString()); } /** * Add a file to be localized to the conf * @param uri The uri of the cache to be localized * @param conf Configuration to add the cache to */ public static void addCacheFile(URI uri, Configuration conf) { String files = conf.get("mapred.cache.files"); conf.set("mapred.cache.files", files == null ? uri.toString() : files + "," + uri.toString()); } /** * Add an file path to the current set of classpath entries It adds the file * to cache as well. * * @param file Path of the file to be added * @param conf Configuration that contains the classpath setting */ public static void addFileToClassPath(Path file, Configuration conf) throws IOException { String classpath = conf.get("mapred.job.classpath.files"); conf.set("mapred.job.classpath.files", classpath == null ? file.toString() : classpath + System.getProperty("path.separator") + file.toString()); FileSystem fs = FileSystem.get(conf); URI uri = fs.makeQualified(file).toUri(); addCacheFile(uri, conf); } /** * Get the file entries in classpath as an array of Path * * @param conf Configuration that contains the classpath setting */ public static Path[] getFileClassPaths(Configuration conf) { String classpath = conf.get("mapred.job.classpath.files"); if (classpath == null) return null; ArrayList list = Collections.list(new StringTokenizer(classpath, System .getProperty("path.separator"))); Path[] paths = new Path[list.size()]; for (int i = 0; i < list.size(); i++) { paths[i] = new Path((String) list.get(i)); } return paths; } /** * Add an archive path to the current set of classpath entries. It adds the * archive to cache as well. * * @param archive Path of the archive to be added * @param conf Configuration that contains the classpath setting */ public static void addArchiveToClassPath(Path archive, Configuration conf) throws IOException { String classpath = conf.get("mapred.job.classpath.archives"); conf.set("mapred.job.classpath.archives", classpath == null ? archive .toString() : classpath + System.getProperty("path.separator") + archive.toString()); FileSystem fs = FileSystem.get(conf); URI uri = fs.makeQualified(archive).toUri(); addCacheArchive(uri, conf); } /** * Get the archive entries in classpath as an array of Path * * @param conf Configuration that contains the classpath setting */ public static Path[] getArchiveClassPaths(Configuration conf) { String classpath = conf.get("mapred.job.classpath.archives"); if (classpath == null) return null; ArrayList list = Collections.list(new StringTokenizer(classpath, System .getProperty("path.separator"))); Path[] paths = new Path[list.size()]; for (int i = 0; i < list.size(); i++) { paths[i] = new Path((String) list.get(i)); } return paths; } /** * This method allows you to create symlinks in the current working directory * of the task to all the cache files/archives * @param conf the jobconf */ public static void createSymlink(Configuration conf){ conf.set("mapred.create.symlink", "yes"); } /** * This method checks to see if symlinks are to be create for the * localized cache files in the current working directory * @param conf the jobconf * @return true if symlinks are to be created- else return false */ public static boolean getSymlink(Configuration conf){ String result = conf.get("mapred.create.symlink"); if ("yes".equals(result)){ return true; } return false; } /** * This method checks if there is a conflict in the fragment names * of the uris. Also makes sure that each uri has a fragment. It * is only to be called if you want to create symlinks for * the various archives and files. * @param uriFiles The uri array of urifiles * @param uriArchives the uri array of uri archives */ public static boolean checkURIs(URI[] uriFiles, URI[] uriArchives){ if ((uriFiles == null) && (uriArchives == null)){ return true; } if (uriFiles != null){ for (int i = 0; i < uriFiles.length; i++){ String frag1 = uriFiles[i].getFragment(); if (frag1 == null) return false; for (int j=i+1; j < uriFiles.length; j++){ String frag2 = uriFiles[j].getFragment(); if (frag2 == null) return false; if (frag1.equalsIgnoreCase(frag2)) return false; } if (uriArchives != null){ for (int j = 0; j < uriArchives.length; j++){ String frag2 = uriArchives[j].getFragment(); if (frag2 == null){ return false; } if (frag1.equalsIgnoreCase(frag2)) return false; for (int k=j+1; k < uriArchives.length; k++){ String frag3 = uriArchives[k].getFragment(); if (frag3 == null) return false; if (frag2.equalsIgnoreCase(frag3)) return false; } } } } } return true; } private static class CacheStatus { // false, not loaded yet, true is loaded boolean currentStatus; // the local load path of this cache Path localLoadPath; // number of instances using this cache int refcount; // the cache-file modification time long mtime; public CacheStatus(Path localLoadPath) { super(); this.currentStatus = false; this.localLoadPath = localLoadPath; this.refcount = 0; this.mtime = -1; } } /** * Clear the entire contents of the cache and delete the backing files. This * should only be used when the server is reinitializing, because the users * are going to lose their files. */ public static void purgeCache(Configuration conf) throws IOException { synchronized (cachedArchives) { FileSystem localFs = FileSystem.getLocal(conf); for (Map.Entry<String,CacheStatus> f: cachedArchives.entrySet()) { try { localFs.delete(f.getValue().localLoadPath, true); } catch (IOException ie) { LOG.debug("Error cleaning up cache", ie); } } cachedArchives.clear(); } } }
true
true
private static Path localizeCache(Configuration conf, URI cache, long confFileStamp, CacheStatus cacheStatus, FileStatus fileStatus, boolean isArchive, Path currentWorkDir) throws IOException { boolean doSymlink = getSymlink(conf); FileSystem fs = getFileSystem(cache, conf); String link = currentWorkDir.toString() + Path.SEPARATOR + cache.getFragment(); File flink = new File(link); if (ifExistsAndFresh(conf, fs, cache, confFileStamp, cacheStatus, fileStatus)) { if (isArchive) { if (doSymlink){ if (!flink.exists()) FileUtil.symLink(cacheStatus.localLoadPath.toString(), link); } return cacheStatus.localLoadPath; } else { if (doSymlink){ if (!flink.exists()) FileUtil.symLink(cacheFilePath(cacheStatus.localLoadPath).toString(), link); } return cacheFilePath(cacheStatus.localLoadPath); } } else { // remove the old archive // if the old archive cannot be removed since it is being used by another // job // return null if (cacheStatus.refcount > 1 && (cacheStatus.currentStatus == true)) throw new IOException("Cache " + cacheStatus.localLoadPath.toString() + " is in use and cannot be refreshed"); FileSystem localFs = FileSystem.getLocal(conf); localFs.delete(cacheStatus.localLoadPath, true); Path parchive = new Path(cacheStatus.localLoadPath, new Path(cacheStatus.localLoadPath.getName())); if (!localFs.mkdirs(cacheStatus.localLoadPath)) { throw new IOException("Mkdirs failed to create directory " + cacheStatus.localLoadPath.toString()); } String cacheId = cache.getPath(); fs.copyToLocalFile(new Path(cacheId), parchive); if (isArchive) { String tmpArchive = parchive.toString().toLowerCase(); File srcFile = new File(parchive.toString()); File destDir = new File(parchive.getParent().toString()); if (tmpArchive.endsWith(".jar")) { RunJar.unJar(srcFile, destDir); } else if (tmpArchive.endsWith(".zip")) { FileUtil.unZip(srcFile, destDir); } else if (isTarFile(tmpArchive)) { FileUtil.unTar(srcFile, destDir); } // else will not do anyhting // and copy the file into the dir as it is } // do chmod here try { FileUtil.chmod(parchive.toString(), "+x"); } catch(InterruptedException e) { LOG.warn("Exception in chmod" + e.toString()); } // update cacheStatus to reflect the newly cached file cacheStatus.currentStatus = true; cacheStatus.mtime = getTimestamp(conf, cache); } if (isArchive){ if (doSymlink){ if (!flink.exists()) FileUtil.symLink(cacheStatus.localLoadPath.toString(), link); } return cacheStatus.localLoadPath; } else { if (doSymlink){ if (!flink.exists()) FileUtil.symLink(cacheFilePath(cacheStatus.localLoadPath).toString(), link); } return cacheFilePath(cacheStatus.localLoadPath); } }
private static Path localizeCache(Configuration conf, URI cache, long confFileStamp, CacheStatus cacheStatus, FileStatus fileStatus, boolean isArchive, Path currentWorkDir) throws IOException { boolean doSymlink = getSymlink(conf); if(cache.getFragment() == null) { doSymlink = false; } FileSystem fs = getFileSystem(cache, conf); String link = currentWorkDir.toString() + Path.SEPARATOR + cache.getFragment(); File flink = new File(link); if (ifExistsAndFresh(conf, fs, cache, confFileStamp, cacheStatus, fileStatus)) { if (isArchive) { if (doSymlink){ if (!flink.exists()) FileUtil.symLink(cacheStatus.localLoadPath.toString(), link); } return cacheStatus.localLoadPath; } else { if (doSymlink){ if (!flink.exists()) FileUtil.symLink(cacheFilePath(cacheStatus.localLoadPath).toString(), link); } return cacheFilePath(cacheStatus.localLoadPath); } } else { // remove the old archive // if the old archive cannot be removed since it is being used by another // job // return null if (cacheStatus.refcount > 1 && (cacheStatus.currentStatus == true)) throw new IOException("Cache " + cacheStatus.localLoadPath.toString() + " is in use and cannot be refreshed"); FileSystem localFs = FileSystem.getLocal(conf); localFs.delete(cacheStatus.localLoadPath, true); Path parchive = new Path(cacheStatus.localLoadPath, new Path(cacheStatus.localLoadPath.getName())); if (!localFs.mkdirs(cacheStatus.localLoadPath)) { throw new IOException("Mkdirs failed to create directory " + cacheStatus.localLoadPath.toString()); } String cacheId = cache.getPath(); fs.copyToLocalFile(new Path(cacheId), parchive); if (isArchive) { String tmpArchive = parchive.toString().toLowerCase(); File srcFile = new File(parchive.toString()); File destDir = new File(parchive.getParent().toString()); if (tmpArchive.endsWith(".jar")) { RunJar.unJar(srcFile, destDir); } else if (tmpArchive.endsWith(".zip")) { FileUtil.unZip(srcFile, destDir); } else if (isTarFile(tmpArchive)) { FileUtil.unTar(srcFile, destDir); } // else will not do anyhting // and copy the file into the dir as it is } // do chmod here try { FileUtil.chmod(parchive.toString(), "+x"); } catch(InterruptedException e) { LOG.warn("Exception in chmod" + e.toString()); } // update cacheStatus to reflect the newly cached file cacheStatus.currentStatus = true; cacheStatus.mtime = getTimestamp(conf, cache); } if (isArchive){ if (doSymlink){ if (!flink.exists()) FileUtil.symLink(cacheStatus.localLoadPath.toString(), link); } return cacheStatus.localLoadPath; } else { if (doSymlink){ if (!flink.exists()) FileUtil.symLink(cacheFilePath(cacheStatus.localLoadPath).toString(), link); } return cacheFilePath(cacheStatus.localLoadPath); } }
diff --git a/test/org/nexml/model/TestContinuousMatrix.java b/test/org/nexml/model/TestContinuousMatrix.java index 740ba63..a5c3efa 100644 --- a/test/org/nexml/model/TestContinuousMatrix.java +++ b/test/org/nexml/model/TestContinuousMatrix.java @@ -1,91 +1,91 @@ package org.nexml.model; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.junit.Test; import org.junit.Assert; import org.xml.sax.SAXException; public class TestContinuousMatrix { @Test public void testContinuousMatrix() { Document doc = null; try { doc = DocumentFactory.createDocument(); } catch (ParserConfigurationException e) { e.printStackTrace(); } OTUs otus = doc.createOTUs(); OTU otu = otus.createOTU(); ContinuousMatrix contmat = doc.createContinuousMatrix(otus); Character character = contmat.createCharacter(); contmat.getCell(otu, character).setValue(0.434534); Assert.assertNotNull("matrix != null", contmat); /** * Now we're going to validate the output, so first we need * to jump through the xml parsing hoops. */ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); factory.setAttribute( "http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); factory.setAttribute( "http://java.sun.com/xml/jaxp/properties/schemaSource", - "http://nexml-dev.nescent.org/1.0/nexml.xsd"); + "http://nexml.org/2009/nexml.xsd"); DocumentBuilder builder = null; /** * We're going to turn the string output of our created * NeXML into an InputStream for the parser. If we don't * have valid UTF-8, we've failed this test. */ InputStream is = null; try { is = new ByteArrayInputStream(doc.getXmlString().getBytes("UTF-8")); } catch (UnsupportedEncodingException e1) { Assert.assertFalse(e1.getMessage(), false); e1.printStackTrace(); } catch (NullPointerException e) { Assert.assertFalse(e.getMessage(),false); e.printStackTrace(); } /** * Let's see if we get through this hoop. Is not our * fault if we don't. */ try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { Assert.assertTrue(e.getMessage(), false); e.printStackTrace(); } /** * Now let's parse our produced xl */ try { builder.parse(is); } catch (SAXException e) { Assert.assertTrue(e.getMessage(), false); e.printStackTrace(); } catch (IOException e) { Assert.assertTrue(e.getMessage(), false); e.printStackTrace(); } //System.out.println(doc.getXmlString()); } }
true
true
public void testContinuousMatrix() { Document doc = null; try { doc = DocumentFactory.createDocument(); } catch (ParserConfigurationException e) { e.printStackTrace(); } OTUs otus = doc.createOTUs(); OTU otu = otus.createOTU(); ContinuousMatrix contmat = doc.createContinuousMatrix(otus); Character character = contmat.createCharacter(); contmat.getCell(otu, character).setValue(0.434534); Assert.assertNotNull("matrix != null", contmat); /** * Now we're going to validate the output, so first we need * to jump through the xml parsing hoops. */ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); factory.setAttribute( "http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); factory.setAttribute( "http://java.sun.com/xml/jaxp/properties/schemaSource", "http://nexml-dev.nescent.org/1.0/nexml.xsd"); DocumentBuilder builder = null; /** * We're going to turn the string output of our created * NeXML into an InputStream for the parser. If we don't * have valid UTF-8, we've failed this test. */ InputStream is = null; try { is = new ByteArrayInputStream(doc.getXmlString().getBytes("UTF-8")); } catch (UnsupportedEncodingException e1) { Assert.assertFalse(e1.getMessage(), false); e1.printStackTrace(); } catch (NullPointerException e) { Assert.assertFalse(e.getMessage(),false); e.printStackTrace(); } /** * Let's see if we get through this hoop. Is not our * fault if we don't. */ try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { Assert.assertTrue(e.getMessage(), false); e.printStackTrace(); } /** * Now let's parse our produced xl */ try { builder.parse(is); } catch (SAXException e) { Assert.assertTrue(e.getMessage(), false); e.printStackTrace(); } catch (IOException e) { Assert.assertTrue(e.getMessage(), false); e.printStackTrace(); } //System.out.println(doc.getXmlString()); }
public void testContinuousMatrix() { Document doc = null; try { doc = DocumentFactory.createDocument(); } catch (ParserConfigurationException e) { e.printStackTrace(); } OTUs otus = doc.createOTUs(); OTU otu = otus.createOTU(); ContinuousMatrix contmat = doc.createContinuousMatrix(otus); Character character = contmat.createCharacter(); contmat.getCell(otu, character).setValue(0.434534); Assert.assertNotNull("matrix != null", contmat); /** * Now we're going to validate the output, so first we need * to jump through the xml parsing hoops. */ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); factory.setAttribute( "http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); factory.setAttribute( "http://java.sun.com/xml/jaxp/properties/schemaSource", "http://nexml.org/2009/nexml.xsd"); DocumentBuilder builder = null; /** * We're going to turn the string output of our created * NeXML into an InputStream for the parser. If we don't * have valid UTF-8, we've failed this test. */ InputStream is = null; try { is = new ByteArrayInputStream(doc.getXmlString().getBytes("UTF-8")); } catch (UnsupportedEncodingException e1) { Assert.assertFalse(e1.getMessage(), false); e1.printStackTrace(); } catch (NullPointerException e) { Assert.assertFalse(e.getMessage(),false); e.printStackTrace(); } /** * Let's see if we get through this hoop. Is not our * fault if we don't. */ try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { Assert.assertTrue(e.getMessage(), false); e.printStackTrace(); } /** * Now let's parse our produced xl */ try { builder.parse(is); } catch (SAXException e) { Assert.assertTrue(e.getMessage(), false); e.printStackTrace(); } catch (IOException e) { Assert.assertTrue(e.getMessage(), false); e.printStackTrace(); } //System.out.println(doc.getXmlString()); }
diff --git a/plugin/src/main/java/com/h3xstream/findsecbugs/crypto/BadHexadecimalConversionDetector.java b/plugin/src/main/java/com/h3xstream/findsecbugs/crypto/BadHexadecimalConversionDetector.java index 5f33ffa6..f3802096 100644 --- a/plugin/src/main/java/com/h3xstream/findsecbugs/crypto/BadHexadecimalConversionDetector.java +++ b/plugin/src/main/java/com/h3xstream/findsecbugs/crypto/BadHexadecimalConversionDetector.java @@ -1,97 +1,97 @@ /** * Find Security Bugs * Copyright (c) 2013, Philippe Arteau, All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3.0 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. */ package com.h3xstream.findsecbugs.crypto; import com.h3xstream.findsecbugs.common.ByteCode; import edu.umd.cs.findbugs.Priorities; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.ConstantPoolGen; import org.apache.bcel.generic.INVOKESTATIC; import org.apache.bcel.generic.INVOKEVIRTUAL; import org.apache.bcel.generic.Instruction; import org.apache.bcel.generic.MethodGen; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.Detector; import edu.umd.cs.findbugs.ba.ClassContext; public class BadHexadecimalConversionDetector implements Detector { private static final boolean DEBUG = false; private static final String BAD_HEXA_CONVERSION_TYPE = "BAD_HEXA_CONVERSION"; private BugReporter bugReporter; public BadHexadecimalConversionDetector(BugReporter bugReporter) { this.bugReporter = bugReporter; } @Override public void visitClassContext(ClassContext classContext) { JavaClass javaClass = classContext.getJavaClass(); Method[] methodList = javaClass.getMethods(); for (Method m : methodList) { MethodGen methodGen = classContext.getMethodGen(m); if (DEBUG) { System.out.println(">>> Method: " + m.getName()); } //To suspect that an invalid String representation is being build, //we identify the construction of a MessageDigest and //the use of a function that trim leading 0. boolean invokeMessageDigest = false; boolean invokeToHexString = false; ConstantPoolGen cpg = classContext.getConstantPoolGen(); - if(methodGen.getInstructionList() == null || methodGen.getInstructionList().getInstructions() == null) { + if(methodGen == null || methodGen.getInstructionList() == null || methodGen.getInstructionList().getInstructions() == null) { continue; //No instruction .. nothing to do } for (Instruction inst : methodGen.getInstructionList().getInstructions()) { if (DEBUG) { ByteCode.printOpCode(inst, cpg); } if (inst instanceof INVOKEVIRTUAL) { //MessageDigest.digest is called INVOKEVIRTUAL invoke = (INVOKEVIRTUAL) inst; if ("java.security.MessageDigest".equals(invoke.getClassName(cpg)) && "digest".equals(invoke.getMethodName(cpg))) { invokeMessageDigest = true; } } else if (inst instanceof INVOKESTATIC && invokeMessageDigest) { //The conversion must occurs after the digest was created INVOKESTATIC invoke = (INVOKESTATIC) inst; if ("java.lang.Integer".equals(invoke.getClassName(cpg)) && "toHexString".equals(invoke.getMethodName(cpg))) { invokeToHexString = true; } } } if (invokeMessageDigest && invokeToHexString) { bugReporter.reportBug(new BugInstance(this, BAD_HEXA_CONVERSION_TYPE, Priorities.NORMAL_PRIORITY) // .addClassAndMethod(javaClass, m)); } } } @Override public void report() { } }
true
true
public void visitClassContext(ClassContext classContext) { JavaClass javaClass = classContext.getJavaClass(); Method[] methodList = javaClass.getMethods(); for (Method m : methodList) { MethodGen methodGen = classContext.getMethodGen(m); if (DEBUG) { System.out.println(">>> Method: " + m.getName()); } //To suspect that an invalid String representation is being build, //we identify the construction of a MessageDigest and //the use of a function that trim leading 0. boolean invokeMessageDigest = false; boolean invokeToHexString = false; ConstantPoolGen cpg = classContext.getConstantPoolGen(); if(methodGen.getInstructionList() == null || methodGen.getInstructionList().getInstructions() == null) { continue; //No instruction .. nothing to do } for (Instruction inst : methodGen.getInstructionList().getInstructions()) { if (DEBUG) { ByteCode.printOpCode(inst, cpg); } if (inst instanceof INVOKEVIRTUAL) { //MessageDigest.digest is called INVOKEVIRTUAL invoke = (INVOKEVIRTUAL) inst; if ("java.security.MessageDigest".equals(invoke.getClassName(cpg)) && "digest".equals(invoke.getMethodName(cpg))) { invokeMessageDigest = true; } } else if (inst instanceof INVOKESTATIC && invokeMessageDigest) { //The conversion must occurs after the digest was created INVOKESTATIC invoke = (INVOKESTATIC) inst; if ("java.lang.Integer".equals(invoke.getClassName(cpg)) && "toHexString".equals(invoke.getMethodName(cpg))) { invokeToHexString = true; } } } if (invokeMessageDigest && invokeToHexString) { bugReporter.reportBug(new BugInstance(this, BAD_HEXA_CONVERSION_TYPE, Priorities.NORMAL_PRIORITY) // .addClassAndMethod(javaClass, m)); } } }
public void visitClassContext(ClassContext classContext) { JavaClass javaClass = classContext.getJavaClass(); Method[] methodList = javaClass.getMethods(); for (Method m : methodList) { MethodGen methodGen = classContext.getMethodGen(m); if (DEBUG) { System.out.println(">>> Method: " + m.getName()); } //To suspect that an invalid String representation is being build, //we identify the construction of a MessageDigest and //the use of a function that trim leading 0. boolean invokeMessageDigest = false; boolean invokeToHexString = false; ConstantPoolGen cpg = classContext.getConstantPoolGen(); if(methodGen == null || methodGen.getInstructionList() == null || methodGen.getInstructionList().getInstructions() == null) { continue; //No instruction .. nothing to do } for (Instruction inst : methodGen.getInstructionList().getInstructions()) { if (DEBUG) { ByteCode.printOpCode(inst, cpg); } if (inst instanceof INVOKEVIRTUAL) { //MessageDigest.digest is called INVOKEVIRTUAL invoke = (INVOKEVIRTUAL) inst; if ("java.security.MessageDigest".equals(invoke.getClassName(cpg)) && "digest".equals(invoke.getMethodName(cpg))) { invokeMessageDigest = true; } } else if (inst instanceof INVOKESTATIC && invokeMessageDigest) { //The conversion must occurs after the digest was created INVOKESTATIC invoke = (INVOKESTATIC) inst; if ("java.lang.Integer".equals(invoke.getClassName(cpg)) && "toHexString".equals(invoke.getMethodName(cpg))) { invokeToHexString = true; } } } if (invokeMessageDigest && invokeToHexString) { bugReporter.reportBug(new BugInstance(this, BAD_HEXA_CONVERSION_TYPE, Priorities.NORMAL_PRIORITY) // .addClassAndMethod(javaClass, m)); } } }
diff --git a/src/main/java/net/sourceforge/cilib/pso/velocityupdatestrategies/GCVelocityUpdate.java b/src/main/java/net/sourceforge/cilib/pso/velocityupdatestrategies/GCVelocityUpdate.java index 975d61ee..7efbe9ff 100644 --- a/src/main/java/net/sourceforge/cilib/pso/velocityupdatestrategies/GCVelocityUpdate.java +++ b/src/main/java/net/sourceforge/cilib/pso/velocityupdatestrategies/GCVelocityUpdate.java @@ -1,202 +1,202 @@ /* * GCVelocityUpdate.java * * Created on September 22, 2003, 2:52 PM * * Copyright (C) 2003 - 2006 * Computational Intelligence Research Group (CIRG@UP) * Department of Computer Science * University of Pretoria * South Africa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package net.sourceforge.cilib.pso.velocityupdatestrategies; import java.util.Random; import net.sourceforge.cilib.algorithm.Algorithm; import net.sourceforge.cilib.math.random.generator.KnuthSubtractive; import net.sourceforge.cilib.pso.PSO; import net.sourceforge.cilib.pso.particle.GCDecorator; import net.sourceforge.cilib.pso.particle.Particle; import net.sourceforge.cilib.type.types.Vector; /** * * @author Edwin Peer */ public class GCVelocityUpdate implements VelocityUpdateStrategy { private StandardVelocityUpdate standard; private Random rhoRandomGenerator; private int successThreshold; private int failureThreshold; private double rhoContractCoefficient; private double rhoExpandCoefficient; /** Creates a new instance of GCVelocityUpdate */ public GCVelocityUpdate() { standard = new StandardVelocityUpdate(); rhoRandomGenerator = new KnuthSubtractive(); successThreshold = 5; failureThreshold = 5; rhoExpandCoefficient = 1.2; rhoContractCoefficient = 0.5; } public GCVelocityUpdate(GCVelocityUpdate copy) { this(); successThreshold = copy.successThreshold; failureThreshold = copy.failureThreshold; rhoExpandCoefficient = copy.rhoExpandCoefficient; rhoContractCoefficient = copy.rhoContractCoefficient; } public GCVelocityUpdate clone() { return new GCVelocityUpdate(this); } public void setStandardVelocityUpdate(StandardVelocityUpdate standard) { this.standard = standard; } public StandardVelocityUpdate getStandardVelocityUpdate() { return standard; } public void updateVelocity(Particle particle) { - if (particle.getNeighbourhoodBest().getId() == particle.getId()) { + if (particle.getNeighbourhoodBest().getId().equals(particle.getId())) { double rho = GCDecorator.extract(particle).getRho(); Vector velocity = (Vector) particle.getVelocity(); Vector nBestPosition = (Vector) particle.getNeighbourhoodBest().getBestPosition(); PSO pso = (PSO) Algorithm.get(); Vector swarmBestPosition = (Vector) pso.getBestParticle().getPosition(); for (int i = 0; i < particle.getDimension(); ++i) { double result = nBestPosition.getReal(i) - swarmBestPosition.getReal(i) + standard.getInertiaWeight().getParameter() * velocity.getReal(i) + rho * (1 - 2 * rhoRandomGenerator.nextFloat()); velocity.setReal(i, result); } } else { standard.updateVelocity(particle); } } /** * Sets the random number generator used in the GC update equation. The default is {@link net.sourceforge.cilib.math.random.generator.KnuthSubtractive}. * * @param rhoRandomGenerator The {@link java.util.Random} generator used in the GC update. */ public void setRhoRandomGenerator(Random rhoRandomGenerator) { this.rhoRandomGenerator = rhoRandomGenerator; } /** * Accessor for the random number generator used in the GC update equation. * * @return The {@link java.util.Random} generator used in the GC update. */ public Random getRhoRandomGenerator() { return rhoRandomGenerator; } /** * Sets the success threshold used to determine when to increase rho. The default is 5. * * @param successThreshold The success threshold. */ public void setSuccessThreshold(int successThreshold) { this.successThreshold = successThreshold; } /** * Accessor for the success threshold used to determine when to increase rho. * * @return The success threshold. */ public int getSuccessThreshold() { return successThreshold; } /** * Sets the failure threshold used to determine when to decrease rho. The default is 5. * * @param failureThreshold The failure threshold. */ public void setFailureThreshold(int failureThreshold) { this.failureThreshold = failureThreshold; } /** * Accessor for the failure threshold used to determine when to decrease rho. The default is 5. * * @return The failure threshold. */ public int getFailureThreshold() { return failureThreshold; } /** * Sets the multiplication coefficient used to increase rho. The default is 1.2. * * @param rhoExpandCoefficient The rho expansion coefficient */ public void setRhoExpandCoefficient(double rhoExpandCoefficient) { this.rhoExpandCoefficient = rhoExpandCoefficient; } /** * Accessor for the multiplication coefficient used to increase rho. * * @return The rho expansion coefficient. */ public double getRhoExpandCoefficient() { return rhoExpandCoefficient; } /** * Sets the multiplication coefficient used to decrease rho. The default is 0.5. * * @param rhoContractCoefficient The rho contraction coefficient. */ public void setRhoContractCoefficient(double rhoContractCoefficient) { this.rhoContractCoefficient = rhoContractCoefficient; } /** * Accessor for the multiplication coefficient used to decrease rho. * * @return The rho contration coefficient. */ public double getRhoContractCoefficient() { return rhoContractCoefficient; } public void updateControlParameters() { // TODO Auto-generated method stub } }
true
true
public void updateVelocity(Particle particle) { if (particle.getNeighbourhoodBest().getId() == particle.getId()) { double rho = GCDecorator.extract(particle).getRho(); Vector velocity = (Vector) particle.getVelocity(); Vector nBestPosition = (Vector) particle.getNeighbourhoodBest().getBestPosition(); PSO pso = (PSO) Algorithm.get(); Vector swarmBestPosition = (Vector) pso.getBestParticle().getPosition(); for (int i = 0; i < particle.getDimension(); ++i) { double result = nBestPosition.getReal(i) - swarmBestPosition.getReal(i) + standard.getInertiaWeight().getParameter() * velocity.getReal(i) + rho * (1 - 2 * rhoRandomGenerator.nextFloat()); velocity.setReal(i, result); } } else { standard.updateVelocity(particle); } }
public void updateVelocity(Particle particle) { if (particle.getNeighbourhoodBest().getId().equals(particle.getId())) { double rho = GCDecorator.extract(particle).getRho(); Vector velocity = (Vector) particle.getVelocity(); Vector nBestPosition = (Vector) particle.getNeighbourhoodBest().getBestPosition(); PSO pso = (PSO) Algorithm.get(); Vector swarmBestPosition = (Vector) pso.getBestParticle().getPosition(); for (int i = 0; i < particle.getDimension(); ++i) { double result = nBestPosition.getReal(i) - swarmBestPosition.getReal(i) + standard.getInertiaWeight().getParameter() * velocity.getReal(i) + rho * (1 - 2 * rhoRandomGenerator.nextFloat()); velocity.setReal(i, result); } } else { standard.updateVelocity(particle); } }
diff --git a/src/com/google/bitcoin/examples/FetchBlock.java b/src/com/google/bitcoin/examples/FetchBlock.java index c2809ed..4747a82 100644 --- a/src/com/google/bitcoin/examples/FetchBlock.java +++ b/src/com/google/bitcoin/examples/FetchBlock.java @@ -1,51 +1,55 @@ /* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.bitcoin.examples; import com.google.bitcoin.core.*; import com.google.bitcoin.store.BlockStore; import com.google.bitcoin.store.MemoryBlockStore; import java.net.InetAddress; import java.util.concurrent.Future; /** * Downloads the block given a block hash from the localhost node and prints it out. */ public class FetchBlock { public static void main(String[] args) throws Exception { System.out.println("Connecting to node"); final NetworkParameters params = NetworkParameters.prodNet(); BlockStore blockStore = new MemoryBlockStore(params); BlockChain chain = new BlockChain(params, blockStore); final Peer peer = new Peer(params, new PeerAddress(InetAddress.getLocalHost()), chain); peer.connect(); new Thread(new Runnable() { public void run() { - peer.run(); + try { + peer.run(); + } catch (PeerException e) { + throw new RuntimeException(e); + } } }).start(); Sha256Hash blockHash = new Sha256Hash(args[0]); Future<Block> future = peer.getBlock(blockHash); System.out.println("Waiting for node to send us the requested block: " + blockHash); Block block = future.get(); System.out.println(block); peer.disconnect(); } }
true
true
public static void main(String[] args) throws Exception { System.out.println("Connecting to node"); final NetworkParameters params = NetworkParameters.prodNet(); BlockStore blockStore = new MemoryBlockStore(params); BlockChain chain = new BlockChain(params, blockStore); final Peer peer = new Peer(params, new PeerAddress(InetAddress.getLocalHost()), chain); peer.connect(); new Thread(new Runnable() { public void run() { peer.run(); } }).start(); Sha256Hash blockHash = new Sha256Hash(args[0]); Future<Block> future = peer.getBlock(blockHash); System.out.println("Waiting for node to send us the requested block: " + blockHash); Block block = future.get(); System.out.println(block); peer.disconnect(); }
public static void main(String[] args) throws Exception { System.out.println("Connecting to node"); final NetworkParameters params = NetworkParameters.prodNet(); BlockStore blockStore = new MemoryBlockStore(params); BlockChain chain = new BlockChain(params, blockStore); final Peer peer = new Peer(params, new PeerAddress(InetAddress.getLocalHost()), chain); peer.connect(); new Thread(new Runnable() { public void run() { try { peer.run(); } catch (PeerException e) { throw new RuntimeException(e); } } }).start(); Sha256Hash blockHash = new Sha256Hash(args[0]); Future<Block> future = peer.getBlock(blockHash); System.out.println("Waiting for node to send us the requested block: " + blockHash); Block block = future.get(); System.out.println(block); peer.disconnect(); }
diff --git a/src/main/java/knapsack/Item.java b/src/main/java/knapsack/Item.java index 13aecc9..28eec9c 100644 --- a/src/main/java/knapsack/Item.java +++ b/src/main/java/knapsack/Item.java @@ -1,18 +1,18 @@ package main.java.knapsack; public class Item { int value; int weight; int lbl; public Item(int value, int weight, int name) { if (weight <= 0) - throw new IllegalArgumentException("weight of item should be positive "); + throw new IllegalArgumentException("weight of item should be positive"); if (value <= 0) - throw new IllegalArgumentException("value of item should be positive "); + throw new IllegalArgumentException("value of item should be positive"); this.value = value; this.weight = weight; this.lbl = name; } }
false
true
public Item(int value, int weight, int name) { if (weight <= 0) throw new IllegalArgumentException("weight of item should be positive "); if (value <= 0) throw new IllegalArgumentException("value of item should be positive "); this.value = value; this.weight = weight; this.lbl = name; }
public Item(int value, int weight, int name) { if (weight <= 0) throw new IllegalArgumentException("weight of item should be positive"); if (value <= 0) throw new IllegalArgumentException("value of item should be positive"); this.value = value; this.weight = weight; this.lbl = name; }
diff --git a/ananya-kilkari-functional-tests/src/test/java/org/motechproject/ananya/kilkari/functional/test/CustomerNotAroundThePhoneFunctionalTest.java b/ananya-kilkari-functional-tests/src/test/java/org/motechproject/ananya/kilkari/functional/test/CustomerNotAroundThePhoneFunctionalTest.java index f52057fa..efdece85 100644 --- a/ananya-kilkari-functional-tests/src/test/java/org/motechproject/ananya/kilkari/functional/test/CustomerNotAroundThePhoneFunctionalTest.java +++ b/ananya-kilkari-functional-tests/src/test/java/org/motechproject/ananya/kilkari/functional/test/CustomerNotAroundThePhoneFunctionalTest.java @@ -1,50 +1,50 @@ package org.motechproject.ananya.kilkari.functional.test; import org.joda.time.DateTime; import org.junit.Test; import org.motechproject.ananya.kilkari.functional.test.builder.SubscriptionDataBuilder; import org.motechproject.ananya.kilkari.functional.test.domain.SubscriptionData; import org.motechproject.ananya.kilkari.functional.test.utils.BaseFunctionalTest; import org.motechproject.ananya.kilkari.subscription.repository.KilkariPropertiesData; import org.springframework.beans.factory.annotation.Autowired; import static org.motechproject.ananya.kilkari.functional.test.Actions.*; public class CustomerNotAroundThePhoneFunctionalTest extends BaseFunctionalTest { @Autowired private KilkariPropertiesData kilkariProperties; @Test public void shouldRetryDeliveryOfMessagesWhenTheSubscriberDoesNotReceiveMessagesOrCallIsNotMade() throws Exception { System.out.println("Now running shouldRetryDeliveryOfMessagesWhenTheSubscriberDoesNotReceiveMessagesOrCallIsNotMade"); int scheduleDeltaDays = kilkariProperties.getCampaignScheduleDeltaDays(); int deltaMinutes = kilkariProperties.getCampaignScheduleDeltaMinutes(); DateTime futureDateForFirstCampaignAlert = DateTime.now().plusDays(scheduleDeltaDays).plusMinutes(deltaMinutes + 1); - DateTime futureDateForFirstDayFirstSlot = futureDateForFirstCampaignAlert.plusDays(1).withHourOfDay(13).withMinuteOfHour(30); - DateTime futureDateForFirstDaySecondSlot = futureDateForFirstCampaignAlert.plusDays(1).withHourOfDay(18).withMinuteOfHour(30); - DateTime futureDateForSecondDayFirstSlot = futureDateForFirstDaySecondSlot.plusDays(1).withHourOfDay(13).withMinuteOfHour(30); + DateTime futureDateForFirstDayFirstSlot = futureDateForFirstCampaignAlert.plusDays(1).withHourOfDay(11).withMinuteOfHour(45); + DateTime futureDateForFirstDaySecondSlot = futureDateForFirstCampaignAlert.plusDays(1).withHourOfDay(16).withMinuteOfHour(45); + DateTime futureDateForSecondDayFirstSlot = futureDateForFirstDaySecondSlot.plusDays(1).withHourOfDay(11).withMinuteOfHour(45); String week1 = "WEEK1"; SubscriptionData subscriptionData = new SubscriptionDataBuilder().withDefaults().build(); when(callCenter).subscribes(subscriptionData); and(subscriptionManager).activates(subscriptionData); and(time).isMovedToFuture(futureDateForFirstCampaignAlert); then(user).messageIsReady(subscriptionData, week1); and(time).isMovedToFuture(futureDateForFirstDayFirstSlot); then(user).messageWasDeliveredDuringFirstSlot(subscriptionData, week1); when(obd).reportsUserDidNotPickUpTheCall(subscriptionData, week1); and(user).resetOnMobileOBDVerifier(); and(time).isMovedToFuture(futureDateForFirstDaySecondSlot); then(user).messageWasDeliveredDuringSecondSlot(subscriptionData, week1); when(obd).doesNotCallTheUser(subscriptionData, week1); and(user).resetOnMobileOBDVerifier(); and(time).isMovedToFuture(futureDateForSecondDayFirstSlot); then(user).messageWasDeliveredDuringFirstSlot(subscriptionData, week1); } }
true
true
public void shouldRetryDeliveryOfMessagesWhenTheSubscriberDoesNotReceiveMessagesOrCallIsNotMade() throws Exception { System.out.println("Now running shouldRetryDeliveryOfMessagesWhenTheSubscriberDoesNotReceiveMessagesOrCallIsNotMade"); int scheduleDeltaDays = kilkariProperties.getCampaignScheduleDeltaDays(); int deltaMinutes = kilkariProperties.getCampaignScheduleDeltaMinutes(); DateTime futureDateForFirstCampaignAlert = DateTime.now().plusDays(scheduleDeltaDays).plusMinutes(deltaMinutes + 1); DateTime futureDateForFirstDayFirstSlot = futureDateForFirstCampaignAlert.plusDays(1).withHourOfDay(13).withMinuteOfHour(30); DateTime futureDateForFirstDaySecondSlot = futureDateForFirstCampaignAlert.plusDays(1).withHourOfDay(18).withMinuteOfHour(30); DateTime futureDateForSecondDayFirstSlot = futureDateForFirstDaySecondSlot.plusDays(1).withHourOfDay(13).withMinuteOfHour(30); String week1 = "WEEK1"; SubscriptionData subscriptionData = new SubscriptionDataBuilder().withDefaults().build(); when(callCenter).subscribes(subscriptionData); and(subscriptionManager).activates(subscriptionData); and(time).isMovedToFuture(futureDateForFirstCampaignAlert); then(user).messageIsReady(subscriptionData, week1); and(time).isMovedToFuture(futureDateForFirstDayFirstSlot); then(user).messageWasDeliveredDuringFirstSlot(subscriptionData, week1); when(obd).reportsUserDidNotPickUpTheCall(subscriptionData, week1); and(user).resetOnMobileOBDVerifier(); and(time).isMovedToFuture(futureDateForFirstDaySecondSlot); then(user).messageWasDeliveredDuringSecondSlot(subscriptionData, week1); when(obd).doesNotCallTheUser(subscriptionData, week1); and(user).resetOnMobileOBDVerifier(); and(time).isMovedToFuture(futureDateForSecondDayFirstSlot); then(user).messageWasDeliveredDuringFirstSlot(subscriptionData, week1); }
public void shouldRetryDeliveryOfMessagesWhenTheSubscriberDoesNotReceiveMessagesOrCallIsNotMade() throws Exception { System.out.println("Now running shouldRetryDeliveryOfMessagesWhenTheSubscriberDoesNotReceiveMessagesOrCallIsNotMade"); int scheduleDeltaDays = kilkariProperties.getCampaignScheduleDeltaDays(); int deltaMinutes = kilkariProperties.getCampaignScheduleDeltaMinutes(); DateTime futureDateForFirstCampaignAlert = DateTime.now().plusDays(scheduleDeltaDays).plusMinutes(deltaMinutes + 1); DateTime futureDateForFirstDayFirstSlot = futureDateForFirstCampaignAlert.plusDays(1).withHourOfDay(11).withMinuteOfHour(45); DateTime futureDateForFirstDaySecondSlot = futureDateForFirstCampaignAlert.plusDays(1).withHourOfDay(16).withMinuteOfHour(45); DateTime futureDateForSecondDayFirstSlot = futureDateForFirstDaySecondSlot.plusDays(1).withHourOfDay(11).withMinuteOfHour(45); String week1 = "WEEK1"; SubscriptionData subscriptionData = new SubscriptionDataBuilder().withDefaults().build(); when(callCenter).subscribes(subscriptionData); and(subscriptionManager).activates(subscriptionData); and(time).isMovedToFuture(futureDateForFirstCampaignAlert); then(user).messageIsReady(subscriptionData, week1); and(time).isMovedToFuture(futureDateForFirstDayFirstSlot); then(user).messageWasDeliveredDuringFirstSlot(subscriptionData, week1); when(obd).reportsUserDidNotPickUpTheCall(subscriptionData, week1); and(user).resetOnMobileOBDVerifier(); and(time).isMovedToFuture(futureDateForFirstDaySecondSlot); then(user).messageWasDeliveredDuringSecondSlot(subscriptionData, week1); when(obd).doesNotCallTheUser(subscriptionData, week1); and(user).resetOnMobileOBDVerifier(); and(time).isMovedToFuture(futureDateForSecondDayFirstSlot); then(user).messageWasDeliveredDuringFirstSlot(subscriptionData, week1); }
diff --git a/src/main/javassist/bytecode/annotation/MemberValue.java b/src/main/javassist/bytecode/annotation/MemberValue.java index 5ce70cb..3122eda 100644 --- a/src/main/javassist/bytecode/annotation/MemberValue.java +++ b/src/main/javassist/bytecode/annotation/MemberValue.java @@ -1,90 +1,90 @@ /* * Javassist, a Java-bytecode translator toolkit. * Copyright (C) 2004 Bill Burke. All Rights Reserved. * * 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. Alternatively, the contents of this file may be used under * the terms of the GNU Lesser General Public License Version 2.1 or later. * * 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. */ package javassist.bytecode.annotation; import javassist.ClassPool; import javassist.bytecode.ConstPool; import javassist.bytecode.Descriptor; import java.io.IOException; import java.lang.reflect.Array; import java.lang.reflect.Method; /** * The value of a member declared in an annotation. * * @see Annotation#getMemberValue(String) * @author <a href="mailto:[email protected]">Bill Burke</a> * @author Shigeru Chiba */ public abstract class MemberValue { ConstPool cp; char tag; MemberValue(char tag, ConstPool cp) { this.cp = cp; this.tag = tag; } /** * Returns the value. If the value type is a primitive type, the * returned value is boxed. */ abstract Object getValue(ClassLoader cl, ClassPool cp, Method m) throws ClassNotFoundException; abstract Class getType(ClassLoader cl) throws ClassNotFoundException; static Class loadClass(ClassLoader cl, String classname) throws ClassNotFoundException, NoSuchClassError { try { return Class.forName(convertFromArray(classname), true, cl); } catch (LinkageError e) { throw new NoSuchClassError(classname, e); } } private static String convertFromArray(String classname) { -// int index = classname.indexOf("[]"); -// if (index != -1) -// { -// String rawType = classname.substring(0, index); -// StringBuffer sb = new StringBuffer(Descriptor.of(rawType)); -// while (index != -1) -// { -// sb.insert(0, "["); -// index = classname.indexOf("[]", index + 1); -// } -// return sb.toString().replace('/', '.'); -// } + int index = classname.indexOf("[]"); + if (index != -1) + { + String rawType = classname.substring(0, index); + StringBuffer sb = new StringBuffer(Descriptor.of(rawType)); + while (index != -1) + { + sb.insert(0, "["); + index = classname.indexOf("[]", index + 1); + } + return sb.toString().replace('/', '.'); + } return classname; } /** * Accepts a visitor. */ public abstract void accept(MemberValueVisitor visitor); /** * Writes the value. */ public abstract void write(AnnotationsWriter w) throws IOException; }
true
true
private static String convertFromArray(String classname) { // int index = classname.indexOf("[]"); // if (index != -1) // { // String rawType = classname.substring(0, index); // StringBuffer sb = new StringBuffer(Descriptor.of(rawType)); // while (index != -1) // { // sb.insert(0, "["); // index = classname.indexOf("[]", index + 1); // } // return sb.toString().replace('/', '.'); // } return classname; }
private static String convertFromArray(String classname) { int index = classname.indexOf("[]"); if (index != -1) { String rawType = classname.substring(0, index); StringBuffer sb = new StringBuffer(Descriptor.of(rawType)); while (index != -1) { sb.insert(0, "["); index = classname.indexOf("[]", index + 1); } return sb.toString().replace('/', '.'); } return classname; }
diff --git a/resthub-samples/roundtable/src/main/java/org/resthub/roundtable/domain/dao/impl/jpa/VoteDaoImpl.java b/resthub-samples/roundtable/src/main/java/org/resthub/roundtable/domain/dao/impl/jpa/VoteDaoImpl.java index 0704d7e0..b7ba782b 100644 --- a/resthub-samples/roundtable/src/main/java/org/resthub/roundtable/domain/dao/impl/jpa/VoteDaoImpl.java +++ b/resthub-samples/roundtable/src/main/java/org/resthub/roundtable/domain/dao/impl/jpa/VoteDaoImpl.java @@ -1,28 +1,28 @@ package org.resthub.roundtable.domain.dao.impl.jpa; import javax.inject.Named; import javax.persistence.Query; import org.resthub.roundtable.domain.dao.VoteDao; import org.resthub.roundtable.domain.model.Poll; import org.resthub.roundtable.domain.model.Vote; import org.resthub.core.domain.dao.jpa.AbstractJpaResourceDao; /** * {@inheritDoc} */ @Named("voteDao") public class VoteDaoImpl extends AbstractJpaResourceDao<Vote> implements VoteDao { /** * {@inheritDoc} */ @Override public boolean exist(String voter, Poll poll) { final Query query = em.createNamedQuery("existVote"); query.setParameter("voter", voter); query.setParameter("pid", poll.getId()); - return ((Long) query.getSingleResult() >= 1) ? true : false; + return ((Long) query.getSingleResult() >= 1); } }
true
true
public boolean exist(String voter, Poll poll) { final Query query = em.createNamedQuery("existVote"); query.setParameter("voter", voter); query.setParameter("pid", poll.getId()); return ((Long) query.getSingleResult() >= 1) ? true : false; }
public boolean exist(String voter, Poll poll) { final Query query = em.createNamedQuery("existVote"); query.setParameter("voter", voter); query.setParameter("pid", poll.getId()); return ((Long) query.getSingleResult() >= 1); }
diff --git a/enablers/sip-publication-client/sbb/src/main/java/org/mobicents/slee/enabler/sip/PublicationClientChildSbb.java b/enablers/sip-publication-client/sbb/src/main/java/org/mobicents/slee/enabler/sip/PublicationClientChildSbb.java index 0e9120301..51248ed58 100644 --- a/enablers/sip-publication-client/sbb/src/main/java/org/mobicents/slee/enabler/sip/PublicationClientChildSbb.java +++ b/enablers/sip-publication-client/sbb/src/main/java/org/mobicents/slee/enabler/sip/PublicationClientChildSbb.java @@ -1,800 +1,800 @@ package org.mobicents.slee.enabler.sip; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sip.ClientTransaction; import javax.sip.InvalidArgumentException; import javax.sip.ResponseEvent; import javax.sip.TimeoutEvent; import javax.sip.TransportNotSupportedException; import javax.sip.address.Address; import javax.sip.address.AddressFactory; import javax.sip.address.URI; import javax.sip.header.CSeqHeader; import javax.sip.header.CallIdHeader; import javax.sip.header.ContentTypeHeader; import javax.sip.header.EventHeader; import javax.sip.header.ExpiresHeader; import javax.sip.header.FromHeader; import javax.sip.header.HeaderFactory; import javax.sip.header.MaxForwardsHeader; import javax.sip.header.MinExpiresHeader; import javax.sip.header.RouteHeader; import javax.sip.header.SIPETagHeader; import javax.sip.header.SIPIfMatchHeader; import javax.sip.header.ToHeader; import javax.sip.header.ViaHeader; import javax.sip.message.MessageFactory; import javax.sip.message.Request; import javax.sip.message.Response; import javax.slee.ActivityContextInterface; import javax.slee.CreateException; import javax.slee.RolledBackContext; import javax.slee.Sbb; import javax.slee.SbbContext; import javax.slee.SbbLocalObject; import javax.slee.facilities.TimerEvent; import javax.slee.facilities.TimerID; import javax.slee.facilities.TimerOptions; import javax.slee.facilities.Tracer; import javax.slee.nullactivity.NullActivity; import javax.slee.resource.ResourceAdaptorTypeID; import net.java.slee.resource.sip.SipActivityContextInterfaceFactory; import net.java.slee.resource.sip.SleeSipProvider; import org.mobicents.slee.ActivityContextInterfaceExt; import org.mobicents.slee.SbbContextExt; /** * SIP Publication Client SLEE Enabler. It creates PUBLISH interaction and manages * it. It automatically refreshes publication based on content of ECS/PA response. It keeps map of ETag to publish interaction. * * @author baranowb * @author martins */ public abstract class PublicationClientChildSbb implements Sbb, PublicationClientChild { private static final int DEFAULT_EXPIRES_DRIFT = 15; private static final ResourceAdaptorTypeID sipResourceAdaptorTypeID = new ResourceAdaptorTypeID("JAIN SIP","javax.sip","1.2"); private static final TimerOptions TIMER_OPTIONS = new TimerOptions(); private static Tracer tracer; protected SbbContextExt sbbContext; //sip ra protected SipActivityContextInterfaceFactory sipActivityContextInterfaceFactory = null; protected SleeSipProvider sleeSipProvider = null; //sip stuff protected MessageFactory messageFactory; protected AddressFactory addressFactory; protected HeaderFactory headerFactory; protected Address ecsAddress; protected int expiresDrift = DEFAULT_EXPIRES_DRIFT; // ////////////////// // SBB LO methods // // ////////////////// @Override public void setParentSbb(PublicationClientParentSbbLocalObject parent) { setParentSbbCMP(parent); } @Override public String getEntity() { return this.getEntityCMP(); } @Override public String getETag() { return this.getETagCMP(); } private boolean isBusy() { return this.getPublishRequestTypeCMP() != null; } @Override public void newPublication(String entity, String eventPackage, String document, String contentType, String contentSubType, int expires) { SbbLocalObject sbbLocalObject = sbbContext.getSbbLocalObject(); try { Request r = createNewPublishRequest(entity,eventPackage,expires,contentType,contentSubType,document); ClientTransaction ctx = this.sleeSipProvider.getNewClientTransaction(r); ActivityContextInterface aci = this.sipActivityContextInterfaceFactory.getActivityContextInterface(ctx); aci.attach(sbbLocalObject); ctx.sendRequest(); // set cmps this.setPublishRequestTypeCMP(PublishRequestType.NEW); this.setEntityCMP(entity); this.setEventPackageCMP(eventPackage); } catch (Throwable e) { if(tracer.isSevereEnabled()) { tracer.severe("Failed to create publication", e); } getParentSbbCMP().newPublicationFailed(Response.SERVER_INTERNAL_ERROR, (PublicationClientChildSbbLocalObject) sbbLocalObject); } } @Override public void modifyPublication(String document, String contentType, String contentSubType, int expires) { // delay the request in case there is another ongoing request if (isBusy()) { setPostponedRequestCMP(new PostponedModifyPublicationRequest(document, contentType, contentSubType, expires)); return; } cancelExpiresTimer(false); //issue request. SbbLocalObject sbbLocalObject = sbbContext.getSbbLocalObject(); try { Request r = createUpdatePublishRequest( contentType, contentSubType, document); ClientTransaction ctx = this.sleeSipProvider.getNewClientTransaction(r); ActivityContextInterface aci = this.sipActivityContextInterfaceFactory.getActivityContextInterface(ctx); aci.attach(sbbLocalObject); ctx.sendRequest(); setPublishRequestTypeCMP(PublishRequestType.UPDATE); } catch (Throwable e) { if(tracer.isSevereEnabled()) { tracer.severe("Failed to modify publication", e); } getParentSbbCMP().modifyPublicationFailed(Response.SERVER_INTERNAL_ERROR, (PublicationClientChildSbbLocalObject) sbbLocalObject); } } @Override public void removePublication() { if(isBusy()) { setPostponedRequestCMP(new PostponedRemovePublicationRequest()); return; } cancelExpiresTimer(true); //issue request. SbbLocalObject sbbLocalObject = sbbContext.getSbbLocalObject(); try { Request r = createRemovePublishRequest(); ClientTransaction ctx = this.sleeSipProvider.getNewClientTransaction(r); ActivityContextInterface aci = this.sipActivityContextInterfaceFactory.getActivityContextInterface(ctx); aci.attach(sbbLocalObject); ctx.sendRequest(); setPublishRequestTypeCMP(PublishRequestType.REMOVE); } catch (Throwable e) { if(tracer.isSevereEnabled()) { tracer.severe("Failed to remove publication", e); } getParentSbbCMP().removePublicationFailed(Response.SERVER_INTERNAL_ERROR, (PublicationClientChildSbbLocalObject) sbbLocalObject); } } ///////////////// // CMP Methods // ///////////////// public abstract void setParentSbbCMP(PublicationClientParentSbbLocalObject parent); public abstract PublicationClientParentSbbLocalObject getParentSbbCMP(); public abstract void setEntityCMP(String d); public abstract String getEntityCMP(); public abstract void setEventPackageCMP(String eventPackage); public abstract String getEventPackageCMP( ); public abstract void setExpiresCMP( int expires); public abstract int getExpiresCMP(); public abstract void setETagCMP(String d); public abstract String getETagCMP(); public abstract void setPostponedRequestCMP(PostponedRequest pr); public abstract PostponedRequest getPostponedRequestCMP(); //type of ongoing request. public abstract void setPublishRequestTypeCMP(PublishRequestType t); public abstract PublishRequestType getPublishRequestTypeCMP(); //////////////////// // Event handlers // //////////////////// public void onSuccessRespEvent(ResponseEvent event, ActivityContextInterface aci) { if (tracer.isFineEnabled()) tracer.fine("Received 2xx (SUCCESS) response:\n"+event.getResponse()); final SbbLocalObject sbbLocalObject = sbbContext.getSbbLocalObject(); aci.detach(sbbLocalObject); final Response response = event.getResponse(); final SIPETagHeader sipeTagHeader = (SIPETagHeader) response.getHeader(SIPETagHeader.NAME); if(sipeTagHeader != null) { this.setETagCMP(sipeTagHeader.getETag()); } final PublishRequestType type = getPublishRequestTypeCMP(); if (type != PublishRequestType.REMOVE) { final ExpiresHeader expiresHeader = (ExpiresHeader) response.getHeader(ExpiresHeader.NAME); if(expiresHeader!=null && expiresHeader.getExpires() != 0) { //update expires time. setExpiresCMP(expiresHeader.getExpires()); startExpiresTimer(); } } PostponedRequest postponedRequest = null; setPublishRequestTypeCMP(null); try{ switch (type) { case NEW: postponedRequest = getPostponedRequestCMP(); this.getParentSbbCMP().newPublicationSucceed((PublicationClientChildSbbLocalObject) sbbLocalObject); break; case REFRESH: postponedRequest = getPostponedRequestCMP(); break; case UPDATE: postponedRequest = getPostponedRequestCMP(); this.getParentSbbCMP().modifyPublicationSucceed((PublicationClientChildSbbLocalObject) sbbLocalObject); break; case REMOVE: this.getParentSbbCMP().removePublicationSucceed((PublicationClientChildSbbLocalObject) sbbLocalObject); break; } } catch(Exception e) { if(tracer.isSevereEnabled()) { tracer.severe("Exception in publication parent!", e); } } if (postponedRequest != null) { // refresh may be concurrent with another request, if there is a // postponed request resume it now postponedRequest.resume(this); } } public void onClientErrorRespEvent(ResponseEvent event, ActivityContextInterface aci) { if (tracer.isFineEnabled()) tracer.fine("Received 4xx (CLIENT ERROR) response:\n"+event.getResponse()); aci.detach(sbbContext.getSbbLocalObject()); final Response response = event.getResponse(); int statusCode = response.getStatusCode(); if(statusCode == 423) { final MinExpiresHeader minExpires = (MinExpiresHeader) response.getHeader(MinExpiresHeader.NAME); // If an EPA receives a 423 (Interval Too Brief) response to a PUBLISH // request, it MAY retry the publication after changing the expiration // interval in the Expires header field to be equal to or greater than // the expiration interval within the Min-Expires header field of the // 423 (Interval Too Brief) response. //in this case, we may issue another command, let PublishRequestType type = getPublishRequestTypeCMP(); setPublishRequestTypeCMP(null); Request request = null; ContentTypeHeader cTypeHeader = null; switch (type) { case NEW: request = event.getClientTransaction().getRequest(); cTypeHeader = (ContentTypeHeader) request.getHeader(ContentTypeHeader.NAME); newPublication(getEntityCMP(), getEventPackageCMP(), (String) request.getContent(), cTypeHeader.getContentType(), cTypeHeader.getContentSubType(), minExpires.getExpires()); break; case UPDATE: request = event.getClientTransaction().getRequest(); cTypeHeader = (ContentTypeHeader) request.getHeader(ContentTypeHeader.NAME); modifyPublication((String) request.getContent(), cTypeHeader.getContentType(), cTypeHeader.getContentSubType(), minExpires.getExpires()); break; case REFRESH: setExpiresCMP(minExpires.getExpires()); //?? doRefresh(); break; case REMOVE: //should not happen? if(tracer.isSevereEnabled()) { tracer.severe("Received 423 on REMOVE request!"); } try{ - this.getParentSbbCMP().refreshPublicationFailed(statusCode, (PublicationClientChildSbbLocalObject) this.sbbContext.getSbbLocalObject()); + this.getParentSbbCMP().removePublicationFailed(statusCode, (PublicationClientChildSbbLocalObject) this.sbbContext.getSbbLocalObject()); } catch(Exception e) { if(tracer.isSevereEnabled()) { tracer.severe("Exception in publication parent!", e); } } break; } } else { //ALL OTHER cases == very bad, can't be repaired? // If an EPA receives a 412 (Conditional Request Failed) response, it // MUST NOT reattempt the PUBLISH request. Instead, to publish event // state, the EPA SHOULD perform an initial publication, i.e., a PUBLISH // request without a SIP-If-Match header field, as described in Section // 4.2. The EPA MUST also discard the entity-tag that produced this // error response. // 1. The ESC inspects the Request-URI to determine whether this request // is targeted to a resource for which the ESC is responsible for // maintaining event state. If not, the ESC MUST return a 404 (Not // Found) response and skip the remaining steps. // The ESC examines the Event header field of the PUBLISH request. // If the Event header field is missing or contains an event package // which the ESC does not support, the ESC MUST respond to the // PUBLISH request with a 489 (Bad Event) response, and skip the // remaining steps. // * Else, if the request has a SIP-If-Match header field, the ESC // checks whether the header field contains a single entity-tag. // If not, the request is invalid, and the ESC MUST return with a // 400 (Invalid Request) response and skip the remaining steps. // 5. The ESC processes the published event state contained in the body // of the PUBLISH request. If the content type of the request does // not match the event package, or is not understood by the ESC, the // ESC MUST reject the request with an appropriate response, such as // 415 (Unsupported Media Type), and skip the remainder of the steps. handleFailure(statusCode,aci); } } public void onServerErrorRespEvent(ResponseEvent event, ActivityContextInterface aci) { if (tracer.isFineEnabled()) tracer.fine("Received 5xx (SERVER ERROR) response:\n"+event.getResponse()); aci.detach(sbbContext.getSbbLocalObject()); handleFailure(event.getResponse().getStatusCode(),aci); } public void onGlobalFailureRespEvent(ResponseEvent event, ActivityContextInterface aci) { if (tracer.isFineEnabled()) tracer.fine("Received 6xx (GLOBAL FAILURE) response:\n"+event.getResponse()); aci.detach(sbbContext.getSbbLocalObject()); handleFailure(event.getResponse().getStatusCode(),aci); } public void onTimerEvent(TimerEvent event, ActivityContextInterface aci) { // refresh time? if(isBusy()) { if(tracer.isFineEnabled()) { tracer.fine("Performing "+getPublishRequestTypeCMP()+", skipping refresh."); } return; } if (tracer.isFineEnabled()) tracer.fine("Refreshing publication."); doRefresh(); } public void onTransactionTimeoutEvent(TimeoutEvent event,ActivityContextInterface aci) { if (tracer.isFineEnabled()) tracer.fine("Received Tx Timeout"); aci.detach(sbbContext.getSbbLocalObject()); handleFailure(Response.SERVER_TIMEOUT,aci); } //////////////////////////// // Private helper methods // //////////////////////////// private ActivityContextInterface getTimerACI() { for(ActivityContextInterface aci : this.sbbContext.getActivities()) { if(aci.getActivity() instanceof NullActivity) { return aci; } } return null; } /** * */ private void startExpiresTimer() { ActivityContextInterface naAci = getTimerACI(); if (naAci == null) { // create activity for this publication; NullActivity na = sbbContext.getNullActivityFactory().createNullActivity(); naAci = sbbContext.getNullActivityContextInterfaceFactory().getActivityContextInterface(na); // attach. naAci.attach(this.sbbContext.getSbbLocalObject()); } long expires = this.getExpiresCMP(); //lets schedule a bit earlier. 5s? if(expires-expiresDrift >0) { expires-=expiresDrift; } sbbContext.getTimerFacility().setTimer(naAci,null,System.currentTimeMillis()+expires*1000,TIMER_OPTIONS); } /** * */ private void cancelExpiresTimer(boolean detachActivity) { ActivityContextInterface naAci = getTimerACI(); if (naAci != null) { ActivityContextInterfaceExt naAciExt = (ActivityContextInterfaceExt) naAci; TimerID[] timerIDs = naAciExt.getTimers(); if (timerIDs.length > 0) { sbbContext.getTimerFacility().cancelTimer(timerIDs[0]); } if (detachActivity) { naAci.detach(sbbContext.getSbbLocalObject()); } } } /** * @param expires * @param eventPackage * @param entity * @param contentType * @param contentSubType * @param document * @return * @throws ParseException * @throws TransportNotSupportedException * @throws InvalidArgumentException */ protected Request createPublishRequest(String entity) throws ParseException, TransportNotSupportedException, InvalidArgumentException{ URI entityURI = addressFactory.createURI(entity); Address entityAddress = addressFactory.createAddress(entityURI); FromHeader fromHeader = headerFactory.createFromHeader(entityAddress,null); ToHeader toHeader = headerFactory.createToHeader(entityAddress, null); List<ViaHeader> viaHeaders = new ArrayList<ViaHeader>(); viaHeaders.add(sleeSipProvider.getLocalVia("UDP", null)); // Create a new CallId header CallIdHeader callIdHeader = sleeSipProvider.getNewCallId(); // Create a new Cseq header CSeqHeader cSeqHeader = headerFactory.createCSeqHeader(1L, Request.PUBLISH); // Create a new MaxForwardsHeader MaxForwardsHeader maxForwards = headerFactory.createMaxForwardsHeader(70); //leave it as 70? // Create the request. Request request = messageFactory.createRequest(entityURI, Request.PUBLISH, callIdHeader, cSeqHeader, fromHeader, toHeader, viaHeaders, maxForwards); //add route header? if(this.ecsAddress!=null) { RouteHeader routeHeader = headerFactory.createRouteHeader(this.ecsAddress); request.addHeader(routeHeader); } return request; } /** * @param contentType * @param contentSubType * @param document * @return */ protected Request createNewPublishRequest(String entity, String eventPackage, int expires, String contentType, String contentSubType, String document) throws ParseException, TransportNotSupportedException, InvalidArgumentException { Request request = this.createPublishRequest(entity); //if expires is >0 add it, if not, skip; if(getExpiresCMP()>0) { ExpiresHeader expiresHeader = this.headerFactory.createExpiresHeader(expires); request.addHeader(expiresHeader); } //add custom header EventHeader eventHeader = this.headerFactory.createEventHeader(eventPackage); request.addHeader(eventHeader); //add content ContentTypeHeader contentTypeHeader = this.headerFactory.createContentTypeHeader(contentType, contentSubType); request.setContent(document, contentTypeHeader); return request; } /** * @param contentType * @param contentSubType * @param document * @return */ protected Request createUpdatePublishRequest(String contentType, String contentSubType, String document)throws ParseException, TransportNotSupportedException, InvalidArgumentException { Request request = this.createPublishRequest(getEntity()); //expires always here ExpiresHeader expiresHeader = this.headerFactory.createExpiresHeader(getExpiresCMP()); request.addHeader(expiresHeader); //add SIP-If-Match SIPIfMatchHeader sipIfMatch = this.headerFactory.createSIPIfMatchHeader(getETagCMP()); request.addHeader(sipIfMatch); //add custom header EventHeader eventHeader = this.headerFactory.createEventHeader(getEventPackageCMP()); request.addHeader(eventHeader); //add content ContentTypeHeader contentTypeHeader = this.headerFactory.createContentTypeHeader(contentType, contentSubType); request.setContent(document, contentTypeHeader); return request; } /** * @return */ protected Request createRemovePublishRequest() throws ParseException, TransportNotSupportedException, InvalidArgumentException{ Request request = this.createPublishRequest(getEntity()); //expires always here ExpiresHeader expiresHeader = this.headerFactory.createExpiresHeader(0); request.addHeader(expiresHeader); //add SIP-If-Match SIPIfMatchHeader sipIfMatch = this.headerFactory.createSIPIfMatchHeader(getETagCMP()); request.addHeader(sipIfMatch); //add custom header EventHeader eventHeader = this.headerFactory.createEventHeader(getEventPackageCMP()); request.addHeader(eventHeader); return request; } protected Request createRefreshPublishRequest() throws ParseException, TransportNotSupportedException, InvalidArgumentException{ Request request = this.createPublishRequest(getEntity()); //expires always here ExpiresHeader expiresHeader = this.headerFactory.createExpiresHeader(getExpiresCMP()); request.addHeader(expiresHeader); //add SIP-If-Match SIPIfMatchHeader sipIfMatch = this.headerFactory.createSIPIfMatchHeader(getETagCMP()); request.addHeader(sipIfMatch); //add custom header EventHeader eventHeader = this.headerFactory.createEventHeader(getEventPackageCMP()); request.addHeader(eventHeader); return request; } /** * @param statusCode */ protected void handleFailure(int statusCode,ActivityContextInterface ac) { //fill data we have. PublishRequestType type = getPublishRequestTypeCMP(); if (type != null) { setPublishRequestTypeCMP(null); } try{ switch (type) { case NEW: this.getParentSbbCMP().newPublicationFailed(statusCode, (PublicationClientChildSbbLocalObject) this.sbbContext.getSbbLocalObject()); break; case REFRESH: this.getParentSbbCMP().refreshPublicationFailed(statusCode, (PublicationClientChildSbbLocalObject) this.sbbContext.getSbbLocalObject()); break; case UPDATE: this.getParentSbbCMP().modifyPublicationFailed(statusCode, (PublicationClientChildSbbLocalObject) this.sbbContext.getSbbLocalObject()); break; case REMOVE: this.getParentSbbCMP().removePublicationFailed(statusCode, (PublicationClientChildSbbLocalObject) this.sbbContext.getSbbLocalObject()); break; } } catch(Exception e) { if(tracer.isSevereEnabled()) { tracer.severe("Exception in publication parent!", e); } } } /** * */ protected void doRefresh() { //issue request. SbbLocalObject sbbLocalObject = sbbContext.getSbbLocalObject(); try { final Request r = createRefreshPublishRequest(); final ClientTransaction ctx = this.sleeSipProvider.getNewClientTransaction(r); ActivityContextInterface ctxAci = this.sipActivityContextInterfaceFactory.getActivityContextInterface(ctx); ctxAci.attach(sbbLocalObject); ctx.sendRequest(); setPublishRequestTypeCMP(PublishRequestType.REFRESH); } catch (Throwable e) { if(tracer.isSevereEnabled()) { tracer.severe("Failed to refresh publication", e); } getParentSbbCMP().refreshPublicationFailed(Response.SERVER_INTERNAL_ERROR, (PublicationClientChildSbbLocalObject) sbbLocalObject); } } ////////////////////////////////// // SBB OBJECT LIFECYCLE METHODS // ////////////////////////////////// /* * (non-Javadoc) * * @see javax.slee.Sbb#sbbActivate() */ @Override public void sbbActivate() { } /* * (non-Javadoc) * * @see javax.slee.Sbb#sbbCreate() */ @Override public void sbbCreate() throws CreateException { } /* * (non-Javadoc) * * @see javax.slee.Sbb#sbbExceptionThrown(java.lang.Exception, * java.lang.Object, javax.slee.ActivityContextInterface) */ @Override public void sbbExceptionThrown(Exception arg0, Object arg1, ActivityContextInterface arg2) { } /* * (non-Javadoc) * * @see javax.slee.Sbb#sbbLoad() */ @Override public void sbbLoad() { } /* * (non-Javadoc) * * @see javax.slee.Sbb#sbbPassivate() */ @Override public void sbbPassivate() { } /* * (non-Javadoc) * * @see javax.slee.Sbb#sbbPostCreate() */ @Override public void sbbPostCreate() throws CreateException { } /* * (non-Javadoc) * * @see javax.slee.Sbb#sbbRemove() */ @Override public void sbbRemove() { } /* * (non-Javadoc) * * @see javax.slee.Sbb#sbbRolledBack(javax.slee.RolledBackContext) */ @Override public void sbbRolledBack(RolledBackContext arg0) { } /* * (non-Javadoc) * * @see javax.slee.Sbb#sbbStore() */ @Override public void sbbStore() { } /* * (non-Javadoc) * * @see javax.slee.Sbb#setSbbContext(javax.slee.SbbContext) */ @Override public void setSbbContext(SbbContext sbbContext) { this.sbbContext = (SbbContextExt) sbbContext; if (tracer == null) { tracer = sbbContext.getTracer(PublicationClientChildSbb.class.getSimpleName()); } try { //sip ra this.sipActivityContextInterfaceFactory = (SipActivityContextInterfaceFactory) this.sbbContext.getActivityContextInterfaceFactory(sipResourceAdaptorTypeID); this.sleeSipProvider = (SleeSipProvider) this.sbbContext.getResourceAdaptorInterface(sipResourceAdaptorTypeID, "SipRA"); //sip stuff this.messageFactory = this.sleeSipProvider.getMessageFactory(); this.addressFactory = this.sleeSipProvider.getAddressFactory(); this.headerFactory = this.sleeSipProvider.getHeaderFactory(); //env, conf Context context = (Context) new InitialContext(); try{ String serverAddress = (String) context.lookup("server.address"); if(serverAddress!=null) { //RFC show entity as SIP URI and ECS address? this.ecsAddress = this.sleeSipProvider.getAddressFactory().createAddress(serverAddress); } } catch(NamingException e) { if(tracer.isInfoEnabled()) { tracer.info("No ECS/PA address to use in Route header."); } } try{ String expireTime = (String) context.lookup("expires.drift"); if(expireTime!=null) { int intExpireTime = Integer.parseInt(expireTime); if(intExpireTime<0) { if(tracer.isInfoEnabled()) { tracer.info("Expire time drift less than zero, using default: "+this.expiresDrift+"s."); } } else { this.expiresDrift = intExpireTime; if(tracer.isInfoEnabled()) { tracer.info("Expire time drift set to: "+this.expiresDrift+"s."); } } } }catch(NamingException e) { if(tracer.isInfoEnabled()) { tracer.info("No Expire time drift, using default: "+this.expiresDrift+"s."); } } } catch (NamingException e) { tracer.severe("Can't set sbb context.", e); } catch (ParseException e) { tracer.severe("Can't set sbb context.", e); } } /* * (non-Javadoc) * * @see javax.slee.Sbb#unsetSbbContext() */ @Override public void unsetSbbContext() { this.sbbContext = null; } }
true
true
public void onClientErrorRespEvent(ResponseEvent event, ActivityContextInterface aci) { if (tracer.isFineEnabled()) tracer.fine("Received 4xx (CLIENT ERROR) response:\n"+event.getResponse()); aci.detach(sbbContext.getSbbLocalObject()); final Response response = event.getResponse(); int statusCode = response.getStatusCode(); if(statusCode == 423) { final MinExpiresHeader minExpires = (MinExpiresHeader) response.getHeader(MinExpiresHeader.NAME); // If an EPA receives a 423 (Interval Too Brief) response to a PUBLISH // request, it MAY retry the publication after changing the expiration // interval in the Expires header field to be equal to or greater than // the expiration interval within the Min-Expires header field of the // 423 (Interval Too Brief) response. //in this case, we may issue another command, let PublishRequestType type = getPublishRequestTypeCMP(); setPublishRequestTypeCMP(null); Request request = null; ContentTypeHeader cTypeHeader = null; switch (type) { case NEW: request = event.getClientTransaction().getRequest(); cTypeHeader = (ContentTypeHeader) request.getHeader(ContentTypeHeader.NAME); newPublication(getEntityCMP(), getEventPackageCMP(), (String) request.getContent(), cTypeHeader.getContentType(), cTypeHeader.getContentSubType(), minExpires.getExpires()); break; case UPDATE: request = event.getClientTransaction().getRequest(); cTypeHeader = (ContentTypeHeader) request.getHeader(ContentTypeHeader.NAME); modifyPublication((String) request.getContent(), cTypeHeader.getContentType(), cTypeHeader.getContentSubType(), minExpires.getExpires()); break; case REFRESH: setExpiresCMP(minExpires.getExpires()); //?? doRefresh(); break; case REMOVE: //should not happen? if(tracer.isSevereEnabled()) { tracer.severe("Received 423 on REMOVE request!"); } try{ this.getParentSbbCMP().refreshPublicationFailed(statusCode, (PublicationClientChildSbbLocalObject) this.sbbContext.getSbbLocalObject()); } catch(Exception e) { if(tracer.isSevereEnabled()) { tracer.severe("Exception in publication parent!", e); } } break; } } else { //ALL OTHER cases == very bad, can't be repaired? // If an EPA receives a 412 (Conditional Request Failed) response, it // MUST NOT reattempt the PUBLISH request. Instead, to publish event // state, the EPA SHOULD perform an initial publication, i.e., a PUBLISH // request without a SIP-If-Match header field, as described in Section // 4.2. The EPA MUST also discard the entity-tag that produced this // error response. // 1. The ESC inspects the Request-URI to determine whether this request // is targeted to a resource for which the ESC is responsible for // maintaining event state. If not, the ESC MUST return a 404 (Not // Found) response and skip the remaining steps. // The ESC examines the Event header field of the PUBLISH request. // If the Event header field is missing or contains an event package // which the ESC does not support, the ESC MUST respond to the // PUBLISH request with a 489 (Bad Event) response, and skip the // remaining steps. // * Else, if the request has a SIP-If-Match header field, the ESC // checks whether the header field contains a single entity-tag. // If not, the request is invalid, and the ESC MUST return with a // 400 (Invalid Request) response and skip the remaining steps. // 5. The ESC processes the published event state contained in the body // of the PUBLISH request. If the content type of the request does // not match the event package, or is not understood by the ESC, the // ESC MUST reject the request with an appropriate response, such as // 415 (Unsupported Media Type), and skip the remainder of the steps. handleFailure(statusCode,aci); } }
public void onClientErrorRespEvent(ResponseEvent event, ActivityContextInterface aci) { if (tracer.isFineEnabled()) tracer.fine("Received 4xx (CLIENT ERROR) response:\n"+event.getResponse()); aci.detach(sbbContext.getSbbLocalObject()); final Response response = event.getResponse(); int statusCode = response.getStatusCode(); if(statusCode == 423) { final MinExpiresHeader minExpires = (MinExpiresHeader) response.getHeader(MinExpiresHeader.NAME); // If an EPA receives a 423 (Interval Too Brief) response to a PUBLISH // request, it MAY retry the publication after changing the expiration // interval in the Expires header field to be equal to or greater than // the expiration interval within the Min-Expires header field of the // 423 (Interval Too Brief) response. //in this case, we may issue another command, let PublishRequestType type = getPublishRequestTypeCMP(); setPublishRequestTypeCMP(null); Request request = null; ContentTypeHeader cTypeHeader = null; switch (type) { case NEW: request = event.getClientTransaction().getRequest(); cTypeHeader = (ContentTypeHeader) request.getHeader(ContentTypeHeader.NAME); newPublication(getEntityCMP(), getEventPackageCMP(), (String) request.getContent(), cTypeHeader.getContentType(), cTypeHeader.getContentSubType(), minExpires.getExpires()); break; case UPDATE: request = event.getClientTransaction().getRequest(); cTypeHeader = (ContentTypeHeader) request.getHeader(ContentTypeHeader.NAME); modifyPublication((String) request.getContent(), cTypeHeader.getContentType(), cTypeHeader.getContentSubType(), minExpires.getExpires()); break; case REFRESH: setExpiresCMP(minExpires.getExpires()); //?? doRefresh(); break; case REMOVE: //should not happen? if(tracer.isSevereEnabled()) { tracer.severe("Received 423 on REMOVE request!"); } try{ this.getParentSbbCMP().removePublicationFailed(statusCode, (PublicationClientChildSbbLocalObject) this.sbbContext.getSbbLocalObject()); } catch(Exception e) { if(tracer.isSevereEnabled()) { tracer.severe("Exception in publication parent!", e); } } break; } } else { //ALL OTHER cases == very bad, can't be repaired? // If an EPA receives a 412 (Conditional Request Failed) response, it // MUST NOT reattempt the PUBLISH request. Instead, to publish event // state, the EPA SHOULD perform an initial publication, i.e., a PUBLISH // request without a SIP-If-Match header field, as described in Section // 4.2. The EPA MUST also discard the entity-tag that produced this // error response. // 1. The ESC inspects the Request-URI to determine whether this request // is targeted to a resource for which the ESC is responsible for // maintaining event state. If not, the ESC MUST return a 404 (Not // Found) response and skip the remaining steps. // The ESC examines the Event header field of the PUBLISH request. // If the Event header field is missing or contains an event package // which the ESC does not support, the ESC MUST respond to the // PUBLISH request with a 489 (Bad Event) response, and skip the // remaining steps. // * Else, if the request has a SIP-If-Match header field, the ESC // checks whether the header field contains a single entity-tag. // If not, the request is invalid, and the ESC MUST return with a // 400 (Invalid Request) response and skip the remaining steps. // 5. The ESC processes the published event state contained in the body // of the PUBLISH request. If the content type of the request does // not match the event package, or is not understood by the ESC, the // ESC MUST reject the request with an appropriate response, such as // 415 (Unsupported Media Type), and skip the remainder of the steps. handleFailure(statusCode,aci); } }
diff --git a/plugin-app/src/main/java/com/my/plugin/app/App.java b/plugin-app/src/main/java/com/my/plugin/app/App.java index 23112a9..1abb241 100644 --- a/plugin-app/src/main/java/com/my/plugin/app/App.java +++ b/plugin-app/src/main/java/com/my/plugin/app/App.java @@ -1,30 +1,30 @@ package com.my.plugin.app; import com.my.plugin.Plugin; import org.eclipse.aether.resolution.ArtifactResult; import java.io.File; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; import static me.smecsia.common.utils.ReflectUtil.classLoaderProxy; public class App { public static void main(String[] args) throws Exception { DependencyResolver resolver = new DependencyResolver(new File(System.getProperty("user.home") + "/.m2/repository")); - DependencyResolver.ResolveResult result = resolver.resolve("com.my.plugin:plugin-impl:jar:1.0-SNAPSHOT"); + DependencyResolver.ResolveResult result = resolver.resolve("com.my.plugin:plugin-impl:jar:0.1-SNAPSHOT"); List<URL> artifactUrls = new ArrayList<URL>(); for (ArtifactResult artRes : result.artifactResults) { artifactUrls.add(artRes.getArtifact().getFile().toURI().toURL()); } final URLClassLoader urlClassLoader = new URLClassLoader(artifactUrls.toArray(new URL[artifactUrls.size()])); Class<?> clazz = urlClassLoader.loadClass("com.my.plugin.impl.PluginAdapter"); final Plugin adapterInstance = classLoaderProxy(urlClassLoader, clazz.newInstance(), Plugin.class); System.out.println("Result: " + adapterInstance.perform(2, 3)); } }
true
true
public static void main(String[] args) throws Exception { DependencyResolver resolver = new DependencyResolver(new File(System.getProperty("user.home") + "/.m2/repository")); DependencyResolver.ResolveResult result = resolver.resolve("com.my.plugin:plugin-impl:jar:1.0-SNAPSHOT"); List<URL> artifactUrls = new ArrayList<URL>(); for (ArtifactResult artRes : result.artifactResults) { artifactUrls.add(artRes.getArtifact().getFile().toURI().toURL()); } final URLClassLoader urlClassLoader = new URLClassLoader(artifactUrls.toArray(new URL[artifactUrls.size()])); Class<?> clazz = urlClassLoader.loadClass("com.my.plugin.impl.PluginAdapter"); final Plugin adapterInstance = classLoaderProxy(urlClassLoader, clazz.newInstance(), Plugin.class); System.out.println("Result: " + adapterInstance.perform(2, 3)); }
public static void main(String[] args) throws Exception { DependencyResolver resolver = new DependencyResolver(new File(System.getProperty("user.home") + "/.m2/repository")); DependencyResolver.ResolveResult result = resolver.resolve("com.my.plugin:plugin-impl:jar:0.1-SNAPSHOT"); List<URL> artifactUrls = new ArrayList<URL>(); for (ArtifactResult artRes : result.artifactResults) { artifactUrls.add(artRes.getArtifact().getFile().toURI().toURL()); } final URLClassLoader urlClassLoader = new URLClassLoader(artifactUrls.toArray(new URL[artifactUrls.size()])); Class<?> clazz = urlClassLoader.loadClass("com.my.plugin.impl.PluginAdapter"); final Plugin adapterInstance = classLoaderProxy(urlClassLoader, clazz.newInstance(), Plugin.class); System.out.println("Result: " + adapterInstance.perform(2, 3)); }
diff --git a/java/test/org/broadinstitute/sting/alignment/AlignerIntegrationTest.java b/java/test/org/broadinstitute/sting/alignment/AlignerIntegrationTest.java index 3e6f9bf67..d258d0481 100644 --- a/java/test/org/broadinstitute/sting/alignment/AlignerIntegrationTest.java +++ b/java/test/org/broadinstitute/sting/alignment/AlignerIntegrationTest.java @@ -1,27 +1,27 @@ package org.broadinstitute.sting.alignment; import org.junit.Test; import org.broadinstitute.sting.WalkerTest; import java.util.Arrays; /** * Integration tests for the aligner. * * @author mhanna * @version 0.1 */ public class AlignerIntegrationTest extends WalkerTest { @Test public void testBasicAlignment() { String md5 = "c6d95d8ae707e78fefdaa7375f130995"; WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec( - "-R /humgen/gsa-scr1/GATK_Data/bwa/human_b36_both.fasta" + + "-R " + b36KGReference + " -T Align" + " -I " + validationDataLocation + "NA12878_Pilot1_20.trimmed.unmapped.bam" + " -ob %s", 1, // just one output file Arrays.asList(md5)); executeTest("testBasicAlignment", spec); } }
true
true
public void testBasicAlignment() { String md5 = "c6d95d8ae707e78fefdaa7375f130995"; WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec( "-R /humgen/gsa-scr1/GATK_Data/bwa/human_b36_both.fasta" + " -T Align" + " -I " + validationDataLocation + "NA12878_Pilot1_20.trimmed.unmapped.bam" + " -ob %s", 1, // just one output file Arrays.asList(md5)); executeTest("testBasicAlignment", spec); }
public void testBasicAlignment() { String md5 = "c6d95d8ae707e78fefdaa7375f130995"; WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec( "-R " + b36KGReference + " -T Align" + " -I " + validationDataLocation + "NA12878_Pilot1_20.trimmed.unmapped.bam" + " -ob %s", 1, // just one output file Arrays.asList(md5)); executeTest("testBasicAlignment", spec); }
diff --git a/cometd-javascript/jquery/src/test/java/org/cometd/javascript/jquery/extension/CometdTimeSyncExtensionTest.java b/cometd-javascript/jquery/src/test/java/org/cometd/javascript/jquery/extension/CometdTimeSyncExtensionTest.java index b7b4b1439..98aac4e97 100644 --- a/cometd-javascript/jquery/src/test/java/org/cometd/javascript/jquery/extension/CometdTimeSyncExtensionTest.java +++ b/cometd-javascript/jquery/src/test/java/org/cometd/javascript/jquery/extension/CometdTimeSyncExtensionTest.java @@ -1,68 +1,70 @@ package org.cometd.javascript.jquery.extension; import java.net.URL; import org.cometd.Bayeux; import org.cometd.javascript.jquery.AbstractCometdJQueryTest; import org.cometd.server.ext.TimesyncExtension; /** * @version $Revision$ $Date$ */ public class CometdTimeSyncExtensionTest extends AbstractCometdJQueryTest { protected void customizeBayeux(Bayeux bayeux) { bayeux.addExtension(new TimesyncExtension()); } public void testTimeSync() throws Exception { URL timesyncExtensionURL = new URL(contextURL + "/org/cometd/TimeSyncExtension.js"); evaluateURL(timesyncExtensionURL); URL jqueryTimesyncExtensionURL = new URL(contextURL + "/jquery/jquery.cometd-timesync.js"); evaluateURL(jqueryTimesyncExtensionURL); evaluateScript("$.cometd.configure({url: '" + cometURL + "', logLevel: 'debug'});"); evaluateScript("var inTimeSync = undefined;"); evaluateScript("var outTimeSync = undefined;"); evaluateScript("$.cometd.registerExtension('test', {" + "incoming: function(message)" + "{" + " var channel = message.channel;" + " if (channel && channel.indexOf('/meta/') == 0)" + " {" + - " inTimeSync = message.ext && message.ext.timesync;" + + " /* The timesync from the server may be missing if it's accurate enough */" + + " var timesync = message.ext && message.ext.timesync;" + + " if (timesync) inTimeSync = timesync;" + " }" + - " return message;" + + " return message;" + "}," + "outgoing: function(message)" + "{" + " var channel = message.channel;" + " if (channel && channel.indexOf('/meta/') == 0)" + " {" + " outTimeSync = message.ext && message.ext.timesync;" + " }" + - " return message;" + + " return message;" + "}" + "});"); evaluateScript("$.cometd.handshake();"); Thread.sleep(500); // Wait for the long poll // Both client and server should support timesync Object outTimeSync = get("outTimeSync"); assertNotNull(outTimeSync); Object inTimeSync = get("inTimeSync"); assertNotNull(inTimeSync); evaluateScript("var timesync = $.cometd.getExtension('timesync');"); evaluateScript("var networkLag = timesync.getNetworkLag();"); evaluateScript("var timeOffset = timesync.getTimeOffset();"); int networkLag = ((Number)get("networkLag")).intValue(); assertTrue(networkLag > 0); evaluateScript("$.cometd.disconnect();"); Thread.sleep(500); // Wait for the disconnect to return } }
false
true
public void testTimeSync() throws Exception { URL timesyncExtensionURL = new URL(contextURL + "/org/cometd/TimeSyncExtension.js"); evaluateURL(timesyncExtensionURL); URL jqueryTimesyncExtensionURL = new URL(contextURL + "/jquery/jquery.cometd-timesync.js"); evaluateURL(jqueryTimesyncExtensionURL); evaluateScript("$.cometd.configure({url: '" + cometURL + "', logLevel: 'debug'});"); evaluateScript("var inTimeSync = undefined;"); evaluateScript("var outTimeSync = undefined;"); evaluateScript("$.cometd.registerExtension('test', {" + "incoming: function(message)" + "{" + " var channel = message.channel;" + " if (channel && channel.indexOf('/meta/') == 0)" + " {" + " inTimeSync = message.ext && message.ext.timesync;" + " }" + " return message;" + "}," + "outgoing: function(message)" + "{" + " var channel = message.channel;" + " if (channel && channel.indexOf('/meta/') == 0)" + " {" + " outTimeSync = message.ext && message.ext.timesync;" + " }" + " return message;" + "}" + "});"); evaluateScript("$.cometd.handshake();"); Thread.sleep(500); // Wait for the long poll // Both client and server should support timesync Object outTimeSync = get("outTimeSync"); assertNotNull(outTimeSync); Object inTimeSync = get("inTimeSync"); assertNotNull(inTimeSync); evaluateScript("var timesync = $.cometd.getExtension('timesync');"); evaluateScript("var networkLag = timesync.getNetworkLag();"); evaluateScript("var timeOffset = timesync.getTimeOffset();"); int networkLag = ((Number)get("networkLag")).intValue(); assertTrue(networkLag > 0); evaluateScript("$.cometd.disconnect();"); Thread.sleep(500); // Wait for the disconnect to return }
public void testTimeSync() throws Exception { URL timesyncExtensionURL = new URL(contextURL + "/org/cometd/TimeSyncExtension.js"); evaluateURL(timesyncExtensionURL); URL jqueryTimesyncExtensionURL = new URL(contextURL + "/jquery/jquery.cometd-timesync.js"); evaluateURL(jqueryTimesyncExtensionURL); evaluateScript("$.cometd.configure({url: '" + cometURL + "', logLevel: 'debug'});"); evaluateScript("var inTimeSync = undefined;"); evaluateScript("var outTimeSync = undefined;"); evaluateScript("$.cometd.registerExtension('test', {" + "incoming: function(message)" + "{" + " var channel = message.channel;" + " if (channel && channel.indexOf('/meta/') == 0)" + " {" + " /* The timesync from the server may be missing if it's accurate enough */" + " var timesync = message.ext && message.ext.timesync;" + " if (timesync) inTimeSync = timesync;" + " }" + " return message;" + "}," + "outgoing: function(message)" + "{" + " var channel = message.channel;" + " if (channel && channel.indexOf('/meta/') == 0)" + " {" + " outTimeSync = message.ext && message.ext.timesync;" + " }" + " return message;" + "}" + "});"); evaluateScript("$.cometd.handshake();"); Thread.sleep(500); // Wait for the long poll // Both client and server should support timesync Object outTimeSync = get("outTimeSync"); assertNotNull(outTimeSync); Object inTimeSync = get("inTimeSync"); assertNotNull(inTimeSync); evaluateScript("var timesync = $.cometd.getExtension('timesync');"); evaluateScript("var networkLag = timesync.getNetworkLag();"); evaluateScript("var timeOffset = timesync.getTimeOffset();"); int networkLag = ((Number)get("networkLag")).intValue(); assertTrue(networkLag > 0); evaluateScript("$.cometd.disconnect();"); Thread.sleep(500); // Wait for the disconnect to return }
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/PreCompilerBuilder.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/PreCompilerBuilder.java index ae5583d70..eb8fc53b4 100644 --- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/PreCompilerBuilder.java +++ b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/PreCompilerBuilder.java @@ -1,1049 +1,1049 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Eclipse Public License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.eclipse.org/org/documents/epl-v10.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.ide.eclipse.adt.internal.build; import com.android.ide.eclipse.adt.AdtConstants; import com.android.ide.eclipse.adt.AdtPlugin; import com.android.ide.eclipse.adt.AndroidConstants; import com.android.ide.eclipse.adt.internal.project.AndroidManifestParser; import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper; import com.android.ide.eclipse.adt.internal.project.FixLaunchConfig; import com.android.ide.eclipse.adt.internal.project.XmlErrorHandler.BasicXmlErrorListener; import com.android.ide.eclipse.adt.internal.sdk.Sdk; import com.android.sdklib.AndroidVersion; import com.android.sdklib.IAndroidTarget; import com.android.sdklib.SdkConstants; import com.android.sdklib.xml.ManifestConstants; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import java.io.IOException; import java.util.ArrayList; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Pre Java Compiler. * This incremental builder performs 2 tasks: * <ul> * <li>compiles the resources located in the res/ folder, along with the * AndroidManifest.xml file into the R.java class.</li> * <li>compiles any .aidl files into a corresponding java file.</li> * </ul> * */ public class PreCompilerBuilder extends BaseBuilder { public static final String ID = "com.android.ide.eclipse.adt.PreCompilerBuilder"; //$NON-NLS-1$ private static final String PROPERTY_PACKAGE = "manifestPackage"; //$NON-NLS-1$ private static final String PROPERTY_COMPILE_RESOURCES = "compileResources"; //$NON-NLS-1$ private static final String PROPERTY_COMPILE_AIDL = "compileAidl"; //$NON-NLS-1$ /** * Single line aidl error<br> * "&lt;path&gt;:&lt;line&gt;: &lt;error&gt;" * or * "&lt;path&gt;:&lt;line&gt; &lt;error&gt;" */ private static Pattern sAidlPattern1 = Pattern.compile("^(.+?):(\\d+):?\\s(.+)$"); //$NON-NLS-1$ /** * Data to temporarly store aidl source file information */ static class AidlData { IFile aidlFile; IFolder sourceFolder; AidlData(IFolder sourceFolder, IFile aidlFile) { this.sourceFolder = sourceFolder; this.aidlFile = aidlFile; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof AidlData) { AidlData file = (AidlData)obj; return aidlFile.equals(file.aidlFile) && sourceFolder.equals(file.sourceFolder); } return false; } } /** * Resource Compile flag. This flag is reset to false after each successful compilation, and * stored in the project persistent properties. This allows the builder to remember its state * when the project is closed/opened. */ private boolean mMustCompileResources = false; /** List of .aidl files found that are modified or new. */ private final ArrayList<AidlData> mAidlToCompile = new ArrayList<AidlData>(); /** List of .aidl files that have been removed. */ private final ArrayList<AidlData> mAidlToRemove = new ArrayList<AidlData>(); /** cache of the java package defined in the manifest */ private String mManifestPackage; /** Output folder for generated Java File. Created on the Builder init * @see #startupOnInitialize() */ private IFolder mGenFolder; /** * Progress monitor used at the end of every build to refresh the content of the 'gen' folder * and set the generated files as derived. */ private DerivedProgressMonitor mDerivedProgressMonitor; /** * Progress monitor waiting the end of the process to set a persistent value * in a file. This is typically used in conjunction with <code>IResource.refresh()</code>, * since this call is asysnchronous, and we need to wait for it to finish for the file * to be known by eclipse, before we can call <code>resource.setPersistentProperty</code> on * a new file. */ private static class DerivedProgressMonitor implements IProgressMonitor { private boolean mCancelled = false; private final ArrayList<IFile> mFileList = new ArrayList<IFile>(); private boolean mDone = false; public DerivedProgressMonitor() { } void addFile(IFile file) { mFileList.add(file); } void reset() { mFileList.clear(); mDone = false; } public void beginTask(String name, int totalWork) { } public void done() { if (mDone == false) { mDone = true; for (IFile file : mFileList) { if (file.exists()) { try { file.setDerived(true); } catch (CoreException e) { // This really shouldn't happen since we check that the resource exist. // Worst case scenario, the resource isn't marked as derived. } } } } } public void internalWorked(double work) { } public boolean isCanceled() { return mCancelled; } public void setCanceled(boolean value) { mCancelled = value; } public void setTaskName(String name) { } public void subTask(String name) { } public void worked(int work) { } } public PreCompilerBuilder() { super(); } // build() returns a list of project from which this project depends for future compilation. @SuppressWarnings("unchecked") @Override protected IProject[] build(int kind, Map args, IProgressMonitor monitor) throws CoreException { try { mDerivedProgressMonitor.reset(); // First thing we do is go through the resource delta to not // lose it if we have to abort the build for any reason. // get the project objects IProject project = getProject(); // Top level check to make sure the build can move forward. abortOnBadSetup(project); IJavaProject javaProject = JavaCore.create(project); IAndroidTarget projectTarget = Sdk.getCurrent().getTarget(project); // now we need to get the classpath list ArrayList<IPath> sourceFolderPathList = BaseProjectHelper.getSourceClasspaths( javaProject); PreCompilerDeltaVisitor dv = null; String javaPackage = null; String minSdkVersion = null; if (kind == FULL_BUILD) { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Start_Full_Pre_Compiler); mMustCompileResources = true; buildAidlCompilationList(project, sourceFolderPathList); } else { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Start_Inc_Pre_Compiler); // Go through the resources and see if something changed. // Even if the mCompileResources flag is true from a previously aborted // build, we need to go through the Resource delta to get a possible // list of aidl files to compile/remove. IResourceDelta delta = getDelta(project); if (delta == null) { mMustCompileResources = true; buildAidlCompilationList(project, sourceFolderPathList); } else { dv = new PreCompilerDeltaVisitor(this, sourceFolderPathList); delta.accept(dv); // record the state mMustCompileResources |= dv.getCompileResources(); if (dv.getForceAidlCompile()) { buildAidlCompilationList(project, sourceFolderPathList); } else { // handle aidl modification, and update mMustCompileAidl mergeAidlFileModifications(dv.getAidlToCompile(), dv.getAidlToRemove()); } // get the java package from the visitor javaPackage = dv.getManifestPackage(); minSdkVersion = dv.getMinSdkVersion(); } } // store the build status in the persistent storage saveProjectBooleanProperty(PROPERTY_COMPILE_RESOURCES , mMustCompileResources); // if there was some XML errors, we just return w/o doing // anything since we've put some markers in the files anyway. if (dv != null && dv.mXmlError) { AdtPlugin.printErrorToConsole(project, Messages.Xml_Error); // This interrupts the build. The next builders will not run. stopBuild(Messages.Xml_Error); } // get the manifest file IFile manifest = AndroidManifestParser.getManifest(project); if (manifest == null) { String msg = String.format(Messages.s_File_Missing, AndroidConstants.FN_ANDROID_MANIFEST); AdtPlugin.printErrorToConsole(project, msg); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); // This interrupts the build. The next builders will not run. stopBuild(msg); // TODO: document whether code below that uses manifest (which is now guaranteed // to be null) will actually be executed or not. } // lets check the XML of the manifest first, if that hasn't been done by the // resource delta visitor yet. if (dv == null || dv.getCheckedManifestXml() == false) { BasicXmlErrorListener errorListener = new BasicXmlErrorListener(); AndroidManifestParser parser = BaseProjectHelper.parseManifestForError(manifest, errorListener); if (errorListener.mHasXmlError == true) { // there was an error in the manifest, its file has been marked, // by the XmlErrorHandler. // We return; String msg = String.format(Messages.s_Contains_Xml_Error, AndroidConstants.FN_ANDROID_MANIFEST); AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, msg); // This interrupts the build. The next builders will not run. stopBuild(msg); } // get the java package from the parser javaPackage = parser.getPackage(); minSdkVersion = parser.getApiLevelRequirement(); } if (minSdkVersion != null) { int minSdkValue = -1; try { minSdkValue = Integer.parseInt(minSdkVersion); } catch (NumberFormatException e) { // it's ok, it means minSdkVersion contains a (hopefully) valid codename. } AndroidVersion projectVersion = projectTarget.getVersion(); if (minSdkValue != -1) { String codename = projectVersion.getCodename(); if (codename != null) { // integer minSdk when the target is a preview => fatal error String msg = String.format( "Platform %1$s is a preview and requires appication manifests to set %2$s to '%1$s'", codename, ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION); AdtPlugin.printErrorToConsole(project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); stopBuild(msg); } else if (minSdkValue < projectVersion.getApiLevel()) { // integer minSdk is not high enough for the target => warning String msg = String.format( "Manifest min SDK version (%1$s) is lower than project target API level (%2$d)", minSdkVersion, projectVersion.getApiLevel()); AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_WARNING); } } else { // looks like the min sdk is a codename, check it matches the codename // of the platform String codename = projectVersion.getCodename(); if (codename == null) { // platform is not a preview => fatal error String msg = String.format( "Manifest attribute '%1$s' is set to '%2$s'. Integer is expected.", - ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION, codename); + ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION, minSdkVersion); AdtPlugin.printErrorToConsole(project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); stopBuild(msg); } else if (codename.equals(minSdkVersion) == false) { // platform and manifest codenames don't match => fatal error. String msg = String.format( "Value of manifest attribute '%1$s' does not match platform codename '%2$s'", ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION, codename); AdtPlugin.printErrorToConsole(project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); stopBuild(msg); } } } else if (projectTarget.getVersion().isPreview()) { // else the minSdkVersion is not set but we are using a preview target. // Display an error String codename = projectTarget.getVersion().getCodename(); String msg = String.format( "Platform %1$s is a preview and requires appication manifests to set %2$s to '%1$s'", codename, ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION); AdtPlugin.printErrorToConsole(project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); stopBuild(msg); } if (javaPackage == null || javaPackage.length() == 0) { // looks like the AndroidManifest file isn't valid. String msg = String.format(Messages.s_Doesnt_Declare_Package_Error, AndroidConstants.FN_ANDROID_MANIFEST); AdtPlugin.printErrorToConsole(project, msg); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); // This interrupts the build. The next builders will not run. stopBuild(msg); // TODO: document whether code below that uses javaPackage (which is now guaranteed // to be null) will actually be executed or not. } // at this point we have the java package. We need to make sure it's not a different // package than the previous one that were built. if (javaPackage != null && javaPackage.equals(mManifestPackage) == false) { // The manifest package has changed, the user may want to update // the launch configuration if (mManifestPackage != null) { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Checking_Package_Change); FixLaunchConfig flc = new FixLaunchConfig(project, mManifestPackage, javaPackage); flc.start(); } // now we delete the generated classes from their previous location deleteObsoleteGeneratedClass(AndroidConstants.FN_RESOURCE_CLASS, mManifestPackage); deleteObsoleteGeneratedClass(AndroidConstants.FN_MANIFEST_CLASS, mManifestPackage); // record the new manifest package, and save it. mManifestPackage = javaPackage; saveProjectStringProperty(PROPERTY_PACKAGE, mManifestPackage); } if (mMustCompileResources) { // we need to figure out where to store the R class. // get the parent folder for R.java and update mManifestPackageSourceFolder IFolder packageFolder = getGenManifestPackageFolder(project); // get the resource folder IFolder resFolder = project.getFolder(AndroidConstants.WS_RESOURCES); // get the file system path IPath outputLocation = mGenFolder.getLocation(); IPath resLocation = resFolder.getLocation(); IPath manifestLocation = manifest == null ? null : manifest.getLocation(); // those locations have to exist for us to do something! if (outputLocation != null && resLocation != null && manifestLocation != null) { String osOutputPath = outputLocation.toOSString(); String osResPath = resLocation.toOSString(); String osManifestPath = manifestLocation.toOSString(); // remove the aapt markers removeMarkersFromFile(manifest, AndroidConstants.MARKER_AAPT_COMPILE); removeMarkersFromContainer(resFolder, AndroidConstants.MARKER_AAPT_COMPILE); AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Preparing_Generated_Files); // since the R.java file may be already existing in read-only // mode we need to make it readable so that aapt can overwrite // it IFile rJavaFile = packageFolder.getFile(AndroidConstants.FN_RESOURCE_CLASS); // do the same for the Manifest.java class IFile manifestJavaFile = packageFolder.getFile( AndroidConstants.FN_MANIFEST_CLASS); // we actually need to delete the manifest.java as it may become empty and // in this case aapt doesn't generate an empty one, but instead doesn't // touch it. manifestJavaFile.delete(true, null); // launch aapt: create the command line ArrayList<String> array = new ArrayList<String>(); array.add(projectTarget.getPath(IAndroidTarget.AAPT)); array.add("package"); //$NON-NLS-1$ array.add("-m"); //$NON-NLS-1$ if (AdtPlugin.getBuildVerbosity() == AdtConstants.BUILD_VERBOSE) { array.add("-v"); //$NON-NLS-1$ } array.add("-J"); //$NON-NLS-1$ array.add(osOutputPath); array.add("-M"); //$NON-NLS-1$ array.add(osManifestPath); array.add("-S"); //$NON-NLS-1$ array.add(osResPath); array.add("-I"); //$NON-NLS-1$ array.add(projectTarget.getPath(IAndroidTarget.ANDROID_JAR)); if (AdtPlugin.getBuildVerbosity() == AdtConstants.BUILD_VERBOSE) { StringBuilder sb = new StringBuilder(); for (String c : array) { sb.append(c); sb.append(' '); } String cmd_line = sb.toString(); AdtPlugin.printToConsole(project, cmd_line); } // launch int execError = 1; try { // launch the command line process Process process = Runtime.getRuntime().exec( array.toArray(new String[array.size()])); // list to store each line of stderr ArrayList<String> results = new ArrayList<String>(); // get the output and return code from the process execError = grabProcessOutput(process, results); // attempt to parse the error output boolean parsingError = parseAaptOutput(results, project); // if we couldn't parse the output we display it in the console. if (parsingError) { if (execError != 0) { AdtPlugin.printErrorToConsole(project, results.toArray()); } else { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_NORMAL, project, results.toArray()); } } if (execError != 0) { // if the exec failed, and we couldn't parse the error output // (and therefore not all files that should have been marked, // were marked), we put a generic marker on the project and abort. if (parsingError) { markProject(AdtConstants.MARKER_ADT, Messages.Unparsed_AAPT_Errors, IMarker.SEVERITY_ERROR); } AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.AAPT_Error); // abort if exec failed. // This interrupts the build. The next builders will not run. stopBuild(Messages.AAPT_Error); } } catch (IOException e1) { // something happen while executing the process, // mark the project and exit String msg = String.format(Messages.AAPT_Exec_Error, array.get(0)); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); // This interrupts the build. The next builders will not run. stopBuild(msg); } catch (InterruptedException e) { // we got interrupted waiting for the process to end... // mark the project and exit String msg = String.format(Messages.AAPT_Exec_Error, array.get(0)); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); // This interrupts the build. The next builders will not run. stopBuild(msg); } // if the return code was OK, we refresh the folder that // contains R.java to force a java recompile. if (execError == 0) { // now add the R.java/Manifest.java to the list of file to be marked // as derived. mDerivedProgressMonitor.addFile(rJavaFile); mDerivedProgressMonitor.addFile(manifestJavaFile); // build has been done. reset the state of the builder mMustCompileResources = false; // and store it saveProjectBooleanProperty(PROPERTY_COMPILE_RESOURCES, mMustCompileResources); } } } else { // nothing to do } // now handle the aidl stuff. boolean aidlStatus = handleAidl(projectTarget, sourceFolderPathList, monitor); if (aidlStatus == false && mMustCompileResources == false) { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Nothing_To_Compile); } } finally { // refresh the 'gen' source folder. Once this is done with the custom progress // monitor to mark all new files as derived mGenFolder.refreshLocal(IResource.DEPTH_INFINITE, mDerivedProgressMonitor); } return null; } @Override protected void clean(IProgressMonitor monitor) throws CoreException { super.clean(monitor); AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, getProject(), Messages.Removing_Generated_Classes); // remove all the derived resources from the 'gen' source folder. removeDerivedResources(mGenFolder, monitor); } @Override protected void startupOnInitialize() { super.startupOnInitialize(); mDerivedProgressMonitor = new DerivedProgressMonitor(); IProject project = getProject(); // load the previous IFolder and java package. mManifestPackage = loadProjectStringProperty(PROPERTY_PACKAGE); // get the source folder in which all the Java files are created mGenFolder = project.getFolder(SdkConstants.FD_GEN_SOURCES); // Load the current compile flags. We ask for true if not found to force a // recompile. mMustCompileResources = loadProjectBooleanProperty(PROPERTY_COMPILE_RESOURCES, true); boolean mustCompileAidl = loadProjectBooleanProperty(PROPERTY_COMPILE_AIDL, true); // if we stored that we have to compile some aidl, we build the list that will compile them // all if (mustCompileAidl) { IJavaProject javaProject = JavaCore.create(project); ArrayList<IPath> sourceFolderPathList = BaseProjectHelper.getSourceClasspaths( javaProject); buildAidlCompilationList(project, sourceFolderPathList); } } /** * Delete the a generated java class associated with the specified java package. * @param filename Name of the generated file to remove. * @param javaPackage the old java package */ private void deleteObsoleteGeneratedClass(String filename, String javaPackage) { if (javaPackage == null) { return; } IPath packagePath = getJavaPackagePath(javaPackage); IPath iPath = packagePath.append(filename); // Find a matching resource object. IResource javaFile = mGenFolder.findMember(iPath); if (javaFile != null && javaFile.exists() && javaFile.getType() == IResource.FILE) { try { // delete javaFile.delete(true, null); // refresh parent javaFile.getParent().refreshLocal(IResource.DEPTH_ONE, new NullProgressMonitor()); } catch (CoreException e) { // failed to delete it, the user will have to delete it manually. String message = String.format(Messages.Delete_Obsolete_Error, javaFile.getFullPath()); IProject project = getProject(); AdtPlugin.printErrorToConsole(project, message); AdtPlugin.printErrorToConsole(project, e.getMessage()); } } } /** * Creates a relative {@link IPath} from a java package. * @param javaPackageName the java package. */ private IPath getJavaPackagePath(String javaPackageName) { // convert the java package into path String[] segments = javaPackageName.split(AndroidConstants.RE_DOT); StringBuilder path = new StringBuilder(); for (String s : segments) { path.append(AndroidConstants.WS_SEP_CHAR); path.append(s); } return new Path(path.toString()); } /** * Returns an {@link IFolder} (located inside the 'gen' source folder), that matches the * package defined in the manifest. This {@link IFolder} may not actually exist * (aapt will create it anyway). * @param project The project. * @return the {@link IFolder} that will contain the R class or null if the folder was not found. * @throws CoreException */ private IFolder getGenManifestPackageFolder(IProject project) throws CoreException { // get the path for the package IPath packagePath = getJavaPackagePath(mManifestPackage); // get a folder for this path under the 'gen' source folder, and return it. // This IFolder may not reference an actual existing folder. return mGenFolder.getFolder(packagePath); } /** * Compiles aidl files into java. This will also removes old java files * created from aidl files that are now gone. * @param projectTarget Target of the project * @param sourceFolders the list of source folders, relative to the workspace. * @param monitor the projess monitor * @returns true if it did something * @throws CoreException */ private boolean handleAidl(IAndroidTarget projectTarget, ArrayList<IPath> sourceFolders, IProgressMonitor monitor) throws CoreException { if (mAidlToCompile.size() == 0 && mAidlToRemove.size() == 0) { return false; } // create the command line String[] command = new String[4 + sourceFolders.size()]; int index = 0; command[index++] = projectTarget.getPath(IAndroidTarget.AIDL); command[index++] = "-p" + Sdk.getCurrent().getTarget(getProject()).getPath( //$NON-NLS-1$ IAndroidTarget.ANDROID_AIDL); // since the path are relative to the workspace and not the project itself, we need // the workspace root. IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot(); for (IPath p : sourceFolders) { IFolder f = wsRoot.getFolder(p); command[index++] = "-I" + f.getLocation().toOSString(); //$NON-NLS-1$ } // list of files that have failed compilation. ArrayList<AidlData> stillNeedCompilation = new ArrayList<AidlData>(); // if an aidl file is being removed before we managed to compile it, it'll be in // both list. We *need* to remove it from the compile list or it'll never go away. for (AidlData aidlFile : mAidlToRemove) { int pos = mAidlToCompile.indexOf(aidlFile); if (pos != -1) { mAidlToCompile.remove(pos); } } // loop until we've compile them all for (AidlData aidlData : mAidlToCompile) { // Remove the AIDL error markers from the aidl file removeMarkersFromFile(aidlData.aidlFile, AndroidConstants.MARKER_AIDL); // get the path of the source file. IPath sourcePath = aidlData.aidlFile.getLocation(); String osSourcePath = sourcePath.toOSString(); IFile javaFile = getGenDestinationFile(aidlData, true /*createFolders*/, monitor); // finish to set the command line. command[index] = osSourcePath; command[index + 1] = javaFile.getLocation().toOSString(); // launch the process if (execAidl(command, aidlData.aidlFile) == false) { // aidl failed. File should be marked. We add the file to the list // of file that will need compilation again. stillNeedCompilation.add(aidlData); // and we move on to the next one. continue; } else { // make sure the file will be marked as derived once we refresh the 'gen' source // folder. mDerivedProgressMonitor.addFile(javaFile); } } // change the list to only contains the file that have failed compilation mAidlToCompile.clear(); mAidlToCompile.addAll(stillNeedCompilation); // Remove the java files created from aidl files that have been removed. for (AidlData aidlData : mAidlToRemove) { IFile javaFile = getGenDestinationFile(aidlData, false /*createFolders*/, monitor); if (javaFile.exists()) { // This confirms the java file was generated by the builder, // we can delete the aidlFile. javaFile.delete(true, null); // Refresh parent. javaFile.getParent().refreshLocal(IResource.DEPTH_ONE, monitor); } } mAidlToRemove.clear(); // store the build state. If there are any files that failed to compile, we will // force a full aidl compile on the next project open. (unless a full compilation succeed // before the project is closed/re-opened.) // TODO: Optimize by saving only the files that need compilation saveProjectBooleanProperty(PROPERTY_COMPILE_AIDL , mAidlToCompile.size() > 0); return true; } /** * Returns the {@link IFile} handle to the destination file for a given aild source file * ({@link AidlData}). * @param aidlData the data for the aidl source file. * @param createFolders whether or not the parent folder of the destination should be created * if it does not exist. * @param monitor the progress monitor * @return the handle to the destination file. * @throws CoreException */ private IFile getGenDestinationFile(AidlData aidlData, boolean createFolders, IProgressMonitor monitor) throws CoreException { // build the destination folder path. // Use the path of the source file, except for the path leading to its source folder, // and for the last segment which is the filename. int segmentToSourceFolderCount = aidlData.sourceFolder.getFullPath().segmentCount(); IPath packagePath = aidlData.aidlFile.getFullPath().removeFirstSegments( segmentToSourceFolderCount).removeLastSegments(1); Path destinationPath = new Path(packagePath.toString()); // get an IFolder for this path. It's relative to the 'gen' folder already IFolder destinationFolder = mGenFolder.getFolder(destinationPath); // create it if needed. if (destinationFolder.exists() == false && createFolders) { createFolder(destinationFolder, monitor); } // Build the Java file name from the aidl name. String javaName = aidlData.aidlFile.getName().replaceAll(AndroidConstants.RE_AIDL_EXT, AndroidConstants.DOT_JAVA); // get the resource for the java file. IFile javaFile = destinationFolder.getFile(javaName); return javaFile; } /** * Creates the destination folder. Because * {@link IFolder#create(boolean, boolean, IProgressMonitor)} only works if the parent folder * already exists, this goes and ensure that all the parent folders actually exist, or it * creates them as well. * @param destinationFolder The folder to create * @param monitor the {@link IProgressMonitor}, * @throws CoreException */ private void createFolder(IFolder destinationFolder, IProgressMonitor monitor) throws CoreException { // check the parent exist and create if necessary. IContainer parent = destinationFolder.getParent(); if (parent.getType() == IResource.FOLDER && parent.exists() == false) { createFolder((IFolder)parent, monitor); } // create the folder. destinationFolder.create(true /*force*/, true /*local*/, new SubProgressMonitor(monitor, 10)); } /** * Execute the aidl command line, parse the output, and mark the aidl file * with any reported errors. * @param command the String array containing the command line to execute. * @param file The IFile object representing the aidl file being * compiled. * @return false if the exec failed, and build needs to be aborted. */ private boolean execAidl(String[] command, IFile file) { // do the exec try { Process p = Runtime.getRuntime().exec(command); // list to store each line of stderr ArrayList<String> results = new ArrayList<String>(); // get the output and return code from the process int result = grabProcessOutput(p, results); // attempt to parse the error output boolean error = parseAidlOutput(results, file); // If the process failed and we couldn't parse the output // we pring a message, mark the project and exit if (result != 0 && error == true) { // display the message in the console. AdtPlugin.printErrorToConsole(getProject(), results.toArray()); // mark the project and exit markProject(AdtConstants.MARKER_ADT, Messages.Unparsed_AIDL_Errors, IMarker.SEVERITY_ERROR); return false; } } catch (IOException e) { // mark the project and exit String msg = String.format(Messages.AIDL_Exec_Error, command[0]); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); return false; } catch (InterruptedException e) { // mark the project and exit String msg = String.format(Messages.AIDL_Exec_Error, command[0]); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); return false; } return true; } /** * Goes through the build paths and fills the list of aidl files to compile * ({@link #mAidlToCompile}). * @param project The project. * @param sourceFolderPathList The list of source folder paths. */ private void buildAidlCompilationList(IProject project, ArrayList<IPath> sourceFolderPathList) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); for (IPath sourceFolderPath : sourceFolderPathList) { IFolder sourceFolder = root.getFolder(sourceFolderPath); // we don't look in the 'gen' source folder as there will be no source in there. if (sourceFolder.exists() && sourceFolder.equals(mGenFolder) == false) { scanFolderForAidl(sourceFolder, sourceFolder); } } } /** * Scans a folder and fills the list of aidl files to compile. * @param sourceFolder the root source folder. * @param folder The folder to scan. */ private void scanFolderForAidl(IFolder sourceFolder, IFolder folder) { try { IResource[] members = folder.members(); for (IResource r : members) { // get the type of the resource switch (r.getType()) { case IResource.FILE: // if this a file, check that the file actually exist // and that it's an aidl file if (r.exists() && AndroidConstants.EXT_AIDL.equalsIgnoreCase(r.getFileExtension())) { mAidlToCompile.add(new AidlData(sourceFolder, (IFile)r)); } break; case IResource.FOLDER: // recursively go through children scanFolderForAidl(sourceFolder, (IFolder)r); break; default: // this would mean it's a project or the workspace root // which is unlikely to happen. we do nothing break; } } } catch (CoreException e) { // Couldn't get the members list for some reason. Just return. } } /** * Parse the output of aidl and mark the file with any errors. * @param lines The output to parse. * @param file The file to mark with error. * @return true if the parsing failed, false if success. */ private boolean parseAidlOutput(ArrayList<String> lines, IFile file) { // nothing to parse? just return false; if (lines.size() == 0) { return false; } Matcher m; for (int i = 0; i < lines.size(); i++) { String p = lines.get(i); m = sAidlPattern1.matcher(p); if (m.matches()) { // we can ignore group 1 which is the location since we already // have a IFile object representing the aidl file. String lineStr = m.group(2); String msg = m.group(3); // get the line number int line = 0; try { line = Integer.parseInt(lineStr); } catch (NumberFormatException e) { // looks like the string we extracted wasn't a valid // file number. Parsing failed and we return true return true; } // mark the file BaseProjectHelper.addMarker(file, AndroidConstants.MARKER_AIDL, msg, line, IMarker.SEVERITY_ERROR); // success, go to the next line continue; } // invalid line format, flag as error, and bail return true; } return false; } /** * Merge the current list of aidl file to compile/remove with the new one. * @param toCompile List of file to compile * @param toRemove List of file to remove */ private void mergeAidlFileModifications(ArrayList<AidlData> toCompile, ArrayList<AidlData> toRemove) { // loop through the new toRemove list, and add it to the old one, // plus remove any file that was still to compile and that are now // removed for (AidlData r : toRemove) { if (mAidlToRemove.indexOf(r) == -1) { mAidlToRemove.add(r); } int index = mAidlToCompile.indexOf(r); if (index != -1) { mAidlToCompile.remove(index); } } // now loop through the new files to compile and add it to the list. // Also look for them in the remove list, this would mean that they // were removed, then added back, and we shouldn't remove them, just // recompile them. for (AidlData r : toCompile) { if (mAidlToCompile.indexOf(r) == -1) { mAidlToCompile.add(r); } int index = mAidlToRemove.indexOf(r); if (index != -1) { mAidlToRemove.remove(index); } } } }
true
true
protected IProject[] build(int kind, Map args, IProgressMonitor monitor) throws CoreException { try { mDerivedProgressMonitor.reset(); // First thing we do is go through the resource delta to not // lose it if we have to abort the build for any reason. // get the project objects IProject project = getProject(); // Top level check to make sure the build can move forward. abortOnBadSetup(project); IJavaProject javaProject = JavaCore.create(project); IAndroidTarget projectTarget = Sdk.getCurrent().getTarget(project); // now we need to get the classpath list ArrayList<IPath> sourceFolderPathList = BaseProjectHelper.getSourceClasspaths( javaProject); PreCompilerDeltaVisitor dv = null; String javaPackage = null; String minSdkVersion = null; if (kind == FULL_BUILD) { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Start_Full_Pre_Compiler); mMustCompileResources = true; buildAidlCompilationList(project, sourceFolderPathList); } else { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Start_Inc_Pre_Compiler); // Go through the resources and see if something changed. // Even if the mCompileResources flag is true from a previously aborted // build, we need to go through the Resource delta to get a possible // list of aidl files to compile/remove. IResourceDelta delta = getDelta(project); if (delta == null) { mMustCompileResources = true; buildAidlCompilationList(project, sourceFolderPathList); } else { dv = new PreCompilerDeltaVisitor(this, sourceFolderPathList); delta.accept(dv); // record the state mMustCompileResources |= dv.getCompileResources(); if (dv.getForceAidlCompile()) { buildAidlCompilationList(project, sourceFolderPathList); } else { // handle aidl modification, and update mMustCompileAidl mergeAidlFileModifications(dv.getAidlToCompile(), dv.getAidlToRemove()); } // get the java package from the visitor javaPackage = dv.getManifestPackage(); minSdkVersion = dv.getMinSdkVersion(); } } // store the build status in the persistent storage saveProjectBooleanProperty(PROPERTY_COMPILE_RESOURCES , mMustCompileResources); // if there was some XML errors, we just return w/o doing // anything since we've put some markers in the files anyway. if (dv != null && dv.mXmlError) { AdtPlugin.printErrorToConsole(project, Messages.Xml_Error); // This interrupts the build. The next builders will not run. stopBuild(Messages.Xml_Error); } // get the manifest file IFile manifest = AndroidManifestParser.getManifest(project); if (manifest == null) { String msg = String.format(Messages.s_File_Missing, AndroidConstants.FN_ANDROID_MANIFEST); AdtPlugin.printErrorToConsole(project, msg); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); // This interrupts the build. The next builders will not run. stopBuild(msg); // TODO: document whether code below that uses manifest (which is now guaranteed // to be null) will actually be executed or not. } // lets check the XML of the manifest first, if that hasn't been done by the // resource delta visitor yet. if (dv == null || dv.getCheckedManifestXml() == false) { BasicXmlErrorListener errorListener = new BasicXmlErrorListener(); AndroidManifestParser parser = BaseProjectHelper.parseManifestForError(manifest, errorListener); if (errorListener.mHasXmlError == true) { // there was an error in the manifest, its file has been marked, // by the XmlErrorHandler. // We return; String msg = String.format(Messages.s_Contains_Xml_Error, AndroidConstants.FN_ANDROID_MANIFEST); AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, msg); // This interrupts the build. The next builders will not run. stopBuild(msg); } // get the java package from the parser javaPackage = parser.getPackage(); minSdkVersion = parser.getApiLevelRequirement(); } if (minSdkVersion != null) { int minSdkValue = -1; try { minSdkValue = Integer.parseInt(minSdkVersion); } catch (NumberFormatException e) { // it's ok, it means minSdkVersion contains a (hopefully) valid codename. } AndroidVersion projectVersion = projectTarget.getVersion(); if (minSdkValue != -1) { String codename = projectVersion.getCodename(); if (codename != null) { // integer minSdk when the target is a preview => fatal error String msg = String.format( "Platform %1$s is a preview and requires appication manifests to set %2$s to '%1$s'", codename, ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION); AdtPlugin.printErrorToConsole(project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); stopBuild(msg); } else if (minSdkValue < projectVersion.getApiLevel()) { // integer minSdk is not high enough for the target => warning String msg = String.format( "Manifest min SDK version (%1$s) is lower than project target API level (%2$d)", minSdkVersion, projectVersion.getApiLevel()); AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_WARNING); } } else { // looks like the min sdk is a codename, check it matches the codename // of the platform String codename = projectVersion.getCodename(); if (codename == null) { // platform is not a preview => fatal error String msg = String.format( "Manifest attribute '%1$s' is set to '%2$s'. Integer is expected.", ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION, codename); AdtPlugin.printErrorToConsole(project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); stopBuild(msg); } else if (codename.equals(minSdkVersion) == false) { // platform and manifest codenames don't match => fatal error. String msg = String.format( "Value of manifest attribute '%1$s' does not match platform codename '%2$s'", ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION, codename); AdtPlugin.printErrorToConsole(project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); stopBuild(msg); } } } else if (projectTarget.getVersion().isPreview()) { // else the minSdkVersion is not set but we are using a preview target. // Display an error String codename = projectTarget.getVersion().getCodename(); String msg = String.format( "Platform %1$s is a preview and requires appication manifests to set %2$s to '%1$s'", codename, ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION); AdtPlugin.printErrorToConsole(project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); stopBuild(msg); } if (javaPackage == null || javaPackage.length() == 0) { // looks like the AndroidManifest file isn't valid. String msg = String.format(Messages.s_Doesnt_Declare_Package_Error, AndroidConstants.FN_ANDROID_MANIFEST); AdtPlugin.printErrorToConsole(project, msg); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); // This interrupts the build. The next builders will not run. stopBuild(msg); // TODO: document whether code below that uses javaPackage (which is now guaranteed // to be null) will actually be executed or not. } // at this point we have the java package. We need to make sure it's not a different // package than the previous one that were built. if (javaPackage != null && javaPackage.equals(mManifestPackage) == false) { // The manifest package has changed, the user may want to update // the launch configuration if (mManifestPackage != null) { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Checking_Package_Change); FixLaunchConfig flc = new FixLaunchConfig(project, mManifestPackage, javaPackage); flc.start(); } // now we delete the generated classes from their previous location deleteObsoleteGeneratedClass(AndroidConstants.FN_RESOURCE_CLASS, mManifestPackage); deleteObsoleteGeneratedClass(AndroidConstants.FN_MANIFEST_CLASS, mManifestPackage); // record the new manifest package, and save it. mManifestPackage = javaPackage; saveProjectStringProperty(PROPERTY_PACKAGE, mManifestPackage); } if (mMustCompileResources) { // we need to figure out where to store the R class. // get the parent folder for R.java and update mManifestPackageSourceFolder IFolder packageFolder = getGenManifestPackageFolder(project); // get the resource folder IFolder resFolder = project.getFolder(AndroidConstants.WS_RESOURCES); // get the file system path IPath outputLocation = mGenFolder.getLocation(); IPath resLocation = resFolder.getLocation(); IPath manifestLocation = manifest == null ? null : manifest.getLocation(); // those locations have to exist for us to do something! if (outputLocation != null && resLocation != null && manifestLocation != null) { String osOutputPath = outputLocation.toOSString(); String osResPath = resLocation.toOSString(); String osManifestPath = manifestLocation.toOSString(); // remove the aapt markers removeMarkersFromFile(manifest, AndroidConstants.MARKER_AAPT_COMPILE); removeMarkersFromContainer(resFolder, AndroidConstants.MARKER_AAPT_COMPILE); AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Preparing_Generated_Files); // since the R.java file may be already existing in read-only // mode we need to make it readable so that aapt can overwrite // it IFile rJavaFile = packageFolder.getFile(AndroidConstants.FN_RESOURCE_CLASS); // do the same for the Manifest.java class IFile manifestJavaFile = packageFolder.getFile( AndroidConstants.FN_MANIFEST_CLASS); // we actually need to delete the manifest.java as it may become empty and // in this case aapt doesn't generate an empty one, but instead doesn't // touch it. manifestJavaFile.delete(true, null); // launch aapt: create the command line ArrayList<String> array = new ArrayList<String>(); array.add(projectTarget.getPath(IAndroidTarget.AAPT)); array.add("package"); //$NON-NLS-1$ array.add("-m"); //$NON-NLS-1$ if (AdtPlugin.getBuildVerbosity() == AdtConstants.BUILD_VERBOSE) { array.add("-v"); //$NON-NLS-1$ } array.add("-J"); //$NON-NLS-1$ array.add(osOutputPath); array.add("-M"); //$NON-NLS-1$ array.add(osManifestPath); array.add("-S"); //$NON-NLS-1$ array.add(osResPath); array.add("-I"); //$NON-NLS-1$ array.add(projectTarget.getPath(IAndroidTarget.ANDROID_JAR)); if (AdtPlugin.getBuildVerbosity() == AdtConstants.BUILD_VERBOSE) { StringBuilder sb = new StringBuilder(); for (String c : array) { sb.append(c); sb.append(' '); } String cmd_line = sb.toString(); AdtPlugin.printToConsole(project, cmd_line); } // launch int execError = 1; try { // launch the command line process Process process = Runtime.getRuntime().exec( array.toArray(new String[array.size()])); // list to store each line of stderr ArrayList<String> results = new ArrayList<String>(); // get the output and return code from the process execError = grabProcessOutput(process, results); // attempt to parse the error output boolean parsingError = parseAaptOutput(results, project); // if we couldn't parse the output we display it in the console. if (parsingError) { if (execError != 0) { AdtPlugin.printErrorToConsole(project, results.toArray()); } else { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_NORMAL, project, results.toArray()); } } if (execError != 0) { // if the exec failed, and we couldn't parse the error output // (and therefore not all files that should have been marked, // were marked), we put a generic marker on the project and abort. if (parsingError) { markProject(AdtConstants.MARKER_ADT, Messages.Unparsed_AAPT_Errors, IMarker.SEVERITY_ERROR); } AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.AAPT_Error); // abort if exec failed. // This interrupts the build. The next builders will not run. stopBuild(Messages.AAPT_Error); } } catch (IOException e1) { // something happen while executing the process, // mark the project and exit String msg = String.format(Messages.AAPT_Exec_Error, array.get(0)); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); // This interrupts the build. The next builders will not run. stopBuild(msg); } catch (InterruptedException e) { // we got interrupted waiting for the process to end... // mark the project and exit String msg = String.format(Messages.AAPT_Exec_Error, array.get(0)); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); // This interrupts the build. The next builders will not run. stopBuild(msg); } // if the return code was OK, we refresh the folder that // contains R.java to force a java recompile. if (execError == 0) { // now add the R.java/Manifest.java to the list of file to be marked // as derived. mDerivedProgressMonitor.addFile(rJavaFile); mDerivedProgressMonitor.addFile(manifestJavaFile); // build has been done. reset the state of the builder mMustCompileResources = false; // and store it saveProjectBooleanProperty(PROPERTY_COMPILE_RESOURCES, mMustCompileResources); } } } else { // nothing to do } // now handle the aidl stuff. boolean aidlStatus = handleAidl(projectTarget, sourceFolderPathList, monitor); if (aidlStatus == false && mMustCompileResources == false) { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Nothing_To_Compile); } } finally { // refresh the 'gen' source folder. Once this is done with the custom progress // monitor to mark all new files as derived mGenFolder.refreshLocal(IResource.DEPTH_INFINITE, mDerivedProgressMonitor); } return null; }
protected IProject[] build(int kind, Map args, IProgressMonitor monitor) throws CoreException { try { mDerivedProgressMonitor.reset(); // First thing we do is go through the resource delta to not // lose it if we have to abort the build for any reason. // get the project objects IProject project = getProject(); // Top level check to make sure the build can move forward. abortOnBadSetup(project); IJavaProject javaProject = JavaCore.create(project); IAndroidTarget projectTarget = Sdk.getCurrent().getTarget(project); // now we need to get the classpath list ArrayList<IPath> sourceFolderPathList = BaseProjectHelper.getSourceClasspaths( javaProject); PreCompilerDeltaVisitor dv = null; String javaPackage = null; String minSdkVersion = null; if (kind == FULL_BUILD) { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Start_Full_Pre_Compiler); mMustCompileResources = true; buildAidlCompilationList(project, sourceFolderPathList); } else { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Start_Inc_Pre_Compiler); // Go through the resources and see if something changed. // Even if the mCompileResources flag is true from a previously aborted // build, we need to go through the Resource delta to get a possible // list of aidl files to compile/remove. IResourceDelta delta = getDelta(project); if (delta == null) { mMustCompileResources = true; buildAidlCompilationList(project, sourceFolderPathList); } else { dv = new PreCompilerDeltaVisitor(this, sourceFolderPathList); delta.accept(dv); // record the state mMustCompileResources |= dv.getCompileResources(); if (dv.getForceAidlCompile()) { buildAidlCompilationList(project, sourceFolderPathList); } else { // handle aidl modification, and update mMustCompileAidl mergeAidlFileModifications(dv.getAidlToCompile(), dv.getAidlToRemove()); } // get the java package from the visitor javaPackage = dv.getManifestPackage(); minSdkVersion = dv.getMinSdkVersion(); } } // store the build status in the persistent storage saveProjectBooleanProperty(PROPERTY_COMPILE_RESOURCES , mMustCompileResources); // if there was some XML errors, we just return w/o doing // anything since we've put some markers in the files anyway. if (dv != null && dv.mXmlError) { AdtPlugin.printErrorToConsole(project, Messages.Xml_Error); // This interrupts the build. The next builders will not run. stopBuild(Messages.Xml_Error); } // get the manifest file IFile manifest = AndroidManifestParser.getManifest(project); if (manifest == null) { String msg = String.format(Messages.s_File_Missing, AndroidConstants.FN_ANDROID_MANIFEST); AdtPlugin.printErrorToConsole(project, msg); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); // This interrupts the build. The next builders will not run. stopBuild(msg); // TODO: document whether code below that uses manifest (which is now guaranteed // to be null) will actually be executed or not. } // lets check the XML of the manifest first, if that hasn't been done by the // resource delta visitor yet. if (dv == null || dv.getCheckedManifestXml() == false) { BasicXmlErrorListener errorListener = new BasicXmlErrorListener(); AndroidManifestParser parser = BaseProjectHelper.parseManifestForError(manifest, errorListener); if (errorListener.mHasXmlError == true) { // there was an error in the manifest, its file has been marked, // by the XmlErrorHandler. // We return; String msg = String.format(Messages.s_Contains_Xml_Error, AndroidConstants.FN_ANDROID_MANIFEST); AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, msg); // This interrupts the build. The next builders will not run. stopBuild(msg); } // get the java package from the parser javaPackage = parser.getPackage(); minSdkVersion = parser.getApiLevelRequirement(); } if (minSdkVersion != null) { int minSdkValue = -1; try { minSdkValue = Integer.parseInt(minSdkVersion); } catch (NumberFormatException e) { // it's ok, it means minSdkVersion contains a (hopefully) valid codename. } AndroidVersion projectVersion = projectTarget.getVersion(); if (minSdkValue != -1) { String codename = projectVersion.getCodename(); if (codename != null) { // integer minSdk when the target is a preview => fatal error String msg = String.format( "Platform %1$s is a preview and requires appication manifests to set %2$s to '%1$s'", codename, ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION); AdtPlugin.printErrorToConsole(project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); stopBuild(msg); } else if (minSdkValue < projectVersion.getApiLevel()) { // integer minSdk is not high enough for the target => warning String msg = String.format( "Manifest min SDK version (%1$s) is lower than project target API level (%2$d)", minSdkVersion, projectVersion.getApiLevel()); AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_WARNING); } } else { // looks like the min sdk is a codename, check it matches the codename // of the platform String codename = projectVersion.getCodename(); if (codename == null) { // platform is not a preview => fatal error String msg = String.format( "Manifest attribute '%1$s' is set to '%2$s'. Integer is expected.", ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION, minSdkVersion); AdtPlugin.printErrorToConsole(project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); stopBuild(msg); } else if (codename.equals(minSdkVersion) == false) { // platform and manifest codenames don't match => fatal error. String msg = String.format( "Value of manifest attribute '%1$s' does not match platform codename '%2$s'", ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION, codename); AdtPlugin.printErrorToConsole(project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); stopBuild(msg); } } } else if (projectTarget.getVersion().isPreview()) { // else the minSdkVersion is not set but we are using a preview target. // Display an error String codename = projectTarget.getVersion().getCodename(); String msg = String.format( "Platform %1$s is a preview and requires appication manifests to set %2$s to '%1$s'", codename, ManifestConstants.ATTRIBUTE_MIN_SDK_VERSION); AdtPlugin.printErrorToConsole(project, msg); BaseProjectHelper.addMarker(manifest, AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); stopBuild(msg); } if (javaPackage == null || javaPackage.length() == 0) { // looks like the AndroidManifest file isn't valid. String msg = String.format(Messages.s_Doesnt_Declare_Package_Error, AndroidConstants.FN_ANDROID_MANIFEST); AdtPlugin.printErrorToConsole(project, msg); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); // This interrupts the build. The next builders will not run. stopBuild(msg); // TODO: document whether code below that uses javaPackage (which is now guaranteed // to be null) will actually be executed or not. } // at this point we have the java package. We need to make sure it's not a different // package than the previous one that were built. if (javaPackage != null && javaPackage.equals(mManifestPackage) == false) { // The manifest package has changed, the user may want to update // the launch configuration if (mManifestPackage != null) { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Checking_Package_Change); FixLaunchConfig flc = new FixLaunchConfig(project, mManifestPackage, javaPackage); flc.start(); } // now we delete the generated classes from their previous location deleteObsoleteGeneratedClass(AndroidConstants.FN_RESOURCE_CLASS, mManifestPackage); deleteObsoleteGeneratedClass(AndroidConstants.FN_MANIFEST_CLASS, mManifestPackage); // record the new manifest package, and save it. mManifestPackage = javaPackage; saveProjectStringProperty(PROPERTY_PACKAGE, mManifestPackage); } if (mMustCompileResources) { // we need to figure out where to store the R class. // get the parent folder for R.java and update mManifestPackageSourceFolder IFolder packageFolder = getGenManifestPackageFolder(project); // get the resource folder IFolder resFolder = project.getFolder(AndroidConstants.WS_RESOURCES); // get the file system path IPath outputLocation = mGenFolder.getLocation(); IPath resLocation = resFolder.getLocation(); IPath manifestLocation = manifest == null ? null : manifest.getLocation(); // those locations have to exist for us to do something! if (outputLocation != null && resLocation != null && manifestLocation != null) { String osOutputPath = outputLocation.toOSString(); String osResPath = resLocation.toOSString(); String osManifestPath = manifestLocation.toOSString(); // remove the aapt markers removeMarkersFromFile(manifest, AndroidConstants.MARKER_AAPT_COMPILE); removeMarkersFromContainer(resFolder, AndroidConstants.MARKER_AAPT_COMPILE); AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Preparing_Generated_Files); // since the R.java file may be already existing in read-only // mode we need to make it readable so that aapt can overwrite // it IFile rJavaFile = packageFolder.getFile(AndroidConstants.FN_RESOURCE_CLASS); // do the same for the Manifest.java class IFile manifestJavaFile = packageFolder.getFile( AndroidConstants.FN_MANIFEST_CLASS); // we actually need to delete the manifest.java as it may become empty and // in this case aapt doesn't generate an empty one, but instead doesn't // touch it. manifestJavaFile.delete(true, null); // launch aapt: create the command line ArrayList<String> array = new ArrayList<String>(); array.add(projectTarget.getPath(IAndroidTarget.AAPT)); array.add("package"); //$NON-NLS-1$ array.add("-m"); //$NON-NLS-1$ if (AdtPlugin.getBuildVerbosity() == AdtConstants.BUILD_VERBOSE) { array.add("-v"); //$NON-NLS-1$ } array.add("-J"); //$NON-NLS-1$ array.add(osOutputPath); array.add("-M"); //$NON-NLS-1$ array.add(osManifestPath); array.add("-S"); //$NON-NLS-1$ array.add(osResPath); array.add("-I"); //$NON-NLS-1$ array.add(projectTarget.getPath(IAndroidTarget.ANDROID_JAR)); if (AdtPlugin.getBuildVerbosity() == AdtConstants.BUILD_VERBOSE) { StringBuilder sb = new StringBuilder(); for (String c : array) { sb.append(c); sb.append(' '); } String cmd_line = sb.toString(); AdtPlugin.printToConsole(project, cmd_line); } // launch int execError = 1; try { // launch the command line process Process process = Runtime.getRuntime().exec( array.toArray(new String[array.size()])); // list to store each line of stderr ArrayList<String> results = new ArrayList<String>(); // get the output and return code from the process execError = grabProcessOutput(process, results); // attempt to parse the error output boolean parsingError = parseAaptOutput(results, project); // if we couldn't parse the output we display it in the console. if (parsingError) { if (execError != 0) { AdtPlugin.printErrorToConsole(project, results.toArray()); } else { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_NORMAL, project, results.toArray()); } } if (execError != 0) { // if the exec failed, and we couldn't parse the error output // (and therefore not all files that should have been marked, // were marked), we put a generic marker on the project and abort. if (parsingError) { markProject(AdtConstants.MARKER_ADT, Messages.Unparsed_AAPT_Errors, IMarker.SEVERITY_ERROR); } AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.AAPT_Error); // abort if exec failed. // This interrupts the build. The next builders will not run. stopBuild(Messages.AAPT_Error); } } catch (IOException e1) { // something happen while executing the process, // mark the project and exit String msg = String.format(Messages.AAPT_Exec_Error, array.get(0)); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); // This interrupts the build. The next builders will not run. stopBuild(msg); } catch (InterruptedException e) { // we got interrupted waiting for the process to end... // mark the project and exit String msg = String.format(Messages.AAPT_Exec_Error, array.get(0)); markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR); // This interrupts the build. The next builders will not run. stopBuild(msg); } // if the return code was OK, we refresh the folder that // contains R.java to force a java recompile. if (execError == 0) { // now add the R.java/Manifest.java to the list of file to be marked // as derived. mDerivedProgressMonitor.addFile(rJavaFile); mDerivedProgressMonitor.addFile(manifestJavaFile); // build has been done. reset the state of the builder mMustCompileResources = false; // and store it saveProjectBooleanProperty(PROPERTY_COMPILE_RESOURCES, mMustCompileResources); } } } else { // nothing to do } // now handle the aidl stuff. boolean aidlStatus = handleAidl(projectTarget, sourceFolderPathList, monitor); if (aidlStatus == false && mMustCompileResources == false) { AdtPlugin.printBuildToConsole(AdtConstants.BUILD_VERBOSE, project, Messages.Nothing_To_Compile); } } finally { // refresh the 'gen' source folder. Once this is done with the custom progress // monitor to mark all new files as derived mGenFolder.refreshLocal(IResource.DEPTH_INFINITE, mDerivedProgressMonitor); } return null; }
diff --git a/src/main/java/com/google/devtools/j2objc/gen/ObjectiveCImplementationGenerator.java b/src/main/java/com/google/devtools/j2objc/gen/ObjectiveCImplementationGenerator.java index 2f92951..fec234a 100644 --- a/src/main/java/com/google/devtools/j2objc/gen/ObjectiveCImplementationGenerator.java +++ b/src/main/java/com/google/devtools/j2objc/gen/ObjectiveCImplementationGenerator.java @@ -1,774 +1,780 @@ /* * Copyright 2011 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.j2objc.gen; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.devtools.j2objc.J2ObjC; import com.google.devtools.j2objc.J2ObjC.Language; import com.google.devtools.j2objc.Options; import com.google.devtools.j2objc.types.IOSMethod; import com.google.devtools.j2objc.types.ImplementationImportCollector; import com.google.devtools.j2objc.types.ImportCollector; import com.google.devtools.j2objc.types.Types; import com.google.devtools.j2objc.util.ErrorReportingASTVisitor; import com.google.devtools.j2objc.util.NameTable; import org.eclipse.jdt.core.dom.AbstractTypeDeclaration; import org.eclipse.jdt.core.dom.AnnotationTypeDeclaration; import org.eclipse.jdt.core.dom.BodyDeclaration; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.ConstructorInvocation; import org.eclipse.jdt.core.dom.EnumConstantDeclaration; import org.eclipse.jdt.core.dom.EnumDeclaration; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.FieldDeclaration; import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.IVariableBinding; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.Statement; import org.eclipse.jdt.core.dom.SuperConstructorInvocation; import org.eclipse.jdt.core.dom.TypeDeclaration; import org.eclipse.jdt.core.dom.VariableDeclarationFragment; import java.util.List; import java.util.Set; /** * Generates Objective-C implementation (.m) files from compilation units. * * @author Tom Ball */ public class ObjectiveCImplementationGenerator extends ObjectiveCSourceFileGenerator { private Set<IVariableBinding> fieldHiders; private final String suffix; /** * Generate an Objective-C implementation file for each type declared in a * specified compilation unit. */ public static void generate(String fileName, Language language, CompilationUnit unit, String source) { ObjectiveCImplementationGenerator implementationGenerator = new ObjectiveCImplementationGenerator(fileName, language, unit, source); implementationGenerator.generate(unit); } private ObjectiveCImplementationGenerator(String fileName, Language language, CompilationUnit unit, String source) { super(fileName, source, unit, Options.emitLineDirectives()); fieldHiders = HiddenFieldDetector.getFieldNameConflicts(unit); suffix = language.getSuffix(); } @Override protected String getSuffix() { return suffix; } public void generate(CompilationUnit unit) { println(J2ObjC.getFileHeader(getSourceFileName())); if (needsPrinting(unit)) { printStart(getSourceFileName()); printImports(unit); unit.accept(new ErrorReportingASTVisitor() { @Override public boolean visit(TypeDeclaration node) { generate(node); return true; } @Override public boolean visit(EnumDeclaration node) { generate(node); return true; } }); } else { // Print a dummy C function so compiled object file is valid. @SuppressWarnings("unchecked") List<AbstractTypeDeclaration> types = unit.types(); // safe by definition if (!types.isEmpty()) { printf("void %s_unused() {}\n", NameTable.getFullName(types.get(0))); } } save(unit); } private boolean needsPrinting(CompilationUnit unit) { final boolean[] result = { false }; unit.accept(new ErrorReportingASTVisitor() { @Override public boolean visit(TypeDeclaration node) { if (!node.isInterface()) { result[0] = true; // always print concrete types return false; } return true; } @Override public boolean visit(EnumDeclaration node) { result[0] = true; // always print enums return false; } @Override public boolean visit(AnnotationTypeDeclaration node) { return false; // never print annotations } @Override public void endVisit(MethodDeclaration node) { // Only print protocols if they have static constants. if (isInterfaceConstantAccessor(Types.getMethodBinding(node))) { result[0] = true; } } }); return result[0]; } @Override public void generate(TypeDeclaration node) { List<IMethodBinding> testMethods = null; if (Types.isJUnitTest(Types.getTypeBinding(node))) { testMethods = findTestMethods(node); } syncLineNumbers(node.getName()); // avoid doc-comment fieldHiders = HiddenFieldDetector.getFieldNameConflicts(node); if (node.isInterface()) { printStaticInterface(node); } else { String typeName = NameTable.getFullName(node); printf("@implementation %s\n\n", typeName); printStaticVars(Lists.newArrayList(node.getFields())); printProperties(node.getFields()); printMethods(node); printObjCTypeMethod(node); println("@end\n"); // Generate main method, if declared. MethodDeclaration main = null; for (MethodDeclaration m : node.getMethods()) { if (isMainMethod(m)) { main = m; break; } } newline(); if (main != null || (testMethods != null && Options.generateTestMain())) { printMainMethod(main, typeName, testMethods); } } } private List<IMethodBinding> findTestMethods(TypeDeclaration node) { ITypeBinding type = Types.getTypeBinding(node); List<IMethodBinding> tests = Lists.newArrayList(); while (type != null) { for (IMethodBinding md : type.getDeclaredMethods()) { int modifiers = md.getModifiers(); if (Modifier.isPublic(modifiers)) { if (md.getName().startsWith("test") && md.getParameterTypes().length == 0) { tests.add(md); } } } type = type.getSuperclass(); } return tests.isEmpty() ? null : tests; } @Override protected void generate(AnnotationTypeDeclaration node) { // No implementation for annotations. } private void printMethods(TypeDeclaration node) { printMethods(Lists.newArrayList(node.getMethods())); // If node implements CharSequence, add forwarding method from the // sequenceDescription method to description (toString()). See // JavaToIOSMethodTranslator.loadCharSequenceMethods() for details. ITypeBinding binding = Types.getTypeBinding(node); for (ITypeBinding interfaze : binding.getInterfaces()) { if (interfaze.getQualifiedName().equals("java.lang.CharSequence")) { println("- (NSString *)description {\n return [self sequenceDescription];\n}\n"); } } // If node defines a primitive number wrapper, add a getValue() method. // This is required by iOS 5.0 to support cloning these types. if (Types.isJavaNumberType(binding)) { ITypeBinding primitiveType = Types.getPrimitiveType(binding); if (primitiveType != null) { // All java.lang primitive type wrappers have a "value" field. printf("- (void)getValue:(void *)buffer {\n *((%s *) buffer) = value_;\n}\n\n", NameTable.getFullName(primitiveType)); } } } private void printStaticInterface(TypeDeclaration node) { // Print implementation for static constants, if any. boolean needsPrinting = false; List<MethodDeclaration> methods = Lists.newArrayList(node.getMethods()); for (MethodDeclaration m : methods) { if (isInterfaceConstantAccessor(Types.getMethodBinding(m))) { needsPrinting = true; break; } } if (needsPrinting) { printf("\n@implementation %s\n\n", NameTable.getFullName(node)); printStaticVars(Lists.newArrayList(node.getFields())); for (MethodDeclaration m : methods) { IMethodBinding binding = Types.getMethodBinding(m); if (binding.isSynthetic() || isInterfaceConstantAccessor(binding)) { printMethod(m); } } println("@end"); } } @Override protected void generate(EnumDeclaration node) { @SuppressWarnings("unchecked") List<EnumConstantDeclaration> constants = node.enumConstants(); // safe by definition List<MethodDeclaration> methods = Lists.newArrayList(); List<FieldDeclaration> fields = Lists.newArrayList(); MethodDeclaration initializeMethod = null; @SuppressWarnings("unchecked") List<BodyDeclaration> declarations = node.bodyDeclarations(); // safe by definition for (BodyDeclaration decl : declarations) { if (decl instanceof FieldDeclaration) { fields.add((FieldDeclaration) decl); } else if (decl instanceof MethodDeclaration) { MethodDeclaration md = (MethodDeclaration) decl; if (md.getName().getIdentifier().equals("initialize")) { initializeMethod = md; } else { methods.add(md); } } } syncLineNumbers(node.getName()); // avoid doc-comment String typeName = NameTable.getFullName(node); for (EnumConstantDeclaration constant : constants) { printf("static %s *%s_%s;\n", typeName, typeName, NameTable.getName(constant.getName())); } printf("IOSObjectArray *%s_values;\n", typeName); newline(); printf("@implementation %s\n\n", typeName); printStaticVars(fields); for (EnumConstantDeclaration constant : constants) { String name = NameTable.getName(constant.getName()); printf("+ (%s *)%s {\n", typeName, name); printf(" return %s_%s;\n", typeName, name); println("}"); } newline(); // Enum constants needs to implement NSCopying. Being singletons, they // can just return self, as long the retain count is incremented. String selfString = Options.useReferenceCounting() ? "[self retain]" : "self"; printf("- (id)copyWithZone:(NSZone *)zone {\n return %s;\n}\n\n", selfString); printProperties(fields.toArray(new FieldDeclaration[0])); printMethods(methods); printf("+ (void)initialize {\n if (self == [%s class]) {\n", typeName); for (int i = 0; i < constants.size(); i++) { EnumConstantDeclaration constant = constants.get(i); @SuppressWarnings("unchecked") List<Expression> args = constant.arguments(); // safe by definition String name = NameTable.getName(constant.getName()); String constantTypeName = NameTable.getFullName(Types.getMethodBinding(constant).getDeclaringClass()); printf(" %s_%s = [[%s alloc] init", typeName, name, constantTypeName); boolean isSimpleEnum = constantTypeName.equals(typeName); // Common-case: no extra fields and no constant anonymous classes. if (args.isEmpty() && isSimpleEnum) { printf("WithNSString:@\"%s\" withInt:%d];\n", name, i); } else { String argString = StatementGenerator.generateArguments(Types.getMethodBinding(constant), args, fieldHiders, getBuilder().getCurrentLine()); print(argString); if (args.isEmpty()) { print("With"); } else { print(" with"); } printf("NSString:@\"%s_%s\" withInt:%d];\n", typeName.replace("Enum", ""), name, i); } } printf(" %s_values = [[IOSObjectArray alloc] initWithObjects:(id[]){ ", typeName); for (EnumConstantDeclaration constant : constants) { printf("%s_%s, ", typeName, NameTable.getName(constant.getName())); } printf("nil } count:%d type:[IOSClass classWithClass:[%s class]]];\n", constants.size(), typeName); if (initializeMethod != null) { @SuppressWarnings("unchecked") List<Statement> stmts = initializeMethod.getBody().statements(); // safe by definition for (Statement s : stmts) { printf(" %s", StatementGenerator.generate(s, fieldHiders, false, getBuilder().getCurrentLine())); } } println(" }\n}\n"); // Print generated values and valueOf methods. println("+ (IOSObjectArray *)values {"); printf(" return [IOSObjectArray arrayWithArray:%s_values];\n", typeName); println("}\n"); printf("+ (%s *)valueOfWithNSString:(NSString *)name {\n", typeName); printf(" for (int i = 0; i < [%s_values count]; i++) {\n", typeName); printf(" %s *e = [%s_values objectAtIndex:i];\n", typeName, typeName); printf(" if ([name isEqual:[e name]]) {\n"); printf(" return e;\n"); printf(" }\n"); printf(" }\n"); - printf(" @throw [[JavaLangIllegalArgumentException alloc] initWithNSString:name];\n"); + if (Options.useReferenceCounting()) { + printf(" @throw [[[JavaLangIllegalArgumentException alloc] initWithNSString:name]" + + " autorelease];\n"); + } + else { + printf(" @throw [[JavaLangIllegalArgumentException alloc] initWithNSString:name];\n"); + } printf(" return nil;\n"); println("}\n"); println("@end"); } @Override protected String methodDeclaration(MethodDeclaration m) { int modifiers = m.getModifiers(); if ((modifiers & Modifier.NATIVE) > 0) { return super.methodDeclaration(m) + " " + extractNativeMethodBody(m) + "\n\n"; } String methodBody = generateMethodBody(m); return super.methodDeclaration(m) + " " + reindent(methodBody) + "\n\n"; } @Override protected String mappedMethodDeclaration(MethodDeclaration method, IOSMethod mappedMethod) { String methodBody; if ((method.getModifiers() & Modifier.NATIVE) > 0) { methodBody = extractNativeMethodBody(method); } else { methodBody = generateMethodBody(method); } return super.mappedMethodDeclaration(method, mappedMethod) + " " + reindent(methodBody) + "\n\n"; } private String generateMethodBody(MethodDeclaration m) { if (Modifier.isAbstract(m.getModifiers())) { // Generate a body which throws a NSInvalidArgumentException. String body = "{\n // can't call an abstract method\n " + "[self doesNotRecognizeSelector:_cmd];\n "; if (!Types.isVoidType(m.getReturnType2())) { body += "return 0;\n"; // Never executes, but avoids a gcc warning. } return body + "}"; } // generate a normal method body String methodBody = generateStatement(m.getBody(), false); if (Types.hasAutoreleasePoolAnnotation(Types.getBinding(m))) { if (Options.useReferenceCounting()) { // TODO(user): use @autoreleasepool like ARC when iOS 5 is minimum. return reindent( "{\nNSAutoreleasePool *pool__ = [[NSAutoreleasePool alloc] init];\n" + methodBody + "[pool__ release];\n}"); } else if (Options.useARC()) { return reindent("{\n@autoreleasepool {\n" + methodBody + "}\n}"); } else { J2ObjC.warning(m, "@AutoreleasePool ignored in GC mode"); } } return methodBody; } @Override protected String getParameterName(SingleVariableDeclaration param) { String name = super.getParameterName(param); IVariableBinding binding = param.resolveBinding(); return binding != null && fieldHiders.contains(binding) ? name + "Arg" : name; } @Override protected String constructorDeclaration(MethodDeclaration m) { String methodBody; IMethodBinding binding = Types.getMethodBinding(m); @SuppressWarnings("unchecked") List<Statement> statements = m.getBody().statements(); if (binding.getDeclaringClass().isEnum()) { return enumConstructorDeclaration(m, statements, binding); } else if (statements.isEmpty()) { methodBody = "{\nreturn (self = [super init]);\n}"; } else if (statements.size() == 1 && (statements.get(0) instanceof ConstructorInvocation || statements.get(0) instanceof SuperConstructorInvocation)) { methodBody = "{\nreturn " + generateStatement(statements.get(0), false, true) + ";\n}"; } else { StringBuffer sb = new StringBuffer(); Statement first = statements.get(0); boolean firstPrinted = false; sb.append("{\nif ((self = "); if (first instanceof ConstructorInvocation || first instanceof SuperConstructorInvocation) { sb.append(generateStatement(first, false, true)); firstPrinted = true; } else { sb.append("[super init]"); } sb.append(")) {\n"); for (int i = firstPrinted ? 1 : 0; i < statements.size(); i++) { sb.append(generateStatement(statements.get(i), false, true)); } sb.append("}\nreturn self;\n}"); methodBody = sb.toString(); } return super.constructorDeclaration(m) + " " + reindent(methodBody) + "\n\n"; } private String enumConstructorDeclaration(MethodDeclaration m, List<Statement> statements, IMethodBinding binding) { assert !statements.isEmpty(); // Append enum generated parameters to invocation. The // InitializationNormalizer should have fixed this constructor so the // first statement is a constructor or super invocation. Statement s = statements.get(0); assert s instanceof ConstructorInvocation || s instanceof SuperConstructorInvocation; String invocation = generateStatement(statements.get(0), false, true) + ";\n"; List<?> args = s instanceof ConstructorInvocation ? ((ConstructorInvocation) s).arguments() : ((SuperConstructorInvocation) s).arguments(); String impliedArgs = (args.isEmpty() ? "W" : " w") + "ithNSString:name withInt:ordinal"; int index = invocation.lastIndexOf(']'); invocation = invocation.substring(0, index) + impliedArgs + ']'; StringBuffer sb = new StringBuffer(); if (statements.size() == 1) { sb.append("{\nreturn "); sb.append(invocation); sb.append(";\n}"); } else { sb.append("{\nif ((self = "); sb.append(invocation); sb.append(")) {\n"); for (int i = 1; i < statements.size(); i++) { sb.append(generateStatement(statements.get(i), false, true)); } sb.append("}\nreturn self;\n}"); } String result = super.constructorDeclaration(m) + " " + reindent(sb.toString()) + "\n\n"; return result; } @Override protected void printStaticConstructorDeclaration(MethodDeclaration m) { String className = NameTable.javaTypeToObjC(Types.getMethodBinding(m).getDeclaringClass(), false); StringBuffer sb = new StringBuffer(); sb.append("{\nif (self == [" + className + " class]) {\n"); @SuppressWarnings("unchecked") List<Statement> statements = m.getBody().statements(); for (Statement statement : statements) { sb.append(generateStatement(statement, false, true)); } sb.append("}\n}"); print("+ (void)initialize " + reindent(sb.toString()) + "\n\n"); } private String generateStatement(Statement stmt, boolean asFunction, boolean inConstructor) { return StatementGenerator.generate(stmt, fieldHiders, asFunction, getBuilder().getCurrentLine()); } private String generateStatement(Statement stmt, boolean asFunction) { return StatementGenerator.generate(stmt, fieldHiders, asFunction, getBuilder().getCurrentLine()); } private String generateExpression(Expression expr) { return StatementGenerator.generate(expr, fieldHiders, false, getBuilder().getCurrentLine()); } private void printMainMethod(MethodDeclaration m, String typeName, List<IMethodBinding> testMethods) { if (m != null) { // True for unit tests. Types.addFunction(Types.getMethodBinding(m)); } println("int main( int argc, const char *argv[] ) {"); if (m != null && (m.getModifiers() & Modifier.NATIVE) > 0) { println(extractNativeMethodBody(m)); return; } indent(); printIndent(); println("int exitCode = 0;"); if (Options.useReferenceCounting()) { // TODO(user): use @autoreleasepool like ARC when iOS 5 is minimum. printIndent(); println("NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];"); } else if (Options.useARC()) { printIndent(); println("@autoreleasepool {"); indent(); } if (m != null) { @SuppressWarnings("unchecked") List<SingleVariableDeclaration> params = m.parameters(); assert params.size() == 1; // Previously checked in isMainMethod(). printIndent(); printf("IOSObjectArray *%s = JreEmulationMainArguments(argc, argv);\n\n", params.get(0).getName().getIdentifier()); printMethodBody(m, true); } if (testMethods != null) { printIndent(); printf("exitCode = [JUnitRunner runTests:[%s class]", typeName); for (IMethodBinding test : testMethods) { printf(", @\"%s\"", test.getName()); } println(", nil];"); } if (Options.useReferenceCounting()) { print('\n'); printIndent(); println("[pool release];"); } else if (Options.useARC()) { unindent(); printIndent(); println("}"); } printIndent(); println("return exitCode;"); unindent(); println("}"); } private void printMethodBody(MethodDeclaration m, boolean isFunction) throws AssertionError { for (Object stmt : m.getBody().statements()) { if (stmt instanceof Statement) { String objcStmt = reindent(generateStatement((Statement) stmt, isFunction)); println(objcStmt); } else { throw new AssertionError("unexpected AST type: " + stmt.getClass()); } } } private String extractNativeMethodBody(MethodDeclaration m) { assert (m.getModifiers() & Modifier.NATIVE) > 0; String nativeCode = extractNativeCode(m.getStartPosition(), m.getLength()); if (nativeCode == null) { J2ObjC.error(m, "no native code found"); return "ERROR"; } indent(); String code = reindent('{' + nativeCode + '}'); unindent(); return code; } private void printImports(CompilationUnit node) { ImplementationImportCollector collector = new ImplementationImportCollector(); collector.collect(node, getSourceFileName()); Set<ImportCollector.Import> imports = collector.getImports(); if (!imports.isEmpty()) { Set<String> importStmts = Sets.newTreeSet(); for (ImportCollector.Import imp : imports) { importStmts.add(String.format("#import \"%s.h\"", imp.getImportFileName())); } for (String stmt : importStmts) { println(stmt); } newline(); } } private void printStaticVars(List<FieldDeclaration> fields) { boolean hadStaticVar = false; for (FieldDeclaration f : fields) { if (Modifier.isStatic(f.getModifiers())) { @SuppressWarnings("unchecked") List<VariableDeclarationFragment> fragments = f.fragments(); // safe by specification for (VariableDeclarationFragment var : fragments) { IVariableBinding binding = Types.getVariableBinding(var); if (!Types.isPrimitiveConstant(binding)) { String name = NameTable.getName(binding); Expression initializer = var.getInitializer(); if (initializer != null) { printConstant(name, initializer); } else { printf("static %s %s;\n", NameTable.javaRefToObjC(f.getType()), name); } hadStaticVar = true; } } } } if (hadStaticVar) { newline(); } } private void printProperties(FieldDeclaration[] fields) { int nPrinted = 0; for (FieldDeclaration field : fields) { if ((field.getModifiers() & Modifier.STATIC) == 0) { @SuppressWarnings("unchecked") List<VariableDeclarationFragment> vars = field.fragments(); // safe by definition for (VariableDeclarationFragment var : vars) { if (var.getName().getIdentifier().startsWith("this$") && superDefinesVariable(var)) { // Don't print, as it shadows an inner field in a super class. continue; } String name = NameTable.getName(var.getName()); ITypeBinding type = Types.getTypeBinding(field.getType()); String typeString = NameTable.javaRefToObjC(type); if (!typeString.endsWith("*")) { typeString += " "; } // Don't emit the getter when there is already a method with the // same name. // TODO(user,user): Update when getters are merged with property // accessors (see issues). boolean noGetter = false; ITypeBinding declaringClass = Types.getTypeBinding(field.getParent()); if (declaringClass != null) { IMethodBinding[] methods = declaringClass.getDeclaredMethods(); for (IMethodBinding method : methods) { if (method.getName().equals(name) && method.getParameterTypes().length == 0) { noGetter = true; break; } } } String objCFieldName = NameTable.javaFieldToObjC(name); // Getter if (!noGetter) { printf(String.format("- (%s)%s {\n return %s;\n}\n\n", typeString.trim(), name, objCFieldName)); } // Setter printf(String.format("- (void)set%s:(%s)new%s {\n", NameTable.capitalize(name), typeString.trim(), NameTable.capitalize(name))); if (type.isPrimitive()) { printf(String.format(" %s = new%s;\n}\n\n", objCFieldName, NameTable.capitalize(name))); } else if (Options.useReferenceCounting() && !Types.isWeakReference(Types.getVariableBinding(var))) { String retentionMethod = type.isEqualTo(Types.getNSString()) ? "copy" : "retain"; printf(String.format(" [%s autorelease];\n %s = [new%s %s];\n}\n\n", objCFieldName, objCFieldName, NameTable.capitalize(name), retentionMethod)); } else { printf(String.format(" %s = new%s;\n}\n\n", objCFieldName, NameTable.capitalize(name))); } nPrinted++; } } } if (nPrinted > 0) { newline(); } } private void printConstant(String name, Expression initializer) { Object constant = initializer.resolveConstantExpressionValue(); String text = generateExpression(initializer); // non-constant initializers were already moved to static blocks assert constant != null; print("static "); if (constant instanceof String) { printf("NSString * %s = %s;\n", name, text); } else if (constant instanceof Boolean) { printf("BOOL %s = %s;\n;", name, ((Boolean) constant).booleanValue() ? "YES" : "NO"); } else if (constant instanceof Character) { printf("unichar %s = %s;\n", name, text); } else { assert constant instanceof Number; Number number = (Number) constant; if (constant instanceof Byte) { printf("char %s = %d;\n", name, number.byteValue()); } else if (constant instanceof Double) { printf("double %s = %s;\n", name, text); } else if (constant instanceof Float) { printf("float %s = %s;\n", name, text); } else if (constant instanceof Integer) { printf("int %s = %s;\n", name, text); } else if (constant instanceof Long) { printf("long long %s = %s;\n", name, text); } else { printf("short %s = %d;\n", name, number.shortValue()); } } } /** * If type extends java.lang.Number, add a required implementation of * NSValue.objCType(). This can't be implemented as a native method * because its return type is const char *. Since this method overrides * the default implementation, the signatures need to match exactly. */ private void printObjCTypeMethod(TypeDeclaration node) { ITypeBinding type = Types.getTypeBinding(node); if (Types.isJavaNumberType(type)) { char objCType; String s = type.getName(); // Strings as case values would be nice here. if (s.equals("Byte")) { objCType = 'c'; } else if (s.equals("Double")) { objCType = 'd'; } else if (s.equals("Float")) { objCType = 'f'; } else if (s.equals("Integer")) { objCType = 'i'; } else if (s.equals("Long")) { objCType = 'q'; } else if (s.equals("Short")) { objCType = 's'; } else { return; // Other numeric types will be returned as objects. } println("- (const char *)objCType {"); printf(" return \"%c\";\n", objCType); println("}\n"); } } }
true
true
protected void generate(EnumDeclaration node) { @SuppressWarnings("unchecked") List<EnumConstantDeclaration> constants = node.enumConstants(); // safe by definition List<MethodDeclaration> methods = Lists.newArrayList(); List<FieldDeclaration> fields = Lists.newArrayList(); MethodDeclaration initializeMethod = null; @SuppressWarnings("unchecked") List<BodyDeclaration> declarations = node.bodyDeclarations(); // safe by definition for (BodyDeclaration decl : declarations) { if (decl instanceof FieldDeclaration) { fields.add((FieldDeclaration) decl); } else if (decl instanceof MethodDeclaration) { MethodDeclaration md = (MethodDeclaration) decl; if (md.getName().getIdentifier().equals("initialize")) { initializeMethod = md; } else { methods.add(md); } } } syncLineNumbers(node.getName()); // avoid doc-comment String typeName = NameTable.getFullName(node); for (EnumConstantDeclaration constant : constants) { printf("static %s *%s_%s;\n", typeName, typeName, NameTable.getName(constant.getName())); } printf("IOSObjectArray *%s_values;\n", typeName); newline(); printf("@implementation %s\n\n", typeName); printStaticVars(fields); for (EnumConstantDeclaration constant : constants) { String name = NameTable.getName(constant.getName()); printf("+ (%s *)%s {\n", typeName, name); printf(" return %s_%s;\n", typeName, name); println("}"); } newline(); // Enum constants needs to implement NSCopying. Being singletons, they // can just return self, as long the retain count is incremented. String selfString = Options.useReferenceCounting() ? "[self retain]" : "self"; printf("- (id)copyWithZone:(NSZone *)zone {\n return %s;\n}\n\n", selfString); printProperties(fields.toArray(new FieldDeclaration[0])); printMethods(methods); printf("+ (void)initialize {\n if (self == [%s class]) {\n", typeName); for (int i = 0; i < constants.size(); i++) { EnumConstantDeclaration constant = constants.get(i); @SuppressWarnings("unchecked") List<Expression> args = constant.arguments(); // safe by definition String name = NameTable.getName(constant.getName()); String constantTypeName = NameTable.getFullName(Types.getMethodBinding(constant).getDeclaringClass()); printf(" %s_%s = [[%s alloc] init", typeName, name, constantTypeName); boolean isSimpleEnum = constantTypeName.equals(typeName); // Common-case: no extra fields and no constant anonymous classes. if (args.isEmpty() && isSimpleEnum) { printf("WithNSString:@\"%s\" withInt:%d];\n", name, i); } else { String argString = StatementGenerator.generateArguments(Types.getMethodBinding(constant), args, fieldHiders, getBuilder().getCurrentLine()); print(argString); if (args.isEmpty()) { print("With"); } else { print(" with"); } printf("NSString:@\"%s_%s\" withInt:%d];\n", typeName.replace("Enum", ""), name, i); } } printf(" %s_values = [[IOSObjectArray alloc] initWithObjects:(id[]){ ", typeName); for (EnumConstantDeclaration constant : constants) { printf("%s_%s, ", typeName, NameTable.getName(constant.getName())); } printf("nil } count:%d type:[IOSClass classWithClass:[%s class]]];\n", constants.size(), typeName); if (initializeMethod != null) { @SuppressWarnings("unchecked") List<Statement> stmts = initializeMethod.getBody().statements(); // safe by definition for (Statement s : stmts) { printf(" %s", StatementGenerator.generate(s, fieldHiders, false, getBuilder().getCurrentLine())); } } println(" }\n}\n"); // Print generated values and valueOf methods. println("+ (IOSObjectArray *)values {"); printf(" return [IOSObjectArray arrayWithArray:%s_values];\n", typeName); println("}\n"); printf("+ (%s *)valueOfWithNSString:(NSString *)name {\n", typeName); printf(" for (int i = 0; i < [%s_values count]; i++) {\n", typeName); printf(" %s *e = [%s_values objectAtIndex:i];\n", typeName, typeName); printf(" if ([name isEqual:[e name]]) {\n"); printf(" return e;\n"); printf(" }\n"); printf(" }\n"); printf(" @throw [[JavaLangIllegalArgumentException alloc] initWithNSString:name];\n"); printf(" return nil;\n"); println("}\n"); println("@end"); }
protected void generate(EnumDeclaration node) { @SuppressWarnings("unchecked") List<EnumConstantDeclaration> constants = node.enumConstants(); // safe by definition List<MethodDeclaration> methods = Lists.newArrayList(); List<FieldDeclaration> fields = Lists.newArrayList(); MethodDeclaration initializeMethod = null; @SuppressWarnings("unchecked") List<BodyDeclaration> declarations = node.bodyDeclarations(); // safe by definition for (BodyDeclaration decl : declarations) { if (decl instanceof FieldDeclaration) { fields.add((FieldDeclaration) decl); } else if (decl instanceof MethodDeclaration) { MethodDeclaration md = (MethodDeclaration) decl; if (md.getName().getIdentifier().equals("initialize")) { initializeMethod = md; } else { methods.add(md); } } } syncLineNumbers(node.getName()); // avoid doc-comment String typeName = NameTable.getFullName(node); for (EnumConstantDeclaration constant : constants) { printf("static %s *%s_%s;\n", typeName, typeName, NameTable.getName(constant.getName())); } printf("IOSObjectArray *%s_values;\n", typeName); newline(); printf("@implementation %s\n\n", typeName); printStaticVars(fields); for (EnumConstantDeclaration constant : constants) { String name = NameTable.getName(constant.getName()); printf("+ (%s *)%s {\n", typeName, name); printf(" return %s_%s;\n", typeName, name); println("}"); } newline(); // Enum constants needs to implement NSCopying. Being singletons, they // can just return self, as long the retain count is incremented. String selfString = Options.useReferenceCounting() ? "[self retain]" : "self"; printf("- (id)copyWithZone:(NSZone *)zone {\n return %s;\n}\n\n", selfString); printProperties(fields.toArray(new FieldDeclaration[0])); printMethods(methods); printf("+ (void)initialize {\n if (self == [%s class]) {\n", typeName); for (int i = 0; i < constants.size(); i++) { EnumConstantDeclaration constant = constants.get(i); @SuppressWarnings("unchecked") List<Expression> args = constant.arguments(); // safe by definition String name = NameTable.getName(constant.getName()); String constantTypeName = NameTable.getFullName(Types.getMethodBinding(constant).getDeclaringClass()); printf(" %s_%s = [[%s alloc] init", typeName, name, constantTypeName); boolean isSimpleEnum = constantTypeName.equals(typeName); // Common-case: no extra fields and no constant anonymous classes. if (args.isEmpty() && isSimpleEnum) { printf("WithNSString:@\"%s\" withInt:%d];\n", name, i); } else { String argString = StatementGenerator.generateArguments(Types.getMethodBinding(constant), args, fieldHiders, getBuilder().getCurrentLine()); print(argString); if (args.isEmpty()) { print("With"); } else { print(" with"); } printf("NSString:@\"%s_%s\" withInt:%d];\n", typeName.replace("Enum", ""), name, i); } } printf(" %s_values = [[IOSObjectArray alloc] initWithObjects:(id[]){ ", typeName); for (EnumConstantDeclaration constant : constants) { printf("%s_%s, ", typeName, NameTable.getName(constant.getName())); } printf("nil } count:%d type:[IOSClass classWithClass:[%s class]]];\n", constants.size(), typeName); if (initializeMethod != null) { @SuppressWarnings("unchecked") List<Statement> stmts = initializeMethod.getBody().statements(); // safe by definition for (Statement s : stmts) { printf(" %s", StatementGenerator.generate(s, fieldHiders, false, getBuilder().getCurrentLine())); } } println(" }\n}\n"); // Print generated values and valueOf methods. println("+ (IOSObjectArray *)values {"); printf(" return [IOSObjectArray arrayWithArray:%s_values];\n", typeName); println("}\n"); printf("+ (%s *)valueOfWithNSString:(NSString *)name {\n", typeName); printf(" for (int i = 0; i < [%s_values count]; i++) {\n", typeName); printf(" %s *e = [%s_values objectAtIndex:i];\n", typeName, typeName); printf(" if ([name isEqual:[e name]]) {\n"); printf(" return e;\n"); printf(" }\n"); printf(" }\n"); if (Options.useReferenceCounting()) { printf(" @throw [[[JavaLangIllegalArgumentException alloc] initWithNSString:name]" + " autorelease];\n"); } else { printf(" @throw [[JavaLangIllegalArgumentException alloc] initWithNSString:name];\n"); } printf(" return nil;\n"); println("}\n"); println("@end"); }
diff --git a/org.projectusus.ui/src/org/projectusus/ui/internal/hotspots/pages/HotspotsLP.java b/org.projectusus.ui/src/org/projectusus/ui/internal/hotspots/pages/HotspotsLP.java index 567aedda..a427beb5 100644 --- a/org.projectusus.ui/src/org/projectusus/ui/internal/hotspots/pages/HotspotsLP.java +++ b/org.projectusus.ui/src/org/projectusus/ui/internal/hotspots/pages/HotspotsLP.java @@ -1,40 +1,40 @@ // Copyright (c) 2009-2010 by the projectusus.org contributors // This software is released under the terms and conditions // of the Eclipse Public License (EPL) 1.0. // See http://www.eclipse.org/legal/epl-v10.html for details. package org.projectusus.ui.internal.hotspots.pages; import java.util.List; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.swt.graphics.Image; import org.projectusus.ui.internal.DisplayHotspot; import org.projectusus.ui.internal.proportions.UsusModelLabelProvider; public class HotspotsLP extends UsusModelLabelProvider implements ITableLabelProvider { private final List<? extends HotspotsColumnDesc> columnDescs; public HotspotsLP( List<? extends HotspotsColumnDesc> columnDescs ) { this.columnDescs = columnDescs; } public String getColumnText( Object element, int columnIndex ) { if( element instanceof DisplayHotspot ) { return columnDescs.get( columnIndex ).getLabel( (DisplayHotspot<?>)element ); } return element.toString(); } public Image getColumnImage( Object element, int columnIndex ) { - HotspotsColumnDesc cockpitColumnDesc = HotspotsColumnDesc.values()[columnIndex]; + HotspotsColumnDesc cockpitColumnDesc = columnDescs.get( columnIndex ); if( cockpitColumnDesc == HotspotsColumnDesc.Trend && element instanceof DisplayHotspot ) { return ((DisplayHotspot<?>)element).getTrendImage(); } if( cockpitColumnDesc.hasImage() ) { return getColumnImageFor( element ); } return null; } }
true
true
public Image getColumnImage( Object element, int columnIndex ) { HotspotsColumnDesc cockpitColumnDesc = HotspotsColumnDesc.values()[columnIndex]; if( cockpitColumnDesc == HotspotsColumnDesc.Trend && element instanceof DisplayHotspot ) { return ((DisplayHotspot<?>)element).getTrendImage(); } if( cockpitColumnDesc.hasImage() ) { return getColumnImageFor( element ); } return null; }
public Image getColumnImage( Object element, int columnIndex ) { HotspotsColumnDesc cockpitColumnDesc = columnDescs.get( columnIndex ); if( cockpitColumnDesc == HotspotsColumnDesc.Trend && element instanceof DisplayHotspot ) { return ((DisplayHotspot<?>)element).getTrendImage(); } if( cockpitColumnDesc.hasImage() ) { return getColumnImageFor( element ); } return null; }
diff --git a/whois-oneshot/src/main/java/net/ripe/db/LogUtil.java b/whois-oneshot/src/main/java/net/ripe/db/LogUtil.java index f6ac14963..e6d784f67 100644 --- a/whois-oneshot/src/main/java/net/ripe/db/LogUtil.java +++ b/whois-oneshot/src/main/java/net/ripe/db/LogUtil.java @@ -1,20 +1,21 @@ package net.ripe.db; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.PatternLayout; public class LogUtil { private LogUtil() { } public static void initLogger() { LogManager.getRootLogger().setLevel(Level.INFO); final ConsoleAppender console = new ConsoleAppender(); console.setLayout(new PatternLayout("%d [%C{1}] %m%n")); + console.setTarget("System.err"); console.setThreshold(Level.INFO); console.activateOptions(); LogManager.getRootLogger().addAppender(console); } }
true
true
public static void initLogger() { LogManager.getRootLogger().setLevel(Level.INFO); final ConsoleAppender console = new ConsoleAppender(); console.setLayout(new PatternLayout("%d [%C{1}] %m%n")); console.setThreshold(Level.INFO); console.activateOptions(); LogManager.getRootLogger().addAppender(console); }
public static void initLogger() { LogManager.getRootLogger().setLevel(Level.INFO); final ConsoleAppender console = new ConsoleAppender(); console.setLayout(new PatternLayout("%d [%C{1}] %m%n")); console.setTarget("System.err"); console.setThreshold(Level.INFO); console.activateOptions(); LogManager.getRootLogger().addAppender(console); }
diff --git a/src/main/java/com/tresys/jalop/producer/JalopAppender.java b/src/main/java/com/tresys/jalop/producer/JalopAppender.java index 002f5a7..5c786a8 100644 --- a/src/main/java/com/tresys/jalop/producer/JalopAppender.java +++ b/src/main/java/com/tresys/jalop/producer/JalopAppender.java @@ -1,308 +1,310 @@ /* * Source code in 3rd-party is licensed and owned by their respective * copyright holders. * * All other source code is copyright Tresys Technology and licensed as below. * * Copyright (c) 2012 Tresys Technology LLC, Columbia, Maryland, USA * * This software was developed by Tresys Technology LLC * with U.S. Government sponsorship. * * 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.tresys.jalop.producer; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.math.BigInteger; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.spec.KeySpec; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.GregorianCalendar; import java.util.Set; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.spi.LocationInfo; import org.apache.log4j.spi.LoggingEvent; import com.tresys.jalop.schemas.mil.dod.jalop_1_0.applicationmetadatatypes.ApplicationMetadataType; import com.tresys.jalop.schemas.mil.dod.jalop_1_0.applicationmetadatatypes.LoggerSeverityType; import com.tresys.jalop.schemas.mil.dod.jalop_1_0.applicationmetadatatypes.LoggerType; import com.tresys.jalop.schemas.mil.dod.jalop_1_0.applicationmetadatatypes.StackFrameType; /** * JalopAppender submits logs to the JALoP local store. */ public class JalopAppender extends AppenderSkeleton { private String path; private String hostName; private String appName; private String publicKeyPath; private String privateKeyPath; private String certPath; private boolean useLocation; private static final String LOG4J = "LOG4J"; public JalopAppender() { useLocation = true; } /** * Does nothing. */ public void activateOptions() { } /** * This method is where logs get sent to the local store */ public void append(LoggingEvent event) { ApplicationMetadataXML xml = createLoggerMetadata(event); Producer producer; try { producer = createProducer(xml, path, hostName, appName, privateKeyPath, publicKeyPath, certPath); producer.jalpLog((String) null); } catch (Exception e) { e.printStackTrace(); } } /** * Close this appender instance. */ public synchronized void close() { if (this.closed) return; this.closed = true; } /* * This method creates and fills out a Producer with the given data */ private Producer createProducer(ApplicationMetadataXML xml, String socketPath, String hostname, String appname, String privateKeyPath, String publicKeyPath, String certPath) throws Exception { Producer producer = new Producer(xml); producer.setSocketFile(socketPath); producer.setApplicationName(appname); producer.setHostName(hostname); if (privateKeyPath != null && !"".equals(privateKeyPath)) { File privateKeyFile = new File(privateKeyPath); DataInputStream privateDis = new DataInputStream( new FileInputStream(privateKeyFile)); byte[] privateKeyBytes = new byte[(int) privateKeyFile.length()]; privateDis.readFully(privateKeyBytes); privateDis.close(); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); KeySpec privateKs = new PKCS8EncodedKeySpec(privateKeyBytes); PrivateKey privateKey = keyFactory.generatePrivate(privateKs); File publicKeyFile = new File(publicKeyPath); DataInputStream publicDis = new DataInputStream( new FileInputStream(publicKeyFile)); byte[] publicKeyBytes = new byte[(int) publicKeyFile.length()]; publicDis.readFully(publicKeyBytes); publicDis.close(); KeySpec publicKs = new X509EncodedKeySpec(publicKeyBytes); PublicKey publicKey = keyFactory.generatePublic(publicKs); producer.setPrivateKey(privateKey); producer.setPublicKey(publicKey); } if (certPath != null && !"".equals(certPath)) { InputStream inputStream = new FileInputStream(certPath); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) cf .generateCertificate(inputStream); inputStream.close(); producer.setCertificate(cert); } return producer; } public boolean requiresLayout() { return false; } /* * This method creates ApplicationMetadataXML from a LoggingEvent */ private ApplicationMetadataXML createLoggerMetadata(LoggingEvent event) { ApplicationMetadataType amt = new ApplicationMetadataType(); LoggerType lt = new LoggerType(); // ApplicationName lt.setApplicationName(appName); // HostName lt.setHostname(hostName); // Location Info if (useLocation) { LocationInfo loInfo = event.getLocationInformation(); LoggerType.Location ltl = new LoggerType.Location(); StackFrameType stackFrame = new StackFrameType(); // stackFrame.setCallerName(value); stackFrame.setClassName(loInfo.getClassName()); // stackFrame.setDepth(value); stackFrame.setFileName(loInfo.getFileName()); try { stackFrame.setLineNumber(BigInteger.valueOf(Long.valueOf(loInfo .getLineNumber()))); } catch (NullPointerException e1) { // this is optional. Fall through + } catch (NumberFormatException e1) { + // this is optional. Fall through } ltl.getStackFrame().add(stackFrame); lt.setLocation(ltl); } // Logger Name lt.setLoggerName(LOG4J); // get mapped diagnostic context Set<String> temp = event.getPropertyKeySet(); String mdc = null; try { mdc = (String) event.getMDC((String) temp.toArray()[0]); } catch (NullPointerException e) { // this is optional. Fall though } lt.setMappedDiagnosticContext(mdc); // Message lt.setMessage((String) event.getMessage()); // NDC lt.setNestedDiagnosticContext(event.getNDC()); // Set Severity Type LoggerSeverityType lst = new LoggerSeverityType(); try { lst.setName(event.getLevel().toString()); lst.setValue(BigInteger.valueOf(event.getLevel().toInt())); } catch (NullPointerException e) { // These are optional. Fall though } lt.setSeverity(lst); // Thread ID lt.setThreadID(event.getThreadName()); // Timestamp GregorianCalendar calendar = new GregorianCalendar(); calendar.setTimeInMillis(event.getTimeStamp()); try { lt.setTimestamp(DatatypeFactory.newInstance() .newXMLGregorianCalendar(calendar)); } catch (DatatypeConfigurationException e1) { // timestamp is optional, fall though } amt.setLogger(lt); // Create ApplicationMetadataXML with filled out ApplicationMetadataType ApplicationMetadataXML xml = null; try { xml = new LoggerXML(amt.getLogger()); } catch (Exception e) { // This is optional, fall though } xml.setEventId(amt.getEventID()); return xml; } public void setPath(String path) { this.path = path; } public String getPath() { return path; } public void setHostName(String hostname) { this.hostName = hostname; } public String getHostName() { return hostName; } public void setAppName(String appName) { this.appName = appName; } public String getAppName() { return appName; } public void setPrivateKeyPath(String privateKeyPath) { this.privateKeyPath = privateKeyPath; } public String getPrivateKeyPath() { return privateKeyPath; } public void setPublicKeyPath(String publicKeyPath) { this.publicKeyPath = publicKeyPath; } public String getPublicKeyPath() { return publicKeyPath; } public void setCertPath(String certPath) { this.certPath = certPath; } public String getCertPath() { return certPath; } public void setUseLocation(boolean useLocation) { this.useLocation = useLocation; } public boolean getUseLocation() { return useLocation; } }
true
true
private ApplicationMetadataXML createLoggerMetadata(LoggingEvent event) { ApplicationMetadataType amt = new ApplicationMetadataType(); LoggerType lt = new LoggerType(); // ApplicationName lt.setApplicationName(appName); // HostName lt.setHostname(hostName); // Location Info if (useLocation) { LocationInfo loInfo = event.getLocationInformation(); LoggerType.Location ltl = new LoggerType.Location(); StackFrameType stackFrame = new StackFrameType(); // stackFrame.setCallerName(value); stackFrame.setClassName(loInfo.getClassName()); // stackFrame.setDepth(value); stackFrame.setFileName(loInfo.getFileName()); try { stackFrame.setLineNumber(BigInteger.valueOf(Long.valueOf(loInfo .getLineNumber()))); } catch (NullPointerException e1) { // this is optional. Fall through } ltl.getStackFrame().add(stackFrame); lt.setLocation(ltl); } // Logger Name lt.setLoggerName(LOG4J); // get mapped diagnostic context Set<String> temp = event.getPropertyKeySet(); String mdc = null; try { mdc = (String) event.getMDC((String) temp.toArray()[0]); } catch (NullPointerException e) { // this is optional. Fall though } lt.setMappedDiagnosticContext(mdc); // Message lt.setMessage((String) event.getMessage()); // NDC lt.setNestedDiagnosticContext(event.getNDC()); // Set Severity Type LoggerSeverityType lst = new LoggerSeverityType(); try { lst.setName(event.getLevel().toString()); lst.setValue(BigInteger.valueOf(event.getLevel().toInt())); } catch (NullPointerException e) { // These are optional. Fall though } lt.setSeverity(lst); // Thread ID lt.setThreadID(event.getThreadName()); // Timestamp GregorianCalendar calendar = new GregorianCalendar(); calendar.setTimeInMillis(event.getTimeStamp()); try { lt.setTimestamp(DatatypeFactory.newInstance() .newXMLGregorianCalendar(calendar)); } catch (DatatypeConfigurationException e1) { // timestamp is optional, fall though } amt.setLogger(lt); // Create ApplicationMetadataXML with filled out ApplicationMetadataType ApplicationMetadataXML xml = null; try { xml = new LoggerXML(amt.getLogger()); } catch (Exception e) { // This is optional, fall though } xml.setEventId(amt.getEventID()); return xml; }
private ApplicationMetadataXML createLoggerMetadata(LoggingEvent event) { ApplicationMetadataType amt = new ApplicationMetadataType(); LoggerType lt = new LoggerType(); // ApplicationName lt.setApplicationName(appName); // HostName lt.setHostname(hostName); // Location Info if (useLocation) { LocationInfo loInfo = event.getLocationInformation(); LoggerType.Location ltl = new LoggerType.Location(); StackFrameType stackFrame = new StackFrameType(); // stackFrame.setCallerName(value); stackFrame.setClassName(loInfo.getClassName()); // stackFrame.setDepth(value); stackFrame.setFileName(loInfo.getFileName()); try { stackFrame.setLineNumber(BigInteger.valueOf(Long.valueOf(loInfo .getLineNumber()))); } catch (NullPointerException e1) { // this is optional. Fall through } catch (NumberFormatException e1) { // this is optional. Fall through } ltl.getStackFrame().add(stackFrame); lt.setLocation(ltl); } // Logger Name lt.setLoggerName(LOG4J); // get mapped diagnostic context Set<String> temp = event.getPropertyKeySet(); String mdc = null; try { mdc = (String) event.getMDC((String) temp.toArray()[0]); } catch (NullPointerException e) { // this is optional. Fall though } lt.setMappedDiagnosticContext(mdc); // Message lt.setMessage((String) event.getMessage()); // NDC lt.setNestedDiagnosticContext(event.getNDC()); // Set Severity Type LoggerSeverityType lst = new LoggerSeverityType(); try { lst.setName(event.getLevel().toString()); lst.setValue(BigInteger.valueOf(event.getLevel().toInt())); } catch (NullPointerException e) { // These are optional. Fall though } lt.setSeverity(lst); // Thread ID lt.setThreadID(event.getThreadName()); // Timestamp GregorianCalendar calendar = new GregorianCalendar(); calendar.setTimeInMillis(event.getTimeStamp()); try { lt.setTimestamp(DatatypeFactory.newInstance() .newXMLGregorianCalendar(calendar)); } catch (DatatypeConfigurationException e1) { // timestamp is optional, fall though } amt.setLogger(lt); // Create ApplicationMetadataXML with filled out ApplicationMetadataType ApplicationMetadataXML xml = null; try { xml = new LoggerXML(amt.getLogger()); } catch (Exception e) { // This is optional, fall though } xml.setEventId(amt.getEventID()); return xml; }
diff --git a/src/nitrogene/objecttree/ImageObject.java b/src/nitrogene/objecttree/ImageObject.java index f5f8453..ac0943e 100644 --- a/src/nitrogene/objecttree/ImageObject.java +++ b/src/nitrogene/objecttree/ImageObject.java @@ -1,119 +1,119 @@ package nitrogene.objecttree; import java.util.ArrayList; import java.util.List; import org.newdawn.slick.Color; import org.newdawn.slick.Image; import org.newdawn.slick.geom.Point; import org.newdawn.slick.geom.Shape; import org.newdawn.slick.geom.Transform; import nitrogene.collision.Vector; import nitrogene.util.ImageBase; import nitrogene.util.Movement; import nitrogene.world.ArenaMap; public class ImageObject extends PhysicalObject{ private float x; private float y; private float centerx; private float centery; public ImageObject(float width, float height, Image img, float scalefactor, ArenaMap map){ super(width, height, img, scalefactor, map); ImageBase.registerImage(this.mainimg); } @Override public void move(int thrust, int delta){ movement.Accelerate(new Vector(getCenterX(),getCenterY()), delta); float mm = delta/1000f; float gj = thrust*1f; setX(getX()+((movement.getDx()*gj)*mm)); setY(getY()+((movement.getDy()*gj)*mm)); } @Override public boolean isColliding(PhysicalObject obj){ /* double dist = Math.sqrt((this.getCenterX()-obj.getCenterX())*(this.getCenterX()-obj.getCenterX()) + (this.getCenterY()-obj.getCenterY())*(this.getCenterY()-obj.getCenterY())); if(this.getCenterX() + width + this.movement.getDx() >= dist || this.getCenterY() + width + this.movement.getDy() >= dist){ */ if(ImageBase.contains(this.mainimg)) { System.out.println("FIRST"); ArrayList<int[]> pixels = ImageBase.getPixels(this.mainimg); for(int i = 0; i < pixels.size(); i++) { if(obj.isContaining(pixels.get(i)[0] + this.getX(), pixels.get(i)[1] + this.getY())) { System.out.println("YAY"); return true; } } } //} return false; } @Override public boolean isContaining(float x, float y){ if(getCenterX() + width + this.movement.getDx() >= x || getCenterY() + height + this.movement.getDy() >= y || getCenterX() - width - this.movement.getDx() <= x || getCenterY() - height - this.movement.getDy() <= y ){ return pointOnImage(x, y); } else return false; } @Override public float getX(){ return this.x; } @Override public float getY(){ return this.y; } @Override public float getCenterX(){ - return centerx; + return getX() + mainimg.getWidth()/2; } @Override public float getCenterY(){ - return centery; + return getY() + mainimg.getHeight()/2; } @Override public void setX(float x){ this.x = x; } @Override public void setY(float y){ this.y = y; } @Override public void setCenterX(float x){ this.centerx = x; } @Override public void setCenterY(float y){ this.centery = y; } public boolean pointOnImage(float x, float y) { if(x-getX() < 0 || x-getX() >= mainimg.getWidth() || y-getY() < 0 || y-getY() >= mainimg.getHeight()) { return false; } Color c = mainimg.getColor((int) (x-getX()), (int)(y-getY())); return c.a == 0f; } }
false
true
public boolean isColliding(PhysicalObject obj){ /* double dist = Math.sqrt((this.getCenterX()-obj.getCenterX())*(this.getCenterX()-obj.getCenterX()) + (this.getCenterY()-obj.getCenterY())*(this.getCenterY()-obj.getCenterY())); if(this.getCenterX() + width + this.movement.getDx() >= dist || this.getCenterY() + width + this.movement.getDy() >= dist){ */ if(ImageBase.contains(this.mainimg)) { System.out.println("FIRST"); ArrayList<int[]> pixels = ImageBase.getPixels(this.mainimg); for(int i = 0; i < pixels.size(); i++) { if(obj.isContaining(pixels.get(i)[0] + this.getX(), pixels.get(i)[1] + this.getY())) { System.out.println("YAY"); return true; } } } //} return false; } @Override public boolean isContaining(float x, float y){ if(getCenterX() + width + this.movement.getDx() >= x || getCenterY() + height + this.movement.getDy() >= y || getCenterX() - width - this.movement.getDx() <= x || getCenterY() - height - this.movement.getDy() <= y ){ return pointOnImage(x, y); } else return false; } @Override public float getX(){ return this.x; } @Override public float getY(){ return this.y; } @Override public float getCenterX(){ return centerx; } @Override public float getCenterY(){ return centery; } @Override public void setX(float x){ this.x = x; } @Override public void setY(float y){ this.y = y; } @Override public void setCenterX(float x){ this.centerx = x; } @Override public void setCenterY(float y){ this.centery = y; } public boolean pointOnImage(float x, float y) { if(x-getX() < 0 || x-getX() >= mainimg.getWidth() || y-getY() < 0 || y-getY() >= mainimg.getHeight()) { return false; } Color c = mainimg.getColor((int) (x-getX()), (int)(y-getY())); return c.a == 0f; } }
public boolean isColliding(PhysicalObject obj){ /* double dist = Math.sqrt((this.getCenterX()-obj.getCenterX())*(this.getCenterX()-obj.getCenterX()) + (this.getCenterY()-obj.getCenterY())*(this.getCenterY()-obj.getCenterY())); if(this.getCenterX() + width + this.movement.getDx() >= dist || this.getCenterY() + width + this.movement.getDy() >= dist){ */ if(ImageBase.contains(this.mainimg)) { System.out.println("FIRST"); ArrayList<int[]> pixels = ImageBase.getPixels(this.mainimg); for(int i = 0; i < pixels.size(); i++) { if(obj.isContaining(pixels.get(i)[0] + this.getX(), pixels.get(i)[1] + this.getY())) { System.out.println("YAY"); return true; } } } //} return false; } @Override public boolean isContaining(float x, float y){ if(getCenterX() + width + this.movement.getDx() >= x || getCenterY() + height + this.movement.getDy() >= y || getCenterX() - width - this.movement.getDx() <= x || getCenterY() - height - this.movement.getDy() <= y ){ return pointOnImage(x, y); } else return false; } @Override public float getX(){ return this.x; } @Override public float getY(){ return this.y; } @Override public float getCenterX(){ return getX() + mainimg.getWidth()/2; } @Override public float getCenterY(){ return getY() + mainimg.getHeight()/2; } @Override public void setX(float x){ this.x = x; } @Override public void setY(float y){ this.y = y; } @Override public void setCenterX(float x){ this.centerx = x; } @Override public void setCenterY(float y){ this.centery = y; } public boolean pointOnImage(float x, float y) { if(x-getX() < 0 || x-getX() >= mainimg.getWidth() || y-getY() < 0 || y-getY() >= mainimg.getHeight()) { return false; } Color c = mainimg.getColor((int) (x-getX()), (int)(y-getY())); return c.a == 0f; } }
diff --git a/src/com/chrishoekstra/trello/adapter/CardAdapter.java b/src/com/chrishoekstra/trello/adapter/CardAdapter.java index 88088a0..71d62c9 100644 --- a/src/com/chrishoekstra/trello/adapter/CardAdapter.java +++ b/src/com/chrishoekstra/trello/adapter/CardAdapter.java @@ -1,54 +1,54 @@ package com.chrishoekstra.trello.adapter; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.chrishoekstra.trello.R; import com.chrishoekstra.trello.vo.CardVO; public class CardAdapter extends ArrayAdapter<CardVO> { public ArrayList<CardVO> mCards; private LayoutInflater mInflater; public CardAdapter(Context context, int textViewResourceId, ArrayList<CardVO> cards) { super(context, textViewResourceId, cards); mInflater = LayoutInflater.from(context); mCards = cards; } public void updateCards(ArrayList<CardVO> cards) { mCards = cards; notifyDataSetChanged(); } @Override public View getView(final int position, View convertView, ViewGroup parent) { TextView nameText; if (convertView == null) { convertView = mInflater.inflate(R.layout.card_row, null); nameText = (TextView) convertView.findViewById(R.id.name); convertView.setTag(R.id.name, nameText); } else { nameText = (TextView) convertView.getTag(R.id.name); } - CardVO board = mCards.get(position); + CardVO card = mCards.get(position); - if (board != null) { - nameText.setText(board.name); + if (card != null) { + nameText.setText(card.name); } return convertView; } }
false
true
public View getView(final int position, View convertView, ViewGroup parent) { TextView nameText; if (convertView == null) { convertView = mInflater.inflate(R.layout.card_row, null); nameText = (TextView) convertView.findViewById(R.id.name); convertView.setTag(R.id.name, nameText); } else { nameText = (TextView) convertView.getTag(R.id.name); } CardVO board = mCards.get(position); if (board != null) { nameText.setText(board.name); } return convertView; }
public View getView(final int position, View convertView, ViewGroup parent) { TextView nameText; if (convertView == null) { convertView = mInflater.inflate(R.layout.card_row, null); nameText = (TextView) convertView.findViewById(R.id.name); convertView.setTag(R.id.name, nameText); } else { nameText = (TextView) convertView.getTag(R.id.name); } CardVO card = mCards.get(position); if (card != null) { nameText.setText(card.name); } return convertView; }
diff --git a/src/haven/Partyview.java b/src/haven/Partyview.java index c787114..9b4fd6b 100644 --- a/src/haven/Partyview.java +++ b/src/haven/Partyview.java @@ -1,116 +1,116 @@ /* * This file is part of the Haven & Hearth game client. * Copyright (C) 2009 Fredrik Tolf <[email protected]>, and * Björn Johannessen <[email protected]> * * Redistribution and/or modification of this file is subject to the * terms of the GNU Lesser General Public License, version 3, as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * Other parts of this source tree adhere to other copying * rights. Please see the file `COPYING' in the root directory of the * source tree for details. * * A copy the GNU Lesser General Public License is distributed along * with the source tree of which this file is a part in the file * `doc/LPGL-3'. If it is missing for any reason, please see the Free * Software Foundation's website at <http://www.fsf.org/>, or write * to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA */ package haven; import haven.Party.Member; import java.util.*; import java.util.Map.Entry; public class Partyview extends Widget { int ign; Party party = ui.sess.glob.party; Map<Integer, Member> om = null; Member ol = null; Map<Member, Avaview> avs = new HashMap<Member, Avaview>(); Button leave = null; static { Widget.addtype("pv", new WidgetFactory() { public Widget create(Coord c, Widget parent, Object[] args) { return(new Partyview(c, parent, (Integer)args[0])); } }); } Partyview(Coord c, Widget parent, int ign) { super(c, new Coord(84, 140), parent); this.ign = ign; update(); } private void update() { if(party.memb != om) { Collection<Member> old = new HashSet<Member>(avs.keySet()); for(Member m : (om = party.memb).values()) { if(m.gobid == ign) continue; Avaview w = avs.get(m); if(w == null) { w = new Avaview(Coord.z, this, m.gobid, new Coord(27, 27)); avs.put(m, w); } else { - old.remove(w); + old.remove(m); } } for(Member m : old) { ui.destroy(avs.get(m)); avs.remove(m); } List<Map.Entry<Member, Avaview>> wl = new ArrayList<Map.Entry<Member, Avaview>>(avs.entrySet()); Collections.sort(wl, new Comparator<Map.Entry<Member, Avaview>>() { public int compare(Entry<Member, Avaview> a, Entry<Member, Avaview> b) { return(a.getKey().gobid - b.getKey().gobid); } }); int i = 0; for(Map.Entry<Member, Avaview> e : wl) { e.getValue().c = new Coord((i % 2) * 43, (i / 2) * 43 + 24); i++; } } for(Map.Entry<Member, Avaview> e : avs.entrySet()) { e.getValue().color = e.getKey().col; } if((avs.size() > 0) && (leave == null)) { leave = new Button(Coord.z, 84, this, "Leave party"); } if((avs.size() == 0) && (leave != null)) { ui.destroy(leave); leave = null; } } public void wdgmsg(Widget sender, String msg, Object... args) { if(sender == leave) { wdgmsg("leave"); return; } for(Member m : avs.keySet()) { if(sender == avs.get(m)) { wdgmsg("click", m.gobid, args[0]); return; } } super.wdgmsg(sender, msg, args); } public void draw(GOut g) { update(); super.draw(g); } }
true
true
private void update() { if(party.memb != om) { Collection<Member> old = new HashSet<Member>(avs.keySet()); for(Member m : (om = party.memb).values()) { if(m.gobid == ign) continue; Avaview w = avs.get(m); if(w == null) { w = new Avaview(Coord.z, this, m.gobid, new Coord(27, 27)); avs.put(m, w); } else { old.remove(w); } } for(Member m : old) { ui.destroy(avs.get(m)); avs.remove(m); } List<Map.Entry<Member, Avaview>> wl = new ArrayList<Map.Entry<Member, Avaview>>(avs.entrySet()); Collections.sort(wl, new Comparator<Map.Entry<Member, Avaview>>() { public int compare(Entry<Member, Avaview> a, Entry<Member, Avaview> b) { return(a.getKey().gobid - b.getKey().gobid); } }); int i = 0; for(Map.Entry<Member, Avaview> e : wl) { e.getValue().c = new Coord((i % 2) * 43, (i / 2) * 43 + 24); i++; } } for(Map.Entry<Member, Avaview> e : avs.entrySet()) { e.getValue().color = e.getKey().col; } if((avs.size() > 0) && (leave == null)) { leave = new Button(Coord.z, 84, this, "Leave party"); } if((avs.size() == 0) && (leave != null)) { ui.destroy(leave); leave = null; } }
private void update() { if(party.memb != om) { Collection<Member> old = new HashSet<Member>(avs.keySet()); for(Member m : (om = party.memb).values()) { if(m.gobid == ign) continue; Avaview w = avs.get(m); if(w == null) { w = new Avaview(Coord.z, this, m.gobid, new Coord(27, 27)); avs.put(m, w); } else { old.remove(m); } } for(Member m : old) { ui.destroy(avs.get(m)); avs.remove(m); } List<Map.Entry<Member, Avaview>> wl = new ArrayList<Map.Entry<Member, Avaview>>(avs.entrySet()); Collections.sort(wl, new Comparator<Map.Entry<Member, Avaview>>() { public int compare(Entry<Member, Avaview> a, Entry<Member, Avaview> b) { return(a.getKey().gobid - b.getKey().gobid); } }); int i = 0; for(Map.Entry<Member, Avaview> e : wl) { e.getValue().c = new Coord((i % 2) * 43, (i / 2) * 43 + 24); i++; } } for(Map.Entry<Member, Avaview> e : avs.entrySet()) { e.getValue().color = e.getKey().col; } if((avs.size() > 0) && (leave == null)) { leave = new Button(Coord.z, 84, this, "Leave party"); } if((avs.size() == 0) && (leave != null)) { ui.destroy(leave); leave = null; } }
diff --git a/core/servicemix-core/src/test/java/org/apache/servicemix/jbi/nmr/flow/jca/JcaFlowWithTxLogTest.java b/core/servicemix-core/src/test/java/org/apache/servicemix/jbi/nmr/flow/jca/JcaFlowWithTxLogTest.java index a987387b0..9e4073602 100644 --- a/core/servicemix-core/src/test/java/org/apache/servicemix/jbi/nmr/flow/jca/JcaFlowWithTxLogTest.java +++ b/core/servicemix-core/src/test/java/org/apache/servicemix/jbi/nmr/flow/jca/JcaFlowWithTxLogTest.java @@ -1,136 +1,137 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.servicemix.jbi.nmr.flow.jca; import javax.jbi.messaging.ExchangeStatus; import javax.jbi.messaging.InOut; import javax.jbi.messaging.MessageExchange; import javax.jbi.messaging.MessagingException; import javax.jbi.messaging.NormalizedMessage; import javax.naming.Context; import javax.xml.namespace.QName; import junit.framework.TestCase; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.store.memory.MemoryPersistenceAdapter; import org.apache.servicemix.MessageExchangeListener; import org.apache.servicemix.client.DefaultServiceMixClient; import org.apache.servicemix.components.util.ComponentSupport; import org.apache.servicemix.jbi.container.ActivationSpec; import org.apache.servicemix.jbi.container.JBIContainer; import org.apache.servicemix.jbi.jaxp.StringSource; import org.apache.servicemix.jbi.nmr.flow.Flow; import org.apache.xbean.spring.jndi.SpringInitialContextFactory; import org.jencks.GeronimoPlatformTransactionManager; import org.jencks.factory.TransactionManagerFactoryBean; /** * @version $Revision: 426415 $ */ public class JcaFlowWithTxLogTest extends TestCase { private JBIContainer senderContainer = new JBIContainer(); private JBIContainer receiverContainer = new JBIContainer(); private BrokerService broker; private GeronimoPlatformTransactionManager tm; public class MyEchoComponent extends ComponentSupport implements MessageExchangeListener { public void onMessageExchange(MessageExchange exchange) throws MessagingException { if(exchange.getStatus() == ExchangeStatus.ACTIVE && exchange instanceof InOut) { InOut inOut = (InOut) exchange; NormalizedMessage inMessage = inOut.getInMessage(); NormalizedMessage outMessage = inOut.createMessage(); outMessage.setContent(inMessage.getContent()); inOut.setOutMessage(outMessage); send(inOut); } } } /* * @see TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); System.setProperty(Context.INITIAL_CONTEXT_FACTORY, SpringInitialContextFactory.class.getName()); System.setProperty(Context.PROVIDER_URL, "jndi.xml"); TransactionManagerFactoryBean factory = new TransactionManagerFactoryBean(); factory.setTransactionLogDir("target/txlog"); tm = (GeronimoPlatformTransactionManager) factory.getObject(); broker = new BrokerService(); broker.setPersistenceAdapter(new MemoryPersistenceAdapter()); broker.addConnector("tcp://localhost:61616"); broker.start(); JCAFlow senderFlow = new JCAFlow(); senderFlow.setJmsURL("tcp://localhost:61616"); senderContainer.setTransactionManager(tm); senderContainer.setEmbedded(true); senderContainer.setName("senderContainer"); senderContainer.setFlows(new Flow[] { senderFlow} ); senderContainer.setMonitorInstallationDirectory(false); senderContainer.setAutoEnlistInTransaction(true); senderContainer.init(); senderContainer.start(); JCAFlow receiverFlow = new JCAFlow(); receiverFlow.setJmsURL("tcp://localhost:61616"); receiverContainer.setTransactionManager(tm); receiverContainer.setEmbedded(true); receiverContainer.setName("receiverContainer"); receiverContainer.setFlows(new Flow[] { receiverFlow} ); receiverContainer.setMonitorInstallationDirectory(false); + receiverContainer.setAutoEnlistInTransaction(true); receiverContainer.init(); receiverContainer.start(); } protected void tearDown() throws Exception{ super.tearDown(); senderContainer.shutDown(); receiverContainer.shutDown(); broker.stop(); } public void testClusteredInOut() throws Exception { QName service = new QName("http://org.echo", "echo"); MyEchoComponent echoComponent = new MyEchoComponent(); echoComponent.setService(service); echoComponent.setEndpoint("echo"); ActivationSpec activationSpec = new ActivationSpec("echo", echoComponent); activationSpec.setService(service); receiverContainer.activateComponent(activationSpec); DefaultServiceMixClient client = new DefaultServiceMixClient(senderContainer); for (int i = 0; i < 10; i++) { InOut inOut = client.createInOutExchange(service, null, null); NormalizedMessage inMessage = inOut.createMessage(); inMessage.setContent(new StringSource("<test id='" + i + "'/>")); inOut.setInMessage(inMessage); client.send(inOut); inOut = (InOut) client.receive(1000); assertNotNull(inOut.getOutMessage()); client.done(inOut); } } }
true
true
protected void setUp() throws Exception { super.setUp(); System.setProperty(Context.INITIAL_CONTEXT_FACTORY, SpringInitialContextFactory.class.getName()); System.setProperty(Context.PROVIDER_URL, "jndi.xml"); TransactionManagerFactoryBean factory = new TransactionManagerFactoryBean(); factory.setTransactionLogDir("target/txlog"); tm = (GeronimoPlatformTransactionManager) factory.getObject(); broker = new BrokerService(); broker.setPersistenceAdapter(new MemoryPersistenceAdapter()); broker.addConnector("tcp://localhost:61616"); broker.start(); JCAFlow senderFlow = new JCAFlow(); senderFlow.setJmsURL("tcp://localhost:61616"); senderContainer.setTransactionManager(tm); senderContainer.setEmbedded(true); senderContainer.setName("senderContainer"); senderContainer.setFlows(new Flow[] { senderFlow} ); senderContainer.setMonitorInstallationDirectory(false); senderContainer.setAutoEnlistInTransaction(true); senderContainer.init(); senderContainer.start(); JCAFlow receiverFlow = new JCAFlow(); receiverFlow.setJmsURL("tcp://localhost:61616"); receiverContainer.setTransactionManager(tm); receiverContainer.setEmbedded(true); receiverContainer.setName("receiverContainer"); receiverContainer.setFlows(new Flow[] { receiverFlow} ); receiverContainer.setMonitorInstallationDirectory(false); receiverContainer.init(); receiverContainer.start(); }
protected void setUp() throws Exception { super.setUp(); System.setProperty(Context.INITIAL_CONTEXT_FACTORY, SpringInitialContextFactory.class.getName()); System.setProperty(Context.PROVIDER_URL, "jndi.xml"); TransactionManagerFactoryBean factory = new TransactionManagerFactoryBean(); factory.setTransactionLogDir("target/txlog"); tm = (GeronimoPlatformTransactionManager) factory.getObject(); broker = new BrokerService(); broker.setPersistenceAdapter(new MemoryPersistenceAdapter()); broker.addConnector("tcp://localhost:61616"); broker.start(); JCAFlow senderFlow = new JCAFlow(); senderFlow.setJmsURL("tcp://localhost:61616"); senderContainer.setTransactionManager(tm); senderContainer.setEmbedded(true); senderContainer.setName("senderContainer"); senderContainer.setFlows(new Flow[] { senderFlow} ); senderContainer.setMonitorInstallationDirectory(false); senderContainer.setAutoEnlistInTransaction(true); senderContainer.init(); senderContainer.start(); JCAFlow receiverFlow = new JCAFlow(); receiverFlow.setJmsURL("tcp://localhost:61616"); receiverContainer.setTransactionManager(tm); receiverContainer.setEmbedded(true); receiverContainer.setName("receiverContainer"); receiverContainer.setFlows(new Flow[] { receiverFlow} ); receiverContainer.setMonitorInstallationDirectory(false); receiverContainer.setAutoEnlistInTransaction(true); receiverContainer.init(); receiverContainer.start(); }
diff --git a/src/org/redbus/BusTimesActivity.java b/src/org/redbus/BusTimesActivity.java index 0507338..b7bc7c0 100644 --- a/src/org/redbus/BusTimesActivity.java +++ b/src/org/redbus/BusTimesActivity.java @@ -1,599 +1,599 @@ /* * Copyright 2010 Andrew De Quincey - [email protected] * This file is part of rEdBus. * * rEdBus 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. * * rEdBus 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 rEdBus. If not, see <http://www.gnu.org/licenses/>. */ package org.redbus; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import android.app.AlarmManager; import android.app.AlertDialog; import android.app.ListActivity; import android.app.PendingIntent; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnCancelListener; import android.location.LocationManager; import android.os.Bundle; import android.os.SystemClock; import android.text.InputFilter; import android.text.InputType; import android.text.method.DigitsKeyListener; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; public class BusTimesActivity extends ListActivity implements BusDataResponseListener { private long StopCode = -1; private String StopName = ""; private String sorting = ""; private ProgressDialog busyDialog = null; private int expectedRequestId = -1; private static final SimpleDateFormat titleDateFormat = new SimpleDateFormat("EEE dd MMM HH:mm"); private static final SimpleDateFormat advanceDateFormat = new SimpleDateFormat("EEE dd MMM yyyy"); private static final String[] temporalAlarmStrings = new String[] { "Due", "5 mins away", "10 mins away" }; private static final int[] temporalAlarmTimeouts = new int[] { 0, 5 * 60, 10 * 60}; private static final String[] proximityAlarmStrings = new String[] { "20 metres", "50 metres", "100 metres", "250 metres", "500 metres" }; private static final int[] proximitylAlarmDistances= new int[] { 20, 50, 100, 200, 500}; public static void showActivity(Context context, long stopCode, String stopName) { Intent i = new Intent(context, BusTimesActivity.class); i.putExtra("StopCode", stopCode); i.putExtra("StopName", stopName); context.startActivity(i); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.bustimes); registerForContextMenu(getListView()); StopCode = getIntent().getLongExtra("StopCode", -1); if (StopCode != -1) findViewById(android.R.id.empty).setVisibility(View.GONE); StopName = ""; CharSequence tmp = getIntent().getCharSequenceExtra("StopName"); if (tmp != null) StopName = tmp.toString(); LocalDBHelper db = new LocalDBHelper(this); try { sorting = db.getGlobalSetting("bustimesort", "arrival"); } finally { db.close(); } update(); } @Override protected void onDestroy() { busyDialog = null; super.onDestroy(); } private void update() { update(0, null); } private void update(int daysInAdvance, Date timeInAdvance) { if (StopCode != -1) { Date displayDate = timeInAdvance; if (displayDate == null) displayDate = new Date(); setTitle(StopName + " (" + titleDateFormat.format(displayDate) + ")"); displayBusy("Getting BusStop times"); expectedRequestId = BusDataHelper.getBusTimesAsync(StopCode, daysInAdvance, timeInAdvance, this); } else { setTitle("Unknown BusStop"); findViewById(android.R.id.empty).setVisibility(View.VISIBLE); } } private void displayBusy(String reason) { dismissBusy(); busyDialog = ProgressDialog.show(this, "", reason, true, true, new OnCancelListener() { public void onCancel(DialogInterface dialog) { BusTimesActivity.this.expectedRequestId = -1; } }); } private void dismissBusy() { if (busyDialog != null) { try { busyDialog.dismiss(); } catch (Throwable t) { } busyDialog = null; } } private void hideStatusBoxes() { findViewById(R.id.bustimes_nodepartures).setVisibility(View.GONE); findViewById(R.id.bustimes_error).setVisibility(View.GONE); findViewById(android.R.id.empty).setVisibility(View.GONE); } public void getBusTimesError(int requestId, int code, String message) { if (requestId != expectedRequestId) return; dismissBusy(); hideStatusBoxes(); setListAdapter(new BusTimesAdapter(this, R.layout.bustimes_item, new ArrayList<BusTime>())); findViewById(R.id.bustimes_error).setVisibility(View.VISIBLE); new AlertDialog.Builder(this).setTitle("Error"). setMessage("Unable to download stop times: " + message). setPositiveButton(android.R.string.ok, null). show(); } public void getBusTimesSuccess(int requestId, List<BusTime> busTimes) { if (requestId != expectedRequestId) return; dismissBusy(); hideStatusBoxes(); if (sorting.equalsIgnoreCase("service")) { Collections.sort(busTimes, new Comparator<BusTime>() { public int compare(BusTime arg0, BusTime arg1) { if (arg0.baseService != arg1.baseService) return arg0.baseService - arg1.baseService; return arg0.service.compareTo(arg1.service); } }); } else if (sorting.equalsIgnoreCase("arrival")) { Collections.sort(busTimes, new Comparator<BusTime>() { public int compare(BusTime arg0, BusTime arg1) { if ((arg0.arrivalAbsoluteTime != null) && (arg1.arrivalAbsoluteTime != null)) { // bus data never seems to span to the next day, so this string comparison should always work return arg0.arrivalAbsoluteTime.compareTo(arg1.arrivalAbsoluteTime); } return arg0.arrivalSortingIndex - arg1.arrivalSortingIndex; } }); } setListAdapter(new BusTimesAdapter(this, R.layout.bustimes_item, busTimes)); if (busTimes.isEmpty()) findViewById(R.id.bustimes_nodepartures).setVisibility(View.VISIBLE); } private void UpdateServicesList(Button b, String[] services, boolean[] selectedServices) { StringBuffer result = new StringBuffer(); for(int i=0; i< services.length; i++) { if (selectedServices[i]) { if (result.length() > 0) result.append(", "); result.append(services[i]); } } b.setText(result); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { // get the bus stop details PointTree pt = PointTree.getPointTree(this); PointTree.BusStopTreeNode busStop = pt.lookupStopByStopCode((int) StopCode); if (busStop == null) return; // get the list of services for this stop ArrayList<String> servicesList = pt.lookupServices(busStop.getServicesMap()); final String[] services = servicesList.toArray(new String[servicesList.size()]); final boolean[] selectedServices = new boolean[services.length]; // preselect the clicked-on service TextView clickedService = (TextView) v.findViewById(R.id.bustimes_service); for(int i=0; i< services.length; i++) { if (clickedService.getText().toString().equalsIgnoreCase(services[i])) { selectedServices[i] = true; break; } } // load the view View dialogView = getLayoutInflater().inflate(R.layout.addtemporalalert, null); // setup services selector final Button servicesButton = (Button) dialogView.findViewById(R.id.addtemporalalert_services); BusTimesActivity.this.UpdateServicesList(servicesButton, services, selectedServices); servicesButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { new AlertDialog.Builder( BusTimesActivity.this ) .setMultiChoiceItems( services, selectedServices, new DialogInterface.OnMultiChoiceClickListener() { public void onClick(DialogInterface dialog, int which, boolean isChecked) { selectedServices[which] = isChecked; } }) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { BusTimesActivity.this.UpdateServicesList(servicesButton, services, selectedServices); } }) .show(); } }); // setup time selector final Spinner timeSpinner = (Spinner) dialogView.findViewById(R.id.addtemporalalert_time); ArrayAdapter<String> timeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, temporalAlarmStrings); timeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); timeSpinner.setAdapter(timeAdapter); // show the dialog! new AlertDialog.Builder(this) .setView(dialogView) .setTitle("Set alarm") .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // figure out list of services ArrayList<String> selectedServicesList = new ArrayList<String>(); for(int i=0; i< services.length; i++) { if (selectedServices[i]) { selectedServicesList.add(services[i]); } } if (selectedServicesList.size() == 0) return; // create/update an intent Intent i = new Intent(BusTimesActivity.this, TemporalAlarmReceiver.class); i.putExtra("StopCode", StopCode); i.putExtra("StopName", StopName); i.putExtra("Services", selectedServicesList.toArray(new String[selectedServicesList.size()])); i.putExtra("StartTime", System.currentTimeMillis()); i.putExtra("TimeoutSecs", temporalAlarmTimeouts[timeSpinner.getSelectedItemPosition()]); PendingIntent pi = PendingIntent.getBroadcast(BusTimesActivity.this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT); // schedule it in 10 seconds AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); am.cancel(pi); am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 10000, pi); Toast.makeText(BusTimesActivity.this, "Alarm added!", Toast.LENGTH_SHORT).show(); } }) .setNegativeButton(android.R.string.cancel, null) .show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.bustimes_menu, menu); LocalDBHelper db = new LocalDBHelper(this); try { if (db.isBookmark(StopCode)) { menu.findItem(R.id.bustimes_menu_addbookmark).setEnabled(false); } else { menu.findItem(R.id.bustimes_menu_renamebookmark).setEnabled(false); menu.findItem(R.id.bustimes_menu_deletebookmark).setEnabled(false); } } finally { db.close(); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.bustimes_menu_refresh: update(); return true; case R.id.bustimes_menu_enterstopcode: { final EditText input = new EditText(this); input.setInputType(InputType.TYPE_CLASS_PHONE); input.setFilters(new InputFilter[] { new InputFilter.LengthFilter(8), new DigitsKeyListener() } ); new AlertDialog.Builder(this) .setTitle("Enter BusStop code") .setView(input) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { long stopCode = -1; try { stopCode = Long.parseLong(input.getText().toString()); } catch (Exception ex) { new AlertDialog.Builder(BusTimesActivity.this) .setTitle("Invalid BusStop code") .setMessage("The code was invalid; please try again using only numbers") .setPositiveButton(android.R.string.ok, null) .show(); return; } PointTree.BusStopTreeNode busStop = PointTree.getPointTree(BusTimesActivity.this).lookupStopByStopCode((int) stopCode); if (busStop != null) { StopCode = busStop.getStopCode(); StopName = busStop.getStopName(); update(); } else { new AlertDialog.Builder(BusTimesActivity.this).setTitle("Error") .setMessage("The code was invalid; please try again") .setPositiveButton(android.R.string.ok, null) .show(); } } }) .setNegativeButton(android.R.string.cancel, null) .show(); return true; } case R.id.bustimes_menu_addbookmark: if (StopCode != -1) { LocalDBHelper db = new LocalDBHelper(this); try { db.addBookmark(StopCode, StopName); } finally { db.close(); } Toast.makeText(this, "Added bookmark", Toast.LENGTH_SHORT).show(); } return true; case R.id.bustimes_menu_renamebookmark: { final EditText input = new EditText(this); input.setText(StopName); new AlertDialog.Builder(this) .setTitle("Rename bookmark") .setView(input) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { LocalDBHelper db = new LocalDBHelper(BusTimesActivity.this); try { db.renameBookmark(BusTimesActivity.this.StopCode, input.getText().toString()); } finally { db.close(); } StopName = input.getText().toString(); update(); } }) .setNegativeButton(android.R.string.cancel, null) .show(); return true; } case R.id.bustimes_menu_deletebookmark: { new AlertDialog.Builder(this). setMessage("Are you sure you want to delete this bookmark?"). setNegativeButton(android.R.string.cancel, null). setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { LocalDBHelper db = new LocalDBHelper(BusTimesActivity.this); try { db.deleteBookmark(BusTimesActivity.this.StopCode); } finally { db.close(); } BusTimesActivity.this.update(); } }). show(); return true; } /* case R.id.bustimes_menu_viewonmap: // FIXME: implement return true; */ case R.id.bustimes_menu_futuredepartures: LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = vi.inflate(R.layout.futuredepartures, null); final GregorianCalendar calendar = new GregorianCalendar(); final TimePicker timePicker = (TimePicker) v.findViewById(R.id.futuredepartures_time); timePicker.setCurrentHour(calendar.get(Calendar.HOUR_OF_DAY)); timePicker.setCurrentMinute(calendar.get(Calendar.MINUTE)); timePicker.setIs24HourView(true); final Spinner datePicker = (Spinner) v.findViewById(R.id.futuredepartures_date); String[] dates = new String[4]; for(int i=0; i < 4; i++) { dates[i] = advanceDateFormat.format(calendar.getTime()); calendar.add(Calendar.DAY_OF_MONTH, 1); } calendar.add(Calendar.DAY_OF_MONTH, -4); ArrayAdapter<String> dateAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, dates); dateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); datePicker.setAdapter(dateAdapter); new AlertDialog.Builder(this) .setTitle("Choose the desired date/time") .setView(v) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { calendar.add(Calendar.DAY_OF_MONTH, datePicker.getSelectedItemPosition()); calendar.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour()); calendar.set(Calendar.MINUTE, timePicker.getCurrentMinute()); update(datePicker.getSelectedItemPosition(), calendar.getTime()); } }) .setNegativeButton(android.R.string.cancel, null) .show(); return true; case R.id.bustimes_menu_sorting_arrival: { sorting = "arrival"; LocalDBHelper db = new LocalDBHelper(this); try { db.setGlobalSetting("bustimesort", sorting); } finally { db.close(); } update(); return true; } case R.id.bustimes_menu_sorting_service: { sorting = "service"; LocalDBHelper db = new LocalDBHelper(this); try { db.setGlobalSetting("bustimesort", sorting); } finally { db.close(); } update(); return true; } case R.id.bustimes_menu_proximityalert: { // get the bus stop details PointTree pt = PointTree.getPointTree(this); final PointTree.BusStopTreeNode busStop = pt.lookupStopByStopCode((int) StopCode); if (busStop == null) break; // load the view View dialogView = getLayoutInflater().inflate(R.layout.addproximityalert, null); // setup distance selector final Spinner distanceSpinner = (Spinner) dialogView.findViewById(R.id.addproximityalert_distance); ArrayAdapter<String> timeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, proximityAlarmStrings); timeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); distanceSpinner.setAdapter(timeAdapter); // show the dialog! new AlertDialog.Builder(this) .setView(dialogView) .setTitle("Set alarm") .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // create/update an intent Intent i = new Intent(BusTimesActivity.this, ProximityAlarmReceiver.class); i.putExtra("StopCode", StopCode); i.putExtra("StopName", StopName); i.putExtra("X", busStop.getX()); i.putExtra("Y", busStop.getY()); i.putExtra("Distance", proximitylAlarmDistances[distanceSpinner.getSelectedItemPosition()]); PendingIntent pi = PendingIntent.getBroadcast(BusTimesActivity.this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT); LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); - lm.addProximityAlert(busStop.getY(), busStop.getX(), proximitylAlarmDistances[distanceSpinner.getSelectedItemPosition()], 60 * 60 * 1000, pi); + lm.addProximityAlert(busStop.getX(), busStop.getY(), proximitylAlarmDistances[distanceSpinner.getSelectedItemPosition()], 60 * 60 * 1000, pi); Toast.makeText(BusTimesActivity.this, "Alarm added!", Toast.LENGTH_SHORT).show(); } }) .setNegativeButton(android.R.string.cancel, null) .show(); } } return false; } private class BusTimesAdapter extends ArrayAdapter<BusTime> { private List<BusTime> items; private int textViewResourceId; public BusTimesAdapter(Context context, int textViewResourceId, List<BusTime> items) { super(context, textViewResourceId, items); this.textViewResourceId = textViewResourceId; this.items = items; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(textViewResourceId, null); } BusTime busTime = items.get(position); if (busTime != null) { TextView serviceView = (TextView) v.findViewById(R.id.bustimes_service); TextView destinationView = (TextView) v.findViewById(R.id.bustimes_destination); TextView timeView = (TextView) v.findViewById(R.id.bustimes_time); serviceView.setText(busTime.service); if (busTime.isDiverted) { destinationView.setText("DIVERTED"); timeView.setText(""); } else { destinationView.setText(busTime.destination); if (busTime.arrivalIsDue) timeView.setText("Due"); else if (busTime.arrivalAbsoluteTime != null) timeView.setText(busTime.arrivalAbsoluteTime); else timeView.setText(Integer.toString(busTime.arrivalMinutesLeft)); if (busTime.arrivalEstimated) timeView.setText("~" + timeView.getText()); } } return v; } } }
true
true
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.bustimes_menu_refresh: update(); return true; case R.id.bustimes_menu_enterstopcode: { final EditText input = new EditText(this); input.setInputType(InputType.TYPE_CLASS_PHONE); input.setFilters(new InputFilter[] { new InputFilter.LengthFilter(8), new DigitsKeyListener() } ); new AlertDialog.Builder(this) .setTitle("Enter BusStop code") .setView(input) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { long stopCode = -1; try { stopCode = Long.parseLong(input.getText().toString()); } catch (Exception ex) { new AlertDialog.Builder(BusTimesActivity.this) .setTitle("Invalid BusStop code") .setMessage("The code was invalid; please try again using only numbers") .setPositiveButton(android.R.string.ok, null) .show(); return; } PointTree.BusStopTreeNode busStop = PointTree.getPointTree(BusTimesActivity.this).lookupStopByStopCode((int) stopCode); if (busStop != null) { StopCode = busStop.getStopCode(); StopName = busStop.getStopName(); update(); } else { new AlertDialog.Builder(BusTimesActivity.this).setTitle("Error") .setMessage("The code was invalid; please try again") .setPositiveButton(android.R.string.ok, null) .show(); } } }) .setNegativeButton(android.R.string.cancel, null) .show(); return true; } case R.id.bustimes_menu_addbookmark: if (StopCode != -1) { LocalDBHelper db = new LocalDBHelper(this); try { db.addBookmark(StopCode, StopName); } finally { db.close(); } Toast.makeText(this, "Added bookmark", Toast.LENGTH_SHORT).show(); } return true; case R.id.bustimes_menu_renamebookmark: { final EditText input = new EditText(this); input.setText(StopName); new AlertDialog.Builder(this) .setTitle("Rename bookmark") .setView(input) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { LocalDBHelper db = new LocalDBHelper(BusTimesActivity.this); try { db.renameBookmark(BusTimesActivity.this.StopCode, input.getText().toString()); } finally { db.close(); } StopName = input.getText().toString(); update(); } }) .setNegativeButton(android.R.string.cancel, null) .show(); return true; } case R.id.bustimes_menu_deletebookmark: { new AlertDialog.Builder(this). setMessage("Are you sure you want to delete this bookmark?"). setNegativeButton(android.R.string.cancel, null). setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { LocalDBHelper db = new LocalDBHelper(BusTimesActivity.this); try { db.deleteBookmark(BusTimesActivity.this.StopCode); } finally { db.close(); } BusTimesActivity.this.update(); } }). show(); return true; } /* case R.id.bustimes_menu_viewonmap: // FIXME: implement return true; */ case R.id.bustimes_menu_futuredepartures: LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = vi.inflate(R.layout.futuredepartures, null); final GregorianCalendar calendar = new GregorianCalendar(); final TimePicker timePicker = (TimePicker) v.findViewById(R.id.futuredepartures_time); timePicker.setCurrentHour(calendar.get(Calendar.HOUR_OF_DAY)); timePicker.setCurrentMinute(calendar.get(Calendar.MINUTE)); timePicker.setIs24HourView(true); final Spinner datePicker = (Spinner) v.findViewById(R.id.futuredepartures_date); String[] dates = new String[4]; for(int i=0; i < 4; i++) { dates[i] = advanceDateFormat.format(calendar.getTime()); calendar.add(Calendar.DAY_OF_MONTH, 1); } calendar.add(Calendar.DAY_OF_MONTH, -4); ArrayAdapter<String> dateAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, dates); dateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); datePicker.setAdapter(dateAdapter); new AlertDialog.Builder(this) .setTitle("Choose the desired date/time") .setView(v) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { calendar.add(Calendar.DAY_OF_MONTH, datePicker.getSelectedItemPosition()); calendar.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour()); calendar.set(Calendar.MINUTE, timePicker.getCurrentMinute()); update(datePicker.getSelectedItemPosition(), calendar.getTime()); } }) .setNegativeButton(android.R.string.cancel, null) .show(); return true; case R.id.bustimes_menu_sorting_arrival: { sorting = "arrival"; LocalDBHelper db = new LocalDBHelper(this); try { db.setGlobalSetting("bustimesort", sorting); } finally { db.close(); } update(); return true; } case R.id.bustimes_menu_sorting_service: { sorting = "service"; LocalDBHelper db = new LocalDBHelper(this); try { db.setGlobalSetting("bustimesort", sorting); } finally { db.close(); } update(); return true; } case R.id.bustimes_menu_proximityalert: { // get the bus stop details PointTree pt = PointTree.getPointTree(this); final PointTree.BusStopTreeNode busStop = pt.lookupStopByStopCode((int) StopCode); if (busStop == null) break; // load the view View dialogView = getLayoutInflater().inflate(R.layout.addproximityalert, null); // setup distance selector final Spinner distanceSpinner = (Spinner) dialogView.findViewById(R.id.addproximityalert_distance); ArrayAdapter<String> timeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, proximityAlarmStrings); timeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); distanceSpinner.setAdapter(timeAdapter); // show the dialog! new AlertDialog.Builder(this) .setView(dialogView) .setTitle("Set alarm") .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // create/update an intent Intent i = new Intent(BusTimesActivity.this, ProximityAlarmReceiver.class); i.putExtra("StopCode", StopCode); i.putExtra("StopName", StopName); i.putExtra("X", busStop.getX()); i.putExtra("Y", busStop.getY()); i.putExtra("Distance", proximitylAlarmDistances[distanceSpinner.getSelectedItemPosition()]); PendingIntent pi = PendingIntent.getBroadcast(BusTimesActivity.this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT); LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); lm.addProximityAlert(busStop.getY(), busStop.getX(), proximitylAlarmDistances[distanceSpinner.getSelectedItemPosition()], 60 * 60 * 1000, pi); Toast.makeText(BusTimesActivity.this, "Alarm added!", Toast.LENGTH_SHORT).show(); } }) .setNegativeButton(android.R.string.cancel, null) .show(); } } return false; }
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.bustimes_menu_refresh: update(); return true; case R.id.bustimes_menu_enterstopcode: { final EditText input = new EditText(this); input.setInputType(InputType.TYPE_CLASS_PHONE); input.setFilters(new InputFilter[] { new InputFilter.LengthFilter(8), new DigitsKeyListener() } ); new AlertDialog.Builder(this) .setTitle("Enter BusStop code") .setView(input) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { long stopCode = -1; try { stopCode = Long.parseLong(input.getText().toString()); } catch (Exception ex) { new AlertDialog.Builder(BusTimesActivity.this) .setTitle("Invalid BusStop code") .setMessage("The code was invalid; please try again using only numbers") .setPositiveButton(android.R.string.ok, null) .show(); return; } PointTree.BusStopTreeNode busStop = PointTree.getPointTree(BusTimesActivity.this).lookupStopByStopCode((int) stopCode); if (busStop != null) { StopCode = busStop.getStopCode(); StopName = busStop.getStopName(); update(); } else { new AlertDialog.Builder(BusTimesActivity.this).setTitle("Error") .setMessage("The code was invalid; please try again") .setPositiveButton(android.R.string.ok, null) .show(); } } }) .setNegativeButton(android.R.string.cancel, null) .show(); return true; } case R.id.bustimes_menu_addbookmark: if (StopCode != -1) { LocalDBHelper db = new LocalDBHelper(this); try { db.addBookmark(StopCode, StopName); } finally { db.close(); } Toast.makeText(this, "Added bookmark", Toast.LENGTH_SHORT).show(); } return true; case R.id.bustimes_menu_renamebookmark: { final EditText input = new EditText(this); input.setText(StopName); new AlertDialog.Builder(this) .setTitle("Rename bookmark") .setView(input) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { LocalDBHelper db = new LocalDBHelper(BusTimesActivity.this); try { db.renameBookmark(BusTimesActivity.this.StopCode, input.getText().toString()); } finally { db.close(); } StopName = input.getText().toString(); update(); } }) .setNegativeButton(android.R.string.cancel, null) .show(); return true; } case R.id.bustimes_menu_deletebookmark: { new AlertDialog.Builder(this). setMessage("Are you sure you want to delete this bookmark?"). setNegativeButton(android.R.string.cancel, null). setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { LocalDBHelper db = new LocalDBHelper(BusTimesActivity.this); try { db.deleteBookmark(BusTimesActivity.this.StopCode); } finally { db.close(); } BusTimesActivity.this.update(); } }). show(); return true; } /* case R.id.bustimes_menu_viewonmap: // FIXME: implement return true; */ case R.id.bustimes_menu_futuredepartures: LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = vi.inflate(R.layout.futuredepartures, null); final GregorianCalendar calendar = new GregorianCalendar(); final TimePicker timePicker = (TimePicker) v.findViewById(R.id.futuredepartures_time); timePicker.setCurrentHour(calendar.get(Calendar.HOUR_OF_DAY)); timePicker.setCurrentMinute(calendar.get(Calendar.MINUTE)); timePicker.setIs24HourView(true); final Spinner datePicker = (Spinner) v.findViewById(R.id.futuredepartures_date); String[] dates = new String[4]; for(int i=0; i < 4; i++) { dates[i] = advanceDateFormat.format(calendar.getTime()); calendar.add(Calendar.DAY_OF_MONTH, 1); } calendar.add(Calendar.DAY_OF_MONTH, -4); ArrayAdapter<String> dateAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, dates); dateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); datePicker.setAdapter(dateAdapter); new AlertDialog.Builder(this) .setTitle("Choose the desired date/time") .setView(v) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { calendar.add(Calendar.DAY_OF_MONTH, datePicker.getSelectedItemPosition()); calendar.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour()); calendar.set(Calendar.MINUTE, timePicker.getCurrentMinute()); update(datePicker.getSelectedItemPosition(), calendar.getTime()); } }) .setNegativeButton(android.R.string.cancel, null) .show(); return true; case R.id.bustimes_menu_sorting_arrival: { sorting = "arrival"; LocalDBHelper db = new LocalDBHelper(this); try { db.setGlobalSetting("bustimesort", sorting); } finally { db.close(); } update(); return true; } case R.id.bustimes_menu_sorting_service: { sorting = "service"; LocalDBHelper db = new LocalDBHelper(this); try { db.setGlobalSetting("bustimesort", sorting); } finally { db.close(); } update(); return true; } case R.id.bustimes_menu_proximityalert: { // get the bus stop details PointTree pt = PointTree.getPointTree(this); final PointTree.BusStopTreeNode busStop = pt.lookupStopByStopCode((int) StopCode); if (busStop == null) break; // load the view View dialogView = getLayoutInflater().inflate(R.layout.addproximityalert, null); // setup distance selector final Spinner distanceSpinner = (Spinner) dialogView.findViewById(R.id.addproximityalert_distance); ArrayAdapter<String> timeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, proximityAlarmStrings); timeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); distanceSpinner.setAdapter(timeAdapter); // show the dialog! new AlertDialog.Builder(this) .setView(dialogView) .setTitle("Set alarm") .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // create/update an intent Intent i = new Intent(BusTimesActivity.this, ProximityAlarmReceiver.class); i.putExtra("StopCode", StopCode); i.putExtra("StopName", StopName); i.putExtra("X", busStop.getX()); i.putExtra("Y", busStop.getY()); i.putExtra("Distance", proximitylAlarmDistances[distanceSpinner.getSelectedItemPosition()]); PendingIntent pi = PendingIntent.getBroadcast(BusTimesActivity.this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT); LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); lm.addProximityAlert(busStop.getX(), busStop.getY(), proximitylAlarmDistances[distanceSpinner.getSelectedItemPosition()], 60 * 60 * 1000, pi); Toast.makeText(BusTimesActivity.this, "Alarm added!", Toast.LENGTH_SHORT).show(); } }) .setNegativeButton(android.R.string.cancel, null) .show(); } } return false; }
diff --git a/src/algo/DynamicSolver.java b/src/algo/DynamicSolver.java index 3d721c4..b09a95d 100644 --- a/src/algo/DynamicSolver.java +++ b/src/algo/DynamicSolver.java @@ -1,164 +1,164 @@ package algo; import io.GbkReader; import io.SolutionWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.apache.commons.lang.time.StopWatch; import model.CGene; import model.Constraints; import model.FamilyCriteria; import model.GlobalContext; import model.Helix; import utils.Utils; public class DynamicSolver { public static class State { public Helix h; public int answer; public int cumulativeAnswer; public List<State> inner; // last included item public State best; // if included, previous one public State prev; public State(Helix h) { super(); this.h = h; answer = -1; } public double getScore() { return answer*2.0/h.getSpan(); } @Override public String toString() { return "Score "+getScore()+" span "+h.getSpan()+" top "+h; } public void collectHelixes(List<Helix> helixes) { helixes.add(h); for (State s: inner) { s.collectHelixes(helixes); } } public void writeDebug(String prefix) { Collections.sort(inner,new Comparator<State>() { @Override public int compare(State x, State y) { return x.h.getRight() < y.h.getRight() ? -1 : 1; } }); System.out.println(prefix+h+" ["); for (State state : inner) { state.writeDebug(prefix+" "); } System.out.println(prefix+" ]"); } } public State[] a; public DynamicSolver(List<Helix> h) { super(); a = new State[h.size()]; for (int i = 0; i < h.size(); ++i) a[i] = new State(h.get(i)); } public List<CGene> solve() { Arrays.sort(a,new Comparator<State>() { @Override public int compare(State x, State y) { return x.h.getRight() - y.h.getRight(); } }); State dummy = new State(new Helix(-1,-1,0)); dummy.cumulativeAnswer = 0; List<CGene> res = new ArrayList<CGene>(); for (int i = 0; i < a.length; i++) { ArrayList<State> inside = new ArrayList<State>(); inside.add(dummy); for (int j = 0; j < i; j++) { if (!(a[i].h.start < a[j].h.getLeft() && a[j].h.getRight() < a[i].h.end) - || a[i].answer == 0) + || a[j].answer == 0) continue; int p = inside.size()-1; while (inside.get(p).h.getRight() >= a[j].h.getLeft()) --p; a[j].cumulativeAnswer = inside.get(p).cumulativeAnswer + a[j].answer; if (inside.get(inside.size()-1).cumulativeAnswer > a[j].cumulativeAnswer) { a[j].cumulativeAnswer = inside.get(inside.size()-1).cumulativeAnswer; a[j].best = inside.get(inside.size()-1).best; } else { a[j].prev = inside.get(p).best; a[j].best = a[j]; } inside.add(a[j]); } if (true) { a[i].inner = new ArrayList<DynamicSolver.State>(); for (State s = inside.get(inside.size()-1).best; s != null; s = s.prev) { a[i].inner.add(s); } } a[i].answer = inside.get(inside.size()-1).cumulativeAnswer; // there is something inside or we have a valid hairpin if (a[i].answer > 0 || a[i].h.isHairpin()) a[i].answer += a[i].h.len; if (a[i].h.getSpan() >= Constraints.GENE_MIN_LEN && a[i].getScore() >= Constraints.PAIRED_MIN_RATIO) if (!a[i].h.isFAT()) { List<Helix> helixes = new ArrayList<Helix>(); a[i].collectHelixes(helixes); res.add(new CGene(helixes)); } } return res; } public static void main(String[] args) throws IOException { StopWatch tm = new StopWatch(); tm.start(); //String gbk = GbkReader.read("c:\\yandex\\Tests\\gbk_for_students\\ref_chr7_00.gbk"); String gbk = GbkReader.read("../ref_chr7_00.gbk"); //gbk = gbk.substring(0, 100000); GlobalContext.init(gbk); int total = 0; List<CGene> all = new ArrayList<CGene>(); for (int i = 0; i < gbk.length(); i+=200) { //if (i%10000 == 0) System.err.println(i); int[] codes = Utils.toInt(gbk.substring(i,Math.min(i+400,gbk.length()))); List<Helix> helixes = HelixFinder.findHelixesUnefficient(codes, 4, 4, 1000000); Helix.addShift(helixes, i); //System.out.println(helixes.size()); DynamicSolver solver = new DynamicSolver(helixes); List<CGene> res = solver.solve(); total += res.size(); all.addAll(res); } Collections.sort(all, new Comparator<CGene>() { @Override public int compare(CGene arg0, CGene arg1) { //return arg0.minPosition - arg1.minPosition; return Double.compare(arg1.getScore(), arg0.getScore()); } }); System.out.println(total); for (int i = 0; i < all.size() && i < 100; ++i) System.out.println(all.get(i)); System.out.println("Elapsed "+tm); tm.reset(); tm.start(); System.out.println("Candidates " + all.size()); List<CGene> filtered = GeneSelection.selectOptimal(all, new FamilyCriteria.Weight()); System.out.println("After "+filtered.size()); SolutionWriter.write(filtered, "../solution1.txt"); System.out.println("Elapsed "+tm); } }
true
true
public List<CGene> solve() { Arrays.sort(a,new Comparator<State>() { @Override public int compare(State x, State y) { return x.h.getRight() - y.h.getRight(); } }); State dummy = new State(new Helix(-1,-1,0)); dummy.cumulativeAnswer = 0; List<CGene> res = new ArrayList<CGene>(); for (int i = 0; i < a.length; i++) { ArrayList<State> inside = new ArrayList<State>(); inside.add(dummy); for (int j = 0; j < i; j++) { if (!(a[i].h.start < a[j].h.getLeft() && a[j].h.getRight() < a[i].h.end) || a[i].answer == 0) continue; int p = inside.size()-1; while (inside.get(p).h.getRight() >= a[j].h.getLeft()) --p; a[j].cumulativeAnswer = inside.get(p).cumulativeAnswer + a[j].answer; if (inside.get(inside.size()-1).cumulativeAnswer > a[j].cumulativeAnswer) { a[j].cumulativeAnswer = inside.get(inside.size()-1).cumulativeAnswer; a[j].best = inside.get(inside.size()-1).best; } else { a[j].prev = inside.get(p).best; a[j].best = a[j]; } inside.add(a[j]); } if (true) { a[i].inner = new ArrayList<DynamicSolver.State>(); for (State s = inside.get(inside.size()-1).best; s != null; s = s.prev) { a[i].inner.add(s); } } a[i].answer = inside.get(inside.size()-1).cumulativeAnswer; // there is something inside or we have a valid hairpin if (a[i].answer > 0 || a[i].h.isHairpin()) a[i].answer += a[i].h.len; if (a[i].h.getSpan() >= Constraints.GENE_MIN_LEN && a[i].getScore() >= Constraints.PAIRED_MIN_RATIO) if (!a[i].h.isFAT()) { List<Helix> helixes = new ArrayList<Helix>(); a[i].collectHelixes(helixes); res.add(new CGene(helixes)); } } return res; }
public List<CGene> solve() { Arrays.sort(a,new Comparator<State>() { @Override public int compare(State x, State y) { return x.h.getRight() - y.h.getRight(); } }); State dummy = new State(new Helix(-1,-1,0)); dummy.cumulativeAnswer = 0; List<CGene> res = new ArrayList<CGene>(); for (int i = 0; i < a.length; i++) { ArrayList<State> inside = new ArrayList<State>(); inside.add(dummy); for (int j = 0; j < i; j++) { if (!(a[i].h.start < a[j].h.getLeft() && a[j].h.getRight() < a[i].h.end) || a[j].answer == 0) continue; int p = inside.size()-1; while (inside.get(p).h.getRight() >= a[j].h.getLeft()) --p; a[j].cumulativeAnswer = inside.get(p).cumulativeAnswer + a[j].answer; if (inside.get(inside.size()-1).cumulativeAnswer > a[j].cumulativeAnswer) { a[j].cumulativeAnswer = inside.get(inside.size()-1).cumulativeAnswer; a[j].best = inside.get(inside.size()-1).best; } else { a[j].prev = inside.get(p).best; a[j].best = a[j]; } inside.add(a[j]); } if (true) { a[i].inner = new ArrayList<DynamicSolver.State>(); for (State s = inside.get(inside.size()-1).best; s != null; s = s.prev) { a[i].inner.add(s); } } a[i].answer = inside.get(inside.size()-1).cumulativeAnswer; // there is something inside or we have a valid hairpin if (a[i].answer > 0 || a[i].h.isHairpin()) a[i].answer += a[i].h.len; if (a[i].h.getSpan() >= Constraints.GENE_MIN_LEN && a[i].getScore() >= Constraints.PAIRED_MIN_RATIO) if (!a[i].h.isFAT()) { List<Helix> helixes = new ArrayList<Helix>(); a[i].collectHelixes(helixes); res.add(new CGene(helixes)); } } return res; }
diff --git a/edu/mit/wi/haploview/HaplotypeDisplay.java b/edu/mit/wi/haploview/HaplotypeDisplay.java index 60073ff..52a7aea 100644 --- a/edu/mit/wi/haploview/HaplotypeDisplay.java +++ b/edu/mit/wi/haploview/HaplotypeDisplay.java @@ -1,471 +1,472 @@ package edu.mit.wi.haploview; import java.awt.*; //import java.awt.geom.*; import java.awt.image.*; import java.io.*; import javax.swing.*; import java.text.*; import java.util.*; public class HaplotypeDisplay extends JComponent { Haplotype[][] orderedHaplos; Haplotype[][] filteredHaplos; HaploData theData; double multidprimeArray[]; int missingLimit = 5; boolean useThickness = true; double thinThresh = 1; double thickThresh = 10; private boolean forExport = false; public int alleleDisp; private Color dullRed = new Color(204,51,51); private Color dullBlue = new Color(51,51,204); public HaplotypeDisplay(HaploData h) throws HaploViewException { theData=h; if (blackNumImages == null) loadFontImages(); getHaps(); // int[][] bk = parent.blockController.blocks; //Vector blockVector = new Vector(); //for (int i = 0; i < bk.length; i++) { // blockVector.add(bk[i]); // } } public BufferedImage export(){ forExport = true; Dimension size = getPreferredSize(); BufferedImage i = new BufferedImage(size.width, size.height, BufferedImage.TYPE_3BYTE_BGR); paintComponent(i.getGraphics()); forExport = false; return i; } public void getHaps() throws HaploViewException{ if (theData.blocks == null) {return;} orderedHaplos = theData.generateHaplotypes(theData.blocks,false); adjustDisplay(); } static Image charImages[]; static Image blackNumImages[]; static Image grayNumImages[]; static Image markerNumImages[]; static final int ROW_HEIGHT = 20; static final int CHAR_WIDTH = 10; static final int CHAR_HEIGHT = 16; static final int MARKER_CHAR_WIDTH = 6; static final int MARKER_CHAR_HEIGHT = 9; // amount of room for lines between things final int LINE_LEFT = 3; final int LINE_RIGHT = 34; final int LINE_SPAN = 37; // border around entire image static final int BORDER = 10; // tag diamond static Image tagImage; // li'l pointy arrow static final int TAG_SPAN = 10; // load fake font as images, since java font stuff is so lousy protected void loadFontImages() { // read images from file Toolkit tk = Toolkit.getDefaultToolkit(); byte data[] = null; try { InputStream is = getClass().getResourceAsStream("orator.raw"); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayOutputStream out = new ByteArrayOutputStream(); int c = bis.read(); while (c != -1) { out.write(c); c = bis.read(); } //return out.toByteArray(); data = out.toByteArray(); } catch (IOException e) { System.err.println("error loading font data from orator.raw"); e.printStackTrace(); System.exit(1); } //byte data[] = loadBytes("orator1675.raw"); int pixels[] = new int[data.length]; for (int i = 0; i < data.length; i++) { // image values are the alpha of the image // image itself would be black pixels[i] = ((255 - (data[i] & 0xff)) << 24) | 0x000000; } MemoryImageSource mis; // top data is 110x48 image // lines are 16 pixels high, each char 10 pixels wide // the fifth 'char' is actually the little down triangle for tags // the eighth char is the 'unknown', which is an 8 in the data struct // (the acgt letters are 1234) // 6 and 7 are blank, but who cares, since it makes the code simpler // ACGT^ x // 012345679. (black) // 012345679. (gray) charImages = new Image[8]; for (int i = 0; i < 8; i++) { mis = new MemoryImageSource(10, 16, pixels, i*CHAR_WIDTH, 110); charImages[i] = tk.createImage(mis); } tagImage = charImages[4]; blackNumImages = new Image[11]; grayNumImages = new Image[11]; for (int i = 0; i < 11; i++) { mis = new MemoryImageSource(CHAR_WIDTH, CHAR_HEIGHT, pixels, 110*CHAR_HEIGHT + i*CHAR_WIDTH, 110); blackNumImages[i] = tk.createImage(mis); mis = new MemoryImageSource(CHAR_WIDTH, CHAR_HEIGHT, pixels, 110*CHAR_HEIGHT*2 + i*CHAR_WIDTH, 110); grayNumImages[i] = tk.createImage(mis); } // tag nums are rotated in the file (as they are used in the vis) // so they start at 9 and go down to 0 markerNumImages = new Image[10]; int offset = 110 * CHAR_HEIGHT * 3; for (int i = 9; i >= 0; --i) { mis = new MemoryImageSource(MARKER_CHAR_HEIGHT, MARKER_CHAR_WIDTH, pixels, offset + MARKER_CHAR_WIDTH*110*(9-i), 110); markerNumImages[i] = tk.createImage(mis); } } public void adjustDisplay(){ //this is called when the controller wants to change the haps //displayed, instead of directly repainting so that none of this math //is done when the screen repaints for other reasons (resizing, focus change, etc) //first filter haps on displaythresh Haplotype[][] filts; filts = new Haplotype[orderedHaplos.length][]; int numhaps = 0; int printable = 0; for (int i = 0; i < orderedHaplos.length; i++){ Vector tempVector = new Vector(); for (int j = 0; j < orderedHaplos[i].length; j++){ if (orderedHaplos[i][j].getPercentage()*100 > Options.getHaplotypeDisplayThreshold()){ tempVector.add(orderedHaplos[i][j]); numhaps++; } } if (numhaps > 1){ printable++; numhaps=0; } filts[i] = new Haplotype[tempVector.size()]; tempVector.copyInto(filts[i]); } // if user sets display thresh higher than most common hap in any given block if (!(printable == filts.length)){ JOptionPane.showMessageDialog(this.getParent(), "Error: At least one block has too few haplotypes of frequency > " + Options.getHaplotypeDisplayThreshold(), "Error", JOptionPane.ERROR_MESSAGE); return; } filteredHaplos = filts; //then re-tag, sort and get MA D' filteredHaplos = theData.orderByCrossing(filteredHaplos); theData.pickTags(filteredHaplos); multidprimeArray = theData.computeMultiDprime(filteredHaplos); //if the haps pane exists, we want to make sure the vert scroll bar appears if necessary if (this.getParent() != null){ if (this.getPreferredSize().height > this.getParent().getHeight()){ ((JScrollPane)this.getParent().getParent()).setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ); }else{ ((JScrollPane)this.getParent().getParent()).setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); } } repaint(); } public Dimension getPreferredSize() { int wide = BORDER*2; int high = BORDER*2; if (filteredHaplos == null) {return new Dimension(wide, high);} // height for the marker digits int markerDigits = (int) (0.0000001 + Math.log(Chromosome.getUnfilteredSize()) / Math.log(10)) + 1; high += MARKER_CHAR_WIDTH * markerDigits; // space for the diamond high += TAG_SPAN; int maxh = 0; for (int i = 0; i < filteredHaplos.length; i++){ maxh = Math.max(filteredHaplos[i].length, maxh); // size of genotypes for this column // +4 for the percentage reading wide += (filteredHaplos[i][0].getGeno().length + 4) * CHAR_WIDTH; // percentage plus the line size if (i != 0) wide += LINE_SPAN; } // +1 because of extra row for multi between the columns high += (maxh + 1) * ROW_HEIGHT; return new Dimension(wide, high); } public void paintComponent(Graphics graphics) { if (filteredHaplos == null){ super.paintComponent(graphics); return; } Graphics2D g = (Graphics2D) graphics; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //System.out.println(getUnfilteredSize()); Dimension size = getSize(); Dimension pref = getPreferredSize(); g.setColor(this.getBackground()); g.fillRect(0,0,pref.width, pref.height); if (!forExport){ g.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); } //g.drawRect(0, 0, pref.width, pref.height); final BasicStroke thinStroke = new BasicStroke(0.5f); final BasicStroke thickStroke = new BasicStroke(2.0f); // width of one letter of the haplotype block //int letterWidth = haploMetrics.charWidth('G'); //int percentWidth = pctMetrics.stringWidth(".000"); //final int verticalOffset = 43; // room for tags and diamonds int left = BORDER; int top = BORDER; //verticalOffset; //int totalWidth = 0; // percentages for each haplotype NumberFormat nf = NumberFormat.getInstance(Locale.US); nf.setMinimumFractionDigits(3); nf.setMaximumFractionDigits(3); nf.setMinimumIntegerDigits(0); nf.setMaximumIntegerDigits(0); // multi reading, between the columns NumberFormat nfMulti = NumberFormat.getInstance(Locale.US); nfMulti.setMinimumFractionDigits(2); nfMulti.setMaximumFractionDigits(2); nfMulti.setMinimumIntegerDigits(0); nfMulti.setMaximumIntegerDigits(0); int[][] lookupPos = new int[filteredHaplos.length][]; for (int p = 0; p < lookupPos.length; p++) { lookupPos[p] = new int[filteredHaplos[p].length]; for (int q = 0; q < lookupPos[p].length; q++){ lookupPos[p][filteredHaplos[p][q].getListOrder()] = q; } } // set number formatter to pad with appropriate number of zeroes NumberFormat nfMarker = NumberFormat.getInstance(Locale.US); + nfMarker.setGroupingUsed(false); int markerCount = Chromosome.getUnfilteredSize(); // the +0.0000001 is because there is // some suckage where log(1000) / log(10) isn't actually 3 int markerDigits = (int) (0.0000001 + Math.log(markerCount) / Math.log(10)) + 1; nfMarker.setMinimumIntegerDigits(markerDigits); nfMarker.setMaximumIntegerDigits(markerDigits); //int tagShapeX[] = new int[3]; //int tagShapeY[] = new int[3]; //Polygon tagShape; int textRight = 0; // gets updated for scooting over // i = 0 to number of columns - 1 for (int i = 0; i < filteredHaplos.length; i++) { int[] markerNums = filteredHaplos[i][0].getMarkers(); boolean[] tags = filteredHaplos[i][0].getTags(); //int headerX = x; //block labels g.setColor(Color.black); g.drawString("Block " + (i+1), left, top - CHAR_HEIGHT); for (int z = 0; z < markerNums.length; z++) { //int tagMiddle = tagMetrics.getAscent() / 2; //int tagLeft = x + z*letterWidth + tagMiddle; //g.translate(tagLeft, 20); // if tag snp, draw little triangle pooper if (tags[z]) { g.drawImage(tagImage, left + z*CHAR_WIDTH, top + markerDigits*MARKER_CHAR_WIDTH -(CHAR_HEIGHT - TAG_SPAN), null); } //g.rotate(-Math.PI / 2.0); //g.drawLine(0, 0, 0, 0); //g.setColor(Color.black); //g.drawString(nfMarker.format(markerNums[z]), 0, tagMiddle); char markerChars[] = nfMarker.format(Chromosome.realIndex[markerNums[z]]+1).toCharArray(); for (int m = 0; m < markerDigits; m++) { g.drawImage(markerNumImages[markerChars[m] - '0'], left + z*CHAR_WIDTH + (1 + CHAR_WIDTH - MARKER_CHAR_HEIGHT)/2, top + (markerDigits-m-1)*MARKER_CHAR_WIDTH, null); } // undo the transform.. no push/pop.. arrgh //g.rotate(Math.PI / 2.0); //g.translate(-tagLeft, -20); } // y position of the first image for the haplotype letter // top + the size of the marker digits + the size of the tag + // the character height centered in the row's height int above = top + markerDigits*MARKER_CHAR_WIDTH + TAG_SPAN + (ROW_HEIGHT - CHAR_HEIGHT) / 2; //figure out which allele is the major allele for each marker int[] majorAllele = new int[filteredHaplos[i][0].getGeno().length]; for (int k = 0; k < majorAllele.length; k++){ majorAllele[k] = Chromosome.getMarker(markerNums[k]).getMajor(); } for (int j = 0; j < filteredHaplos[i].length; j++){ int curHapNum = lookupPos[i][j]; //String theHap = new String(); //String thePercentage = new String(); int[] theGeno = filteredHaplos[i][curHapNum].getGeno(); //getGeno(); // j is the row of haplotype for (int k = 0; k < theGeno.length; k++) { // theGeno[k] will be 1,2,3,4 (acgt) or 8 (for bad) if (alleleDisp == 0){ g.drawImage(charImages[theGeno[k] - 1], left + k*CHAR_WIDTH, above + j*ROW_HEIGHT, null); }else if (alleleDisp == 1){ g.drawImage(blackNumImages[theGeno[k]], left + k*CHAR_WIDTH, above + j*ROW_HEIGHT, null); }else{ if (theGeno[k] == majorAllele[k]){ g.setColor(dullBlue); }else{ g.setColor(dullRed); } g.fillRect(left + k*CHAR_WIDTH, above + j*ROW_HEIGHT + (ROW_HEIGHT - CHAR_WIDTH)/2, CHAR_WIDTH, CHAR_WIDTH); } } //draw the percentage value in non mono font double percent = filteredHaplos[i][curHapNum].getPercentage(); //thePercentage = " " + nf.format(percent); char percentChars[] = nf.format(percent).toCharArray(); // perhaps need an exceptional case for 1.0 being the percent for (int m = 0; m < percentChars.length; m++) { g.drawImage(grayNumImages[(m == 0) ? 10 : percentChars[m]-'0'], left + theGeno.length*CHAR_WIDTH + m*CHAR_WIDTH, above + j*ROW_HEIGHT, null); } // 4 is the number of chars in .999 for the percent textRight = left + theGeno.length*CHAR_WIDTH + 4*CHAR_WIDTH; g.setColor(Color.black); if (i < filteredHaplos.length - 1) { //draw crossovers for (int crossCount = 0; crossCount < filteredHaplos[i+1].length; crossCount++) { double crossVal = filteredHaplos[i][curHapNum].getCrossover(crossCount); //draw thin and thick lines double crossValue = (crossVal*100); if (crossValue > thinThresh) { g.setStroke(crossValue > thickThresh ? thickStroke : thinStroke); int connectTo = filteredHaplos[i+1][crossCount].getListOrder(); g.drawLine(textRight + LINE_LEFT, above + j*ROW_HEIGHT + ROW_HEIGHT/2, textRight + LINE_RIGHT, above + connectTo*ROW_HEIGHT + ROW_HEIGHT/2); } } } } left = textRight; // add the multilocus d prime if appropriate if (i < filteredHaplos.length - 1) { //put the numbers in the right place vertically int depth; if (filteredHaplos[i].length > filteredHaplos[i+1].length){ depth = filteredHaplos[i].length; }else{ depth = filteredHaplos[i+1].length; } char multiChars[] = nfMulti.format(multidprimeArray[i]).toCharArray(); if (multidprimeArray[i] > 0.99){ //draw 1.0 vals specially g.drawImage(blackNumImages[1], left + (LINE_SPAN - 7*CHAR_WIDTH/2)/2 + CHAR_WIDTH, above + (depth * ROW_HEIGHT), null); g.drawImage(blackNumImages[10], left + (LINE_SPAN - 9*CHAR_WIDTH/2)/2 + 2*CHAR_WIDTH, above + (depth * ROW_HEIGHT), null); g.drawImage(blackNumImages[0], left + (LINE_SPAN - 9*CHAR_WIDTH/2)/2 + 3*CHAR_WIDTH, above + (depth * ROW_HEIGHT), null); }else{ for (int m = 0; m < 3; m++) { g.drawImage(blackNumImages[(m == 0) ? 10 : multiChars[m]-'0'], left + (LINE_SPAN - 7*CHAR_WIDTH/2)/2 + m*CHAR_WIDTH, above + (depth * ROW_HEIGHT), null); } } } left += LINE_SPAN; } } }
true
true
public void paintComponent(Graphics graphics) { if (filteredHaplos == null){ super.paintComponent(graphics); return; } Graphics2D g = (Graphics2D) graphics; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //System.out.println(getUnfilteredSize()); Dimension size = getSize(); Dimension pref = getPreferredSize(); g.setColor(this.getBackground()); g.fillRect(0,0,pref.width, pref.height); if (!forExport){ g.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); } //g.drawRect(0, 0, pref.width, pref.height); final BasicStroke thinStroke = new BasicStroke(0.5f); final BasicStroke thickStroke = new BasicStroke(2.0f); // width of one letter of the haplotype block //int letterWidth = haploMetrics.charWidth('G'); //int percentWidth = pctMetrics.stringWidth(".000"); //final int verticalOffset = 43; // room for tags and diamonds int left = BORDER; int top = BORDER; //verticalOffset; //int totalWidth = 0; // percentages for each haplotype NumberFormat nf = NumberFormat.getInstance(Locale.US); nf.setMinimumFractionDigits(3); nf.setMaximumFractionDigits(3); nf.setMinimumIntegerDigits(0); nf.setMaximumIntegerDigits(0); // multi reading, between the columns NumberFormat nfMulti = NumberFormat.getInstance(Locale.US); nfMulti.setMinimumFractionDigits(2); nfMulti.setMaximumFractionDigits(2); nfMulti.setMinimumIntegerDigits(0); nfMulti.setMaximumIntegerDigits(0); int[][] lookupPos = new int[filteredHaplos.length][]; for (int p = 0; p < lookupPos.length; p++) { lookupPos[p] = new int[filteredHaplos[p].length]; for (int q = 0; q < lookupPos[p].length; q++){ lookupPos[p][filteredHaplos[p][q].getListOrder()] = q; } } // set number formatter to pad with appropriate number of zeroes NumberFormat nfMarker = NumberFormat.getInstance(Locale.US); int markerCount = Chromosome.getUnfilteredSize(); // the +0.0000001 is because there is // some suckage where log(1000) / log(10) isn't actually 3 int markerDigits = (int) (0.0000001 + Math.log(markerCount) / Math.log(10)) + 1; nfMarker.setMinimumIntegerDigits(markerDigits); nfMarker.setMaximumIntegerDigits(markerDigits); //int tagShapeX[] = new int[3]; //int tagShapeY[] = new int[3]; //Polygon tagShape; int textRight = 0; // gets updated for scooting over // i = 0 to number of columns - 1 for (int i = 0; i < filteredHaplos.length; i++) { int[] markerNums = filteredHaplos[i][0].getMarkers(); boolean[] tags = filteredHaplos[i][0].getTags(); //int headerX = x; //block labels g.setColor(Color.black); g.drawString("Block " + (i+1), left, top - CHAR_HEIGHT); for (int z = 0; z < markerNums.length; z++) { //int tagMiddle = tagMetrics.getAscent() / 2; //int tagLeft = x + z*letterWidth + tagMiddle; //g.translate(tagLeft, 20); // if tag snp, draw little triangle pooper if (tags[z]) { g.drawImage(tagImage, left + z*CHAR_WIDTH, top + markerDigits*MARKER_CHAR_WIDTH -(CHAR_HEIGHT - TAG_SPAN), null); } //g.rotate(-Math.PI / 2.0); //g.drawLine(0, 0, 0, 0); //g.setColor(Color.black); //g.drawString(nfMarker.format(markerNums[z]), 0, tagMiddle); char markerChars[] = nfMarker.format(Chromosome.realIndex[markerNums[z]]+1).toCharArray(); for (int m = 0; m < markerDigits; m++) { g.drawImage(markerNumImages[markerChars[m] - '0'], left + z*CHAR_WIDTH + (1 + CHAR_WIDTH - MARKER_CHAR_HEIGHT)/2, top + (markerDigits-m-1)*MARKER_CHAR_WIDTH, null); } // undo the transform.. no push/pop.. arrgh //g.rotate(Math.PI / 2.0); //g.translate(-tagLeft, -20); } // y position of the first image for the haplotype letter // top + the size of the marker digits + the size of the tag + // the character height centered in the row's height int above = top + markerDigits*MARKER_CHAR_WIDTH + TAG_SPAN + (ROW_HEIGHT - CHAR_HEIGHT) / 2; //figure out which allele is the major allele for each marker int[] majorAllele = new int[filteredHaplos[i][0].getGeno().length]; for (int k = 0; k < majorAllele.length; k++){ majorAllele[k] = Chromosome.getMarker(markerNums[k]).getMajor(); } for (int j = 0; j < filteredHaplos[i].length; j++){ int curHapNum = lookupPos[i][j]; //String theHap = new String(); //String thePercentage = new String(); int[] theGeno = filteredHaplos[i][curHapNum].getGeno(); //getGeno(); // j is the row of haplotype for (int k = 0; k < theGeno.length; k++) { // theGeno[k] will be 1,2,3,4 (acgt) or 8 (for bad) if (alleleDisp == 0){ g.drawImage(charImages[theGeno[k] - 1], left + k*CHAR_WIDTH, above + j*ROW_HEIGHT, null); }else if (alleleDisp == 1){ g.drawImage(blackNumImages[theGeno[k]], left + k*CHAR_WIDTH, above + j*ROW_HEIGHT, null); }else{ if (theGeno[k] == majorAllele[k]){ g.setColor(dullBlue); }else{ g.setColor(dullRed); } g.fillRect(left + k*CHAR_WIDTH, above + j*ROW_HEIGHT + (ROW_HEIGHT - CHAR_WIDTH)/2, CHAR_WIDTH, CHAR_WIDTH); } } //draw the percentage value in non mono font double percent = filteredHaplos[i][curHapNum].getPercentage(); //thePercentage = " " + nf.format(percent); char percentChars[] = nf.format(percent).toCharArray(); // perhaps need an exceptional case for 1.0 being the percent for (int m = 0; m < percentChars.length; m++) { g.drawImage(grayNumImages[(m == 0) ? 10 : percentChars[m]-'0'], left + theGeno.length*CHAR_WIDTH + m*CHAR_WIDTH, above + j*ROW_HEIGHT, null); } // 4 is the number of chars in .999 for the percent textRight = left + theGeno.length*CHAR_WIDTH + 4*CHAR_WIDTH; g.setColor(Color.black); if (i < filteredHaplos.length - 1) { //draw crossovers for (int crossCount = 0; crossCount < filteredHaplos[i+1].length; crossCount++) { double crossVal = filteredHaplos[i][curHapNum].getCrossover(crossCount); //draw thin and thick lines double crossValue = (crossVal*100); if (crossValue > thinThresh) { g.setStroke(crossValue > thickThresh ? thickStroke : thinStroke); int connectTo = filteredHaplos[i+1][crossCount].getListOrder(); g.drawLine(textRight + LINE_LEFT, above + j*ROW_HEIGHT + ROW_HEIGHT/2, textRight + LINE_RIGHT, above + connectTo*ROW_HEIGHT + ROW_HEIGHT/2); } } } } left = textRight; // add the multilocus d prime if appropriate if (i < filteredHaplos.length - 1) { //put the numbers in the right place vertically int depth; if (filteredHaplos[i].length > filteredHaplos[i+1].length){ depth = filteredHaplos[i].length; }else{ depth = filteredHaplos[i+1].length; } char multiChars[] = nfMulti.format(multidprimeArray[i]).toCharArray(); if (multidprimeArray[i] > 0.99){ //draw 1.0 vals specially g.drawImage(blackNumImages[1], left + (LINE_SPAN - 7*CHAR_WIDTH/2)/2 + CHAR_WIDTH, above + (depth * ROW_HEIGHT), null); g.drawImage(blackNumImages[10], left + (LINE_SPAN - 9*CHAR_WIDTH/2)/2 + 2*CHAR_WIDTH, above + (depth * ROW_HEIGHT), null); g.drawImage(blackNumImages[0], left + (LINE_SPAN - 9*CHAR_WIDTH/2)/2 + 3*CHAR_WIDTH, above + (depth * ROW_HEIGHT), null); }else{ for (int m = 0; m < 3; m++) { g.drawImage(blackNumImages[(m == 0) ? 10 : multiChars[m]-'0'], left + (LINE_SPAN - 7*CHAR_WIDTH/2)/2 + m*CHAR_WIDTH, above + (depth * ROW_HEIGHT), null); } } } left += LINE_SPAN; } }
public void paintComponent(Graphics graphics) { if (filteredHaplos == null){ super.paintComponent(graphics); return; } Graphics2D g = (Graphics2D) graphics; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //System.out.println(getUnfilteredSize()); Dimension size = getSize(); Dimension pref = getPreferredSize(); g.setColor(this.getBackground()); g.fillRect(0,0,pref.width, pref.height); if (!forExport){ g.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); } //g.drawRect(0, 0, pref.width, pref.height); final BasicStroke thinStroke = new BasicStroke(0.5f); final BasicStroke thickStroke = new BasicStroke(2.0f); // width of one letter of the haplotype block //int letterWidth = haploMetrics.charWidth('G'); //int percentWidth = pctMetrics.stringWidth(".000"); //final int verticalOffset = 43; // room for tags and diamonds int left = BORDER; int top = BORDER; //verticalOffset; //int totalWidth = 0; // percentages for each haplotype NumberFormat nf = NumberFormat.getInstance(Locale.US); nf.setMinimumFractionDigits(3); nf.setMaximumFractionDigits(3); nf.setMinimumIntegerDigits(0); nf.setMaximumIntegerDigits(0); // multi reading, between the columns NumberFormat nfMulti = NumberFormat.getInstance(Locale.US); nfMulti.setMinimumFractionDigits(2); nfMulti.setMaximumFractionDigits(2); nfMulti.setMinimumIntegerDigits(0); nfMulti.setMaximumIntegerDigits(0); int[][] lookupPos = new int[filteredHaplos.length][]; for (int p = 0; p < lookupPos.length; p++) { lookupPos[p] = new int[filteredHaplos[p].length]; for (int q = 0; q < lookupPos[p].length; q++){ lookupPos[p][filteredHaplos[p][q].getListOrder()] = q; } } // set number formatter to pad with appropriate number of zeroes NumberFormat nfMarker = NumberFormat.getInstance(Locale.US); nfMarker.setGroupingUsed(false); int markerCount = Chromosome.getUnfilteredSize(); // the +0.0000001 is because there is // some suckage where log(1000) / log(10) isn't actually 3 int markerDigits = (int) (0.0000001 + Math.log(markerCount) / Math.log(10)) + 1; nfMarker.setMinimumIntegerDigits(markerDigits); nfMarker.setMaximumIntegerDigits(markerDigits); //int tagShapeX[] = new int[3]; //int tagShapeY[] = new int[3]; //Polygon tagShape; int textRight = 0; // gets updated for scooting over // i = 0 to number of columns - 1 for (int i = 0; i < filteredHaplos.length; i++) { int[] markerNums = filteredHaplos[i][0].getMarkers(); boolean[] tags = filteredHaplos[i][0].getTags(); //int headerX = x; //block labels g.setColor(Color.black); g.drawString("Block " + (i+1), left, top - CHAR_HEIGHT); for (int z = 0; z < markerNums.length; z++) { //int tagMiddle = tagMetrics.getAscent() / 2; //int tagLeft = x + z*letterWidth + tagMiddle; //g.translate(tagLeft, 20); // if tag snp, draw little triangle pooper if (tags[z]) { g.drawImage(tagImage, left + z*CHAR_WIDTH, top + markerDigits*MARKER_CHAR_WIDTH -(CHAR_HEIGHT - TAG_SPAN), null); } //g.rotate(-Math.PI / 2.0); //g.drawLine(0, 0, 0, 0); //g.setColor(Color.black); //g.drawString(nfMarker.format(markerNums[z]), 0, tagMiddle); char markerChars[] = nfMarker.format(Chromosome.realIndex[markerNums[z]]+1).toCharArray(); for (int m = 0; m < markerDigits; m++) { g.drawImage(markerNumImages[markerChars[m] - '0'], left + z*CHAR_WIDTH + (1 + CHAR_WIDTH - MARKER_CHAR_HEIGHT)/2, top + (markerDigits-m-1)*MARKER_CHAR_WIDTH, null); } // undo the transform.. no push/pop.. arrgh //g.rotate(Math.PI / 2.0); //g.translate(-tagLeft, -20); } // y position of the first image for the haplotype letter // top + the size of the marker digits + the size of the tag + // the character height centered in the row's height int above = top + markerDigits*MARKER_CHAR_WIDTH + TAG_SPAN + (ROW_HEIGHT - CHAR_HEIGHT) / 2; //figure out which allele is the major allele for each marker int[] majorAllele = new int[filteredHaplos[i][0].getGeno().length]; for (int k = 0; k < majorAllele.length; k++){ majorAllele[k] = Chromosome.getMarker(markerNums[k]).getMajor(); } for (int j = 0; j < filteredHaplos[i].length; j++){ int curHapNum = lookupPos[i][j]; //String theHap = new String(); //String thePercentage = new String(); int[] theGeno = filteredHaplos[i][curHapNum].getGeno(); //getGeno(); // j is the row of haplotype for (int k = 0; k < theGeno.length; k++) { // theGeno[k] will be 1,2,3,4 (acgt) or 8 (for bad) if (alleleDisp == 0){ g.drawImage(charImages[theGeno[k] - 1], left + k*CHAR_WIDTH, above + j*ROW_HEIGHT, null); }else if (alleleDisp == 1){ g.drawImage(blackNumImages[theGeno[k]], left + k*CHAR_WIDTH, above + j*ROW_HEIGHT, null); }else{ if (theGeno[k] == majorAllele[k]){ g.setColor(dullBlue); }else{ g.setColor(dullRed); } g.fillRect(left + k*CHAR_WIDTH, above + j*ROW_HEIGHT + (ROW_HEIGHT - CHAR_WIDTH)/2, CHAR_WIDTH, CHAR_WIDTH); } } //draw the percentage value in non mono font double percent = filteredHaplos[i][curHapNum].getPercentage(); //thePercentage = " " + nf.format(percent); char percentChars[] = nf.format(percent).toCharArray(); // perhaps need an exceptional case for 1.0 being the percent for (int m = 0; m < percentChars.length; m++) { g.drawImage(grayNumImages[(m == 0) ? 10 : percentChars[m]-'0'], left + theGeno.length*CHAR_WIDTH + m*CHAR_WIDTH, above + j*ROW_HEIGHT, null); } // 4 is the number of chars in .999 for the percent textRight = left + theGeno.length*CHAR_WIDTH + 4*CHAR_WIDTH; g.setColor(Color.black); if (i < filteredHaplos.length - 1) { //draw crossovers for (int crossCount = 0; crossCount < filteredHaplos[i+1].length; crossCount++) { double crossVal = filteredHaplos[i][curHapNum].getCrossover(crossCount); //draw thin and thick lines double crossValue = (crossVal*100); if (crossValue > thinThresh) { g.setStroke(crossValue > thickThresh ? thickStroke : thinStroke); int connectTo = filteredHaplos[i+1][crossCount].getListOrder(); g.drawLine(textRight + LINE_LEFT, above + j*ROW_HEIGHT + ROW_HEIGHT/2, textRight + LINE_RIGHT, above + connectTo*ROW_HEIGHT + ROW_HEIGHT/2); } } } } left = textRight; // add the multilocus d prime if appropriate if (i < filteredHaplos.length - 1) { //put the numbers in the right place vertically int depth; if (filteredHaplos[i].length > filteredHaplos[i+1].length){ depth = filteredHaplos[i].length; }else{ depth = filteredHaplos[i+1].length; } char multiChars[] = nfMulti.format(multidprimeArray[i]).toCharArray(); if (multidprimeArray[i] > 0.99){ //draw 1.0 vals specially g.drawImage(blackNumImages[1], left + (LINE_SPAN - 7*CHAR_WIDTH/2)/2 + CHAR_WIDTH, above + (depth * ROW_HEIGHT), null); g.drawImage(blackNumImages[10], left + (LINE_SPAN - 9*CHAR_WIDTH/2)/2 + 2*CHAR_WIDTH, above + (depth * ROW_HEIGHT), null); g.drawImage(blackNumImages[0], left + (LINE_SPAN - 9*CHAR_WIDTH/2)/2 + 3*CHAR_WIDTH, above + (depth * ROW_HEIGHT), null); }else{ for (int m = 0; m < 3; m++) { g.drawImage(blackNumImages[(m == 0) ? 10 : multiChars[m]-'0'], left + (LINE_SPAN - 7*CHAR_WIDTH/2)/2 + m*CHAR_WIDTH, above + (depth * ROW_HEIGHT), null); } } } left += LINE_SPAN; } }
diff --git a/as/plugins/org.jboss.ide.eclipse.as.ui/jbossui/org/jboss/ide/eclipse/as/ui/views/server/extensions/JBossServerViewExtension.java b/as/plugins/org.jboss.ide.eclipse.as.ui/jbossui/org/jboss/ide/eclipse/as/ui/views/server/extensions/JBossServerViewExtension.java index 9fccd10df..26cce4c19 100755 --- a/as/plugins/org.jboss.ide.eclipse.as.ui/jbossui/org/jboss/ide/eclipse/as/ui/views/server/extensions/JBossServerViewExtension.java +++ b/as/plugins/org.jboss.ide.eclipse.as.ui/jbossui/org/jboss/ide/eclipse/as/ui/views/server/extensions/JBossServerViewExtension.java @@ -1,170 +1,167 @@ /** * 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.ui.views.server.extensions; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.views.properties.IPropertySheetPage; import org.eclipse.wst.server.core.IServer; import org.jboss.ide.eclipse.as.core.server.IDeployableServer; import org.jboss.ide.eclipse.as.core.server.internal.JBossServer; import org.jboss.ide.eclipse.as.ui.JBossServerUIPlugin; import org.jboss.ide.eclipse.as.ui.preferencepages.ViewProviderPreferenceComposite; import org.jboss.ide.eclipse.as.ui.views.server.ExtensionTableViewer; import org.jboss.ide.eclipse.as.ui.views.server.JBossServerView; import org.jboss.ide.eclipse.as.ui.views.server.ExtensionTableViewer.ContentWrapper; /** * * @author Rob Stryker <[email protected]> * */ public abstract class JBossServerViewExtension { protected ServerViewProvider provider; /** * Which extension point is mine. * @param provider */ public void setViewProvider(ServerViewProvider provider) { this.provider = provider; } /** * Should query preferencestore to see if I'm enabled or not * @return */ public boolean isEnabled() { return provider.isEnabled(); } public void init() { } public void enable() { } public void disable() { } public void dispose() { if( getPropertySheetPage() != null ) getPropertySheetPage().dispose(); } public void fillContextMenu(Shell shell, IMenuManager menu, Object[] selected) { } public ITreeContentProvider getContentProvider() { return null; } public LabelProvider getLabelProvider() { return null; } public IPropertySheetPage getPropertySheetPage() { return null; } public ViewProviderPreferenceComposite createPreferenceComposite(Composite parent) { return null; } public Image createIcon() { return null; } public void refreshModel(Object object) { // override me } protected void suppressingRefresh(Runnable runnable) { JBossServerView.getDefault().getExtensionFrame().getViewer().suppressingRefresh(runnable); } protected void refreshViewer() { refreshViewer(null); } protected void refreshViewer(final Object o) { Runnable r = new Runnable() { public void run() { if( isEnabled() ) { - try { - if( o == null || o == provider ) { - JBossServerView.getDefault().getExtensionFrame().getViewer().refresh(provider); - } else { - ExtensionTableViewer viewer = JBossServerView.getDefault().getExtensionFrame().getViewer(); - ContentWrapper wrapped = new ContentWrapper(o, provider); - if( viewer.elementInTree(wrapped)) - viewer.refresh(new ContentWrapper(o, provider)); - else - viewer.refresh(provider); - } - } catch(Exception e) { - // non-critical error, ignore + if( o == null || o == provider ) { + JBossServerView.getDefault().getExtensionFrame().getViewer().refresh(provider); + } else { + ExtensionTableViewer viewer = JBossServerView.getDefault().getExtensionFrame().getViewer(); + ContentWrapper wrapped = new ContentWrapper(o, provider); + if( viewer.elementInTree(wrapped)) + viewer.refresh(new ContentWrapper(o, provider)); + else + viewer.refresh(provider); } } } }; - if( JBossServerView.getDefault() == null ) return; + if( JBossServerView.getDefault() == null ) + return; if( Display.getCurrent() == null ) Display.getDefault().asyncExec(r); else r.run(); } protected void removeElement(Object o) { JBossServerView.getDefault().getServerFrame().getViewer().remove(new ContentWrapper(o, provider)); } protected void addElement(Object parent, Object child) { JBossServerView.getDefault().getServerFrame().getViewer().add(new ContentWrapper(parent, provider), new ContentWrapper(child, provider)); } // what servers should i show for? protected boolean supports(IServer server) { if( server == null ) return false; return isJBossDeployable(server); } // show for anything that's jboss deployable protected boolean isJBossDeployable(IServer server) { return (IDeployableServer)server.loadAdapter(IDeployableServer.class, new NullProgressMonitor()) != null; } // show only for full jboss servers protected boolean isJBossServer(IServer server) { return (JBossServer)server.loadAdapter(JBossServer.class, new NullProgressMonitor()) != null; } protected boolean allAre(Object[] list, Class clazz) { for( int i = 0; i < list.length; i++ ) if( list[i].getClass() != clazz ) return false; return true; } }
false
true
protected void refreshViewer(final Object o) { Runnable r = new Runnable() { public void run() { if( isEnabled() ) { try { if( o == null || o == provider ) { JBossServerView.getDefault().getExtensionFrame().getViewer().refresh(provider); } else { ExtensionTableViewer viewer = JBossServerView.getDefault().getExtensionFrame().getViewer(); ContentWrapper wrapped = new ContentWrapper(o, provider); if( viewer.elementInTree(wrapped)) viewer.refresh(new ContentWrapper(o, provider)); else viewer.refresh(provider); } } catch(Exception e) { // non-critical error, ignore } } } }; if( JBossServerView.getDefault() == null ) return; if( Display.getCurrent() == null ) Display.getDefault().asyncExec(r); else r.run(); }
protected void refreshViewer(final Object o) { Runnable r = new Runnable() { public void run() { if( isEnabled() ) { if( o == null || o == provider ) { JBossServerView.getDefault().getExtensionFrame().getViewer().refresh(provider); } else { ExtensionTableViewer viewer = JBossServerView.getDefault().getExtensionFrame().getViewer(); ContentWrapper wrapped = new ContentWrapper(o, provider); if( viewer.elementInTree(wrapped)) viewer.refresh(new ContentWrapper(o, provider)); else viewer.refresh(provider); } } } }; if( JBossServerView.getDefault() == null ) return; if( Display.getCurrent() == null ) Display.getDefault().asyncExec(r); else r.run(); }
diff --git a/Flags/src/alshain01/Flags/Flags.java b/Flags/src/alshain01/Flags/Flags.java index a995824..2dcc2f5 100644 --- a/Flags/src/alshain01/Flags/Flags.java +++ b/Flags/src/alshain01/Flags/Flags.java @@ -1,264 +1,264 @@ package alshain01.Flags; import java.util.List; import net.milkbowl.vault.economy.Economy; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.command.*; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import alshain01.Flags.Director.LandSystem; import alshain01.Flags.Updater.UpdateResult; import alshain01.Flags.commands.Command; import alshain01.Flags.data.CustomYML; import alshain01.Flags.data.DataStore; import alshain01.Flags.data.YamlDataStore; import alshain01.Flags.importer.GPFImport; import alshain01.Flags.metrics.MetricsManager; /** * Flags * * @author Alshain01 */ public class Flags extends JavaPlugin{ protected static CustomYML messageStore; protected static LandSystem currentSystem = LandSystem.NONE; private static Flags instance; private static DataStore dataStore; private static Updater updater = null; private static Economy economy = null; private static Boolean DEBUG = false; private static final Registrar flagRegistrar = new Registrar(); /** * Called when this plug-in is enabled */ @Override public void onEnable(){ instance = this; // Create the configuration file if it doesn't exist this.saveDefaultConfig(); - this.DEBUG = this.getConfig().getBoolean("Flags.Debug"); + DEBUG = this.getConfig().getBoolean("Flags.Debug"); if(this.getConfig().getBoolean("Flags.Update.Check")) { String key = this.getConfig().getString("Flags.Update.ServerModsAPIKey"); if(this.getConfig().getBoolean("Flags.Update.Download")) { updater = new Updater(this, 65024, this.getFile(), Updater.UpdateType.DEFAULT, key, true); } else { updater = new Updater(this, 65024, this.getFile(), Updater.UpdateType.NO_DOWNLOAD, key, false); } if(updater.getResult() == UpdateResult.UPDATE_AVAILABLE) { Bukkit.getServer().getConsoleSender().sendMessage("[Flags] " + ChatColor.DARK_PURPLE + "The version of Flags that this server is running is out of date. " + "Please consider updating to the latest version at dev.bukkit.org/bukkit-plugins/flags/."); } else if(updater.getResult() == UpdateResult.SUCCESS) { Bukkit.getServer().reload(); } } this.getServer().getPluginManager().registerEvents(new UpdateListener(), instance); // Create the specific implementation of DataStore // TODO: Add sub-interface for SQL dataStore = new YamlDataStore(this); messageStore = new CustomYML(this, "message.yml"); messageStore.saveDefaultConfig(); if (!dataStore.exists(this)) { // New installation if (!dataStore.create(this)) { this.getLogger().warning("Failed to create database schema. Shutting down Flags."); this.getServer().getPluginManager().disablePlugin(this); return; } } // Update the data to current as needed. dataStore.update(this); // Find the first available land management system currentSystem = findSystem(getServer().getPluginManager()); if (currentSystem == LandSystem.NONE) { getLogger().info("No system detected. Only world flags will be available."); } else { getLogger().info(currentSystem.getDisplayName() + " detected. Enabling integrated support."); } // Check for older database and import as necessary. if(currentSystem == LandSystem.GRIEF_PREVENTION && !getServer().getPluginManager().isPluginEnabled("GriefPreventionFlags")) { GPFImport.importGPF(); } // Enable Vault support if(setupEconomy()) { //this.getServer().getPluginManager().registerEvents(new EconomyListener(), instance); } // Load Mr. Clean Director.enableMrClean(this.getServer().getPluginManager()); // Load Border Patrol if (this.getConfig().getBoolean("Flags.BorderPatrol.Enable")) { this.getServer().getPluginManager().registerEvents(new BorderPatrol(), instance); } if(!DEBUG && checkAPI("1.3.2")) { MetricsManager.StartMetrics(); } this.getLogger().info("Flags Has Been Enabled."); } /** * Called when this plug-in is disabled */ @Override public void onDisable(){ //if(dataStore instanceof SQLDataStore) { ((SQLDataStore)dataStore).close(); } getLogger().info("Flags Has Been Disabled."); } /** * Gets the static instance of Flags. * * @return The vault economy. */ public static Flags getInstance() { return instance; } /** * Gets the DataStore used by Flags. * In most cases, plugins should not attempt to access this directly. * * @return The vault economy. */ public static DataStore getDataStore() { return dataStore; } /** * Gets the registrar for this instance of Flags. * * @return The flag registrar. */ public static Registrar getRegistrar() { return flagRegistrar; } /** * Gets the vault economy for this instance of Flags. * * @return The vault economy. */ public static Economy getEconomy() { return economy; } /** * Executes the given command, returning its success * * @param sender Source of the command * @param cmd Command which was executed * @param label Alias of the command which was used * @param args Passed command arguments * @return true if a valid command, otherwise false * */ @Override public boolean onCommand(CommandSender sender, org.bukkit.command.Command cmd, String label, String[] args){ if(cmd.getName().equalsIgnoreCase("flag")) { return Command.onFlagCommand(sender, args); } if(cmd.getName().equalsIgnoreCase("bundle")) { return Command.onBundleCommand(sender, args); } return false; } /** * Returns true if the provided string represents a * version number that is equal to or lower than the * current Bukkit API version. * * String should be formatted with 3 numbers: x.y.z * * @return True if the version provided is compatible */ public static boolean checkAPI(String version) { float APIVersion = Float.valueOf(Bukkit.getServer().getBukkitVersion().substring(0, 3)); float CompareVersion = Float.valueOf(version.substring(0, 3)); int APIBuild = Integer.valueOf(Bukkit.getServer().getBukkitVersion().substring(4, 5)); int CompareBuild = Integer.valueOf(version.substring(4, 5)); if (APIVersion > CompareVersion || (APIVersion == CompareVersion && APIBuild >= CompareBuild)) { return true; } return false; } /** * Sends a debug message through the Flags logger if the plug-in is a development build. * @param message The debug message */ public static final void Debug(String message) { if (DEBUG) { Flags.instance.getLogger().info("DEBUG: " + message); } } /* * Register with the Vault economy plugin. * * @return True if the economy was successfully configured. */ private static boolean setupEconomy() { if (!Flags.instance.getServer().getPluginManager().isPluginEnabled("Vault")) { return false; } RegisteredServiceProvider<Economy> economyProvider = Bukkit.getServer().getServicesManager() .getRegistration(net.milkbowl.vault.economy.Economy.class); if (economyProvider != null) { economy = economyProvider.getProvider(); } return (economy != null); } /* * Acquires the land management plugin. */ private static LandSystem findSystem(PluginManager pm) { List<?> pluginList = Flags.instance.getConfig().getList("Flags.AreaPlugins"); for(Object o : pluginList) { if (pm.isPluginEnabled((String)o)) { return LandSystem.getByName((String)o); } } return LandSystem.NONE; } private static class UpdateListener implements Listener { @EventHandler(ignoreCancelled = true) private void onPlayerJoin(PlayerJoinEvent e) { if(e.getPlayer().hasPermission("flags.admin.notifyupdate") && updater.getResult() == UpdateResult.UPDATE_AVAILABLE) { e.getPlayer().sendMessage( ChatColor.DARK_PURPLE + "The version of Flags that this server is running is out of date. " + "Please consider updating to the latest version at dev.bukkit.org/bukkit-plugins/flags/."); } } } }
true
true
public void onEnable(){ instance = this; // Create the configuration file if it doesn't exist this.saveDefaultConfig(); this.DEBUG = this.getConfig().getBoolean("Flags.Debug"); if(this.getConfig().getBoolean("Flags.Update.Check")) { String key = this.getConfig().getString("Flags.Update.ServerModsAPIKey"); if(this.getConfig().getBoolean("Flags.Update.Download")) { updater = new Updater(this, 65024, this.getFile(), Updater.UpdateType.DEFAULT, key, true); } else { updater = new Updater(this, 65024, this.getFile(), Updater.UpdateType.NO_DOWNLOAD, key, false); } if(updater.getResult() == UpdateResult.UPDATE_AVAILABLE) { Bukkit.getServer().getConsoleSender().sendMessage("[Flags] " + ChatColor.DARK_PURPLE + "The version of Flags that this server is running is out of date. " + "Please consider updating to the latest version at dev.bukkit.org/bukkit-plugins/flags/."); } else if(updater.getResult() == UpdateResult.SUCCESS) { Bukkit.getServer().reload(); } } this.getServer().getPluginManager().registerEvents(new UpdateListener(), instance); // Create the specific implementation of DataStore // TODO: Add sub-interface for SQL dataStore = new YamlDataStore(this); messageStore = new CustomYML(this, "message.yml"); messageStore.saveDefaultConfig(); if (!dataStore.exists(this)) { // New installation if (!dataStore.create(this)) { this.getLogger().warning("Failed to create database schema. Shutting down Flags."); this.getServer().getPluginManager().disablePlugin(this); return; } } // Update the data to current as needed. dataStore.update(this); // Find the first available land management system currentSystem = findSystem(getServer().getPluginManager()); if (currentSystem == LandSystem.NONE) { getLogger().info("No system detected. Only world flags will be available."); } else { getLogger().info(currentSystem.getDisplayName() + " detected. Enabling integrated support."); } // Check for older database and import as necessary. if(currentSystem == LandSystem.GRIEF_PREVENTION && !getServer().getPluginManager().isPluginEnabled("GriefPreventionFlags")) { GPFImport.importGPF(); } // Enable Vault support if(setupEconomy()) { //this.getServer().getPluginManager().registerEvents(new EconomyListener(), instance); } // Load Mr. Clean Director.enableMrClean(this.getServer().getPluginManager()); // Load Border Patrol if (this.getConfig().getBoolean("Flags.BorderPatrol.Enable")) { this.getServer().getPluginManager().registerEvents(new BorderPatrol(), instance); } if(!DEBUG && checkAPI("1.3.2")) { MetricsManager.StartMetrics(); } this.getLogger().info("Flags Has Been Enabled."); }
public void onEnable(){ instance = this; // Create the configuration file if it doesn't exist this.saveDefaultConfig(); DEBUG = this.getConfig().getBoolean("Flags.Debug"); if(this.getConfig().getBoolean("Flags.Update.Check")) { String key = this.getConfig().getString("Flags.Update.ServerModsAPIKey"); if(this.getConfig().getBoolean("Flags.Update.Download")) { updater = new Updater(this, 65024, this.getFile(), Updater.UpdateType.DEFAULT, key, true); } else { updater = new Updater(this, 65024, this.getFile(), Updater.UpdateType.NO_DOWNLOAD, key, false); } if(updater.getResult() == UpdateResult.UPDATE_AVAILABLE) { Bukkit.getServer().getConsoleSender().sendMessage("[Flags] " + ChatColor.DARK_PURPLE + "The version of Flags that this server is running is out of date. " + "Please consider updating to the latest version at dev.bukkit.org/bukkit-plugins/flags/."); } else if(updater.getResult() == UpdateResult.SUCCESS) { Bukkit.getServer().reload(); } } this.getServer().getPluginManager().registerEvents(new UpdateListener(), instance); // Create the specific implementation of DataStore // TODO: Add sub-interface for SQL dataStore = new YamlDataStore(this); messageStore = new CustomYML(this, "message.yml"); messageStore.saveDefaultConfig(); if (!dataStore.exists(this)) { // New installation if (!dataStore.create(this)) { this.getLogger().warning("Failed to create database schema. Shutting down Flags."); this.getServer().getPluginManager().disablePlugin(this); return; } } // Update the data to current as needed. dataStore.update(this); // Find the first available land management system currentSystem = findSystem(getServer().getPluginManager()); if (currentSystem == LandSystem.NONE) { getLogger().info("No system detected. Only world flags will be available."); } else { getLogger().info(currentSystem.getDisplayName() + " detected. Enabling integrated support."); } // Check for older database and import as necessary. if(currentSystem == LandSystem.GRIEF_PREVENTION && !getServer().getPluginManager().isPluginEnabled("GriefPreventionFlags")) { GPFImport.importGPF(); } // Enable Vault support if(setupEconomy()) { //this.getServer().getPluginManager().registerEvents(new EconomyListener(), instance); } // Load Mr. Clean Director.enableMrClean(this.getServer().getPluginManager()); // Load Border Patrol if (this.getConfig().getBoolean("Flags.BorderPatrol.Enable")) { this.getServer().getPluginManager().registerEvents(new BorderPatrol(), instance); } if(!DEBUG && checkAPI("1.3.2")) { MetricsManager.StartMetrics(); } this.getLogger().info("Flags Has Been Enabled."); }
diff --git a/GAE/src/org/waterforpeople/mapping/app/web/SummaryDataRestServlet.java b/GAE/src/org/waterforpeople/mapping/app/web/SummaryDataRestServlet.java index 121150743..e40955cdc 100644 --- a/GAE/src/org/waterforpeople/mapping/app/web/SummaryDataRestServlet.java +++ b/GAE/src/org/waterforpeople/mapping/app/web/SummaryDataRestServlet.java @@ -1,172 +1,179 @@ package org.waterforpeople.mapping.app.web; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import net.sf.jsr107cache.Cache; import net.sf.jsr107cache.CacheException; import net.sf.jsr107cache.CacheFactory; import net.sf.jsr107cache.CacheManager; import org.json.JSONObject; import org.waterforpeople.mapping.analytics.dao.AccessPointMetricSummaryDao; import org.waterforpeople.mapping.analytics.domain.AccessPointMetricSummary; import org.waterforpeople.mapping.app.gwt.client.accesspoint.AccessPointMetricSummaryDto; import org.waterforpeople.mapping.app.util.DtoMarshaller; import org.waterforpeople.mapping.app.web.dto.PlacemarkRestResponse; import org.waterforpeople.mapping.app.web.dto.SummaryDataRequest; import org.waterforpeople.mapping.app.web.dto.SummaryDataResponse; import com.gallatinsystems.common.util.PropertyUtil; import com.gallatinsystems.framework.rest.AbstractRestApiServlet; import com.gallatinsystems.framework.rest.RestRequest; import com.gallatinsystems.framework.rest.RestResponse; import com.google.appengine.api.memcache.MemcacheService; import com.google.appengine.api.memcache.jsr107cache.GCacheFactory; /** * handles requests for summary data * * @author Christopher Fagiani * */ public class SummaryDataRestServlet extends AbstractRestApiServlet { private static final String IMAGE_ROOT = "imageroot"; private Cache cache; private static final Logger log = Logger .getLogger(SummaryDataRestServlet.class.getName()); private static final long serialVersionUID = 7550953090927763716L; private AccessPointMetricSummaryDao apMetricSummaryDao; private static String imageRoot; public SummaryDataRestServlet() { setMode(JSON_MODE); apMetricSummaryDao = new AccessPointMetricSummaryDao(); imageRoot = PropertyUtil.getProperty(IMAGE_ROOT); CacheFactory cacheFactory; try { cacheFactory = CacheManager.getInstance().getCacheFactory(); Map configMap = new HashMap(); configMap.put(GCacheFactory.EXPIRATION_DELTA, 3600); configMap.put(MemcacheService.SetPolicy.SET_ALWAYS, true); cache = cacheFactory.createCache(Collections.emptyMap()); } catch (CacheException e) { log.log(Level.SEVERE, "Could not initialize cache", e); } } @Override protected RestRequest convertRequest() throws Exception { HttpServletRequest req = getRequest(); RestRequest restRequest = new SummaryDataRequest(); restRequest.populateFromHttpRequest(req); return restRequest; } @Override protected RestResponse handleRequest(RestRequest req) throws Exception { SummaryDataRequest dataReq = (SummaryDataRequest) req; SummaryDataResponse response = new SummaryDataResponse(); if (cache != null) { SummaryDataResponse cachedResponse = null; try { cachedResponse = (SummaryDataResponse) cache.get(dataReq .getCacheKey()); } catch (Throwable t) { log.log(Level.WARNING, "Could not look up data in cache", t); } if (cachedResponse != null) { return cachedResponse; } } if (SummaryDataRequest.GET_AP_METRIC_SUMMARY_ACTION .equalsIgnoreCase(dataReq.getAction())) { response.setDtoList(convertAccessPointMetric( seachAPMetrics(dataReq), dataReq.getIncludePlacemarkFlag())); } + if (response != null && cache != null) { + try { + cache.put(dataReq.getCacheKey(), response); + } catch (Throwable t) { + log.log(Level.WARNING, "Could not cache results", t); + } + } return response; } @Override protected void writeOkResponse(RestResponse resp) throws Exception { getResponse().setStatus(200); JSONObject obj = new JSONObject(resp, true); getResponse().getWriter().println(obj.toString()); } /** * searches the ap metrics based on values in the request * * @param dataReq * @return */ private List<AccessPointMetricSummary> seachAPMetrics( SummaryDataRequest dataReq) { AccessPointMetricSummary prototype = new AccessPointMetricSummary(); prototype.setCountry(dataReq.getCountry()); prototype.setOrganization(dataReq.getOrganization()); // prototype.setDistrict(dataReq.getDistrict()); prototype.setMetricName(dataReq.getMetricName()); if (dataReq.getSubValue() != null) prototype.setSubLevelName(dataReq.getSubValue()); if (dataReq.getSubLevel() != null) prototype.setSubLevel(dataReq.getSubLevel()); if(dataReq.getAccessPointType()!=null) prototype.setMetricValue(dataReq.getAccessPointType()); if(dataReq.getParentSubPath()!=null) prototype.setParentSubName(dataReq.getParentSubPath()); prototype.setYear(dataReq.getYear()); return apMetricSummaryDao.listMetrics(prototype); } /** * converts all summary objects in the list to a AccessPointMetricSummaryDto * and return in a list * * @param summaryList * @return */ private List<AccessPointMetricSummaryDto> convertAccessPointMetric( List<AccessPointMetricSummary> summaryList, Boolean includePlacemark) { List<AccessPointMetricSummaryDto> dtoList = new ArrayList<AccessPointMetricSummaryDto>(); if (summaryList != null) { for (AccessPointMetricSummary summary : summaryList) { AccessPointMetricSummaryDto dto = new AccessPointMetricSummaryDto(); DtoMarshaller.copyToDto(summary, dto); if (includePlacemark) { dto.setIconUrl(getIconUrl(dto)); try { dto.setPlacemarkContents(generatePlacemarkContents(dto)); } catch (Exception ex) { log.log(Level.INFO, "couldn't bind summary placemark: " + ex.getMessage()); } } dtoList.add(dto); } } return dtoList; } private String getIconUrl(AccessPointMetricSummaryDto dto) { return imageRoot + "/images/solidOrange64.png"; } private String generatePlacemarkContents(AccessPointMetricSummaryDto dto) throws Exception { KMLGenerator kmlGen = new KMLGenerator(); return kmlGen.bindSummaryPlacemark(dto, "summaryPlacemarkExternalMap.vm"); } }
true
true
protected RestResponse handleRequest(RestRequest req) throws Exception { SummaryDataRequest dataReq = (SummaryDataRequest) req; SummaryDataResponse response = new SummaryDataResponse(); if (cache != null) { SummaryDataResponse cachedResponse = null; try { cachedResponse = (SummaryDataResponse) cache.get(dataReq .getCacheKey()); } catch (Throwable t) { log.log(Level.WARNING, "Could not look up data in cache", t); } if (cachedResponse != null) { return cachedResponse; } } if (SummaryDataRequest.GET_AP_METRIC_SUMMARY_ACTION .equalsIgnoreCase(dataReq.getAction())) { response.setDtoList(convertAccessPointMetric( seachAPMetrics(dataReq), dataReq.getIncludePlacemarkFlag())); } return response; }
protected RestResponse handleRequest(RestRequest req) throws Exception { SummaryDataRequest dataReq = (SummaryDataRequest) req; SummaryDataResponse response = new SummaryDataResponse(); if (cache != null) { SummaryDataResponse cachedResponse = null; try { cachedResponse = (SummaryDataResponse) cache.get(dataReq .getCacheKey()); } catch (Throwable t) { log.log(Level.WARNING, "Could not look up data in cache", t); } if (cachedResponse != null) { return cachedResponse; } } if (SummaryDataRequest.GET_AP_METRIC_SUMMARY_ACTION .equalsIgnoreCase(dataReq.getAction())) { response.setDtoList(convertAccessPointMetric( seachAPMetrics(dataReq), dataReq.getIncludePlacemarkFlag())); } if (response != null && cache != null) { try { cache.put(dataReq.getCacheKey(), response); } catch (Throwable t) { log.log(Level.WARNING, "Could not cache results", t); } } return response; }
diff --git a/project-set/components/client-auth/src/main/java/com/rackspace/papi/components/clientauth/common/AuthenticationHandler.java b/project-set/components/client-auth/src/main/java/com/rackspace/papi/components/clientauth/common/AuthenticationHandler.java index 6eddfedb97..19abc01441 100644 --- a/project-set/components/client-auth/src/main/java/com/rackspace/papi/components/clientauth/common/AuthenticationHandler.java +++ b/project-set/components/client-auth/src/main/java/com/rackspace/papi/components/clientauth/common/AuthenticationHandler.java @@ -1,317 +1,320 @@ package com.rackspace.papi.components.clientauth.common; import com.rackspace.auth.AuthGroup; import com.rackspace.auth.AuthGroups; import com.rackspace.auth.AuthServiceException; import com.rackspace.auth.AuthToken; import com.rackspace.papi.commons.util.StringUriUtilities; import com.rackspace.papi.commons.util.StringUtilities; import com.rackspace.papi.commons.util.http.CommonHttpHeader; import com.rackspace.papi.commons.util.http.HttpStatusCode; import com.rackspace.papi.commons.util.regex.ExtractorResult; import com.rackspace.papi.commons.util.regex.KeyedRegexExtractor; import com.rackspace.papi.commons.util.servlet.http.ReadableHttpServletResponse; import com.rackspace.papi.filter.logic.FilterAction; import com.rackspace.papi.filter.logic.FilterDirector; import com.rackspace.papi.filter.logic.common.AbstractFilterLogicHandler; import com.rackspace.papi.filter.logic.impl.FilterDirectorImpl; import com.sun.jersey.api.client.ClientHandlerException; import org.slf4j.Logger; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * @author fran */ public abstract class AuthenticationHandler extends AbstractFilterLogicHandler { private static final Logger LOG = org.slf4j.LoggerFactory.getLogger(AuthenticationHandler.class); protected abstract AuthToken validateToken(ExtractorResult<String> account, String token); protected abstract AuthGroups getGroups(String group); protected abstract String getEndpointsBase64(String token, EndpointsConfiguration endpointsConfiguration); protected abstract FilterDirector processResponse(ReadableHttpServletResponse response); protected abstract void setFilterDirectorValues(String authToken, AuthToken cachableToken, Boolean delegatable, FilterDirector filterDirector, String extractedResult, List<AuthGroup> groups, String endpointsBase64); private final boolean delegable; private final KeyedRegexExtractor<String> keyedRegexExtractor; private final AuthTokenCache cache; private final AuthGroupCache grpCache; private final EndpointsCache endpointsCache; private final UriMatcher uriMatcher; private final boolean tenanted; private final long groupCacheTtl; private final long userCacheTtl; private final boolean requestGroups; private final EndpointsConfiguration endpointsConfiguration; protected AuthenticationHandler(Configurables configurables, AuthTokenCache cache, AuthGroupCache grpCache, EndpointsCache endpointsCache, UriMatcher uriMatcher) { this.delegable = configurables.isDelegable(); this.keyedRegexExtractor = configurables.getKeyedRegexExtractor(); this.cache = cache; this.grpCache = grpCache; this.endpointsCache = endpointsCache; this.uriMatcher = uriMatcher; this.tenanted = configurables.isTenanted(); this.groupCacheTtl = configurables.getGroupCacheTtl(); this.userCacheTtl = configurables.getUserCacheTtl(); this.requestGroups= configurables.isRequestGroups(); this.endpointsConfiguration = configurables.getEndpointsConfiguration(); } @Override public FilterDirector handleRequest(HttpServletRequest request, ReadableHttpServletResponse response) { FilterDirector filterDirector = new FilterDirectorImpl(); filterDirector.setResponseStatus(HttpStatusCode.UNAUTHORIZED); filterDirector.setFilterAction(FilterAction.RETURN); final String uri = request.getRequestURI(); LOG.debug("Uri is " + uri); if (uriMatcher.isUriOnWhiteList(uri)) { filterDirector.setFilterAction(FilterAction.PASS); LOG.debug("Uri is on whitelist! Letting request pass through."); } else { filterDirector = this.authenticate(request); } return filterDirector; } @Override public FilterDirector handleResponse(HttpServletRequest request, ReadableHttpServletResponse response) { return processResponse(response); } private FilterDirector authenticate(HttpServletRequest request) { final FilterDirector filterDirector = new FilterDirectorImpl(); filterDirector.setResponseStatus(HttpStatusCode.UNAUTHORIZED); filterDirector.setFilterAction(FilterAction.RETURN); final String authToken = request.getHeader(CommonHttpHeader.AUTH_TOKEN.toString()); ExtractorResult<String> account = null; AuthToken token = null; if (tenanted) { account = extractAccountIdentification(request); } final boolean allow = allowAccount(account); if ((!StringUtilities.isBlank(authToken) && allow)) { token = checkToken(account, authToken); if (token == null) { try { token = validateToken(account, StringUriUtilities.encodeUri(authToken)); cacheUserInfo(token); } catch (ClientHandlerException ex) { LOG.error("Failure communicating with the auth service: " + ex.getMessage(), ex); filterDirector.setResponseStatus(HttpStatusCode.INTERNAL_SERVER_ERROR); } catch (AuthServiceException ex) { LOG.error("Failure in Auth-N: " + ex.getMessage()); filterDirector.setResponseStatus(HttpStatusCode.INTERNAL_SERVER_ERROR); }catch (IllegalArgumentException ex){ LOG.error("Failure in Auth-N: " + ex.getMessage()); filterDirector.setResponseStatus(HttpStatusCode.INTERNAL_SERVER_ERROR); } catch (Exception ex) { LOG.error("Failure in auth: " + ex.getMessage(), ex); filterDirector.setResponseStatus(HttpStatusCode.INTERNAL_SERVER_ERROR); } } } - List<AuthGroup> groups = getAuthGroups(token); // copy this pattern + List<AuthGroup> groups = getAuthGroups(token); - //getting the encoded endpoints to pass into the header - String endpointsInBase64 = getEndpointsInBase64(token); + //getting the encoded endpoints to pass into the header, if the endpoints config is not null + String endpointsInBase64 = null; + if (endpointsConfiguration != null){ + endpointsInBase64 = getEndpointsInBase64(token); + } setFilterDirectorValues(authToken, token, delegable, filterDirector, account == null ? "" : account.getResult(), groups, endpointsInBase64); return filterDirector; } //check for null, check for it already in cache private String getEndpointsInBase64(AuthToken token) { String tokenId = null; if (token != null) { tokenId = token.getTokenId(); } String endpoints = checkEndpointsCache(tokenId); //if endpoints are not already in the cache then make a call for them and cache what comes back if (endpoints == null) { endpoints = getEndpointsBase64(tokenId, endpointsConfiguration); cacheEndpoints(tokenId, endpoints); } return endpoints; } //cache check for endpoints private String checkEndpointsCache(String token) { if (endpointsCache == null) { return null; } return endpointsCache.getEndpoints(token); } private List<AuthGroup> getAuthGroups(AuthToken token) { if (token != null && requestGroups) { AuthGroups authGroups = checkGroupCache(token); if (authGroups == null) { try { authGroups = getGroups(token.getUserId()); cacheGroupInfo(token, authGroups); } catch (ClientHandlerException ex) { LOG.error("Failure communicating with the auth service when retrieving groups: " + ex.getMessage(), ex); LOG.error("X-PP-Groups will not be set."); } catch (Exception ex) { LOG.error("Failure in auth when retrieving groups: " + ex.getMessage(), ex); LOG.error("X-PP-Groups will not be set."); } } if (authGroups != null && authGroups.getGroups() != null) { return authGroups.getGroups(); } } return new ArrayList<AuthGroup>(); } private ExtractorResult<String> extractAccountIdentification(HttpServletRequest request) { StringBuilder accountString = new StringBuilder(request.getRequestURI()); return keyedRegexExtractor.extract(accountString.toString()); } private boolean allowAccount(ExtractorResult<String> account) { if (tenanted) { return account != null; } else { return true; } } private AuthToken checkToken(ExtractorResult<String> account, String authToken) { if (tenanted) { return checkUserCache(account.getResult(), authToken); } else { return checkUserCache("", authToken); } } private AuthToken checkUserCache(String tenantId, String token) { if (cache == null) { return null; } String key; if (StringUtilities.isNotBlank(tenantId)) { key = tenantId + ":" + token; } else { key = token; } return cache.getUserToken(key, token); } private void cacheUserInfo(AuthToken user) { if (user == null || cache == null) { return; } String key; if (tenanted) { key = user.getTenantId() + ":" + user.getTokenId(); } else { key = user.getTokenId(); } try { long ttl = userCacheTtl > 0 ? Math.min(userCacheTtl, user.tokenTtl().intValue()) : user.tokenTtl().intValue(); cache.storeToken(key, user, Long.valueOf(ttl).intValue()); } catch (IOException ex) { LOG.warn("Unable to cache user token information: " + user.getUserId() + " Reason: " + ex.getMessage(), ex); } } private String getGroupCacheKey(AuthToken token) { return token.getTenantId() + ":" + token.getTokenId(); } private AuthGroups checkGroupCache(AuthToken token) { if (grpCache == null) { return null; } return grpCache.getUserGroup(getGroupCacheKey(token)); } private void cacheGroupInfo(AuthToken token, AuthGroups groups) { if (groups == null || grpCache == null) { return; } try { grpCache.storeGroups(getGroupCacheKey(token), groups, safeGroupTtl()); } catch (IOException ex) { LOG.warn("Unable to cache user group information: " + token + " Reason: " + ex.getMessage(), ex); } } //store endpoints in cache private void cacheEndpoints(String token, String endpoints) { if (token == null || endpointsCache == null) { return; } try { endpointsCache.storeEndpoints(token, endpoints, safeEndpointsTtl()); } catch (IOException ex) { LOG.warn("Unable to cache endpoints information: " + token + " Reason: " + ex.getMessage(), ex); } } private int safeGroupTtl() { final Long grpTtl = this.groupCacheTtl; if (grpTtl >= Integer.MAX_VALUE) { return Integer.MAX_VALUE; } return grpTtl.intValue(); } //get the ttl but prevent bad integers private Integer safeEndpointsTtl() { final Long endpointsTtl; if (endpointsConfiguration != null) { endpointsTtl = endpointsConfiguration.getCacheTimeout(); } else { return null; } if (endpointsTtl >= Integer.MAX_VALUE) { return Integer.MAX_VALUE; } return endpointsTtl.intValue(); } }
false
true
private FilterDirector authenticate(HttpServletRequest request) { final FilterDirector filterDirector = new FilterDirectorImpl(); filterDirector.setResponseStatus(HttpStatusCode.UNAUTHORIZED); filterDirector.setFilterAction(FilterAction.RETURN); final String authToken = request.getHeader(CommonHttpHeader.AUTH_TOKEN.toString()); ExtractorResult<String> account = null; AuthToken token = null; if (tenanted) { account = extractAccountIdentification(request); } final boolean allow = allowAccount(account); if ((!StringUtilities.isBlank(authToken) && allow)) { token = checkToken(account, authToken); if (token == null) { try { token = validateToken(account, StringUriUtilities.encodeUri(authToken)); cacheUserInfo(token); } catch (ClientHandlerException ex) { LOG.error("Failure communicating with the auth service: " + ex.getMessage(), ex); filterDirector.setResponseStatus(HttpStatusCode.INTERNAL_SERVER_ERROR); } catch (AuthServiceException ex) { LOG.error("Failure in Auth-N: " + ex.getMessage()); filterDirector.setResponseStatus(HttpStatusCode.INTERNAL_SERVER_ERROR); }catch (IllegalArgumentException ex){ LOG.error("Failure in Auth-N: " + ex.getMessage()); filterDirector.setResponseStatus(HttpStatusCode.INTERNAL_SERVER_ERROR); } catch (Exception ex) { LOG.error("Failure in auth: " + ex.getMessage(), ex); filterDirector.setResponseStatus(HttpStatusCode.INTERNAL_SERVER_ERROR); } } } List<AuthGroup> groups = getAuthGroups(token); // copy this pattern //getting the encoded endpoints to pass into the header String endpointsInBase64 = getEndpointsInBase64(token); setFilterDirectorValues(authToken, token, delegable, filterDirector, account == null ? "" : account.getResult(), groups, endpointsInBase64); return filterDirector; }
private FilterDirector authenticate(HttpServletRequest request) { final FilterDirector filterDirector = new FilterDirectorImpl(); filterDirector.setResponseStatus(HttpStatusCode.UNAUTHORIZED); filterDirector.setFilterAction(FilterAction.RETURN); final String authToken = request.getHeader(CommonHttpHeader.AUTH_TOKEN.toString()); ExtractorResult<String> account = null; AuthToken token = null; if (tenanted) { account = extractAccountIdentification(request); } final boolean allow = allowAccount(account); if ((!StringUtilities.isBlank(authToken) && allow)) { token = checkToken(account, authToken); if (token == null) { try { token = validateToken(account, StringUriUtilities.encodeUri(authToken)); cacheUserInfo(token); } catch (ClientHandlerException ex) { LOG.error("Failure communicating with the auth service: " + ex.getMessage(), ex); filterDirector.setResponseStatus(HttpStatusCode.INTERNAL_SERVER_ERROR); } catch (AuthServiceException ex) { LOG.error("Failure in Auth-N: " + ex.getMessage()); filterDirector.setResponseStatus(HttpStatusCode.INTERNAL_SERVER_ERROR); }catch (IllegalArgumentException ex){ LOG.error("Failure in Auth-N: " + ex.getMessage()); filterDirector.setResponseStatus(HttpStatusCode.INTERNAL_SERVER_ERROR); } catch (Exception ex) { LOG.error("Failure in auth: " + ex.getMessage(), ex); filterDirector.setResponseStatus(HttpStatusCode.INTERNAL_SERVER_ERROR); } } } List<AuthGroup> groups = getAuthGroups(token); //getting the encoded endpoints to pass into the header, if the endpoints config is not null String endpointsInBase64 = null; if (endpointsConfiguration != null){ endpointsInBase64 = getEndpointsInBase64(token); } setFilterDirectorValues(authToken, token, delegable, filterDirector, account == null ? "" : account.getResult(), groups, endpointsInBase64); return filterDirector; }
diff --git a/src/org/napile/idea/plugin/refactoring/introduceVariable/NapileInplaceVariableIntroducer.java b/src/org/napile/idea/plugin/refactoring/introduceVariable/NapileInplaceVariableIntroducer.java index 901b595..7ae464e 100644 --- a/src/org/napile/idea/plugin/refactoring/introduceVariable/NapileInplaceVariableIntroducer.java +++ b/src/org/napile/idea/plugin/refactoring/introduceVariable/NapileInplaceVariableIntroducer.java @@ -1,229 +1,229 @@ /* * Copyright 2010-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.napile.idea.plugin.refactoring.introduceVariable; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Box; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JPanel; import org.jetbrains.annotations.Nullable; import org.napile.compiler.lang.psi.NapileExpression; import org.napile.compiler.lang.types.NapileType; import org.napile.compiler.lang.lexer.NapileTokens; import org.napile.compiler.lang.psi.NapileVariable; import org.napile.idea.plugin.intentions.SpecifyTypeExplicitlyAction; import com.intellij.codeInsight.template.impl.TemplateManagerImpl; import com.intellij.codeInsight.template.impl.TemplateState; import com.intellij.lang.ASTNode; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.Result; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiNamedElement; import com.intellij.refactoring.introduce.inplace.InplaceVariableIntroducer; import com.intellij.ui.NonFocusableCheckBox; /** * User: Alefas * Date: 01.02.12 */ public class NapileInplaceVariableIntroducer extends InplaceVariableIntroducer<NapileExpression> { private final boolean myReplaceOccurrence; private final NapileVariable myProperty; private final boolean isVar; private final boolean myDoNotChangeVar; @Nullable private final NapileType myExprType; private final boolean noTypeInference; private JCheckBox myVarCheckbox; private JCheckBox myExprTypeCheckbox; public NapileInplaceVariableIntroducer(PsiNamedElement elementToRename, Editor editor, Project project, String title, NapileExpression[] occurrences, @Nullable NapileExpression expr, boolean replaceOccurrence, NapileVariable property, boolean isVar, boolean doNotChangeVar, @Nullable NapileType exprType, boolean noTypeInference) { super(elementToRename, editor, project, title, occurrences, expr); this.myReplaceOccurrence = replaceOccurrence; myProperty = property; this.isVar = isVar; myDoNotChangeVar = doNotChangeVar; myExprType = exprType; this.noTypeInference = noTypeInference; } @Override @Nullable protected JComponent getComponent() { if(!myDoNotChangeVar) { myVarCheckbox = new NonFocusableCheckBox("Declare with var"); myVarCheckbox.setSelected(isVar); myVarCheckbox.setMnemonic('v'); myVarCheckbox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { new WriteCommandAction(myProject, getCommandName(), getCommandName()) { @Override protected void run(Result result) throws Throwable { PsiDocumentManager.getInstance(myProject).commitDocument(myEditor.getDocument()); NapileChangePropertyActions.declareValueOrVariable(myProject, myVarCheckbox.isSelected(), myProperty); } }.execute(); } }); } if(myExprType != null && !noTypeInference) { myExprTypeCheckbox = new NonFocusableCheckBox("Specify type explicitly"); myExprTypeCheckbox.setSelected(false); myExprTypeCheckbox.setMnemonic('t'); myExprTypeCheckbox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final Ref<Boolean> greedyToRight = new Ref<Boolean>(); new WriteCommandAction(myProject, getCommandName(), getCommandName()) { @Override protected void run(Result result) throws Throwable { PsiDocumentManager.getInstance(myProject).commitDocument(myEditor.getDocument()); if(myExprTypeCheckbox.isSelected()) { ASTNode identifier = myProperty.getNode().findChildByType(NapileTokens.IDENTIFIER); if(identifier != null) { TextRange range = identifier.getTextRange(); RangeHighlighter[] highlighters = myEditor.getMarkupModel().getAllHighlighters(); for(RangeHighlighter highlighter : highlighters) { if(highlighter.getStartOffset() == range.getStartOffset()) { if(highlighter.getEndOffset() == range.getEndOffset()) { greedyToRight.set(highlighter.isGreedyToRight()); highlighter.setGreedyToRight(false); } } } } SpecifyTypeExplicitlyAction.addTypeAnnotation(myProject, myProperty, myExprType); PsiDocumentManager.getInstance(myProject).commitDocument(myEditor.getDocument()); TemplateState templateState = TemplateManagerImpl.getTemplateState(myEditor); if(templateState != null) { - templateState.doReformat(myProperty.getTextRange()); + //templateState.doReformat(myProperty.getTextRange()); } } else { SpecifyTypeExplicitlyAction.removeTypeAnnotation(myProperty); } } }.execute(); ApplicationManager.getApplication().runReadAction(new Runnable() { @Override public void run() { if(myExprTypeCheckbox.isSelected()) { ASTNode identifier = myProperty.getNode().findChildByType(NapileTokens.IDENTIFIER); if(identifier != null) { TextRange range = identifier.getTextRange(); RangeHighlighter[] highlighters = myEditor.getMarkupModel().getAllHighlighters(); for(RangeHighlighter highlighter : highlighters) { if(highlighter.getStartOffset() == range.getStartOffset()) { if(highlighter.getEndOffset() == range.getEndOffset()) { highlighter.setGreedyToRight(greedyToRight.get()); } } } } } } }); } }); } final JPanel panel = new JPanel(new GridBagLayout()); panel.setBorder(null); int count = 1; if(myVarCheckbox != null) { panel.add(myVarCheckbox, new GridBagConstraints(0, count, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); ++count; } if(myExprTypeCheckbox != null) { panel.add(myExprTypeCheckbox, new GridBagConstraints(0, count, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); ++count; } panel.add(Box.createVerticalBox(), new GridBagConstraints(0, count, 1, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); return panel; } @Override protected void moveOffsetAfter(boolean success) { if(!myReplaceOccurrence || myExprMarker == null) { myEditor.getCaretModel().moveToOffset(myProperty.getTextRange().getEndOffset()); } else { int startOffset = myExprMarker.getStartOffset(); PsiFile file = myProperty.getContainingFile(); PsiElement elementAt = file.findElementAt(startOffset); if(elementAt != null) { myEditor.getCaretModel().moveToOffset(elementAt.getTextRange().getEndOffset()); } else { myEditor.getCaretModel().moveToOffset(myExprMarker.getEndOffset()); } } } }
true
true
protected JComponent getComponent() { if(!myDoNotChangeVar) { myVarCheckbox = new NonFocusableCheckBox("Declare with var"); myVarCheckbox.setSelected(isVar); myVarCheckbox.setMnemonic('v'); myVarCheckbox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { new WriteCommandAction(myProject, getCommandName(), getCommandName()) { @Override protected void run(Result result) throws Throwable { PsiDocumentManager.getInstance(myProject).commitDocument(myEditor.getDocument()); NapileChangePropertyActions.declareValueOrVariable(myProject, myVarCheckbox.isSelected(), myProperty); } }.execute(); } }); } if(myExprType != null && !noTypeInference) { myExprTypeCheckbox = new NonFocusableCheckBox("Specify type explicitly"); myExprTypeCheckbox.setSelected(false); myExprTypeCheckbox.setMnemonic('t'); myExprTypeCheckbox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final Ref<Boolean> greedyToRight = new Ref<Boolean>(); new WriteCommandAction(myProject, getCommandName(), getCommandName()) { @Override protected void run(Result result) throws Throwable { PsiDocumentManager.getInstance(myProject).commitDocument(myEditor.getDocument()); if(myExprTypeCheckbox.isSelected()) { ASTNode identifier = myProperty.getNode().findChildByType(NapileTokens.IDENTIFIER); if(identifier != null) { TextRange range = identifier.getTextRange(); RangeHighlighter[] highlighters = myEditor.getMarkupModel().getAllHighlighters(); for(RangeHighlighter highlighter : highlighters) { if(highlighter.getStartOffset() == range.getStartOffset()) { if(highlighter.getEndOffset() == range.getEndOffset()) { greedyToRight.set(highlighter.isGreedyToRight()); highlighter.setGreedyToRight(false); } } } } SpecifyTypeExplicitlyAction.addTypeAnnotation(myProject, myProperty, myExprType); PsiDocumentManager.getInstance(myProject).commitDocument(myEditor.getDocument()); TemplateState templateState = TemplateManagerImpl.getTemplateState(myEditor); if(templateState != null) { templateState.doReformat(myProperty.getTextRange()); } } else { SpecifyTypeExplicitlyAction.removeTypeAnnotation(myProperty); } } }.execute(); ApplicationManager.getApplication().runReadAction(new Runnable() { @Override public void run() { if(myExprTypeCheckbox.isSelected()) { ASTNode identifier = myProperty.getNode().findChildByType(NapileTokens.IDENTIFIER); if(identifier != null) { TextRange range = identifier.getTextRange(); RangeHighlighter[] highlighters = myEditor.getMarkupModel().getAllHighlighters(); for(RangeHighlighter highlighter : highlighters) { if(highlighter.getStartOffset() == range.getStartOffset()) { if(highlighter.getEndOffset() == range.getEndOffset()) { highlighter.setGreedyToRight(greedyToRight.get()); } } } } } } }); } }); } final JPanel panel = new JPanel(new GridBagLayout()); panel.setBorder(null); int count = 1; if(myVarCheckbox != null) { panel.add(myVarCheckbox, new GridBagConstraints(0, count, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); ++count; } if(myExprTypeCheckbox != null) { panel.add(myExprTypeCheckbox, new GridBagConstraints(0, count, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); ++count; } panel.add(Box.createVerticalBox(), new GridBagConstraints(0, count, 1, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); return panel; }
protected JComponent getComponent() { if(!myDoNotChangeVar) { myVarCheckbox = new NonFocusableCheckBox("Declare with var"); myVarCheckbox.setSelected(isVar); myVarCheckbox.setMnemonic('v'); myVarCheckbox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { new WriteCommandAction(myProject, getCommandName(), getCommandName()) { @Override protected void run(Result result) throws Throwable { PsiDocumentManager.getInstance(myProject).commitDocument(myEditor.getDocument()); NapileChangePropertyActions.declareValueOrVariable(myProject, myVarCheckbox.isSelected(), myProperty); } }.execute(); } }); } if(myExprType != null && !noTypeInference) { myExprTypeCheckbox = new NonFocusableCheckBox("Specify type explicitly"); myExprTypeCheckbox.setSelected(false); myExprTypeCheckbox.setMnemonic('t'); myExprTypeCheckbox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final Ref<Boolean> greedyToRight = new Ref<Boolean>(); new WriteCommandAction(myProject, getCommandName(), getCommandName()) { @Override protected void run(Result result) throws Throwable { PsiDocumentManager.getInstance(myProject).commitDocument(myEditor.getDocument()); if(myExprTypeCheckbox.isSelected()) { ASTNode identifier = myProperty.getNode().findChildByType(NapileTokens.IDENTIFIER); if(identifier != null) { TextRange range = identifier.getTextRange(); RangeHighlighter[] highlighters = myEditor.getMarkupModel().getAllHighlighters(); for(RangeHighlighter highlighter : highlighters) { if(highlighter.getStartOffset() == range.getStartOffset()) { if(highlighter.getEndOffset() == range.getEndOffset()) { greedyToRight.set(highlighter.isGreedyToRight()); highlighter.setGreedyToRight(false); } } } } SpecifyTypeExplicitlyAction.addTypeAnnotation(myProject, myProperty, myExprType); PsiDocumentManager.getInstance(myProject).commitDocument(myEditor.getDocument()); TemplateState templateState = TemplateManagerImpl.getTemplateState(myEditor); if(templateState != null) { //templateState.doReformat(myProperty.getTextRange()); } } else { SpecifyTypeExplicitlyAction.removeTypeAnnotation(myProperty); } } }.execute(); ApplicationManager.getApplication().runReadAction(new Runnable() { @Override public void run() { if(myExprTypeCheckbox.isSelected()) { ASTNode identifier = myProperty.getNode().findChildByType(NapileTokens.IDENTIFIER); if(identifier != null) { TextRange range = identifier.getTextRange(); RangeHighlighter[] highlighters = myEditor.getMarkupModel().getAllHighlighters(); for(RangeHighlighter highlighter : highlighters) { if(highlighter.getStartOffset() == range.getStartOffset()) { if(highlighter.getEndOffset() == range.getEndOffset()) { highlighter.setGreedyToRight(greedyToRight.get()); } } } } } } }); } }); } final JPanel panel = new JPanel(new GridBagLayout()); panel.setBorder(null); int count = 1; if(myVarCheckbox != null) { panel.add(myVarCheckbox, new GridBagConstraints(0, count, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); ++count; } if(myExprTypeCheckbox != null) { panel.add(myExprTypeCheckbox, new GridBagConstraints(0, count, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); ++count; } panel.add(Box.createVerticalBox(), new GridBagConstraints(0, count, 1, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); return panel; }
diff --git a/src/main/java/water/api/Upload.java b/src/main/java/water/api/Upload.java index 90c669710..e84830d89 100644 --- a/src/main/java/water/api/Upload.java +++ b/src/main/java/water/api/Upload.java @@ -1,32 +1,32 @@ package water.api; import com.google.gson.JsonObject; public class Upload extends HTMLOnlyRequest { protected String build(Response response) { return "<script type='text/javascript' src='jquery.fileupload/js/vendor/jquery.ui.widget.js'></script>" + "<script type='text/javascript' src='jquery.fileupload/js/jquery.iframe-transport.js'></script>" + "<script type='text/javascript' src='jquery.fileupload/js/jquery.fileupload.js'></script>" + "<script type='text/javascript' src='jquery.fileupload/js/main.js'></script>" + "<div class='container' style='margin: 0px auto'>" - + "<h3>Request Upload ( <a href='Upload.help'>help</a> )</h3>" + + "<h3>Request Upload<a href='Upload.help'><i class='icon-question-sign'></i></a></h3>" + "<p>Please specify the file to be uploaded.</p>" + "<form id='Fileupload'>" + " <span class='btn but-success fileinput-button'>" + " <i class='icon-plus icon-white'></i>" + " <span>Select file...</span>" + " <input type='file'>" + " </span>" + "</form>" + "<table class='table' style='border:0px' id='UploadTable'>" + "</table>" + "</div>"; } public static class PostFile extends JSONOnlyRequest { @Override protected Response serve() { return Response.done(new JsonObject()); } } }
true
true
protected String build(Response response) { return "<script type='text/javascript' src='jquery.fileupload/js/vendor/jquery.ui.widget.js'></script>" + "<script type='text/javascript' src='jquery.fileupload/js/jquery.iframe-transport.js'></script>" + "<script type='text/javascript' src='jquery.fileupload/js/jquery.fileupload.js'></script>" + "<script type='text/javascript' src='jquery.fileupload/js/main.js'></script>" + "<div class='container' style='margin: 0px auto'>" + "<h3>Request Upload ( <a href='Upload.help'>help</a> )</h3>" + "<p>Please specify the file to be uploaded.</p>" + "<form id='Fileupload'>" + " <span class='btn but-success fileinput-button'>" + " <i class='icon-plus icon-white'></i>" + " <span>Select file...</span>" + " <input type='file'>" + " </span>" + "</form>" + "<table class='table' style='border:0px' id='UploadTable'>" + "</table>" + "</div>"; }
protected String build(Response response) { return "<script type='text/javascript' src='jquery.fileupload/js/vendor/jquery.ui.widget.js'></script>" + "<script type='text/javascript' src='jquery.fileupload/js/jquery.iframe-transport.js'></script>" + "<script type='text/javascript' src='jquery.fileupload/js/jquery.fileupload.js'></script>" + "<script type='text/javascript' src='jquery.fileupload/js/main.js'></script>" + "<div class='container' style='margin: 0px auto'>" + "<h3>Request Upload<a href='Upload.help'><i class='icon-question-sign'></i></a></h3>" + "<p>Please specify the file to be uploaded.</p>" + "<form id='Fileupload'>" + " <span class='btn but-success fileinput-button'>" + " <i class='icon-plus icon-white'></i>" + " <span>Select file...</span>" + " <input type='file'>" + " </span>" + "</form>" + "<table class='table' style='border:0px' id='UploadTable'>" + "</table>" + "</div>"; }
diff --git a/src/main/java/com/google/gwt/audio/recorder/client/Recorder.java b/src/main/java/com/google/gwt/audio/recorder/client/Recorder.java index ec090a6..4526e71 100644 --- a/src/main/java/com/google/gwt/audio/recorder/client/Recorder.java +++ b/src/main/java/com/google/gwt/audio/recorder/client/Recorder.java @@ -1,436 +1,436 @@ package com.google.gwt.audio.recorder.client; import com.google.gwt.audio.recorder.client.event.MicrophoneConnectedEvent; import com.google.gwt.audio.recorder.client.event.MicrophoneNotConnectedEvent; import com.google.gwt.audio.recorder.client.event.MicrophoneUserRequestEvent; import com.google.gwt.audio.recorder.client.event.NoMicrophoneFoundEvent; import com.google.gwt.audio.recorder.client.event.PlaybackStartedEvent; import com.google.gwt.audio.recorder.client.event.PlaybackStoppedEvent; import com.google.gwt.audio.recorder.client.event.PlayingEvent; import com.google.gwt.audio.recorder.client.event.RecorderReadyEvent; import com.google.gwt.audio.recorder.client.event.RecordingEvent; import com.google.gwt.audio.recorder.client.event.RecordingStoppedEvent; import com.google.gwt.audio.recorder.client.event.SaveFailedEvent; import com.google.gwt.audio.recorder.client.event.SavePressedEvent; import com.google.gwt.audio.recorder.client.event.SaveProgressEvent; import com.google.gwt.audio.recorder.client.event.SavedEvent; import com.google.gwt.audio.recorder.client.event.SavingEvent; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.dom.client.DivElement; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.FormElement; import com.google.gwt.dom.client.InputElement; import com.google.gwt.event.shared.EventHandler; import com.google.gwt.event.shared.GwtEvent; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.uibinder.client.UiConstructor; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HTMLPanel; public class Recorder extends Composite { private final static int DEFAULT_WIDTH = 24; private final static int DEFAULT_HEIGHT = 24; private final static String DEFAULT_APPLICATION_NAME = "RECORDER_APPLICATION"; private final static String SWF_OBJECT = GWT.getModuleBaseURL() + "recorder.swf"; private final static String FLASH_CONTAINER_ID = "RECORDER_FLASH_CONTAINER"; private final static String UPLOAD_FORM_ID = "RECORDER_UPLOAD_FORM"; private final static String UPLOAD_FIELD_NAME = "RECORDER_UPLOAD_FILE"; private JavaScriptObject flashRecorder; private int recorderOriginalWidth = DEFAULT_WIDTH; private int recorderOriginalHeight = DEFAULT_HEIGHT; private String uploadFormId = UPLOAD_FORM_ID; private String uploadFieldName = UPLOAD_FIELD_NAME + "[filename]"; private String uploadImage; private String uploadURL; private String filename; private FormElement form; @UiConstructor public Recorder(String uploadImage) { this.uploadImage = uploadImage; HTMLPanel mainContent = new HTMLPanel(""); // Flash container DivElement flashContainer = Document.get().createDivElement(); flashContainer.setId(FLASH_CONTAINER_ID); flashContainer.setInnerHTML("Your browser must have JavaScript enabled and the Adobe Flash Player installed."); mainContent.getElement().appendChild(flashContainer); // Form form = Document.get().createFormElement(); form.setId(UPLOAD_FORM_ID); form.setName(UPLOAD_FORM_ID); InputElement fileInput = Document.get().createHiddenInputElement(); fileInput.setName(UPLOAD_FIELD_NAME + "[parent_id]"); fileInput.setValue("1"); form.appendChild(fileInput); mainContent.getElement().appendChild(form); initWidget(mainContent); } @Override protected void onAttach() { super.onAttach(); this.loadFlashRecorder(DEFAULT_WIDTH, DEFAULT_HEIGHT, uploadImage, DEFAULT_APPLICATION_NAME, SWF_OBJECT, FLASH_CONTAINER_ID, UPLOAD_FORM_ID, UPLOAD_FIELD_NAME); } private native void loadFlashRecorder(int width, int height, String uploadImage, String applicationName, String swfObject, String containerId, String uploadFormId, String uploadFieldname) /*-{ var instance = this; // Event management $wnd.microphone_recorder_events = function() { switch (arguments[0]) { case "ready": var width = parseInt(arguments[1]); var height = parseInt(arguments[2]); [email protected]::onRecorderReady(II)(width, height); [email protected]::connect(Ljava/lang/String;I)(applicationName, 0); break; case "no_microphone_found": [email protected]::onNoMicrophoneFound()(); break; case "microphone_user_request": [email protected]::showPermissionWindow()(); [email protected]::onMicrophoneUserRequest()(); break; case "microphone_connected": var mic = arguments[1]; [email protected]::defaultSize()(); [email protected]::onMicrophoneConnected(Ljava/lang/String;)(mic.name); break; case "microphone_not_connected": [email protected]::defaultSize()(); [email protected]::onMicrophoneNotConnected()(); break; case "recording": var name = arguments[1]; [email protected]::onRecording(Ljava/lang/String;)(name); [email protected]::hide()(); break; case "recording_stopped": var name = arguments[1]; var duration = arguments[2]; [email protected]::flashRecorder.show(); [email protected]::onRecordingStop(Ljava/lang/String;I)(name, duration); break; case "playing": var name = arguments[1]; [email protected]::onPlaying(Ljava/lang/String;)(name); break; case "playback_started": var name = arguments[1]; var latency = arguments[2]; [email protected]::onPlaybackStarted(Ljava/lang/String;I)(name, latency); break; case "stopped": var name = arguments[1]; [email protected]::onPlaybackStopped(Ljava/lang/String;)(name); break; case "save_pressed": [email protected]::updateForm()(); [email protected]::onSavePressed()(); break; case "saving": var name = arguments[1]; [email protected]::onSaving(Ljava/lang/String;)(name); break; case "saved": var name = arguments[1]; // var data = $.parseJSON(arguments[2]); // if (data.saved) { [email protected]::onSaved(Ljava/lang/String;)(name); break; case "save_failed": var name = arguments[1]; var errorMessage = arguments[2]; - // [email protected]::onSaveProgress(II)(bytesLoaded, bytesTotal); + [email protected]::onSaveFailed(Ljava/lang/String;Ljava/lang/String;)(name, errorMessage); break; } } var appWidth = width; var appHeight = height; var flashvars = { 'event_handler' : 'microphone_recorder_events', 'upload_image' : uploadImage }; var params = {}; var attributes = { 'id' : applicationName, 'name' : applicationName }; $wnd.swfobject.embedSWF(swfObject, containerId, appWidth, appHeight, "10.1.0", "", flashvars, params, attributes); }-*/; private native void connect(String applicationName, int attempts) /*-{ var instance = this; if (navigator.appName.indexOf("Microsoft") != -1) { [email protected]::flashRecorder = $wnd.window[applicationName]; } else { [email protected]::flashRecorder = $wnd.document[applicationName]; } if (attempts >= 40) { return; } // flash app needs time to load and initialize if ([email protected]::flashRecorder && [email protected]::flashRecorder.init) { [email protected]::recorderOriginalWidth = [email protected]::flashRecorder.width; [email protected]::recorderOriginalHeight = [email protected]::flashRecorder.height; if ([email protected]::uploadFormId) { var frm; if (navigator.appName.indexOf("Microsoft") != -1) { frm = $wnd.window[[email protected]::uploadFormId]; } else { frm = $wnd.document[[email protected]::uploadFormId]; } [email protected]::flashRecorder .init( frm.getAttribute('action'), [email protected]::uploadFieldName); } return; } setTimeout( function() { [email protected]::connect(Ljava/lang/String;I)(applicationName, attempts + 1); }, 100); }-*/; public native void play() /*-{ var filename = [email protected]::filename; [email protected]::flashRecorder.playBack(filename); }-*/; public native void record() /*-{ var filename = [email protected]::filename; [email protected]::flashRecorder.record(filename, filename); }-*/; public native void resize(int width, int height) /*-{ [email protected]::flashRecorder.width = width + "px"; [email protected]::flashRecorder.height = height + "px"; }-*/; public native void defaultSize() /*-{ this [email protected]::resize(II) ( [email protected]::recorderOriginalWidth, [email protected]::recorderOriginalHeight); }-*/; /** * show the save button */ public native void show() /*-{ [email protected]::flashRecorder .show(); }-*/; /** * hide the save button */ public native void hide() /*-{ [email protected]::flashRecorder .hide(); }-*/; /** * update the form data */ public native void updateForm() /*-{ // Not working // var data = new Object; // data.name = "id"; // data.value = [email protected]::filename; // [email protected]::flashRecorder.update(JSON.stringify(data)); [email protected]::flashRecorder.update(); }-*/; /** * returns the duration of the recording * * @param name * name of the recording * @return */ public native int getDuration(String name) /*-{ return [email protected]::flashRecorder .duration(name); }-*/; /** * show the permissions dialog for microphone access, make sure the flash * application is large enough for the dialog box before calling this * method. Must be at least 240x160. */ public native void showPermissionWindow() /*-{ var instance = this; [email protected]::resize(II)(240, 160); // need to wait until app is resized before displaying permissions screen setTimeout( function() { [email protected]::flashRecorder .permit(); }, 1); }-*/; /** * Configures microphone settings * * @param rate * at which the microphone captures sound, in kHz. default is 22. * Currently we only support 44 and 22. * @param gain * the amount by which the microphone should multiply the signal * before transmitting it. default is 100 * @param silenceLevel * amount of sound required to activate the microphone and * dispatch the activity event. default is 0 * @param silenceTimeout * number of milliseconds between the time the microphone stops * detecting sound and the time the activity event is dispatched. * default is 4000 */ public native void configure(int rate, int gain, int silenceLevel, int silenceTimeout) /*-{ [email protected]::flashRecorder .configure(rate, gain, silenceLevel, silenceTimeout); }-*/; /** * use echo suppression * * @param use */ private native void setUseEchoSuppression(boolean use) /*-{ [email protected]::flashRecorder .setUseEchoSuppression(value); }-*/; /** * routes audio captured by a microphone to the local speakers * * @param loopBack */ private native void setLoopBack(boolean loopBack) /*-{ [email protected]::flashRecorder .setLoopBack(value); }-*/; private void onRecorderReady(int width, int height) { this.fireEvent(new RecorderReadyEvent(width, height)); } private void onNoMicrophoneFound() { this.fireEvent(new NoMicrophoneFoundEvent()); } private void onMicrophoneUserRequest() { this.fireEvent(new MicrophoneUserRequestEvent()); } private void onMicrophoneConnected(String name) { this.fireEvent(new MicrophoneConnectedEvent(name)); } private void onMicrophoneNotConnected() { this.fireEvent(new MicrophoneNotConnectedEvent()); } private void onRecording(String name) { this.fireEvent(new RecordingEvent(name)); } private void onRecordingStop(String name, int duration) { this.fireEvent(new RecordingStoppedEvent(name, duration)); } private void onPlaying(String name) { this.fireEvent(new PlayingEvent(name)); } private void onPlaybackStopped(String name) { this.fireEvent(new PlaybackStoppedEvent(name)); } private void onPlaybackStarted(String name, int latency) { this.fireEvent(new PlaybackStartedEvent(name, latency)); } private void onSavePressed() { this.fireEvent(new SavePressedEvent()); } private void onSaved(String name) { this.fireEvent(new SavedEvent(name)); } private void onSaveFailed(String name, String error) { this.fireEvent(new SaveFailedEvent(name, error)); } private void onSaveProgress(int byteLoaded, int bytesTotal) { this.fireEvent(new SaveProgressEvent(byteLoaded, bytesTotal)); } private void onSaving(String name) { this.fireEvent(new SavingEvent(name)); } /** * Adds this handler to the widget. * * @param <H> * the type of handler to add * @param type * the event type * @param handler * the handler * @return {@link HandlerRegistration} used to remove the handler */ public final <H extends EventHandler> HandlerRegistration addHandler(GwtEvent.Type<H> type, final H handler) { return this.addHandler(handler, type); } public String getUploadURL() { return uploadURL; } public void setUploadURL(String uploadURL) { this.uploadURL = uploadURL; this.form.setAction(this.uploadURL); } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } }
true
true
private native void loadFlashRecorder(int width, int height, String uploadImage, String applicationName, String swfObject, String containerId, String uploadFormId, String uploadFieldname) /*-{ var instance = this; // Event management $wnd.microphone_recorder_events = function() { switch (arguments[0]) { case "ready": var width = parseInt(arguments[1]); var height = parseInt(arguments[2]); [email protected]::onRecorderReady(II)(width, height); [email protected]::connect(Ljava/lang/String;I)(applicationName, 0); break; case "no_microphone_found": [email protected]::onNoMicrophoneFound()(); break; case "microphone_user_request": [email protected]::showPermissionWindow()(); [email protected]::onMicrophoneUserRequest()(); break; case "microphone_connected": var mic = arguments[1]; [email protected]::defaultSize()(); [email protected]::onMicrophoneConnected(Ljava/lang/String;)(mic.name); break; case "microphone_not_connected": [email protected]::defaultSize()(); [email protected]::onMicrophoneNotConnected()(); break; case "recording": var name = arguments[1]; [email protected]::onRecording(Ljava/lang/String;)(name); [email protected]::hide()(); break; case "recording_stopped": var name = arguments[1]; var duration = arguments[2]; [email protected]::flashRecorder.show(); [email protected]::onRecordingStop(Ljava/lang/String;I)(name, duration); break; case "playing": var name = arguments[1]; [email protected]::onPlaying(Ljava/lang/String;)(name); break; case "playback_started": var name = arguments[1]; var latency = arguments[2]; [email protected]::onPlaybackStarted(Ljava/lang/String;I)(name, latency); break; case "stopped": var name = arguments[1]; [email protected]::onPlaybackStopped(Ljava/lang/String;)(name); break; case "save_pressed": [email protected]::updateForm()(); [email protected]::onSavePressed()(); break; case "saving": var name = arguments[1]; [email protected]::onSaving(Ljava/lang/String;)(name); break; case "saved": var name = arguments[1]; // var data = $.parseJSON(arguments[2]); // if (data.saved) { [email protected]::onSaved(Ljava/lang/String;)(name); break; case "save_failed": var name = arguments[1]; var errorMessage = arguments[2]; // [email protected]::onSaveProgress(II)(bytesLoaded, bytesTotal); break; } } var appWidth = width; var appHeight = height; var flashvars = { 'event_handler' : 'microphone_recorder_events', 'upload_image' : uploadImage }; var params = {}; var attributes = { 'id' : applicationName, 'name' : applicationName }; $wnd.swfobject.embedSWF(swfObject, containerId, appWidth, appHeight, "10.1.0", "", flashvars, params, attributes); }-*/;
private native void loadFlashRecorder(int width, int height, String uploadImage, String applicationName, String swfObject, String containerId, String uploadFormId, String uploadFieldname) /*-{ var instance = this; // Event management $wnd.microphone_recorder_events = function() { switch (arguments[0]) { case "ready": var width = parseInt(arguments[1]); var height = parseInt(arguments[2]); [email protected]::onRecorderReady(II)(width, height); [email protected]::connect(Ljava/lang/String;I)(applicationName, 0); break; case "no_microphone_found": [email protected]::onNoMicrophoneFound()(); break; case "microphone_user_request": [email protected]::showPermissionWindow()(); [email protected]::onMicrophoneUserRequest()(); break; case "microphone_connected": var mic = arguments[1]; [email protected]::defaultSize()(); [email protected]::onMicrophoneConnected(Ljava/lang/String;)(mic.name); break; case "microphone_not_connected": [email protected]::defaultSize()(); [email protected]::onMicrophoneNotConnected()(); break; case "recording": var name = arguments[1]; [email protected]::onRecording(Ljava/lang/String;)(name); [email protected]::hide()(); break; case "recording_stopped": var name = arguments[1]; var duration = arguments[2]; [email protected]::flashRecorder.show(); [email protected]::onRecordingStop(Ljava/lang/String;I)(name, duration); break; case "playing": var name = arguments[1]; [email protected]::onPlaying(Ljava/lang/String;)(name); break; case "playback_started": var name = arguments[1]; var latency = arguments[2]; [email protected]::onPlaybackStarted(Ljava/lang/String;I)(name, latency); break; case "stopped": var name = arguments[1]; [email protected]::onPlaybackStopped(Ljava/lang/String;)(name); break; case "save_pressed": [email protected]::updateForm()(); [email protected]::onSavePressed()(); break; case "saving": var name = arguments[1]; [email protected]::onSaving(Ljava/lang/String;)(name); break; case "saved": var name = arguments[1]; // var data = $.parseJSON(arguments[2]); // if (data.saved) { [email protected]::onSaved(Ljava/lang/String;)(name); break; case "save_failed": var name = arguments[1]; var errorMessage = arguments[2]; [email protected]::onSaveFailed(Ljava/lang/String;Ljava/lang/String;)(name, errorMessage); break; } } var appWidth = width; var appHeight = height; var flashvars = { 'event_handler' : 'microphone_recorder_events', 'upload_image' : uploadImage }; var params = {}; var attributes = { 'id' : applicationName, 'name' : applicationName }; $wnd.swfobject.embedSWF(swfObject, containerId, appWidth, appHeight, "10.1.0", "", flashvars, params, attributes); }-*/;
diff --git a/compiler/src/main/java/dagger/internal/codegen/GraphAnalysisInjectBinding.java b/compiler/src/main/java/dagger/internal/codegen/GraphAnalysisInjectBinding.java index dddd6e62..aafa6c7d 100644 --- a/compiler/src/main/java/dagger/internal/codegen/GraphAnalysisInjectBinding.java +++ b/compiler/src/main/java/dagger/internal/codegen/GraphAnalysisInjectBinding.java @@ -1,146 +1,146 @@ /* * Copyright (C) 2012 Square, 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 dagger.internal.codegen; import dagger.internal.Binding; import dagger.internal.Linker; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import javax.inject.Inject; import javax.inject.Singleton; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import static dagger.internal.codegen.TypeUtils.getApplicationSupertype; /** * A build time binding that injects the constructor and fields of a class. */ final class GraphAnalysisInjectBinding extends Binding<Object> { private final TypeElement type; private final List<String> keys; private final Binding<?>[] bindings; private final String supertypeKey; private GraphAnalysisInjectBinding(String provideKey, String membersKey, TypeElement type, List<String> keys, String supertypeKey) { super(provideKey, membersKey, type.getAnnotation(Singleton.class) != null, type.getQualifiedName().toString()); this.type = type; this.keys = keys; this.bindings = new Binding<?>[keys.size()]; this.supertypeKey = supertypeKey; } static GraphAnalysisInjectBinding create(TypeElement type, boolean mustHaveInjections) { List<String> requiredKeys = new ArrayList<String>(); boolean hasInjectConstructor = false; boolean hasNoArgsConstructor = false; for (Element enclosed : type.getEnclosedElements()) { switch (enclosed.getKind()) { case FIELD: if (hasAtInject(enclosed) && !enclosed.getModifiers().contains(Modifier.STATIC)) { // Attach the non-static fields of 'type'. requiredKeys.add(GeneratorKeys.get((VariableElement) enclosed)); } break; case CONSTRUCTOR: ExecutableElement constructor = (ExecutableElement) enclosed; List<? extends VariableElement> parameters = constructor.getParameters(); if (hasAtInject(enclosed)) { if (hasAtSingleton(enclosed)) { - throw new IllegalArgumentException("Singleton annotations have no effect on " + - "constructors. Did you mean to annotate the class? " + - type.getQualifiedName().toString()); + throw new IllegalArgumentException("Singleton annotations have no effect on " + + "constructors. Did you mean to annotate the class? " + + type.getQualifiedName().toString()); } if (hasInjectConstructor) { throw new IllegalArgumentException("Too many injectable constructors on " + type.getQualifiedName().toString()); } hasInjectConstructor = true; for (VariableElement parameter : parameters) { requiredKeys.add(GeneratorKeys.get(parameter)); } } else if (parameters.isEmpty()) { hasNoArgsConstructor = true; } break; default: if (hasAtInject(enclosed)) { throw new IllegalArgumentException("Unexpected @Inject annotation on " + enclosed); } } } if (!hasInjectConstructor && requiredKeys.isEmpty() && mustHaveInjections) { throw new IllegalArgumentException("No injectable members on " + type.getQualifiedName().toString() + ". Do you want to add an injectable constructor?"); } // Attach the supertype. TypeMirror supertype = getApplicationSupertype(type); String supertypeKey = supertype != null ? GeneratorKeys.rawMembersKey(supertype) : null; String provideKey = hasInjectConstructor || (hasNoArgsConstructor && !requiredKeys.isEmpty()) ? GeneratorKeys.get(type.asType()) : null; String membersKey = GeneratorKeys.rawMembersKey(type.asType()); return new GraphAnalysisInjectBinding(provideKey, membersKey, type, requiredKeys, supertypeKey); } private static boolean hasAtInject(Element enclosed) { return enclosed.getAnnotation(Inject.class) != null; } private static boolean hasAtSingleton(Element enclosed) { return enclosed.getAnnotation(Singleton.class) != null; } @Override public void attach(Linker linker) { String requiredBy = type.getQualifiedName().toString(); for (int i = 0; i < keys.size(); i++) { bindings[i] = linker.requestBinding(keys.get(i), requiredBy, getClass().getClassLoader()); } if (supertypeKey != null) { // Force the binding lookup. linker.requestBinding(supertypeKey, requiredBy, getClass().getClassLoader(), false, true); } } @Override public Object get() { throw new AssertionError("Compile-time binding should never be called to inject."); } @Override public void injectMembers(Object t) { throw new AssertionError("Compile-time binding should never be called to inject."); } @Override public void getDependencies(Set<Binding<?>> get, Set<Binding<?>> injectMembers) { Collections.addAll(get, bindings); } }
true
true
static GraphAnalysisInjectBinding create(TypeElement type, boolean mustHaveInjections) { List<String> requiredKeys = new ArrayList<String>(); boolean hasInjectConstructor = false; boolean hasNoArgsConstructor = false; for (Element enclosed : type.getEnclosedElements()) { switch (enclosed.getKind()) { case FIELD: if (hasAtInject(enclosed) && !enclosed.getModifiers().contains(Modifier.STATIC)) { // Attach the non-static fields of 'type'. requiredKeys.add(GeneratorKeys.get((VariableElement) enclosed)); } break; case CONSTRUCTOR: ExecutableElement constructor = (ExecutableElement) enclosed; List<? extends VariableElement> parameters = constructor.getParameters(); if (hasAtInject(enclosed)) { if (hasAtSingleton(enclosed)) { throw new IllegalArgumentException("Singleton annotations have no effect on " + "constructors. Did you mean to annotate the class? " + type.getQualifiedName().toString()); } if (hasInjectConstructor) { throw new IllegalArgumentException("Too many injectable constructors on " + type.getQualifiedName().toString()); } hasInjectConstructor = true; for (VariableElement parameter : parameters) { requiredKeys.add(GeneratorKeys.get(parameter)); } } else if (parameters.isEmpty()) { hasNoArgsConstructor = true; } break; default: if (hasAtInject(enclosed)) { throw new IllegalArgumentException("Unexpected @Inject annotation on " + enclosed); } } } if (!hasInjectConstructor && requiredKeys.isEmpty() && mustHaveInjections) { throw new IllegalArgumentException("No injectable members on " + type.getQualifiedName().toString() + ". Do you want to add an injectable constructor?"); } // Attach the supertype. TypeMirror supertype = getApplicationSupertype(type); String supertypeKey = supertype != null ? GeneratorKeys.rawMembersKey(supertype) : null; String provideKey = hasInjectConstructor || (hasNoArgsConstructor && !requiredKeys.isEmpty()) ? GeneratorKeys.get(type.asType()) : null; String membersKey = GeneratorKeys.rawMembersKey(type.asType()); return new GraphAnalysisInjectBinding(provideKey, membersKey, type, requiredKeys, supertypeKey); }
static GraphAnalysisInjectBinding create(TypeElement type, boolean mustHaveInjections) { List<String> requiredKeys = new ArrayList<String>(); boolean hasInjectConstructor = false; boolean hasNoArgsConstructor = false; for (Element enclosed : type.getEnclosedElements()) { switch (enclosed.getKind()) { case FIELD: if (hasAtInject(enclosed) && !enclosed.getModifiers().contains(Modifier.STATIC)) { // Attach the non-static fields of 'type'. requiredKeys.add(GeneratorKeys.get((VariableElement) enclosed)); } break; case CONSTRUCTOR: ExecutableElement constructor = (ExecutableElement) enclosed; List<? extends VariableElement> parameters = constructor.getParameters(); if (hasAtInject(enclosed)) { if (hasAtSingleton(enclosed)) { throw new IllegalArgumentException("Singleton annotations have no effect on " + "constructors. Did you mean to annotate the class? " + type.getQualifiedName().toString()); } if (hasInjectConstructor) { throw new IllegalArgumentException("Too many injectable constructors on " + type.getQualifiedName().toString()); } hasInjectConstructor = true; for (VariableElement parameter : parameters) { requiredKeys.add(GeneratorKeys.get(parameter)); } } else if (parameters.isEmpty()) { hasNoArgsConstructor = true; } break; default: if (hasAtInject(enclosed)) { throw new IllegalArgumentException("Unexpected @Inject annotation on " + enclosed); } } } if (!hasInjectConstructor && requiredKeys.isEmpty() && mustHaveInjections) { throw new IllegalArgumentException("No injectable members on " + type.getQualifiedName().toString() + ". Do you want to add an injectable constructor?"); } // Attach the supertype. TypeMirror supertype = getApplicationSupertype(type); String supertypeKey = supertype != null ? GeneratorKeys.rawMembersKey(supertype) : null; String provideKey = hasInjectConstructor || (hasNoArgsConstructor && !requiredKeys.isEmpty()) ? GeneratorKeys.get(type.asType()) : null; String membersKey = GeneratorKeys.rawMembersKey(type.asType()); return new GraphAnalysisInjectBinding(provideKey, membersKey, type, requiredKeys, supertypeKey); }
diff --git a/tests/org.eclipse.gmf.tests.lite/src/org/eclipse/gmf/tests/lite/gen/LiteCompilationTestWithImportConflicts.java b/tests/org.eclipse.gmf.tests.lite/src/org/eclipse/gmf/tests/lite/gen/LiteCompilationTestWithImportConflicts.java index ea544235c..e0f06f147 100644 --- a/tests/org.eclipse.gmf.tests.lite/src/org/eclipse/gmf/tests/lite/gen/LiteCompilationTestWithImportConflicts.java +++ b/tests/org.eclipse.gmf.tests.lite/src/org/eclipse/gmf/tests/lite/gen/LiteCompilationTestWithImportConflicts.java @@ -1,60 +1,60 @@ /** * Copyright (c) 2006 Borland Software Corporation * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * bblajer - initial API and implementation */ package org.eclipse.gmf.tests.lite.gen; import java.text.MessageFormat; import java.util.Collections; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.emf.codegen.ecore.Generator; import org.eclipse.gmf.tests.setup.DiaGenSource; import org.eclipse.jdt.core.IBuffer; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.JavaCore; public class LiteCompilationTestWithImportConflicts extends LiteCompilationTest { public LiteCompilationTestWithImportConflicts(String name) { super(name); } public void testPreexistingImportConflicts() throws Exception { - DiaGenSource gmfGenSource = loadSource(); + DiaGenSource gmfGenSource = getLibraryGen(); gmfGenSource.getGenDiagram().getEditorGen().setSameFileForDiagramAndModel(false); String pluginId = gmfGenSource.getGenDiagram().getEditorGen().getPlugin().getID(); IProject diagramProject = ResourcesPlugin.getWorkspace().getRoot().getProject(pluginId); if (!diagramProject.isAccessible()) { //Initialize the plugin the same way it would be initialized if present. Generator.createEMFProject(diagramProject.getFolder("src").getFullPath(), null, Collections.EMPTY_LIST, new NullProgressMonitor(), Generator.EMF_PLUGIN_PROJECT_STYLE); //$NON-NLS-1$ } IJavaProject javaProject = JavaCore.create(diagramProject); assertTrue(javaProject.exists()); IPackageFragment pf = javaProject.getPackageFragmentRoot(diagramProject.getFolder("src")).createPackageFragment(gmfGenSource.getGenDiagram().getNotationViewFactoriesPackageName(), false, new NullProgressMonitor()); //$NON-NLS-1$ ICompilationUnit cu = pf.getCompilationUnit(gmfGenSource.getGenDiagram().getNotationViewFactoryClassName() + ".java"); //$NON-NLS-1$ String contents = createContents(gmfGenSource.getGenDiagram().getNotationViewFactoriesPackageName(), gmfGenSource.getGenDiagram().getNotationViewFactoryClassName(), "javax.swing.text.View"); //$NON-NLS-1$ if (cu.exists()) { IBuffer buffer = cu.getBuffer(); buffer.setContents(contents); buffer.save(new NullProgressMonitor(), true); } else { pf.createCompilationUnit(cu.getElementName(), contents, false, new NullProgressMonitor()); } generateAndCompile(gmfGenSource); } private String createContents(String packageName, String className, String conflictingImport) { return MessageFormat.format("package {0};\nimport {2};\n /**\n * @generated\n */\npublic class {1} '{ }'", packageName, className, conflictingImport); //$NON-NLS-1$ } }
true
true
public void testPreexistingImportConflicts() throws Exception { DiaGenSource gmfGenSource = loadSource(); gmfGenSource.getGenDiagram().getEditorGen().setSameFileForDiagramAndModel(false); String pluginId = gmfGenSource.getGenDiagram().getEditorGen().getPlugin().getID(); IProject diagramProject = ResourcesPlugin.getWorkspace().getRoot().getProject(pluginId); if (!diagramProject.isAccessible()) { //Initialize the plugin the same way it would be initialized if present. Generator.createEMFProject(diagramProject.getFolder("src").getFullPath(), null, Collections.EMPTY_LIST, new NullProgressMonitor(), Generator.EMF_PLUGIN_PROJECT_STYLE); //$NON-NLS-1$ } IJavaProject javaProject = JavaCore.create(diagramProject); assertTrue(javaProject.exists()); IPackageFragment pf = javaProject.getPackageFragmentRoot(diagramProject.getFolder("src")).createPackageFragment(gmfGenSource.getGenDiagram().getNotationViewFactoriesPackageName(), false, new NullProgressMonitor()); //$NON-NLS-1$ ICompilationUnit cu = pf.getCompilationUnit(gmfGenSource.getGenDiagram().getNotationViewFactoryClassName() + ".java"); //$NON-NLS-1$ String contents = createContents(gmfGenSource.getGenDiagram().getNotationViewFactoriesPackageName(), gmfGenSource.getGenDiagram().getNotationViewFactoryClassName(), "javax.swing.text.View"); //$NON-NLS-1$ if (cu.exists()) { IBuffer buffer = cu.getBuffer(); buffer.setContents(contents); buffer.save(new NullProgressMonitor(), true); } else { pf.createCompilationUnit(cu.getElementName(), contents, false, new NullProgressMonitor()); } generateAndCompile(gmfGenSource); }
public void testPreexistingImportConflicts() throws Exception { DiaGenSource gmfGenSource = getLibraryGen(); gmfGenSource.getGenDiagram().getEditorGen().setSameFileForDiagramAndModel(false); String pluginId = gmfGenSource.getGenDiagram().getEditorGen().getPlugin().getID(); IProject diagramProject = ResourcesPlugin.getWorkspace().getRoot().getProject(pluginId); if (!diagramProject.isAccessible()) { //Initialize the plugin the same way it would be initialized if present. Generator.createEMFProject(diagramProject.getFolder("src").getFullPath(), null, Collections.EMPTY_LIST, new NullProgressMonitor(), Generator.EMF_PLUGIN_PROJECT_STYLE); //$NON-NLS-1$ } IJavaProject javaProject = JavaCore.create(diagramProject); assertTrue(javaProject.exists()); IPackageFragment pf = javaProject.getPackageFragmentRoot(diagramProject.getFolder("src")).createPackageFragment(gmfGenSource.getGenDiagram().getNotationViewFactoriesPackageName(), false, new NullProgressMonitor()); //$NON-NLS-1$ ICompilationUnit cu = pf.getCompilationUnit(gmfGenSource.getGenDiagram().getNotationViewFactoryClassName() + ".java"); //$NON-NLS-1$ String contents = createContents(gmfGenSource.getGenDiagram().getNotationViewFactoriesPackageName(), gmfGenSource.getGenDiagram().getNotationViewFactoryClassName(), "javax.swing.text.View"); //$NON-NLS-1$ if (cu.exists()) { IBuffer buffer = cu.getBuffer(); buffer.setContents(contents); buffer.save(new NullProgressMonitor(), true); } else { pf.createCompilationUnit(cu.getElementName(), contents, false, new NullProgressMonitor()); } generateAndCompile(gmfGenSource); }
diff --git a/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/mopp/TaskItemBuilderGenerator.java b/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/mopp/TaskItemBuilderGenerator.java index 95e01042e..36ee7db5b 100644 --- a/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/mopp/TaskItemBuilderGenerator.java +++ b/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/mopp/TaskItemBuilderGenerator.java @@ -1,115 +1,115 @@ package org.emftext.sdk.codegen.resource.generators.mopp; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.CORE_EXCEPTION; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.INPUT_STREAM; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.IO_EXCEPTION; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.I_CONTAINER; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.I_FILE; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.I_MARKER; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.I_PROGRESS_MONITOR; import org.emftext.sdk.codegen.composites.JavaComposite; import org.emftext.sdk.codegen.parameters.ArtifactParameter; import org.emftext.sdk.codegen.resource.GenerationContext; import org.emftext.sdk.codegen.resource.generators.JavaBaseGenerator; import org.emftext.sdk.codegen.util.NameUtil; import org.emftext.sdk.concretesyntax.ConcreteSyntax; public class TaskItemBuilderGenerator extends JavaBaseGenerator<ArtifactParameter<GenerationContext>> { private final NameUtil nameUtil = new NameUtil(); @Override public void generateJavaContents(JavaComposite sc) { ConcreteSyntax syntax = getContext().getConcreteSyntax(); String builderID = nameUtil.getTaskItemBuilderID(syntax); sc.add("package " + getResourcePackageName() + ";"); sc.addLineBreak(); sc.addJavadoc( "The " + getResourceClassName() + " is used to find task items in " + "text documents. The current implementation uses the generated lexer " + "and the TaskItemDetector to detect task items." ); sc.add("public class " + getResourceClassName() + " extends " + builderAdapterClassName + " {"); sc.addLineBreak(); addConstants(sc, builderID); addMethods(sc); sc.add("}"); } private void addConstants(JavaComposite sc, String builderID) { sc.addJavadoc("The ID of the item task builder."); sc.add("public final static String BUILDER_ID = \"" + builderID + "\";"); sc.addLineBreak(); } private void addMethods(JavaComposite sc) { addBuildMethod(sc); addGetBuilderMarkerIdMethod(sc); addIsInBinFolderMethod(sc); } private void addBuildMethod(JavaComposite sc) { sc.add("@Override").addLineBreak(); sc.add("public void build(" + I_FILE + " resource, " + I_PROGRESS_MONITOR + " monitor) {"); sc.add("monitor.setTaskName(\"Searching for task items\");"); sc.add("new " + markerHelperClassName + "().removeAllMarkers(resource, " + I_MARKER + ".TASK);"); sc.add("if (isInBinFolder(resource)) {"); sc.add("return;"); sc.add("}"); sc.add(sc.declareArrayList("taskItems", taskItemClassName)); sc.add(taskItemDetectorClassName + " taskItemDetector = new " + taskItemDetectorClassName + "();"); sc.add("try {"); sc.add(INPUT_STREAM + " inputStream = resource.getContents();"); sc.add("String content = " + streamUtilClassName + ".getContent(inputStream);"); sc.add(iTextScannerClassName + " lexer = new " + metaInformationClassName + "().createLexer();"); sc.add("lexer.setText(content);"); sc.addLineBreak(); sc.add(iTextTokenClassName + " nextToken = lexer.getNextToken();"); sc.add("while (nextToken != null) {"); sc.add("String text = nextToken.getText();"); sc.add("taskItems.addAll(taskItemDetector.findTaskItems(text, nextToken.getLine(), nextToken.getOffset()));"); sc.add("nextToken = lexer.getNextToken();"); sc.add("}"); sc.add("} catch (" + IO_EXCEPTION + " e) {"); - sc.add("HedlPlugin.logError(\"Exception while searching for task items\", e);"); + sc.add(pluginActivatorClassName + ".logError(\"Exception while searching for task items\", e);"); sc.add("} catch (" + CORE_EXCEPTION + " e) {"); - sc.add("HedlPlugin.logError(\"Exception while searching for task items\", e);"); + sc.add(pluginActivatorClassName + ".logError(\"Exception while searching for task items\", e);"); sc.add("}"); sc.addLineBreak(); sc.add("for (" + taskItemClassName + " taskItem : taskItems) {"); sc.add(sc.declareLinkedHashMap("markerAttributes", "String", "Object")); sc.add("markerAttributes.put(" + I_MARKER + ".USER_EDITABLE, false);"); sc.add("markerAttributes.put(" + I_MARKER + ".DONE, false);"); sc.add("markerAttributes.put(" + I_MARKER + ".LINE_NUMBER, taskItem.getLine());"); sc.add("markerAttributes.put(" + I_MARKER + ".CHAR_START, taskItem.getCharStart());"); sc.add("markerAttributes.put(" + I_MARKER + ".CHAR_END, taskItem.getCharEnd());"); sc.add("markerAttributes.put(" + I_MARKER + ".MESSAGE, taskItem.getMessage());"); sc.add("new " + markerHelperClassName + "().createMarker(resource, " + I_MARKER + ".TASK, markerAttributes);"); sc.add("}"); sc.add("}"); sc.addLineBreak(); } private void addGetBuilderMarkerIdMethod(JavaComposite sc) { sc.add("public String getBuilderMarkerId() {"); sc.add("return " + I_MARKER + ".TASK;"); sc.add("}"); sc.addLineBreak(); } private void addIsInBinFolderMethod(JavaComposite sc) { sc.add("public boolean isInBinFolder(" + I_FILE + " resource) {"); sc.add(I_CONTAINER + " parent = resource.getParent();"); sc.add("while (parent != null) {"); sc.add("if (\"bin\".equals(parent.getName())) {"); sc.add("return true;"); sc.add("}"); sc.add("parent = parent.getParent();"); sc.add("}"); sc.add("return false;"); sc.add("}"); sc.addLineBreak(); } }
false
true
private void addBuildMethod(JavaComposite sc) { sc.add("@Override").addLineBreak(); sc.add("public void build(" + I_FILE + " resource, " + I_PROGRESS_MONITOR + " monitor) {"); sc.add("monitor.setTaskName(\"Searching for task items\");"); sc.add("new " + markerHelperClassName + "().removeAllMarkers(resource, " + I_MARKER + ".TASK);"); sc.add("if (isInBinFolder(resource)) {"); sc.add("return;"); sc.add("}"); sc.add(sc.declareArrayList("taskItems", taskItemClassName)); sc.add(taskItemDetectorClassName + " taskItemDetector = new " + taskItemDetectorClassName + "();"); sc.add("try {"); sc.add(INPUT_STREAM + " inputStream = resource.getContents();"); sc.add("String content = " + streamUtilClassName + ".getContent(inputStream);"); sc.add(iTextScannerClassName + " lexer = new " + metaInformationClassName + "().createLexer();"); sc.add("lexer.setText(content);"); sc.addLineBreak(); sc.add(iTextTokenClassName + " nextToken = lexer.getNextToken();"); sc.add("while (nextToken != null) {"); sc.add("String text = nextToken.getText();"); sc.add("taskItems.addAll(taskItemDetector.findTaskItems(text, nextToken.getLine(), nextToken.getOffset()));"); sc.add("nextToken = lexer.getNextToken();"); sc.add("}"); sc.add("} catch (" + IO_EXCEPTION + " e) {"); sc.add("HedlPlugin.logError(\"Exception while searching for task items\", e);"); sc.add("} catch (" + CORE_EXCEPTION + " e) {"); sc.add("HedlPlugin.logError(\"Exception while searching for task items\", e);"); sc.add("}"); sc.addLineBreak(); sc.add("for (" + taskItemClassName + " taskItem : taskItems) {"); sc.add(sc.declareLinkedHashMap("markerAttributes", "String", "Object")); sc.add("markerAttributes.put(" + I_MARKER + ".USER_EDITABLE, false);"); sc.add("markerAttributes.put(" + I_MARKER + ".DONE, false);"); sc.add("markerAttributes.put(" + I_MARKER + ".LINE_NUMBER, taskItem.getLine());"); sc.add("markerAttributes.put(" + I_MARKER + ".CHAR_START, taskItem.getCharStart());"); sc.add("markerAttributes.put(" + I_MARKER + ".CHAR_END, taskItem.getCharEnd());"); sc.add("markerAttributes.put(" + I_MARKER + ".MESSAGE, taskItem.getMessage());"); sc.add("new " + markerHelperClassName + "().createMarker(resource, " + I_MARKER + ".TASK, markerAttributes);"); sc.add("}"); sc.add("}"); sc.addLineBreak(); }
private void addBuildMethod(JavaComposite sc) { sc.add("@Override").addLineBreak(); sc.add("public void build(" + I_FILE + " resource, " + I_PROGRESS_MONITOR + " monitor) {"); sc.add("monitor.setTaskName(\"Searching for task items\");"); sc.add("new " + markerHelperClassName + "().removeAllMarkers(resource, " + I_MARKER + ".TASK);"); sc.add("if (isInBinFolder(resource)) {"); sc.add("return;"); sc.add("}"); sc.add(sc.declareArrayList("taskItems", taskItemClassName)); sc.add(taskItemDetectorClassName + " taskItemDetector = new " + taskItemDetectorClassName + "();"); sc.add("try {"); sc.add(INPUT_STREAM + " inputStream = resource.getContents();"); sc.add("String content = " + streamUtilClassName + ".getContent(inputStream);"); sc.add(iTextScannerClassName + " lexer = new " + metaInformationClassName + "().createLexer();"); sc.add("lexer.setText(content);"); sc.addLineBreak(); sc.add(iTextTokenClassName + " nextToken = lexer.getNextToken();"); sc.add("while (nextToken != null) {"); sc.add("String text = nextToken.getText();"); sc.add("taskItems.addAll(taskItemDetector.findTaskItems(text, nextToken.getLine(), nextToken.getOffset()));"); sc.add("nextToken = lexer.getNextToken();"); sc.add("}"); sc.add("} catch (" + IO_EXCEPTION + " e) {"); sc.add(pluginActivatorClassName + ".logError(\"Exception while searching for task items\", e);"); sc.add("} catch (" + CORE_EXCEPTION + " e) {"); sc.add(pluginActivatorClassName + ".logError(\"Exception while searching for task items\", e);"); sc.add("}"); sc.addLineBreak(); sc.add("for (" + taskItemClassName + " taskItem : taskItems) {"); sc.add(sc.declareLinkedHashMap("markerAttributes", "String", "Object")); sc.add("markerAttributes.put(" + I_MARKER + ".USER_EDITABLE, false);"); sc.add("markerAttributes.put(" + I_MARKER + ".DONE, false);"); sc.add("markerAttributes.put(" + I_MARKER + ".LINE_NUMBER, taskItem.getLine());"); sc.add("markerAttributes.put(" + I_MARKER + ".CHAR_START, taskItem.getCharStart());"); sc.add("markerAttributes.put(" + I_MARKER + ".CHAR_END, taskItem.getCharEnd());"); sc.add("markerAttributes.put(" + I_MARKER + ".MESSAGE, taskItem.getMessage());"); sc.add("new " + markerHelperClassName + "().createMarker(resource, " + I_MARKER + ".TASK, markerAttributes);"); sc.add("}"); sc.add("}"); sc.addLineBreak(); }
diff --git a/src/Main.java b/src/Main.java index 96215b4..0ad7eb2 100644 --- a/src/Main.java +++ b/src/Main.java @@ -1,224 +1,225 @@ import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; import java.util.Stack; public class Main { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); BufferedReader br = null; String filepath; int count = 0; //counter int option; //Specifies the option that the user selects from the menu String x; //general purpose variable for user input/loading String classType; Stack<Team> teams = new Stack<Team>(); Stack<Player> players; Stack<Coach> coaches; System.out.println("Welcome to H.P.A. - The Hockey Performance Analyzer."); System.out.println("Press ENTER to continue."); in.nextLine(); boolean menuRunning; menuRunning = true; System.out.println("Stage 1: Input Information"); System.out.println("Note: More than one team may be inputted."); do { //resets players and coaches players = new Stack<Player>(); coaches = new Stack<Coach>(); System.out.println("1 - Manually enter a team's statistics."); System.out.println("2 - Load a team's statistics from a text file."); System.out.println("3 - Continue to Stage 2: Operations"); //continues to next step once more than 1 team is loaded System.out.println("Select an option: "); option = in.nextInt(); if (option == 1) { boolean continuePrompt; int type; //Prompts for team stats System.out.println("Step 1: Team Information"); teams.push(new Team()); //Prompts for player stats System.out.println("Step 2: Player Information"); do { do { System.out.println("1 - Forward"); System.out.println("2 - Defense"); System.out.println("3 - Goalie"); System.out.println("Select player type: "); type = in.nextInt(); } while (type<1||type>3); if (type == 1) players.push(new Forward()); else if (type == 2) players.push(new Defense()); else players.push(new Goalie()); System.out.println("Add another player? (Y/N"); x = in.next(); if (x.equalsIgnoreCase("Y")) continuePrompt = true; else continuePrompt = false; } while (continuePrompt); players.copyInto(teams.get(count).getPlayers()); //copies stack into player array //prompts for coach stats System.out.println("Step 3: Coach Information"); do { do { System.out.println("1 - Head"); System.out.println("2 - Assistant"); System.out.println("3 - Goaltender"); System.out.println("4 - Trainer"); System.out.println("Select player type: "); type = in.nextInt(); } while (type<1||type>4); if (type == 1) coaches.push(new head()); else if (type == 2) coaches.push(new assistant()); else if (type == 3) coaches.push(new goaltender()); else coaches.push(new trainer()); System.out.println("Add another coach? (Y/N"); x = in.next(); if (x.equalsIgnoreCase("Y")) continuePrompt = true; else continuePrompt = false; } while (continuePrompt); coaches.copyInto(teams.get(count).getCoachingstaff()); //copies stack into coach array teams.get(count).updateconf(); teams.get(count).updatediv(); count++; } else if (option == 2) { //loads from team from text file boolean fileFound; in = new Scanner(System.in); //or else catch behaves weirdly do { System.out.println("Enter location of the text file you want to load from: "); filepath = in.nextLine(); try { br = new BufferedReader(new FileReader(filepath)); fileFound = true; } catch (FileNotFoundException e) { fileFound = false; System.out.println("File not found."); } } while (fileFound == false); teams.push(new Team(br)); //loads players from text file br.readLine(); //skips empty line do { x = br.readLine(); classType = x.substring(x.indexOf(": ")+2,x.length()); if (classType.equals("forward")) players.push(new Forward(br)); else if (classType.equals("defense")) { players.push(new Defense(br)); } else players.push(new Goalie(br)); br.readLine();//skips the space between each player br.mark(1000); //stores this location in the memory so program can revisit this part of the stream later x = br.readLine(); //reads next object classType = x.substring(x.indexOf(": ")+2,x.length()); br.reset();//moves cursor back to where stream was marked } while (classType.equals("forward")||classType.equals("defense")||classType.equals("goalie")); teams.get(count).putplayersize(players.size()); players.copyInto(teams.get(count).getPlayers()); //copies stack into player array //loads coaches from text file do { x = br.readLine(); classType = x.substring(x.indexOf(": ")+2,x.length()); if (classType.equals("head")) coaches.push(new head(br)); else if (classType.equals("assistant")) coaches.push(new assistant(br)); else if (classType.equals("goaltender")) coaches.push(new goaltender(br)); else coaches.push(new trainer(br)); x = br.readLine();//skips the space between each coach br.mark(1000); //stores this location in the memory so program can revisit this part of the stream later x = br.readLine(); //checks if next line in the text file is end of file or not br.reset(); } while (x != null && !x.equals("")); teams.get(count).putcoachingstaffsize(coaches.size()); coaches.copyInto(teams.get(count).getCoachingstaff()); //copies stack into coach array count++; } else if (option == 3) { if (count<1) System.out.println("Error - Information is required for at least 1 team."); else menuRunning = false; } else System.out.println("Invalid option."); } while (menuRunning); br.close(); PrintWriter pw = null; //initializes printwriter System.out.println("Stage 2: Operations"); menuRunning = true; do { System.out.println("1 - Save teams onto a text file."); System.out.println("2 - Sort a team."); //by stats that users specify System.out.println("3 - Rank the teams."); System.out.println("4 - Rank the players."); //make gigantic array of players and bubble sort according to rating System.out.println("5 - Terminate the program."); System.out.println("Select an operation: "); option = in.nextInt(); String folder; File someFolder; if (option == 1) { do { in = new Scanner(System.in); System.out.println("Enter location to save text files: "); folder = in.nextLine(); someFolder = new File(folder); if (!someFolder.exists()||!someFolder.isDirectory()||!folder.substring(folder.length()-1).equals("\\")) System.out.println("Location not found."); } while (!someFolder.exists()||!someFolder.isDirectory()||!folder.substring(folder.length()-1).equals("\\")); for (int i = 0; i < teams.size(); i++) { filepath = folder + teams.get(i).getName() + ".txt"; pw = new PrintWriter(new FileWriter(filepath)); pw.println("League: NHL"); pw.println(""); teams.get(i).save(pw); //already skips line in methods + pw.close(); } } else if (option == 5) { System.out.println("Terminating program."); System.out.println("Thank you for using H.P.A."); menuRunning = false; in.close(); pw.close(); } else System.out.println("Invalid option."); } while (menuRunning); } }
true
true
public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); BufferedReader br = null; String filepath; int count = 0; //counter int option; //Specifies the option that the user selects from the menu String x; //general purpose variable for user input/loading String classType; Stack<Team> teams = new Stack<Team>(); Stack<Player> players; Stack<Coach> coaches; System.out.println("Welcome to H.P.A. - The Hockey Performance Analyzer."); System.out.println("Press ENTER to continue."); in.nextLine(); boolean menuRunning; menuRunning = true; System.out.println("Stage 1: Input Information"); System.out.println("Note: More than one team may be inputted."); do { //resets players and coaches players = new Stack<Player>(); coaches = new Stack<Coach>(); System.out.println("1 - Manually enter a team's statistics."); System.out.println("2 - Load a team's statistics from a text file."); System.out.println("3 - Continue to Stage 2: Operations"); //continues to next step once more than 1 team is loaded System.out.println("Select an option: "); option = in.nextInt(); if (option == 1) { boolean continuePrompt; int type; //Prompts for team stats System.out.println("Step 1: Team Information"); teams.push(new Team()); //Prompts for player stats System.out.println("Step 2: Player Information"); do { do { System.out.println("1 - Forward"); System.out.println("2 - Defense"); System.out.println("3 - Goalie"); System.out.println("Select player type: "); type = in.nextInt(); } while (type<1||type>3); if (type == 1) players.push(new Forward()); else if (type == 2) players.push(new Defense()); else players.push(new Goalie()); System.out.println("Add another player? (Y/N"); x = in.next(); if (x.equalsIgnoreCase("Y")) continuePrompt = true; else continuePrompt = false; } while (continuePrompt); players.copyInto(teams.get(count).getPlayers()); //copies stack into player array //prompts for coach stats System.out.println("Step 3: Coach Information"); do { do { System.out.println("1 - Head"); System.out.println("2 - Assistant"); System.out.println("3 - Goaltender"); System.out.println("4 - Trainer"); System.out.println("Select player type: "); type = in.nextInt(); } while (type<1||type>4); if (type == 1) coaches.push(new head()); else if (type == 2) coaches.push(new assistant()); else if (type == 3) coaches.push(new goaltender()); else coaches.push(new trainer()); System.out.println("Add another coach? (Y/N"); x = in.next(); if (x.equalsIgnoreCase("Y")) continuePrompt = true; else continuePrompt = false; } while (continuePrompt); coaches.copyInto(teams.get(count).getCoachingstaff()); //copies stack into coach array teams.get(count).updateconf(); teams.get(count).updatediv(); count++; } else if (option == 2) { //loads from team from text file boolean fileFound; in = new Scanner(System.in); //or else catch behaves weirdly do { System.out.println("Enter location of the text file you want to load from: "); filepath = in.nextLine(); try { br = new BufferedReader(new FileReader(filepath)); fileFound = true; } catch (FileNotFoundException e) { fileFound = false; System.out.println("File not found."); } } while (fileFound == false); teams.push(new Team(br)); //loads players from text file br.readLine(); //skips empty line do { x = br.readLine(); classType = x.substring(x.indexOf(": ")+2,x.length()); if (classType.equals("forward")) players.push(new Forward(br)); else if (classType.equals("defense")) { players.push(new Defense(br)); } else players.push(new Goalie(br)); br.readLine();//skips the space between each player br.mark(1000); //stores this location in the memory so program can revisit this part of the stream later x = br.readLine(); //reads next object classType = x.substring(x.indexOf(": ")+2,x.length()); br.reset();//moves cursor back to where stream was marked } while (classType.equals("forward")||classType.equals("defense")||classType.equals("goalie")); teams.get(count).putplayersize(players.size()); players.copyInto(teams.get(count).getPlayers()); //copies stack into player array //loads coaches from text file do { x = br.readLine(); classType = x.substring(x.indexOf(": ")+2,x.length()); if (classType.equals("head")) coaches.push(new head(br)); else if (classType.equals("assistant")) coaches.push(new assistant(br)); else if (classType.equals("goaltender")) coaches.push(new goaltender(br)); else coaches.push(new trainer(br)); x = br.readLine();//skips the space between each coach br.mark(1000); //stores this location in the memory so program can revisit this part of the stream later x = br.readLine(); //checks if next line in the text file is end of file or not br.reset(); } while (x != null && !x.equals("")); teams.get(count).putcoachingstaffsize(coaches.size()); coaches.copyInto(teams.get(count).getCoachingstaff()); //copies stack into coach array count++; } else if (option == 3) { if (count<1) System.out.println("Error - Information is required for at least 1 team."); else menuRunning = false; } else System.out.println("Invalid option."); } while (menuRunning); br.close(); PrintWriter pw = null; //initializes printwriter System.out.println("Stage 2: Operations"); menuRunning = true; do { System.out.println("1 - Save teams onto a text file."); System.out.println("2 - Sort a team."); //by stats that users specify System.out.println("3 - Rank the teams."); System.out.println("4 - Rank the players."); //make gigantic array of players and bubble sort according to rating System.out.println("5 - Terminate the program."); System.out.println("Select an operation: "); option = in.nextInt(); String folder; File someFolder; if (option == 1) { do { in = new Scanner(System.in); System.out.println("Enter location to save text files: "); folder = in.nextLine(); someFolder = new File(folder); if (!someFolder.exists()||!someFolder.isDirectory()||!folder.substring(folder.length()-1).equals("\\")) System.out.println("Location not found."); } while (!someFolder.exists()||!someFolder.isDirectory()||!folder.substring(folder.length()-1).equals("\\")); for (int i = 0; i < teams.size(); i++) { filepath = folder + teams.get(i).getName() + ".txt"; pw = new PrintWriter(new FileWriter(filepath)); pw.println("League: NHL"); pw.println(""); teams.get(i).save(pw); //already skips line in methods } } else if (option == 5) { System.out.println("Terminating program."); System.out.println("Thank you for using H.P.A."); menuRunning = false; in.close(); pw.close(); } else System.out.println("Invalid option."); } while (menuRunning); }
public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); BufferedReader br = null; String filepath; int count = 0; //counter int option; //Specifies the option that the user selects from the menu String x; //general purpose variable for user input/loading String classType; Stack<Team> teams = new Stack<Team>(); Stack<Player> players; Stack<Coach> coaches; System.out.println("Welcome to H.P.A. - The Hockey Performance Analyzer."); System.out.println("Press ENTER to continue."); in.nextLine(); boolean menuRunning; menuRunning = true; System.out.println("Stage 1: Input Information"); System.out.println("Note: More than one team may be inputted."); do { //resets players and coaches players = new Stack<Player>(); coaches = new Stack<Coach>(); System.out.println("1 - Manually enter a team's statistics."); System.out.println("2 - Load a team's statistics from a text file."); System.out.println("3 - Continue to Stage 2: Operations"); //continues to next step once more than 1 team is loaded System.out.println("Select an option: "); option = in.nextInt(); if (option == 1) { boolean continuePrompt; int type; //Prompts for team stats System.out.println("Step 1: Team Information"); teams.push(new Team()); //Prompts for player stats System.out.println("Step 2: Player Information"); do { do { System.out.println("1 - Forward"); System.out.println("2 - Defense"); System.out.println("3 - Goalie"); System.out.println("Select player type: "); type = in.nextInt(); } while (type<1||type>3); if (type == 1) players.push(new Forward()); else if (type == 2) players.push(new Defense()); else players.push(new Goalie()); System.out.println("Add another player? (Y/N"); x = in.next(); if (x.equalsIgnoreCase("Y")) continuePrompt = true; else continuePrompt = false; } while (continuePrompt); players.copyInto(teams.get(count).getPlayers()); //copies stack into player array //prompts for coach stats System.out.println("Step 3: Coach Information"); do { do { System.out.println("1 - Head"); System.out.println("2 - Assistant"); System.out.println("3 - Goaltender"); System.out.println("4 - Trainer"); System.out.println("Select player type: "); type = in.nextInt(); } while (type<1||type>4); if (type == 1) coaches.push(new head()); else if (type == 2) coaches.push(new assistant()); else if (type == 3) coaches.push(new goaltender()); else coaches.push(new trainer()); System.out.println("Add another coach? (Y/N"); x = in.next(); if (x.equalsIgnoreCase("Y")) continuePrompt = true; else continuePrompt = false; } while (continuePrompt); coaches.copyInto(teams.get(count).getCoachingstaff()); //copies stack into coach array teams.get(count).updateconf(); teams.get(count).updatediv(); count++; } else if (option == 2) { //loads from team from text file boolean fileFound; in = new Scanner(System.in); //or else catch behaves weirdly do { System.out.println("Enter location of the text file you want to load from: "); filepath = in.nextLine(); try { br = new BufferedReader(new FileReader(filepath)); fileFound = true; } catch (FileNotFoundException e) { fileFound = false; System.out.println("File not found."); } } while (fileFound == false); teams.push(new Team(br)); //loads players from text file br.readLine(); //skips empty line do { x = br.readLine(); classType = x.substring(x.indexOf(": ")+2,x.length()); if (classType.equals("forward")) players.push(new Forward(br)); else if (classType.equals("defense")) { players.push(new Defense(br)); } else players.push(new Goalie(br)); br.readLine();//skips the space between each player br.mark(1000); //stores this location in the memory so program can revisit this part of the stream later x = br.readLine(); //reads next object classType = x.substring(x.indexOf(": ")+2,x.length()); br.reset();//moves cursor back to where stream was marked } while (classType.equals("forward")||classType.equals("defense")||classType.equals("goalie")); teams.get(count).putplayersize(players.size()); players.copyInto(teams.get(count).getPlayers()); //copies stack into player array //loads coaches from text file do { x = br.readLine(); classType = x.substring(x.indexOf(": ")+2,x.length()); if (classType.equals("head")) coaches.push(new head(br)); else if (classType.equals("assistant")) coaches.push(new assistant(br)); else if (classType.equals("goaltender")) coaches.push(new goaltender(br)); else coaches.push(new trainer(br)); x = br.readLine();//skips the space between each coach br.mark(1000); //stores this location in the memory so program can revisit this part of the stream later x = br.readLine(); //checks if next line in the text file is end of file or not br.reset(); } while (x != null && !x.equals("")); teams.get(count).putcoachingstaffsize(coaches.size()); coaches.copyInto(teams.get(count).getCoachingstaff()); //copies stack into coach array count++; } else if (option == 3) { if (count<1) System.out.println("Error - Information is required for at least 1 team."); else menuRunning = false; } else System.out.println("Invalid option."); } while (menuRunning); br.close(); PrintWriter pw = null; //initializes printwriter System.out.println("Stage 2: Operations"); menuRunning = true; do { System.out.println("1 - Save teams onto a text file."); System.out.println("2 - Sort a team."); //by stats that users specify System.out.println("3 - Rank the teams."); System.out.println("4 - Rank the players."); //make gigantic array of players and bubble sort according to rating System.out.println("5 - Terminate the program."); System.out.println("Select an operation: "); option = in.nextInt(); String folder; File someFolder; if (option == 1) { do { in = new Scanner(System.in); System.out.println("Enter location to save text files: "); folder = in.nextLine(); someFolder = new File(folder); if (!someFolder.exists()||!someFolder.isDirectory()||!folder.substring(folder.length()-1).equals("\\")) System.out.println("Location not found."); } while (!someFolder.exists()||!someFolder.isDirectory()||!folder.substring(folder.length()-1).equals("\\")); for (int i = 0; i < teams.size(); i++) { filepath = folder + teams.get(i).getName() + ".txt"; pw = new PrintWriter(new FileWriter(filepath)); pw.println("League: NHL"); pw.println(""); teams.get(i).save(pw); //already skips line in methods pw.close(); } } else if (option == 5) { System.out.println("Terminating program."); System.out.println("Thank you for using H.P.A."); menuRunning = false; in.close(); pw.close(); } else System.out.println("Invalid option."); } while (menuRunning); }
diff --git a/src/org/vika/routing/network/jade/AgentsUtil.java b/src/org/vika/routing/network/jade/AgentsUtil.java index aeceece..477e3d3 100644 --- a/src/org/vika/routing/network/jade/AgentsUtil.java +++ b/src/org/vika/routing/network/jade/AgentsUtil.java @@ -1,37 +1,37 @@ package org.vika.routing.network.jade; import jade.core.AID; import jade.core.Agent; import jade.domain.FIPAAgentManagement.AMSAgentDescription; import jade.lang.acl.ACLMessage; import org.vika.routing.Message; import java.io.IOException; /** * @author oleg * @date 21.04.11 */ public class AgentsUtil { /** * Send message to the agent with given id */ public static void sendMessage(final Agent[] agents, final int receiver, final Message message){ final AMSAgentDescription agent = findAMSAgentDescription(agents, receiver); ACLMessage msg = new ACLMessage(ACLMessage.INFORM); msg.addReceiver(agent.getName()); try { msg.setContentObject(message); } catch (IOException e) { // Ignore this } - send(msg); + agents[receiver].send(msg); } static AMSAgentDescription findAMSAgentDescription(final Agent[] agents, final int id) { final AMSAgentDescription description = new AMSAgentDescription(); final AID aid = agents[id].getAID(); description.setName(aid); return description; } }
true
true
public static void sendMessage(final Agent[] agents, final int receiver, final Message message){ final AMSAgentDescription agent = findAMSAgentDescription(agents, receiver); ACLMessage msg = new ACLMessage(ACLMessage.INFORM); msg.addReceiver(agent.getName()); try { msg.setContentObject(message); } catch (IOException e) { // Ignore this } send(msg); }
public static void sendMessage(final Agent[] agents, final int receiver, final Message message){ final AMSAgentDescription agent = findAMSAgentDescription(agents, receiver); ACLMessage msg = new ACLMessage(ACLMessage.INFORM); msg.addReceiver(agent.getName()); try { msg.setContentObject(message); } catch (IOException e) { // Ignore this } agents[receiver].send(msg); }
diff --git a/bundles/org.eclipse.equinox.ds/src/org/eclipse/equinox/internal/ds/model/DeclarationParser.java b/bundles/org.eclipse.equinox.ds/src/org/eclipse/equinox/internal/ds/model/DeclarationParser.java index c67fbc5a..8f9d8960 100644 --- a/bundles/org.eclipse.equinox.ds/src/org/eclipse/equinox/internal/ds/model/DeclarationParser.java +++ b/bundles/org.eclipse.equinox.ds/src/org/eclipse/equinox/internal/ds/model/DeclarationParser.java @@ -1,698 +1,698 @@ /******************************************************************************* * Copyright (c) 1997-2007 by ProSyst Software GmbH * http://www.prosyst.com * 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: * ProSyst Software GmbH - initial API and implementation *******************************************************************************/ package org.eclipse.equinox.internal.ds.model; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.*; import org.eclipse.equinox.internal.ds.Activator; import org.eclipse.equinox.internal.util.xml.*; import org.osgi.framework.*; import org.osgi.service.metatype.AttributeDefinition; /** * ComponentParser.java * * @author Valentin Valchev * @author Stoyan Boshev * @author Pavlin Dobrev * @author Teodor Bakardzhiev * @version 1.0 */ public class DeclarationParser implements ExTagListener { private static final String XMLNS = "http://www.osgi.org/xmlns/scr/v1.0.0"; private static final String ATTR_XMLNS = "xmlns"; private static final String ATTR_AUTOENABLE = "enabled"; private static final String ATTR_NAME = "name"; private static final String ATTR_FACTORY = "factory"; private static final String ATTR_IMMEDIATE = "immediate"; private static final String TAG_IMPLEMENTATION = "implementation"; private static final String ATTR_CLASS = "class"; private static final String TAG_PROPERTY = "property"; private static final String ATTR_VALUE = "value"; private static final String ATTR_TYPE = "type"; private static final String TAG_PROPERTIES = "properties"; private static final String ATTR_ENTRY = "entry"; private static final String TAG_SERVICE = "service"; private static final String ATTR_SERVICEFACTORY = "servicefactory"; private static final String TAG_PROVIDE = "provide"; private static final String ATTR_INTERFACE = "interface"; private static final String TAG_REFERENCE = "reference"; private static final String ATTR_CARDINALITY = "cardinality"; private static final String ATTR_POLICY = "policy"; private static final String ATTR_TARGET = "target"; private static final String ATTR_BIND = "bind"; private static final String ATTR_UNBIND = "unbind"; public Vector components; private Bundle bundle; private BundleContext bc; private ServiceComponent currentComponent; private String closeTag; boolean immediateSet = false; private Hashtable namespaces = null; private boolean rootPassed = false; /** * This method parses an XML file read from the given stream and converts * the components definitions into a java object. * <p> * * It also performs a full XML verification of the definition.� * * @param in * the input stream to the XML declaration file * @param bundle * this is used to load the 'properties' tag */ public void parse(InputStream in, Bundle bundle, Vector components) throws Exception { this.components = components; this.bundle = bundle; this.bc = bundle.getBundleContext(); rootPassed = false; XMLParser.parseXML(in, this, -1); // release temporary objects this.bundle = null; this.bc = null; this.currentComponent = null; this.closeTag = null; this.namespaces = null; } /* * (non-Javadoc) * * @see org.eclipse.equinox.internal.util.xml.ExTagListener#startTag(org.eclipse.equinox.internal.util.xml.Tag) */ public final void startTag(Tag tag) { try { processNamespacesEnter(tag); String tagName = tag.getName(); if (isCorrectComponentTag(tagName)) { doCorrectComponentTag(tag, tagName); } } catch (Throwable e) { Activator.log.error("[SCR - DeclarationParser.startTag()] Error occured while processing start tag in bundle " + bundle, e); } finally { if (!rootPassed) { rootPassed = true; } } } private void doEndTag(Tag tag) throws InvalidSyntaxException { String tagName = tag.getName().intern(); if (currentComponent != null) { if (tagName == TAG_IMPLEMENTATION) { doImplementation(tag); } else if (tagName == TAG_PROPERTY) { doProperty(tag); } else if (tagName == TAG_PROPERTIES) { doProperties(tag); } else if (tagName == TAG_SERVICE) { doService(tag); } else if (tagName == TAG_REFERENCE) { doReference(tag); } else if (tagName == TAG_PROVIDE) { // empty - this tag is processed within the service tag } else if (tagName == closeTag) { // the component is completed - we can now fully validate it! if (!immediateSet && (currentComponent.factory == null)) { // if unset, immediate attribute is false if service element // is // specified or true otherwise // if component factory then immediate by default is false currentComponent.setImmediate(currentComponent.serviceInterfaces == null); } currentComponent.validate(tag.getLine()); if (components == null) { components = new Vector(1, 1); } components.addElement(currentComponent); currentComponent = null; closeTag = null; } else { IllegalArgumentException e = new IllegalArgumentException("Found illegal tag named '" + tagName + "' in component XML, at line " + tag.getLine()); Activator.log.error("[SCR] " + e.toString(), e); throw e; } } } /* * (non-Javadoc) * * @see org.eclipse.equinox.internal.util.xml.ExTagListener#endTag(org.eclipse.equinox.internal.util.xml.Tag) */ public final void endTag(Tag tag) { try { doEndTag(tag); processNamespacesLeave(tag); } catch (Throwable e) { currentComponent = null; closeTag = null; Activator.log.error("[SCR - DeclarationParser.endTag()] Error occured while processing end tag in bundle " + bundle, e); } } /** * This method will return convert a string to a cardinality constant * * @param value * the input string * @return the cardinality or -1 to indicate error */ private int getCardinality(String value) { if ("0..1".equals(value)) { return ComponentReference.CARDINALITY_0_1; } else if ("0..n".equals(value)) { return ComponentReference.CARDINALITY_0_N; } else if ("1..1".equals(value)) { return ComponentReference.CARDINALITY_1_1; } else if ("1..n".equals(value)) { return ComponentReference.CARDINALITY_1_N; } else { return -1; } } private void doReference(Tag tag) throws InvalidSyntaxException { String name = tag.getAttribute(ATTR_NAME); if (name == null) { IllegalArgumentException e = new IllegalArgumentException("The 'reference' tag must have 'name' attribute, at line " + tag.getLine()); Activator.log.error("[SCR] " + e.getMessage(), e); throw e; } String iface = tag.getAttribute(ATTR_INTERFACE); if (iface == null) { IllegalArgumentException e = new IllegalArgumentException("The 'reference' tag must have 'interface' attribute, at line " + tag.getLine()); Activator.log.error("[SCR] " + e.getMessage(), e); throw e; } String cardinalityS = tag.getAttribute(ATTR_CARDINALITY); int cardinality = ComponentReference.CARDINALITY_1_1; // default if (cardinalityS != null) { cardinality = getCardinality(cardinalityS); if (cardinality < 0) { IllegalArgumentException e = new IllegalArgumentException("The 'cardinality' attribute has invalid value '" + name + "' at line " + tag.getLine()); Activator.log.error("[SCR] " + e.getMessage(), e); throw e; } } // if null - default cardinality is already initialized in // constructor String policyS = tag.getAttribute(ATTR_POLICY); int policy = ComponentReference.POLICY_STATIC; // default if (policyS != null) { // verify the policy attribute values if (policyS.equals("static")) { policy = ComponentReference.POLICY_STATIC; } else if (policyS.equals("dynamic")) { policy = ComponentReference.POLICY_DYNAMIC; } else { IllegalArgumentException e = new IllegalArgumentException("The 'policy' attribute has invalid value '" + name + "' at line" + tag.getLine()); Activator.log.error("[SCR] " + e.getMessage(), e); throw e; } } // if null - default policy is already initialized in constructor String bind = tag.getAttribute(ATTR_BIND); String unbind = tag.getAttribute(ATTR_UNBIND); if ((bind != null && ((unbind == null) || bind.equals(unbind))) || (unbind != null && ((bind == null) || unbind.equals(bind)))) { IllegalArgumentException e = new IllegalArgumentException("The 'reference' tag at line " + tag.getLine() + " is invalid: you must specify both but different 'bind' and 'unbind' attributes!"); Activator.log.error("[SCR] " + e.getMessage(), e); throw e; } // the reference is autoadded in the ServiceComponent's list of // references // in its constructor ComponentReference ref = new ComponentReference(currentComponent); ref.name = name; ref.interfaceName = iface; ref.cardinality = cardinality; ref.policy = policy; ref.bind = bind; ref.unbind = unbind; ref.target = tag.getAttribute(ATTR_TARGET); // validate the target filter if (ref.target != null) { Activator.createFilter(ref.target); } } private void doImplementation(Tag tag) { if (currentComponent.implementation != null) { IllegalArgumentException e = new IllegalArgumentException("The 'component' tag must have exactly one 'implementation' attribute at line " + tag.getLine()); Activator.log.error("[SCR] " + e.getMessage(), e); throw e; } String tmp = tag.getAttribute(ATTR_CLASS); if (tmp == null) { IllegalArgumentException e = new IllegalArgumentException("The 'implementation' element must have 'class' attribute set at line " + tag.getLine()); Activator.log.error("[SCR] " + e.getMessage(), e); throw e; } currentComponent.implementation = tmp; } private void doService(Tag tag) { String tmp = tag.getAttribute(ATTR_SERVICEFACTORY); if (tmp != null) { currentComponent.serviceFactory = Boolean.valueOf(tmp).booleanValue(); } int size = tag.size(); if (size == 0) { IllegalArgumentException e = new IllegalArgumentException("The 'service' tag must have one 'provide' tag set at line " + tag.getLine()); Activator.log.error("[SCR] " + e.getMessage(), e); throw e; } for (int i = 0; i < size; i++) { Tag p = tag.getTagAt(i); String pName = p.getName().intern(); if (pName == TAG_PROVIDE) { String iFace = p.getAttribute(ATTR_INTERFACE); if (iFace == null) { IllegalArgumentException e = new IllegalArgumentException("The 'provide' tag must have 'interface' attribute set at line " + tag.getLine()); Activator.log.error("[SCR] " + e.getMessage(), e); throw e; } if (currentComponent.serviceInterfaces == null) { currentComponent.serviceInterfaces = new Vector(size); } currentComponent.serviceInterfaces.addElement(iFace); } else { IllegalArgumentException e = new IllegalArgumentException("Found illegal element '" + pName + "' for tag 'service' at line " + tag.getLine()); Activator.log.error("[SCR] " + e.getMessage(), e); throw e; } } } private void doProperty(Tag tag) { String name = null; try { name = tag.getAttribute(ATTR_NAME); if (name == null) { IllegalArgumentException e = new IllegalArgumentException("The 'property' tag must have 'name' attribute set at line " + tag.getLine()); Activator.log.error("[SCR] " + e.getMessage(), e); throw e; } String type = tag.getAttribute(ATTR_TYPE); int mtType; if (type == null || "String".equals(type)) { mtType = AttributeDefinition.STRING; } else if ("Boolean".equals(type)) { mtType = AttributeDefinition.BOOLEAN; } else if ("Integer".equals(type)) { mtType = AttributeDefinition.INTEGER; } else if ("Long".equals(type)) { mtType = AttributeDefinition.LONG; - } else if ("Char".equals(type)) { + } else if ("Char".equals(type) || "Character".equals(type)) { mtType = AttributeDefinition.CHARACTER; } else if ("Double".equals(type)) { mtType = AttributeDefinition.DOUBLE; } else if ("Float".equals(type)) { mtType = AttributeDefinition.FLOAT; } else if ("Byte".equals(type)) { mtType = AttributeDefinition.BYTE; } else if ("Short".equals(type)) { mtType = AttributeDefinition.SHORT; } else { IllegalArgumentException e = new IllegalArgumentException("Illegal property type '" + type + "' on line " + tag.getLine()); Activator.log.error("[SCR] " + e.getMessage(), e); throw e; } String value = tag.getAttribute(ATTR_VALUE); Object _value; if (value != null) { _value = makeObject(value, mtType); } else { // body must be specified value = tag.getContent(); if (value == null) { IllegalArgumentException e = new IllegalArgumentException("The 'property' tag must have body content if 'value' attribute is not specified!"); Activator.log.error("[SCR] " + e.getMessage(), e); throw e; } StringTokenizer tok = new StringTokenizer(value, "\n\r"); Vector el = new Vector(10); while (tok.hasMoreTokens()) { String next = tok.nextToken().trim(); if (next.length() > 0) { el.addElement(next); } } if (el.size() == 0) { IllegalArgumentException e = new IllegalArgumentException("The 'property' tag must have body content if 'value' attribute is not specified!"); Activator.log.error("[SCR] " + e.getMessage(), e); throw e; } String[] values = new String[el.size()]; el.copyInto(values); _value = makeArr(values, mtType); } if (currentComponent.properties == null) { currentComponent.properties = new Properties(); } currentComponent.properties.put(name, _value); } catch (Throwable e) { Activator.log.error("[SCR - DeclarationParser.doProperty()] Error while processing property " + name, e); } } private void doProperties(Tag tag) { String fileEntry = tag.getAttribute(ATTR_ENTRY); if (fileEntry == null) { IllegalArgumentException e = new IllegalArgumentException("The 'properties' tag must include 'entry' attribute, at line " + tag.getLine()); Activator.log.error("[SCR] " + e.getMessage(), e); throw e; } InputStream is = null; try { URL resource = bundle.getResource(fileEntry); is = resource != null ? resource.openStream() : null; } catch (IOException ignore) { } boolean invalid = true; // FIXME: this will not work on properties defined like // com.prosyst.bla.component.properties // in this case the path should be converted as // com/prosyst/bla/component.properties if (is != null) { if (currentComponent.properties == null) { currentComponent.properties = new Properties(); } try { currentComponent.properties.load(is); invalid = false; } catch (IOException e) { Activator.log.error("[SCR - DeclarationParser.doProperties()] Error while loading properties file", e); } } if (invalid) { IllegalArgumentException e = new IllegalArgumentException("The specified 'entry' for the 'properties' tag at line " + tag.getLine() + " doesn't contain valid reference to a property file: " + fileEntry); Activator.log.error("[SCR] " + e.getMessage(), e); throw e; } } private static String COMPONENT_TAG_NAME = "component"; private void doCorrectComponentTag(Tag tag, String tagName) { closeTag = tagName.intern(); String tmp = tag.getAttribute(ATTR_NAME); if (tmp == null) { IllegalArgumentException e = new IllegalArgumentException("The 'component' tag MUST have 'name' tag set, at line " + tag.getLine()); Activator.log.error("[SCR] " + e.getMessage(), e); return; } immediateSet = false; currentComponent = new ServiceComponent(); // make sure that the bundle attribute is set - it is required further currentComponent.bundle = bundle; currentComponent.bc = bc; currentComponent.name = tmp; tmp = tag.getAttribute(ATTR_AUTOENABLE); if (tmp != null) { currentComponent.autoenable = Boolean.valueOf(tmp).booleanValue(); } tmp = tag.getAttribute(ATTR_FACTORY); if (tmp != null && tmp.length() == 0) { tmp = null; } currentComponent.factory = tmp; tmp = tag.getAttribute(ATTR_IMMEDIATE); if (tmp != null && tmp.length() == 0) { tmp = null; } if (tmp != null) { currentComponent.immediate = Boolean.valueOf(tmp).booleanValue(); immediateSet = true; } } private boolean isCorrectComponentTag(String tagName) { String qualifier = getNamespaceQualifier(tagName); String localTagName = (qualifier.length() == 0) ? tagName : tagName.substring(qualifier.length() + 1); // + one char for ':' if (!localTagName.equals(COMPONENT_TAG_NAME)) { return false; } String namespace = getCurrentNamespace(qualifier); if (!rootPassed) { // this is the root element return namespace.length() == 0 || namespace.equals(XMLNS); } else { // not a root element return namespace.equals(XMLNS); } } /** * Creates an object from a <code>String</code> value and a type, as * returned by the corresponding {@link AttributeDefinition#getType()} * method. * * @param string * The <code>String</code> value representation of the object. * @param syntax * The object's type as defined by * <code>AttributeDefinition</code>. * * @return an Object, which is of a type, corresponding to the given, and * value - got from the string parameter. E.g. if syntax is equal to * <code>AttributeDefinition.INTEGER</code> and string is "1", * then the value returned should be Integer("1"). * * @exception IllegalArgumentException * if a proper object can not be created due to * incompatibility of syntax and value or if the parameters * are not correct (e.g. syntax is not a valid * <code>AttributeDefinition</code> constant). */ public static Object makeObject(String string, int syntax) throws IllegalArgumentException { try { switch (syntax) { case AttributeDefinition.STRING : { return string; } case AttributeDefinition.INTEGER : { return new Integer(string); } case AttributeDefinition.LONG : { return new Long(string); } case AttributeDefinition.FLOAT : { return new Float(string); } case AttributeDefinition.DOUBLE : { return new Double(string); } case AttributeDefinition.BYTE : { return new Byte(string); } case AttributeDefinition.SHORT : { return new Short(string); } case AttributeDefinition.CHARACTER : { if (string.length() == 0) { throw new IllegalArgumentException("Missing character "); } return new Character(string.charAt(0)); } case AttributeDefinition.BOOLEAN : { return Boolean.valueOf(string); } default : { throw new IllegalArgumentException("Unsupported type: ".concat(String.valueOf(syntax))); } } } catch (NumberFormatException ex) { throw new IllegalArgumentException("Value: " + string + " does not fit its type!"); } } /** * Makes an array from the string array value and the syntax. * * @param array * <code>String</code> array representation of an array, which * follows the rules defined by <code>AttributeDefinition</code>. * @param syntax * The array's type as defined by * <code>AttributeDefinition</code>. * * @return an arary of primitives or objects, whose component type * corresponds to <code>syntax</code>, and value build from the * string array passed. * * @exception IllegalArgumentException * if any of the elements in the string array can not be * converted to a proper object or primitive, or if the * <code>syntax</code> is not a valid * <code>AttributeDefinition</code> type constant. */ public static Object makeArr(String[] array, int syntax) throws IllegalArgumentException { switch (syntax) { case AttributeDefinition.STRING : { return array; } case AttributeDefinition.INTEGER : { int[] ints = new int[array.length]; for (int i = 0; i < array.length; i++) { ints[i] = Integer.parseInt(array[i]); } return ints; } case AttributeDefinition.LONG : { long[] longs = new long[array.length]; for (int i = 0; i < array.length; i++) { longs[i] = Long.parseLong(array[i]); } return longs; } case AttributeDefinition.FLOAT : { float[] floats = new float[array.length]; for (int i = 0; i < array.length; i++) { floats[i] = Float.valueOf(array[i]).floatValue(); } return floats; } case AttributeDefinition.DOUBLE : { double[] doubles = new double[array.length]; for (int i = 0; i < array.length; i++) { doubles[i] = Double.valueOf(array[i]).doubleValue(); } return doubles; } case AttributeDefinition.BYTE : { byte[] bytes = new byte[array.length]; for (int i = 0; i < array.length; i++) { bytes[i] = Byte.parseByte(array[i]); } return bytes; } case AttributeDefinition.SHORT : { short[] shorts = new short[array.length]; for (int i = 0; i < array.length; i++) { shorts[i] = Short.parseShort(array[i]); } return shorts; } case AttributeDefinition.CHARACTER : { char[] chars = new char[array.length]; for (int i = 0; i < array.length; i++) { chars[i] = array[i].charAt(0); } return chars; } case AttributeDefinition.BOOLEAN : { boolean[] booleans = new boolean[array.length]; for (int i = 0; i < array.length; i++) { booleans[i] = Boolean.valueOf(array[i]).booleanValue(); } return booleans; } default : { throw new IllegalArgumentException("Unsupported type: ".concat(String.valueOf(syntax))); } } } private void processNamespacesEnter(Tag tag) { Enumeration en = tag.getAttributeNames(); while (en.hasMoreElements()) { String attrName = (String) en.nextElement(); if (attrName.startsWith(ATTR_XMLNS)) { String qualifier = attrName.substring(ATTR_XMLNS.length()); if ((qualifier.length() == 0) || // <- default namespace ((qualifier.charAt(0) == ':') ? (qualifier = qualifier.substring(1)).length() > 0 : false)) { if (namespaces == null) { namespaces = new Hashtable(); } Stack stack = null; if ((stack = (Stack) namespaces.get(qualifier)) == null) { stack = new Stack(); namespaces.put(qualifier, stack); } stack.push(tag.getAttribute(attrName)); } } } } private String getCurrentNamespace(String qualifier) { if (namespaces == null || qualifier == null) { return ""; } Stack stack = (Stack) namespaces.get(qualifier); if (stack == null || stack.empty()) { return ""; } return (String) stack.peek(); } private void processNamespacesLeave(Tag tag) { if (namespaces == null) { return; } Enumeration en = tag.getAttributeNames(); while (en.hasMoreElements()) { String attrName = (String) en.nextElement(); if (attrName.startsWith(ATTR_XMLNS)) { String qualifier = attrName.substring(ATTR_XMLNS.length()); if ((qualifier.length() == 0) || // <- default namespace ((qualifier.charAt(0) == ':') ? (qualifier = qualifier.substring(1)).length() > 0 : false)) { Stack stack = (Stack) namespaces.get(qualifier); if (stack != null) { if (!stack.empty()) { stack.pop(); } if (stack.empty()) { namespaces.remove(qualifier); } } } } } } private String getNamespaceQualifier(String name) { int index = name.indexOf(':'); if (index < 0) { return ""; } return name.substring(0, index); } }
true
true
private void doProperty(Tag tag) { String name = null; try { name = tag.getAttribute(ATTR_NAME); if (name == null) { IllegalArgumentException e = new IllegalArgumentException("The 'property' tag must have 'name' attribute set at line " + tag.getLine()); Activator.log.error("[SCR] " + e.getMessage(), e); throw e; } String type = tag.getAttribute(ATTR_TYPE); int mtType; if (type == null || "String".equals(type)) { mtType = AttributeDefinition.STRING; } else if ("Boolean".equals(type)) { mtType = AttributeDefinition.BOOLEAN; } else if ("Integer".equals(type)) { mtType = AttributeDefinition.INTEGER; } else if ("Long".equals(type)) { mtType = AttributeDefinition.LONG; } else if ("Char".equals(type)) { mtType = AttributeDefinition.CHARACTER; } else if ("Double".equals(type)) { mtType = AttributeDefinition.DOUBLE; } else if ("Float".equals(type)) { mtType = AttributeDefinition.FLOAT; } else if ("Byte".equals(type)) { mtType = AttributeDefinition.BYTE; } else if ("Short".equals(type)) { mtType = AttributeDefinition.SHORT; } else { IllegalArgumentException e = new IllegalArgumentException("Illegal property type '" + type + "' on line " + tag.getLine()); Activator.log.error("[SCR] " + e.getMessage(), e); throw e; } String value = tag.getAttribute(ATTR_VALUE); Object _value; if (value != null) { _value = makeObject(value, mtType); } else { // body must be specified value = tag.getContent(); if (value == null) { IllegalArgumentException e = new IllegalArgumentException("The 'property' tag must have body content if 'value' attribute is not specified!"); Activator.log.error("[SCR] " + e.getMessage(), e); throw e; } StringTokenizer tok = new StringTokenizer(value, "\n\r"); Vector el = new Vector(10); while (tok.hasMoreTokens()) { String next = tok.nextToken().trim(); if (next.length() > 0) { el.addElement(next); } } if (el.size() == 0) { IllegalArgumentException e = new IllegalArgumentException("The 'property' tag must have body content if 'value' attribute is not specified!"); Activator.log.error("[SCR] " + e.getMessage(), e); throw e; } String[] values = new String[el.size()]; el.copyInto(values); _value = makeArr(values, mtType); } if (currentComponent.properties == null) { currentComponent.properties = new Properties(); } currentComponent.properties.put(name, _value); } catch (Throwable e) { Activator.log.error("[SCR - DeclarationParser.doProperty()] Error while processing property " + name, e); } }
private void doProperty(Tag tag) { String name = null; try { name = tag.getAttribute(ATTR_NAME); if (name == null) { IllegalArgumentException e = new IllegalArgumentException("The 'property' tag must have 'name' attribute set at line " + tag.getLine()); Activator.log.error("[SCR] " + e.getMessage(), e); throw e; } String type = tag.getAttribute(ATTR_TYPE); int mtType; if (type == null || "String".equals(type)) { mtType = AttributeDefinition.STRING; } else if ("Boolean".equals(type)) { mtType = AttributeDefinition.BOOLEAN; } else if ("Integer".equals(type)) { mtType = AttributeDefinition.INTEGER; } else if ("Long".equals(type)) { mtType = AttributeDefinition.LONG; } else if ("Char".equals(type) || "Character".equals(type)) { mtType = AttributeDefinition.CHARACTER; } else if ("Double".equals(type)) { mtType = AttributeDefinition.DOUBLE; } else if ("Float".equals(type)) { mtType = AttributeDefinition.FLOAT; } else if ("Byte".equals(type)) { mtType = AttributeDefinition.BYTE; } else if ("Short".equals(type)) { mtType = AttributeDefinition.SHORT; } else { IllegalArgumentException e = new IllegalArgumentException("Illegal property type '" + type + "' on line " + tag.getLine()); Activator.log.error("[SCR] " + e.getMessage(), e); throw e; } String value = tag.getAttribute(ATTR_VALUE); Object _value; if (value != null) { _value = makeObject(value, mtType); } else { // body must be specified value = tag.getContent(); if (value == null) { IllegalArgumentException e = new IllegalArgumentException("The 'property' tag must have body content if 'value' attribute is not specified!"); Activator.log.error("[SCR] " + e.getMessage(), e); throw e; } StringTokenizer tok = new StringTokenizer(value, "\n\r"); Vector el = new Vector(10); while (tok.hasMoreTokens()) { String next = tok.nextToken().trim(); if (next.length() > 0) { el.addElement(next); } } if (el.size() == 0) { IllegalArgumentException e = new IllegalArgumentException("The 'property' tag must have body content if 'value' attribute is not specified!"); Activator.log.error("[SCR] " + e.getMessage(), e); throw e; } String[] values = new String[el.size()]; el.copyInto(values); _value = makeArr(values, mtType); } if (currentComponent.properties == null) { currentComponent.properties = new Properties(); } currentComponent.properties.put(name, _value); } catch (Throwable e) { Activator.log.error("[SCR - DeclarationParser.doProperty()] Error while processing property " + name, e); } }
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/ui/IScrollTable.java b/src/com/itmill/toolkit/terminal/gwt/client/ui/IScrollTable.java index 5abbe6c09..fefec11b9 100644 --- a/src/com/itmill/toolkit/terminal/gwt/client/ui/IScrollTable.java +++ b/src/com/itmill/toolkit/terminal/gwt/client/ui/IScrollTable.java @@ -1,1922 +1,1922 @@ package com.itmill.toolkit.terminal.gwt.client.ui; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Vector; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.DeferredCommand; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.ScrollListener; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.Widget; import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection; import com.itmill.toolkit.terminal.gwt.client.ContainerResizedListener; import com.itmill.toolkit.terminal.gwt.client.Paintable; import com.itmill.toolkit.terminal.gwt.client.UIDL; import com.itmill.toolkit.terminal.gwt.client.Util; import com.itmill.toolkit.terminal.gwt.client.ui.IScrollTable.IScrollTableBody.IScrollTableRow; /** * Constructor for IScrollTable * * IScrollTable is a FlowPanel having two widgets in it: * TableHead component * * ScrollPanel * * TableHead contains table's header and widgets + logic for resizing, * reordering and hiding columns. * * ScrollPanel contains IScrollTableBody object which handles content. To save * some bandwidth and to improve clients responsiveness with loads of data, in * IScrollTableBody all rows are not necessary rendered. There are "spacer" in * IScrollTableBody to use the exact same space as non-rendered rows would use. * This way we can use seamlessly traditional scrollbars and scrolling to fetch * more rows instead of "paging". * * In IScrollTable we listen to scroll events. On horizontal scrolling we also * update TableHeads scroll position which has its scrollbars hidden. On * vertical scroll events we will check if we are reaching the end of area where * we have rows rendered and * * TODO implement unregistering for child componts in Cells */ public class IScrollTable extends Composite implements Table, ScrollListener, ContainerResizedListener { public static final String CLASSNAME = "i-table"; /** * multiple of pagelenght which component will cache when requesting more * rows */ private static final double CACHE_RATE = 2; /** * fraction of pageLenght which can be scrolled without making new request */ private static final double CACHE_REACT_RATE = 1.5; public static final char ALIGN_CENTER = 'c'; public static final char ALIGN_LEFT = 'b'; public static final char ALIGN_RIGHT = 'e'; private int firstRowInViewPort = 0; private int pageLength = 15; private boolean rowHeaders = false; private String[] columnOrder; private ApplicationConnection client; private String paintableId; private boolean immediate; private int selectMode = Table.SELECT_MODE_NONE; private Vector selectedRowKeys = new Vector(); private boolean initializedAndAttached = false; private TableHead tHead = new TableHead(); private ScrollPanel bodyContainer = new ScrollPanel(); private int totalRows; private Set collapsedColumns; private RowRequestHandler rowRequestHandler; private IScrollTableBody tBody; private String width; private String height; private int firstvisible = 0; private boolean sortAscending; private String sortColumn; private boolean columnReordering; /** * This map contains captions and icon urls for actions like: * "33_c" -> * "Edit" * "33_i" -> "http://dom.com/edit.png" */ private HashMap actionMap = new HashMap(); private String[] visibleColOrder; private boolean initialContentReceived = false; private Element scrollPositionElement; private FlowPanel panel; public IScrollTable() { bodyContainer.addScrollListener(this); bodyContainer.setStyleName(CLASSNAME + "-body"); panel = new FlowPanel(); panel.setStyleName(CLASSNAME); panel.add(tHead); panel.add(bodyContainer); rowRequestHandler = new RowRequestHandler(); initWidget(panel); } public void updateFromUIDL(UIDL uidl, ApplicationConnection client) { if (client.updateComponent(this, uidl, true)) return; this.client = client; this.paintableId = uidl.getStringAttribute("id"); this.immediate = uidl.getBooleanAttribute("immediate"); this.totalRows = uidl.getIntAttribute("totalrows"); this.pageLength = uidl.getIntAttribute("pagelength"); if (pageLength == 0) pageLength = totalRows; this.firstvisible = uidl.hasVariable("firstvisible") ? uidl .getIntVariable("firstvisible") : 0; if (uidl.hasAttribute("rowheaders")) rowHeaders = true; if (uidl.hasAttribute("width")) { width = uidl.getStringAttribute("width"); } if (uidl.hasAttribute("height")) height = uidl.getStringAttribute("height"); if (uidl.hasVariable("sortascending")) { this.sortAscending = uidl.getBooleanVariable("sortascending"); this.sortColumn = uidl.getStringVariable("sortcolumn"); } if (uidl.hasVariable("selected")) { Set selectedKeys = uidl.getStringArrayVariableAsSet("selected"); selectedRowKeys.clear(); for (Iterator it = selectedKeys.iterator(); it.hasNext();) selectedRowKeys.add((String) it.next()); } if (uidl.hasAttribute("selectmode")) { if (uidl.getStringAttribute("selectmode").equals("multi")) selectMode = Table.SELECT_MODE_MULTI; else selectMode = Table.SELECT_MODE_SINGLE; } if (uidl.hasVariable("columnorder")) { this.columnReordering = true; this.columnOrder = uidl.getStringArrayVariable("columnorder"); } if (uidl.hasVariable("collapsedcolumns")) { tHead.setColumnCollapsingAllowed(true); this.collapsedColumns = uidl .getStringArrayVariableAsSet("collapsedcolumns"); } else { tHead.setColumnCollapsingAllowed(false); } UIDL rowData = null; for (Iterator it = uidl.getChildIterator(); it.hasNext();) { UIDL c = (UIDL) it.next(); if (c.getTag().equals("rows")) rowData = c; else if (c.getTag().equals("actions")) updateActionMap(c); else if (c.getTag().equals("visiblecolumns")) updateVisibleColumns(c); } updateHeader(uidl.getStringArrayAttribute("vcolorder")); if (initializedAndAttached) { updateBody(rowData, uidl.getIntAttribute("firstrow"), uidl .getIntAttribute("rows")); } else { getTBody().renderInitialRows(rowData, uidl.getIntAttribute("firstrow"), uidl.getIntAttribute("rows"), totalRows); bodyContainer.add(tBody); initialContentReceived = true; if (isAttached()) { sizeInit(); } } hideScrollPositionAnnotation(); } private void updateVisibleColumns(UIDL uidl) { Iterator it = uidl.getChildIterator(); while (it.hasNext()) { UIDL col = (UIDL) it.next(); tHead.updateCellFromUIDL(col); } } private IScrollTableBody getTBody() { if (tBody == null || totalRows != tBody.getTotalRows()) { if (tBody != null) tBody.removeFromParent(); tBody = new IScrollTableBody(); } return tBody; } private void updateActionMap(UIDL c) { Iterator it = c.getChildIterator(); while (it.hasNext()) { UIDL action = (UIDL) it.next(); String key = action.getStringAttribute("key"); String caption = action.getStringAttribute("caption"); actionMap.put(key + "_c", caption); if (action.hasAttribute("icon")) { // TODO need some uri handling ?? actionMap.put(key + "_i", action.getStringAttribute("icon")); } } } public String getActionCaption(String actionKey) { return (String) actionMap.get(actionKey + "_c"); } public String getActionIcon(String actionKey) { return (String) actionMap.get(actionKey + "_i"); } private void updateHeader(String[] strings) { if (strings == null) return; int visibleCols = strings.length; int colIndex = 0; if (rowHeaders) { tHead.enableColumn("0", colIndex); visibleCols++; visibleColOrder = new String[visibleCols]; visibleColOrder[colIndex] = "0"; colIndex++; } else { visibleColOrder = new String[visibleCols]; } for (int i = 0; i < strings.length; i++) { String cid = strings[i]; visibleColOrder[colIndex] = cid; tHead.enableColumn(cid, colIndex); colIndex++; } } /** * @param uidl * which contains row data * @param firstRow * first row in data set * @param reqRows * amount of rows in data set */ private void updateBody(UIDL uidl, int firstRow, int reqRows) { if (uidl == null || reqRows < 1) return; tBody.renderRows(uidl, firstRow, reqRows); int optimalFirstRow = (int) (firstRowInViewPort - pageLength * CACHE_RATE); while (tBody.getFirstRendered() < optimalFirstRow) { // client.console.log("removing row from start"); tBody.unlinkRow(true); } int optimalLastRow = (int) (firstRowInViewPort + pageLength + pageLength * CACHE_RATE); while (tBody.getLastRendered() > optimalLastRow) { // client.console.log("removing row from the end"); tBody.unlinkRow(false); } } /** * Gives correct column index for given column key ("cid" in UIDL). * * @param colKey * @return column index of visible columns, -1 if column not visible */ private int getColIndexByKey(String colKey) { // return 0 if asked for rowHeaders if ("0".equals(colKey)) return 0; for (int i = 0; i < visibleColOrder.length; i++) { if (visibleColOrder[i].equals(colKey)) return i; } return -1; } private boolean isCollapsedColumn(String colKey) { if (collapsedColumns == null) return false; if (collapsedColumns.contains(colKey)) return true; return false; } private String getColKeyByIndex(int index) { return tHead.getHeaderCell(index).getColKey(); } private void setColWidth(int colIndex, int w) { HeaderCell cell = tHead.getHeaderCell(colIndex); cell.setWidth(w); tBody.setColWidth(colIndex, w); } private int getColWidth(String colKey) { return tHead.getHeaderCell(colKey).getWidth(); } private IScrollTableRow getRenderedRowByKey(String key) { Iterator it = tBody.iterator(); IScrollTableRow r = null; while (it.hasNext()) { r = (IScrollTableRow) it.next(); if (r.getKey().equals(key)) return r; } return null; } private void reOrderColumn(String columnKey, int newIndex) { int oldIndex = getColIndexByKey(columnKey); // Change header order tHead.moveCell(oldIndex, newIndex); // Change body order tBody.moveCol(oldIndex, newIndex); /* * Build new columnOrder and update it to server Note that columnOrder * also contains collapsed columns so we cannot directly build it from * cells vector Loop the old columnOrder and append in order to new * array unless on moved columnKey. On new index also put the moved key * i == index on columnOrder, j == index on newOrder */ String oldKeyOnNewIndex = visibleColOrder[newIndex]; if (rowHeaders) newIndex--; // columnOrder don't have rowHeader // add back hidden rows, for (int i = 0; i < columnOrder.length; i++) { if (columnOrder[i].equals(oldKeyOnNewIndex)) break; // break loop at target if (isCollapsedColumn(columnOrder[i])) newIndex++; } // finally we can build the new columnOrder for server String[] newOrder = new String[columnOrder.length]; for (int i = 0, j = 0; j < newOrder.length; i++) { if (j == newIndex) { newOrder[j] = columnKey; j++; } if (i == columnOrder.length) break; if (columnOrder[i].equals(columnKey)) continue; newOrder[j] = columnOrder[i]; j++; } columnOrder = newOrder; // also update visibleColumnOrder int i = rowHeaders ? 1 : 0; for (int j = 0; j < newOrder.length; j++) { String cid = newOrder[j]; if (!isCollapsedColumn(cid)) visibleColOrder[i++] = cid; } client.updateVariable(paintableId, "columnorder", columnOrder, false); } protected void onAttach() { super.onAttach(); if (initialContentReceived) { sizeInit(); } } protected void onDetach() { rowRequestHandler.cancel(); super.onDetach(); // ensure that scrollPosElement will be detached if (scrollPositionElement != null) { Element parent = DOM.getParent(scrollPositionElement); if (parent != null) DOM.removeChild(parent, scrollPositionElement); } } /** * Run only once when component is attached and received its initial * content. This function : * Syncs headers and bodys "natural widths and * saves the values. * Sets proper width and height * Makes deferred request * to get some cache rows */ private void sizeInit() { /* * We will use browsers table rendering algorithm to find proper column * widths. If content and header take less space than available, we will * divide extra space relatively to each column which has not width set. * * Overflow pixels are added to last column. * */ Iterator headCells = tHead.iterator(); int i = 0; int totalExplicitColumnsWidths = 0; int total = 0; int[] widths = new int[tHead.visibleCells.size()]; // first loop: collect natural widths while (headCells.hasNext()) { HeaderCell hCell = (HeaderCell) headCells.next(); int w; if (hCell.getWidth() > 0) { // server has defined column width explicitly w = hCell.getWidth(); totalExplicitColumnsWidths += w; } else { int hw = DOM.getElementPropertyInt(hCell.getElement(), "offsetWidth"); int cw = tBody.getColWidth(i); w = (hw > cw ? hw : cw) + IScrollTableBody.CELL_EXTRA_WIDTH; } widths[i] = w; total += w; i++; } tHead.disableBrowserIntelligence(); if (height == null) { bodyContainer.setHeight((tBody.getRowHeight() * pageLength) + "px"); } else { setHeight(height); iLayout(); } if (width == null) { int w = total; w += getScrollbarWidth(); bodyContainer.setWidth(w + "px"); tHead.setWidth(w + "px"); this.setWidth(w + "px"); } else { if (width.indexOf("px") > 0) { bodyContainer.setWidth(width); tHead.setWidth(width); this.setWidth(width); } else if (width.indexOf("%") > 0) { if (!width.equals("100%")) this.setWidth(width); // contained blocks are relative to parents bodyContainer.setWidth("100%"); tHead.setWidth("100%"); } } int availW = tBody.getAvailableWidth(); // Hey IE, are you really sure about this? availW = tBody.getAvailableWidth(); if (availW > total) { // natural size is smaller than available space int extraSpace = availW - total; int totalWidthR = total - totalExplicitColumnsWidths; if (totalWidthR > 0) { // now we will share this sum relatively to those without // explicit width headCells = tHead.iterator(); i = 0; HeaderCell hCell; while (headCells.hasNext()) { hCell = (HeaderCell) headCells.next(); if (hCell.getWidth() == -1) { int w = widths[i]; int newSpace = extraSpace * w / totalWidthR; w += newSpace; widths[i] = w; } i++; } } } else { // bodys size will be more than available and scrollbar will appear } // last loop: set possibly modified values i = 0; headCells = tHead.iterator(); while (headCells.hasNext()) { HeaderCell hCell = (HeaderCell) headCells.next(); if (hCell.getWidth() == -1) { int w = widths[i]; setColWidth(i, w); } i++; } if (firstvisible > 0) { bodyContainer .setScrollPosition(firstvisible * tBody.getRowHeight()); firstRowInViewPort = firstvisible; } DeferredCommand.addCommand(new Command() { public void execute() { if (totalRows - 1 > tBody.getLastRendered()) { // fetch cache rows rowRequestHandler .setReqFirstRow(tBody.getLastRendered() + 1); rowRequestHandler .setReqRows((int) (pageLength * CACHE_RATE)); - rowRequestHandler.deferRowFetch(0); + rowRequestHandler.deferRowFetch(1); } } }); initializedAndAttached = true; } public void iLayout() { if (height != null) { if(height.equals("100%")) { // we define height in pixels with 100% not to include borders setHeight(height); } int contentH = (DOM.getElementPropertyInt(getElement(), "clientHeight") - tHead.getOffsetHeight()); if (contentH < 0) contentH = 0; bodyContainer.setHeight(contentH + "px"); } } private int getScrollbarWidth() { return bodyContainer.getOffsetWidth() - DOM.getElementPropertyInt(bodyContainer.getElement(), "clientWidth"); } /** * This method has logick which rows needs to be requested from server when * user scrolls * */ public void onScroll(Widget widget, int scrollLeft, int scrollTop) { if (!initializedAndAttached) return; rowRequestHandler.cancel(); // fix headers horizontal scrolling tHead.setHorizontalScrollPosition(scrollLeft); firstRowInViewPort = (int) Math.ceil(scrollTop / (double) tBody.getRowHeight()); ApplicationConnection.getConsole().log( "At scrolltop: " + scrollTop + " At row " + firstRowInViewPort); int postLimit = (int) (firstRowInViewPort + pageLength + pageLength * CACHE_REACT_RATE); if (postLimit > totalRows - 1) postLimit = totalRows - 1; int preLimit = (int) (firstRowInViewPort - pageLength * CACHE_REACT_RATE); if (preLimit < 0) preLimit = 0; int lastRendered = tBody.getLastRendered(); int firstRendered = tBody.getFirstRendered(); if (postLimit <= lastRendered && preLimit >= firstRendered) { client.updateVariable(this.paintableId, "firstvisible", firstRowInViewPort, false); return; // scrolled withing "non-react area" } if (firstRowInViewPort - pageLength * CACHE_RATE > lastRendered || firstRowInViewPort + pageLength + pageLength * CACHE_RATE < firstRendered) { // need a totally new set ApplicationConnection.getConsole().log( "Table: need a totally new set"); rowRequestHandler .setReqFirstRow((int) (firstRowInViewPort - pageLength * CACHE_RATE)); rowRequestHandler .setReqRows((int) (2 * CACHE_RATE * pageLength + pageLength)); rowRequestHandler.deferRowFetch(); return; } if (preLimit < firstRendered) { // need some rows to the beginning of the rendered area ApplicationConnection .getConsole() .log( "Table: need some rows to the beginning of the rendered area"); rowRequestHandler .setReqFirstRow((int) (firstRowInViewPort - pageLength * CACHE_RATE)); rowRequestHandler.setReqRows(firstRendered - rowRequestHandler.getReqFirstRow()); rowRequestHandler.deferRowFetch(); return; } if (postLimit > lastRendered) { // need some rows to the end of the rendered area ApplicationConnection.getConsole().log( "need some rows to the end of the rendered area"); rowRequestHandler.setReqFirstRow(lastRendered + 1); rowRequestHandler.setReqRows((int) ((firstRowInViewPort + pageLength + pageLength * CACHE_RATE) - lastRendered)); rowRequestHandler.deferRowFetch(); } } private void announceScrollPosition() { ApplicationConnection.getConsole().log("" + firstRowInViewPort); if (scrollPositionElement == null) { scrollPositionElement = DOM.createDiv(); DOM.setElementProperty(scrollPositionElement, "className", "i-table-scrollposition"); DOM.appendChild(getElement(), scrollPositionElement); } DOM.setStyleAttribute(scrollPositionElement, "position", "absolute"); DOM.setStyleAttribute(scrollPositionElement, "marginLeft", (DOM .getElementPropertyInt(getElement(), "offsetWidth") / 2 - 80) + "px"); DOM.setStyleAttribute(scrollPositionElement, "marginTop", -(DOM .getElementPropertyInt(getElement(), "offsetHeight") / 2) + "px"); int last = (firstRowInViewPort + pageLength); if (last > totalRows) last = totalRows; DOM.setInnerHTML(scrollPositionElement, "<span>" + firstRowInViewPort + " &ndash; " + last + "..." + "</span>"); DOM.setStyleAttribute(scrollPositionElement, "display", "block"); } private void hideScrollPositionAnnotation() { if (scrollPositionElement != null) DOM.setStyleAttribute(scrollPositionElement, "display", "none"); } private class RowRequestHandler extends Timer { private int reqFirstRow = 0; private int reqRows = 0; public void deferRowFetch() { deferRowFetch(250); } public void deferRowFetch(int msec) { if (reqRows > 0 && reqFirstRow < totalRows) { schedule(msec); // tell scroll position to user if currently "visible" rows are // not rendered if ((firstRowInViewPort + pageLength > tBody.getLastRendered()) || (firstRowInViewPort < tBody.getFirstRendered())) { announceScrollPosition(); } else { hideScrollPositionAnnotation(); } } } public void setReqFirstRow(int reqFirstRow) { if (reqFirstRow < 0) reqFirstRow = 0; else if (reqFirstRow >= totalRows) reqFirstRow = totalRows - 1; this.reqFirstRow = reqFirstRow; } public void setReqRows(int reqRows) { this.reqRows = reqRows; } public void run() { ApplicationConnection.getConsole().log( "Getting " + reqRows + " rows from " + reqFirstRow); client.updateVariable(paintableId, "firstvisible", firstRowInViewPort, false); client.updateVariable(paintableId, "reqfirstrow", reqFirstRow, false); client.updateVariable(paintableId, "reqrows", reqRows, true); } public int getReqFirstRow() { return reqFirstRow; } public int getReqRows() { return reqRows; } /** * Sends request to refresh content at this position. */ public void refreshContent() { int first = (int) (firstRowInViewPort - pageLength * CACHE_RATE); int reqRows = (int) (2 * pageLength * CACHE_RATE + pageLength); if (first < 0) { reqRows = reqRows + first; first = 0; } this.setReqFirstRow(first); this.setReqRows(reqRows); run(); } } public class HeaderCell extends Widget { private static final int DRAG_WIDGET_WIDTH = 4; private static final int MINIMUM_COL_WIDTH = 20; Element td = DOM.createTD(); Element captionContainer = DOM.createDiv(); Element colResizeWidget = DOM.createDiv(); Element floatingCopyOfHeaderCell; private boolean sortable = false; private String cid; private boolean dragging; private int dragStartX; private int colIndex; private int originalWidth; private boolean isResizing; private int headerX; private boolean moved; private int closestSlot; private int width = -1; private char align = ALIGN_LEFT; private HeaderCell() { }; public void setSortable(boolean b) { sortable = b; } public HeaderCell(String colId, String headerText) { this.cid = colId; DOM.setElementProperty(colResizeWidget, "className", CLASSNAME + "-resizer"); DOM.setStyleAttribute(colResizeWidget, "width", DRAG_WIDGET_WIDTH + "px"); DOM.sinkEvents(colResizeWidget, Event.MOUSEEVENTS); setText(headerText); DOM.appendChild(td, colResizeWidget); DOM.setElementProperty(captionContainer, "className", CLASSNAME + "-caption-container"); DOM.sinkEvents(captionContainer, Event.MOUSEEVENTS); DOM.appendChild(td, captionContainer); DOM.sinkEvents(td, Event.MOUSEEVENTS); setElement(td); } public void setWidth(int w) { this.width = w; DOM.setStyleAttribute(captionContainer, "width", (w - DRAG_WIDGET_WIDTH - 4) + "px"); setWidth(w + "px"); } public int getWidth() { return width; } public void setText(String headerText) { DOM.setInnerHTML(captionContainer, headerText); } public String getColKey() { return cid; } private void setSorted(boolean sorted) { if (sorted) { if (sortAscending) this.setStyleName(CLASSNAME + "-header-cell-asc"); else this.setStyleName(CLASSNAME + "-header-cell-desc"); } else { this.setStyleName(CLASSNAME + "-header-cell"); } } /** * Handle column reordering. */ public void onBrowserEvent(Event event) { if (isResizing || DOM.compare(DOM.eventGetTarget(event), colResizeWidget)) { onResizeEvent(event); } else { handleCaptionEvent(event); } super.onBrowserEvent(event); } private void createFloatingCopy() { floatingCopyOfHeaderCell = DOM.createDiv(); DOM.setInnerHTML(floatingCopyOfHeaderCell, DOM.getInnerHTML(td)); floatingCopyOfHeaderCell = DOM .getChild(floatingCopyOfHeaderCell, 1); // TODO isolate non-standard css attribute (filter) // TODO move styles to css file DOM.setElementProperty(floatingCopyOfHeaderCell, "className", CLASSNAME + "-header-drag"); updateFloatingCopysPosition(DOM.getAbsoluteLeft(td), DOM .getAbsoluteTop(td)); DOM.appendChild(RootPanel.get().getElement(), floatingCopyOfHeaderCell); } private void updateFloatingCopysPosition(int x, int y) { x -= DOM.getElementPropertyInt(floatingCopyOfHeaderCell, "offsetWidth") / 2; DOM.setStyleAttribute(floatingCopyOfHeaderCell, "left", x + "px"); if (y > 0) DOM.setStyleAttribute(floatingCopyOfHeaderCell, "top", (y + 7) + "px"); } private void hideFloatingCopy() { DOM.removeChild(RootPanel.get().getElement(), floatingCopyOfHeaderCell); floatingCopyOfHeaderCell = null; } protected void handleCaptionEvent(Event event) { switch (DOM.eventGetType(event)) { case Event.ONMOUSEDOWN: ApplicationConnection.getConsole().log( "HeaderCaption: mouse down"); if (columnReordering) { dragging = true; moved = false; colIndex = getColIndexByKey(cid); DOM.setCapture(getElement()); this.headerX = tHead.getAbsoluteLeft(); ApplicationConnection .getConsole() .log( "HeaderCaption: Caption set to capture mouse events"); DOM.eventPreventDefault(event); // prevent selecting text } break; case Event.ONMOUSEUP: ApplicationConnection.getConsole() .log("HeaderCaption: mouseUP"); if (columnReordering) { dragging = false; DOM.releaseCapture(getElement()); ApplicationConnection.getConsole().log( "HeaderCaption: Stopped column reordering"); if (moved) { hideFloatingCopy(); tHead.removeSlotFocus(); if (closestSlot != colIndex && closestSlot != (colIndex + 1)) { if (closestSlot > colIndex) reOrderColumn(cid, closestSlot - 1); else reOrderColumn(cid, closestSlot); } } } if (!moved) { // mouse event was a click to header -> sort column if (sortable) { if (sortColumn.equals(cid)) { // just toggle order client.updateVariable(paintableId, "sortascending", !sortAscending, false); } else { // set table scrolled by this column client.updateVariable(paintableId, "sortcolumn", cid, false); } // get also cache columns at the same request bodyContainer.setScrollPosition(0); firstvisible = 0; rowRequestHandler.setReqFirstRow(0); rowRequestHandler.setReqRows((int) (2 * pageLength * CACHE_RATE + pageLength)); rowRequestHandler.deferRowFetch(); } break; } break; case Event.ONMOUSEMOVE: if (dragging) { ApplicationConnection.getConsole().log( "HeaderCaption: Dragging column, optimal index..."); if (!moved) { createFloatingCopy(); moved = true; } int x = DOM.eventGetClientX(event); int slotX = headerX; closestSlot = colIndex; int closestDistance = -1; int start = 0; if (rowHeaders) { start++; } int visibleCellCount = tHead.getVisibleCellCount(); for (int i = start; i <= visibleCellCount; i++) { if (i > 0) { String colKey = getColKeyByIndex(i - 1); slotX += getColWidth(colKey); } int dist = Math.abs(x - slotX); if (closestDistance == -1 || dist < closestDistance) { closestDistance = dist; closestSlot = i; } } tHead.focusSlot(closestSlot); updateFloatingCopysPosition(x, -1); ApplicationConnection.getConsole().log("" + closestSlot); } break; default: break; } } private void onResizeEvent(Event event) { switch (DOM.eventGetType(event)) { case Event.ONMOUSEDOWN: isResizing = true; DOM.setCapture(getElement()); dragStartX = DOM.eventGetClientX(event); colIndex = getColIndexByKey(cid); originalWidth = getWidth(); DOM.eventPreventDefault(event); break; case Event.ONMOUSEUP: isResizing = false; DOM.releaseCapture(getElement()); break; case Event.ONMOUSEMOVE: if (isResizing) { int deltaX = DOM.eventGetClientX(event) - dragStartX; if (deltaX == 0) return; int newWidth = originalWidth + deltaX; if (newWidth < MINIMUM_COL_WIDTH) newWidth = MINIMUM_COL_WIDTH; setColWidth(colIndex, newWidth); } break; default: break; } } public String getCaption() { return DOM.getInnerText(captionContainer); } public boolean isEnabled() { return getParent() != null; } public void setAlign(char c) { if (align != c) { switch (c) { case ALIGN_CENTER: DOM.setStyleAttribute(captionContainer, "textAlign", "center"); break; case ALIGN_RIGHT: DOM.setStyleAttribute(captionContainer, "textAlign", "right"); break; default: DOM.setStyleAttribute(captionContainer, "textAlign", ""); break; } } align = c; } public char getAlign() { return align; } } /** * HeaderCell that is header cell for row headers. * * Reordering disabled and clicking on it resets sorting. */ public class RowHeadersHeaderCell extends HeaderCell { RowHeadersHeaderCell() { super("0", ""); } protected void handleCaptionEvent(Event event) { // NOP: RowHeaders cannot be reordered // TODO It'd be nice to reset sorting here } } public class TableHead extends Panel implements ActionOwner { private static final int WRAPPER_WIDTH = 9000; Vector visibleCells = new Vector(); HashMap availableCells = new HashMap(); Element div = DOM.createDiv(); Element hTableWrapper = DOM.createDiv(); Element hTableContainer = DOM.createDiv(); Element table = DOM.createTable(); Element headerTableBody = DOM.createTBody(); Element tr = DOM.createTR(); private Element columnSelector = DOM.createDiv(); private int focusedSlot = -1; private boolean columnCollapsing = false; public TableHead() { DOM.setStyleAttribute(hTableWrapper, "overflow", "hidden"); DOM.setElementProperty(hTableWrapper, "className", CLASSNAME + "-header"); // TODO move styles to CSS DOM.setElementProperty(columnSelector, "className", CLASSNAME + "-column-selector"); DOM.setStyleAttribute(columnSelector, "display", "none"); DOM.appendChild(table, headerTableBody); DOM.appendChild(headerTableBody, tr); DOM.appendChild(hTableContainer, table); DOM.appendChild(hTableWrapper, hTableContainer); DOM.appendChild(div, hTableWrapper); DOM.appendChild(div, columnSelector); setElement(div); setStyleName(CLASSNAME + "-header-wrap"); DOM.sinkEvents(columnSelector, Event.ONCLICK); availableCells.put("0", new RowHeadersHeaderCell()); } public void updateCellFromUIDL(UIDL col) { String cid = col.getStringAttribute("cid"); HeaderCell c = getHeaderCell(cid); if (c == null) { c = new HeaderCell(cid, col.getStringAttribute("caption")); availableCells.put(cid, c); } else { c.setText(col.getStringAttribute("caption")); } if (col.hasAttribute("sortable")) { c.setSortable(true); if (cid.equals(sortColumn)) c.setSorted(true); else c.setSorted(false); } if (col.hasAttribute("align")) { c.setAlign(col.getStringAttribute("align").charAt(0)); } if (col.hasAttribute("width")) { String width = col.getStringAttribute("width"); c.setWidth(Integer.parseInt(width)); } // TODO icon } public void enableColumn(String cid, int index) { HeaderCell c = getHeaderCell(cid); if (!c.isEnabled()) { setHeaderCell(index, c); } } public int getVisibleCellCount() { return visibleCells.size(); } public void setHorizontalScrollPosition(int scrollLeft) { DOM.setElementPropertyInt(hTableWrapper, "scrollLeft", scrollLeft); } public void setColumnCollapsingAllowed(boolean cc) { columnCollapsing = cc; if (cc) { DOM.setStyleAttribute(columnSelector, "display", "block"); } else { DOM.setStyleAttribute(columnSelector, "display", "none"); } } public void disableBrowserIntelligence() { DOM.setStyleAttribute(hTableContainer, "width", WRAPPER_WIDTH + "px"); } public void setHeaderCell(int index, HeaderCell cell) { if (index < visibleCells.size()) { // insert to right slot DOM.insertChild(tr, cell.getElement(), index); adopt(cell); visibleCells.insertElementAt(cell, index); } else if (index == visibleCells.size()) { // simply append DOM.appendChild(tr, cell.getElement()); adopt(cell); visibleCells.add(cell); } else { throw new RuntimeException( "Header cells must be appended in order"); } } public HeaderCell getHeaderCell(int index) { if (index < visibleCells.size()) return (HeaderCell) visibleCells.get(index); else return null; } /** * Get's HeaderCell by it's column Key. * * Note that this returns HeaderCell even if it is currently collapsed. * * @param cid * Column key of accessed HeaderCell * @return HeaderCell */ public HeaderCell getHeaderCell(String cid) { return (HeaderCell) availableCells.get(cid); } public void moveCell(int oldIndex, int newIndex) { HeaderCell hCell = getHeaderCell(oldIndex); Element cell = hCell.getElement(); visibleCells.remove(oldIndex); DOM.removeChild(tr, cell); DOM.insertChild(tr, cell, newIndex); visibleCells.insertElementAt(hCell, newIndex); } public Iterator iterator() { return visibleCells.iterator(); } public boolean remove(Widget w) { if (visibleCells.contains(w)) { visibleCells.remove(w); orphan(w); DOM.removeChild(DOM.getParent(w.getElement()), w.getElement()); return true; } return false; } public void removeCell(String colKey) { HeaderCell c = getHeaderCell(colKey); remove(c); } private void focusSlot(int index) { removeSlotFocus(); if (index > 0) DOM.setElementProperty(DOM.getFirstChild(DOM.getChild(tr, index - 1)), "className", CLASSNAME + "-resizer " + CLASSNAME + "-focus-slot-right"); else DOM.setElementProperty(DOM.getFirstChild(DOM .getChild(tr, index)), "className", CLASSNAME + "-resizer " + CLASSNAME + "-focus-slot-left"); focusedSlot = index; } private void removeSlotFocus() { if (focusedSlot < 0) return; if (focusedSlot == 0) DOM.setElementProperty(DOM.getFirstChild(DOM.getChild(tr, focusedSlot)), "className", CLASSNAME + "-resizer"); else if (focusedSlot > 0) DOM.setElementProperty(DOM.getFirstChild(DOM.getChild(tr, focusedSlot - 1)), "className", CLASSNAME + "-resizer"); focusedSlot = -1; } public void onBrowserEvent(Event event) { super.onBrowserEvent(event); if (DOM.compare(DOM.eventGetTarget(event), columnSelector)) { int left = DOM.getAbsoluteLeft(columnSelector); int top = DOM.getAbsoluteTop(columnSelector) + DOM.getElementPropertyInt(columnSelector, "offsetHeight"); client.getContextMenu().showAt(this, left, top); } } class VisibleColumnAction extends Action { String colKey; private boolean collapsed; public VisibleColumnAction(String colKey) { super(IScrollTable.TableHead.this); this.colKey = colKey; caption = tHead.getHeaderCell(colKey).getCaption(); } public void execute() { client.getContextMenu().hide(); // toggle selected column if (collapsedColumns.contains(colKey)) { collapsedColumns.remove(colKey); } else { tHead.removeCell(colKey); collapsedColumns.add(colKey); } // update variable to server client.updateVariable(paintableId, "collapsedcolumns", collapsedColumns.toArray(), false); // let rowRequestHandler determine proper rows rowRequestHandler.refreshContent(); } public void setCollapsed(boolean b) { collapsed = b; } /** * Override default method to distinguish on/off columns */ public String getHTML() { StringBuffer buf = new StringBuffer(); if (collapsed) buf.append("<span class=\"i-off\">"); buf.append(super.getHTML()); if (collapsed) buf.append("</span>"); return buf.toString(); } } /* * Returns columns as Action array for column select popup */ public Action[] getActions() { Object[] cols; if (IScrollTable.this.columnReordering) { cols = columnOrder; } else { // if columnReordering is disabled, we need different way to get // all available columns cols = visibleColOrder; cols = new Object[visibleColOrder.length + collapsedColumns.size()]; int i; for (i = 0; i < visibleColOrder.length; i++) { cols[i] = visibleColOrder[i]; } for (Iterator it = collapsedColumns.iterator(); it.hasNext();) cols[i++] = it.next(); } Action[] actions = new Action[cols.length]; for (int i = 0; i < cols.length; i++) { String cid = (String) cols[i]; HeaderCell c = getHeaderCell(cid); VisibleColumnAction a = new VisibleColumnAction(c.getColKey()); a.setCaption(c.getCaption()); if (!c.isEnabled()) a.setCollapsed(true); actions[i] = a; } return actions; } public ApplicationConnection getClient() { return client; } public String getPaintableId() { return paintableId; } /** * Returns column alignments for visible columns */ public char[] getColumnAlignments() { Iterator it = visibleCells.iterator(); char[] aligns = new char[visibleCells.size()]; int colIndex = 0; while (it.hasNext()) { aligns[colIndex++] = ((HeaderCell) it.next()).getAlign(); } return aligns; } } /** * This Panel can only contain IScrollTableRow type of widgets. This * "simulates" very large table, keeping spacers which take room of * unrendered rows. * * @author mattitahvonen * */ public class IScrollTableBody extends Panel { public static final int CELL_EXTRA_WIDTH = 20; public static final int DEFAULT_ROW_HEIGHT = 25; public static final int CELL_CONTENT_PADDING = 3; private int rowHeight = -1; private List renderedRows = new Vector(); private boolean initDone = false; private int totalRows; Element preSpacer = DOM.createDiv(); Element postSpacer = DOM.createDiv(); Element container = DOM.createDiv(); Element tBody = DOM.createTBody(); Element table = DOM.createTable(); private int firstRendered; private int lastRendered; private char[] aligns; IScrollTableBody() { constructDOM(); setElement(container); } private void constructDOM() { DOM.setElementProperty(table, "className", CLASSNAME + "-table"); DOM.setElementProperty(preSpacer, "className", CLASSNAME + "-row-spacer"); DOM.setElementProperty(postSpacer, "className", CLASSNAME + "-row-spacer"); DOM.appendChild(table, tBody); DOM.appendChild(container, preSpacer); DOM.appendChild(container, table); DOM.appendChild(container, postSpacer); } public int getAvailableWidth() { return DOM.getElementPropertyInt(preSpacer, "offsetWidth"); } public void renderInitialRows(UIDL rowData, int firstIndex, int rows, int totalRows) { this.totalRows = totalRows; this.firstRendered = firstIndex; this.lastRendered = firstIndex + rows - 1; Iterator it = rowData.getChildIterator(); aligns = tHead.getColumnAlignments(); while (it.hasNext()) { IScrollTableRow row = new IScrollTableRow((UIDL) it.next(), aligns); addRow(row); } if (isAttached()) fixSpacers(); } public void renderRows(UIDL rowData, int firstIndex, int rows) { aligns = tHead.getColumnAlignments(); Iterator it = rowData.getChildIterator(); if (firstIndex == lastRendered + 1) { while (it.hasNext()) { IScrollTableRow row = createRow((UIDL) it.next()); addRow(row); lastRendered++; } fixSpacers(); } else if (firstIndex + rows == firstRendered) { IScrollTableRow[] rowArray = new IScrollTableRow[rows]; int i = rows; while (it.hasNext()) { i--; rowArray[i] = createRow((UIDL) it.next()); } for (i = 0; i < rows; i++) { addRowBeforeFirstRendered(rowArray[i]); firstRendered--; } // } else if (firstIndex > lastRendered || firstIndex + rows < // firstRendered) { } else if (true) { // completely new set of rows // create one row before truncating row IScrollTableRow row = createRow((UIDL) it.next()); while (lastRendered + 1 > firstRendered) unlinkRow(false); firstRendered = firstIndex; lastRendered = firstIndex - 1; fixSpacers(); addRow(row); lastRendered++; while (it.hasNext()) { addRow(createRow((UIDL) it.next())); lastRendered++; } fixSpacers(); } else { // sorted or column reordering changed ApplicationConnection.getConsole().log( "Bad update" + firstIndex + "/" + rows); } } /** * This mehtod is used to instantiate new rows for this table. It * automatically sets correct widths to rows cells and assigns correct * client reference for child widgets. * * This method can be called only after table has been initialized * * @param uidl */ private IScrollTableRow createRow(UIDL uidl) { IScrollTableRow row = new IScrollTableRow(uidl, aligns); int cells = DOM.getChildCount(row.getElement()); for (int i = 0; i < cells; i++) { Element cell = DOM.getChild(row.getElement(), i); int w = IScrollTable.this.getColWidth(getColKeyByIndex(i)); DOM.setStyleAttribute(DOM.getFirstChild(cell), "width", (w - CELL_CONTENT_PADDING) + "px"); DOM.setStyleAttribute(cell, "width", w + "px"); } return row; } private void addRowBeforeFirstRendered(IScrollTableRow row) { IScrollTableRow first = null; if (renderedRows.size() > 0) first = (IScrollTableRow) renderedRows.get(0); if (first != null && first.getStyleName().indexOf("-odd") == -1) row.setStyleName(CLASSNAME + "-row-odd"); if (row.isSelected()) row.addStyleName("i-selected"); DOM.insertChild(tBody, row.getElement(), 0); adopt(row); renderedRows.add(0, row); } private void addRow(IScrollTableRow row) { IScrollTableRow last = null; if (renderedRows.size() > 0) last = (IScrollTableRow) renderedRows .get(renderedRows.size() - 1); if (last != null && last.getStyleName().indexOf("-odd") == -1) row.setStyleName(CLASSNAME + "-row-odd"); if (row.isSelected()) row.addStyleName("i-selected"); DOM.appendChild(tBody, row.getElement()); adopt(row); renderedRows.add(row); } public Iterator iterator() { return renderedRows.iterator(); } public void unlinkRow(boolean fromBeginning) { if (lastRendered - firstRendered < 0) return; int index; if (fromBeginning) { index = 0; firstRendered++; } else { index = renderedRows.size() - 1; lastRendered--; } IScrollTableRow toBeRemoved = (IScrollTableRow) renderedRows .get(index); client.unregisterChildPaintables(toBeRemoved); DOM.removeChild(tBody, toBeRemoved.getElement()); this.orphan(toBeRemoved); renderedRows.remove(index); fixSpacers(); } public boolean remove(Widget w) { throw new UnsupportedOperationException(); } protected void onAttach() { super.onAttach(); fixSpacers(); // fix container blocks height to avoid "bouncing" when scrolling DOM.setStyleAttribute(container, "height", totalRows * getRowHeight() + "px"); } private void fixSpacers() { DOM.setStyleAttribute(preSpacer, "height", getRowHeight() * firstRendered + "px"); DOM.setStyleAttribute(postSpacer, "height", getRowHeight() * (totalRows - 1 - lastRendered) + "px"); } public int getTotalRows() { return totalRows; } public int getRowHeight() { if (initDone) return rowHeight; else { if (DOM.getChildCount(tBody) > 0) { rowHeight = DOM .getElementPropertyInt(tBody, "offsetHeight") / DOM.getChildCount(tBody); } else { return DEFAULT_ROW_HEIGHT; } initDone = true; return rowHeight; } } public int getColWidth(int i) { if (initDone) { Element e = DOM.getChild(DOM.getChild(tBody, 0), i); return DOM.getElementPropertyInt(e, "offsetWidth"); } else { return 0; } } public void setColWidth(int colIndex, int w) { int rows = DOM.getChildCount(tBody); for (int i = 0; i < rows; i++) { Element cell = DOM.getChild(DOM.getChild(tBody, i), colIndex); DOM.setStyleAttribute(DOM.getFirstChild(cell), "width", (w - CELL_CONTENT_PADDING) + "px"); DOM.setStyleAttribute(cell, "width", w + "px"); } } public int getLastRendered() { return lastRendered; } public int getFirstRendered() { return firstRendered; } public void moveCol(int oldIndex, int newIndex) { // loop all rows and move given index to its new place Iterator rows = iterator(); while (rows.hasNext()) { IScrollTableRow row = (IScrollTableRow) rows.next(); Element td = DOM.getChild(row.getElement(), oldIndex); DOM.removeChild(row.getElement(), td); DOM.insertChild(row.getElement(), td, newIndex); } } public class IScrollTableRow extends Panel implements ActionOwner { Vector childWidgets = new Vector(); private boolean selected = false; private int rowKey; private String[] actionKeys = null; private IScrollTableRow(int rowKey) { this.rowKey = rowKey; setElement(DOM.createElement("tr")); DOM.sinkEvents(getElement(), Event.ONCLICK); attachContextMenuEvent(getElement()); setStyleName(CLASSNAME + "-row"); } protected void onDetach() { Util.removeContextMenuEvent(getElement()); super.onDetach(); } /** * Attaches context menu event handler to given element. Attached * handler fires showContextMenu function. * * @param el * element where to attach contenxt menu event */ private native void attachContextMenuEvent(Element el) /*-{ var row = this; el.oncontextmenu = function(e) { if(!e) e = $wnd.event; row.@com.itmill.toolkit.terminal.gwt.client.ui.IScrollTable.IScrollTableBody.IScrollTableRow::showContextMenu(Lcom/google/gwt/user/client/Event;)(e); return false; }; }-*/; public String getKey() { return String.valueOf(rowKey); } public IScrollTableRow(UIDL uidl, char[] aligns) { this(uidl.getIntAttribute("key")); tHead.getColumnAlignments(); int col = 0; // row header if (rowHeaders) { addCell(uidl.getStringAttribute("caption"), aligns[col++]); } if (uidl.hasAttribute("al")) actionKeys = uidl.getStringArrayAttribute("al"); Iterator cells = uidl.getChildIterator(); while (cells.hasNext()) { Object cell = cells.next(); if (cell instanceof String) { addCell(cell.toString(), aligns[col++]); } else { Widget cellContent = client.getWidget((UIDL) cell); ((Paintable) cellContent).updateFromUIDL((UIDL) cell, client); addCell(cellContent, aligns[col++]); } } if (uidl.hasAttribute("selected") && !isSelected()) toggleSelection(); } public void addCell(String text, char align) { // String only content is optimized by not using Label widget Element td = DOM.createTD(); Element container = DOM.createDiv(); DOM.setElementProperty(container, "className", CLASSNAME + "-cell-content"); DOM.setInnerHTML(container, text); if (align != ALIGN_LEFT) { switch (align) { case ALIGN_CENTER: DOM.setStyleAttribute(container, "textAlign", "center"); break; case ALIGN_RIGHT: default: DOM.setStyleAttribute(container, "textAlign", "right"); break; } } DOM.appendChild(td, container); DOM.appendChild(getElement(), td); } public void addCell(Widget w, char align) { Element td = DOM.createTD(); Element container = DOM.createDiv(); DOM.setElementProperty(container, "className", CLASSNAME + "-cell-content"); // TODO make widget cells respect align. text-align:center for // IE, margin: auto for others DOM.appendChild(td, container); DOM.appendChild(getElement(), td); DOM.appendChild(container, w.getElement()); adopt(w); childWidgets.add(w); } public Iterator iterator() { return childWidgets.iterator(); } public boolean remove(Widget w) { // TODO Auto-generated method stub return false; } /* * React on click that occur on content cells only */ public void onBrowserEvent(Event event) { String s = DOM.getElementProperty(DOM.eventGetTarget(event), "className"); switch (DOM.eventGetType(event)) { case Event.ONCLICK: if ((CLASSNAME + "-cell-content").equals(s)) { ApplicationConnection.getConsole().log("Row click"); if (selectMode > Table.SELECT_MODE_NONE) { toggleSelection(); client.updateVariable(paintableId, "selected", selectedRowKeys.toArray(), immediate); } } break; default: break; } super.onBrowserEvent(event); } public void showContextMenu(Event event) { ApplicationConnection.getConsole().log("Context menu"); if (actionKeys != null) { int left = DOM.eventGetClientX(event); int top = DOM.eventGetClientY(event); top += Window.getScrollTop(); left += Window.getScrollLeft(); client.getContextMenu().showAt(this, left, top); } } public boolean isSelected() { return selected; } private void toggleSelection() { selected = !selected; if (selected) { if (selectMode == Table.SELECT_MODE_SINGLE) IScrollTable.this.deselectAll(); selectedRowKeys.add(String.valueOf(rowKey)); addStyleName("i-selected"); } else { selectedRowKeys.remove(String.valueOf(rowKey)); removeStyleName("i-selected"); } } /* * (non-Javadoc) * * @see com.itmill.toolkit.terminal.gwt.client.ui.IActionOwner#getActions() */ public Action[] getActions() { if (actionKeys == null) return new Action[] {}; Action[] actions = new Action[actionKeys.length]; for (int i = 0; i < actions.length; i++) { String actionKey = actionKeys[i]; TreeAction a = new TreeAction(this, String.valueOf(rowKey), actionKey); a.setCaption(getActionCaption(actionKey)); a.setIconUrl(getActionIcon(actionKey)); actions[i] = a; } return actions; } public ApplicationConnection getClient() { return client; } public String getPaintableId() { return paintableId; } } } public void deselectAll() { Object[] keys = selectedRowKeys.toArray(); for (int i = 0; i < keys.length; i++) { IScrollTableRow row = getRenderedRowByKey((String) keys[i]); if (row != null && row.isSelected()) row.toggleSelection(); } // still ensure all selects are removed from (not necessary rendered) selectedRowKeys.clear(); } public void add(Widget w) { throw new UnsupportedOperationException( "ITable can contain only rows created by itself."); } public void clear() { panel.clear(); } public Iterator iterator() { return panel.iterator(); } public boolean remove(Widget w) { return panel.remove(w); } public void setHeight(String height) { // workaround very common 100% height problem - extract borders if(height.equals("100%")) { final int borders = getBorderSpace(); Element elem = getElement(); Element parentElem = DOM.getParent(elem); // put table away from flow for a moment DOM.setStyleAttribute(getElement(), "position", "absolute"); // get containers natural space for table int availPixels = DOM.getElementPropertyInt(parentElem, "clientHeight"); // put table back to flow DOM.setStyleAttribute(getElement(), "position", "static"); // set 100% height with borders super.setHeight((availPixels - borders) + "px"); } else { // normally height don't include borders super.setHeight(height); } } private int getBorderSpace() { Element el = getElement(); return DOM.getElementPropertyInt(el, "offsetHeight") - DOM.getElementPropertyInt(el, "clientHeight"); } }
true
true
private void sizeInit() { /* * We will use browsers table rendering algorithm to find proper column * widths. If content and header take less space than available, we will * divide extra space relatively to each column which has not width set. * * Overflow pixels are added to last column. * */ Iterator headCells = tHead.iterator(); int i = 0; int totalExplicitColumnsWidths = 0; int total = 0; int[] widths = new int[tHead.visibleCells.size()]; // first loop: collect natural widths while (headCells.hasNext()) { HeaderCell hCell = (HeaderCell) headCells.next(); int w; if (hCell.getWidth() > 0) { // server has defined column width explicitly w = hCell.getWidth(); totalExplicitColumnsWidths += w; } else { int hw = DOM.getElementPropertyInt(hCell.getElement(), "offsetWidth"); int cw = tBody.getColWidth(i); w = (hw > cw ? hw : cw) + IScrollTableBody.CELL_EXTRA_WIDTH; } widths[i] = w; total += w; i++; } tHead.disableBrowserIntelligence(); if (height == null) { bodyContainer.setHeight((tBody.getRowHeight() * pageLength) + "px"); } else { setHeight(height); iLayout(); } if (width == null) { int w = total; w += getScrollbarWidth(); bodyContainer.setWidth(w + "px"); tHead.setWidth(w + "px"); this.setWidth(w + "px"); } else { if (width.indexOf("px") > 0) { bodyContainer.setWidth(width); tHead.setWidth(width); this.setWidth(width); } else if (width.indexOf("%") > 0) { if (!width.equals("100%")) this.setWidth(width); // contained blocks are relative to parents bodyContainer.setWidth("100%"); tHead.setWidth("100%"); } } int availW = tBody.getAvailableWidth(); // Hey IE, are you really sure about this? availW = tBody.getAvailableWidth(); if (availW > total) { // natural size is smaller than available space int extraSpace = availW - total; int totalWidthR = total - totalExplicitColumnsWidths; if (totalWidthR > 0) { // now we will share this sum relatively to those without // explicit width headCells = tHead.iterator(); i = 0; HeaderCell hCell; while (headCells.hasNext()) { hCell = (HeaderCell) headCells.next(); if (hCell.getWidth() == -1) { int w = widths[i]; int newSpace = extraSpace * w / totalWidthR; w += newSpace; widths[i] = w; } i++; } } } else { // bodys size will be more than available and scrollbar will appear } // last loop: set possibly modified values i = 0; headCells = tHead.iterator(); while (headCells.hasNext()) { HeaderCell hCell = (HeaderCell) headCells.next(); if (hCell.getWidth() == -1) { int w = widths[i]; setColWidth(i, w); } i++; } if (firstvisible > 0) { bodyContainer .setScrollPosition(firstvisible * tBody.getRowHeight()); firstRowInViewPort = firstvisible; } DeferredCommand.addCommand(new Command() { public void execute() { if (totalRows - 1 > tBody.getLastRendered()) { // fetch cache rows rowRequestHandler .setReqFirstRow(tBody.getLastRendered() + 1); rowRequestHandler .setReqRows((int) (pageLength * CACHE_RATE)); rowRequestHandler.deferRowFetch(0); } } }); initializedAndAttached = true; }
private void sizeInit() { /* * We will use browsers table rendering algorithm to find proper column * widths. If content and header take less space than available, we will * divide extra space relatively to each column which has not width set. * * Overflow pixels are added to last column. * */ Iterator headCells = tHead.iterator(); int i = 0; int totalExplicitColumnsWidths = 0; int total = 0; int[] widths = new int[tHead.visibleCells.size()]; // first loop: collect natural widths while (headCells.hasNext()) { HeaderCell hCell = (HeaderCell) headCells.next(); int w; if (hCell.getWidth() > 0) { // server has defined column width explicitly w = hCell.getWidth(); totalExplicitColumnsWidths += w; } else { int hw = DOM.getElementPropertyInt(hCell.getElement(), "offsetWidth"); int cw = tBody.getColWidth(i); w = (hw > cw ? hw : cw) + IScrollTableBody.CELL_EXTRA_WIDTH; } widths[i] = w; total += w; i++; } tHead.disableBrowserIntelligence(); if (height == null) { bodyContainer.setHeight((tBody.getRowHeight() * pageLength) + "px"); } else { setHeight(height); iLayout(); } if (width == null) { int w = total; w += getScrollbarWidth(); bodyContainer.setWidth(w + "px"); tHead.setWidth(w + "px"); this.setWidth(w + "px"); } else { if (width.indexOf("px") > 0) { bodyContainer.setWidth(width); tHead.setWidth(width); this.setWidth(width); } else if (width.indexOf("%") > 0) { if (!width.equals("100%")) this.setWidth(width); // contained blocks are relative to parents bodyContainer.setWidth("100%"); tHead.setWidth("100%"); } } int availW = tBody.getAvailableWidth(); // Hey IE, are you really sure about this? availW = tBody.getAvailableWidth(); if (availW > total) { // natural size is smaller than available space int extraSpace = availW - total; int totalWidthR = total - totalExplicitColumnsWidths; if (totalWidthR > 0) { // now we will share this sum relatively to those without // explicit width headCells = tHead.iterator(); i = 0; HeaderCell hCell; while (headCells.hasNext()) { hCell = (HeaderCell) headCells.next(); if (hCell.getWidth() == -1) { int w = widths[i]; int newSpace = extraSpace * w / totalWidthR; w += newSpace; widths[i] = w; } i++; } } } else { // bodys size will be more than available and scrollbar will appear } // last loop: set possibly modified values i = 0; headCells = tHead.iterator(); while (headCells.hasNext()) { HeaderCell hCell = (HeaderCell) headCells.next(); if (hCell.getWidth() == -1) { int w = widths[i]; setColWidth(i, w); } i++; } if (firstvisible > 0) { bodyContainer .setScrollPosition(firstvisible * tBody.getRowHeight()); firstRowInViewPort = firstvisible; } DeferredCommand.addCommand(new Command() { public void execute() { if (totalRows - 1 > tBody.getLastRendered()) { // fetch cache rows rowRequestHandler .setReqFirstRow(tBody.getLastRendered() + 1); rowRequestHandler .setReqRows((int) (pageLength * CACHE_RATE)); rowRequestHandler.deferRowFetch(1); } } }); initializedAndAttached = true; }
diff --git a/src/org/ohmage/service/UploadService.java b/src/org/ohmage/service/UploadService.java index b4dd769..8c35d7a 100644 --- a/src/org/ohmage/service/UploadService.java +++ b/src/org/ohmage/service/UploadService.java @@ -1,494 +1,494 @@ package org.ohmage.service; import com.commonsware.cwac.wakeful.WakefulIntentService; import edu.ucla.cens.mobility.glue.MobilityInterface; import edu.ucla.cens.systemlog.Analytics; import edu.ucla.cens.systemlog.Analytics.Status; import edu.ucla.cens.systemlog.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.ohmage.Config; import org.ohmage.NotificationHelper; import org.ohmage.OhmageApi; import org.ohmage.OhmageApi.Result; import org.ohmage.SharedPreferencesHelper; import org.ohmage.Utilities; import org.ohmage.db.DbContract.Campaigns; import org.ohmage.db.DbContract.PromptResponses; import org.ohmage.db.DbContract.Responses; import org.ohmage.db.DbContract.SurveyPrompts; import org.ohmage.db.DbHelper; import org.ohmage.db.DbHelper.Tables; import org.ohmage.db.Models.Response; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import java.io.File; import java.io.FilenameFilter; import java.text.SimpleDateFormat; import java.util.ArrayList; public class UploadService extends WakefulIntentService { /** Extra to tell the upload service to upload mobility points */ public static final String EXTRA_UPLOAD_MOBILITY = "upload_mobility"; /** Extra to tell the upload service to upload surveys */ public static final String EXTRA_UPLOAD_SURVEYS = "upload_surveys"; /** Extra to tell the upload service if it is running in the background */ public static final String EXTRA_BACKGROUND = "is_background"; private static final String TAG = "UploadService"; public static final String MOBILITY_UPLOAD_STARTED = "org.ohmage.MOBILITY_UPLOAD_STARTED"; public static final String MOBILITY_UPLOAD_FINISHED = "org.ohmage.MOBILITY_UPLOAD_FINISHED"; private OhmageApi mApi; private boolean isBackground; public UploadService() { super(TAG); } @Override public void onCreate() { super.onCreate(); Analytics.service(this, Status.ON); } @Override public void onDestroy() { super.onDestroy(); Analytics.service(this, Status.OFF); } @Override protected void doWakefulWork(Intent intent) { if(mApi == null) setOhmageApi(new OhmageApi(this)); isBackground = intent.getBooleanExtra(EXTRA_BACKGROUND, false); if (intent.getBooleanExtra(EXTRA_UPLOAD_SURVEYS, false)) { uploadSurveyResponses(intent); } if (intent.getBooleanExtra(EXTRA_UPLOAD_MOBILITY, false)) { uploadMobility(intent); } } public void setOhmageApi(OhmageApi api) { mApi = api; } private void uploadSurveyResponses(Intent intent) { String serverUrl = Config.DEFAULT_SERVER_URL; SharedPreferencesHelper helper = new SharedPreferencesHelper(this); String username = helper.getUsername(); String hashedPassword = helper.getHashedPassword(); boolean uploadErrorOccurred = false; boolean authErrorOccurred = false; DbHelper dbHelper = new DbHelper(this); Uri dataUri = intent.getData(); if(!Responses.isResponseUri(dataUri)) { Log.e(TAG, "Upload service can only be called with a response URI"); return; } ContentResolver cr = getContentResolver(); String [] projection = new String [] { Tables.RESPONSES + "." + Responses._ID, Responses.RESPONSE_UUID, Responses.RESPONSE_DATE, Responses.RESPONSE_TIME, Responses.RESPONSE_TIMEZONE, Responses.RESPONSE_LOCATION_STATUS, Responses.RESPONSE_LOCATION_LATITUDE, Responses.RESPONSE_LOCATION_LONGITUDE, Responses.RESPONSE_LOCATION_PROVIDER, Responses.RESPONSE_LOCATION_ACCURACY, Responses.RESPONSE_LOCATION_TIME, Tables.RESPONSES + "." + Responses.SURVEY_ID, Responses.RESPONSE_SURVEY_LAUNCH_CONTEXT, Responses.RESPONSE_JSON, Tables.RESPONSES + "." + Responses.CAMPAIGN_URN, Campaigns.CAMPAIGN_CREATED}; String select = Responses.RESPONSE_STATUS + "!=" + Response.STATUS_DOWNLOADED + " AND " + Responses.RESPONSE_STATUS + "!=" + Response.STATUS_UPLOADED + " AND " + Responses.RESPONSE_STATUS + "!=" + Response.STATUS_WAITING_FOR_LOCATION; Cursor cursor = cr.query(dataUri, projection, select, null, null); // If there is no data we should just return if(cursor == null || !cursor.moveToFirst()) return; ContentValues cv = new ContentValues(); cv.put(Responses.RESPONSE_STATUS, Response.STATUS_QUEUED); cr.update(dataUri, cv, select, null); for (int i = 0; i < cursor.getCount(); i++) { long responseId = cursor.getLong(cursor.getColumnIndex(Responses._ID)); ContentValues values = new ContentValues(); values.put(Responses.RESPONSE_STATUS, Response.STATUS_UPLOADING); cr.update(Responses.buildResponseUri(responseId), values, null, null); // cr.update(Responses.CONTENT_URI, values, Tables.RESPONSES + "." + Responses._ID + "=" + responseId, null); JSONArray responsesJsonArray = new JSONArray(); JSONObject responseJson = new JSONObject(); final ArrayList<String> photoUUIDs = new ArrayList<String>(); try { responseJson.put("survey_key", cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_UUID))); responseJson.put("time", cursor.getLong(cursor.getColumnIndex(Responses.RESPONSE_TIME))); responseJson.put("timezone", cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_TIMEZONE))); String locationStatus = cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_STATUS)); responseJson.put("location_status", locationStatus); if (! locationStatus.equals(SurveyGeotagService.LOCATION_UNAVAILABLE)) { JSONObject locationJson = new JSONObject(); locationJson.put("latitude", cursor.getDouble(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_LATITUDE))); locationJson.put("longitude", cursor.getDouble(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_LONGITUDE))); String provider = cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_PROVIDER)); locationJson.put("provider", provider); Log.i(TAG, "Response uploaded with " + provider + " location"); locationJson.put("accuracy", cursor.getFloat(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_ACCURACY))); locationJson.put("time", cursor.getLong(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_TIME))); - locationJson.put("timezone", cursor.getLong(cursor.getColumnIndex(Responses.RESPONSE_TIMEZONE))); + locationJson.put("timezone", cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_TIMEZONE))); responseJson.put("location", locationJson); } else { Log.w(TAG, "Response uploaded without a location"); } responseJson.put("survey_id", cursor.getString(cursor.getColumnIndex(Responses.SURVEY_ID))); responseJson.put("survey_launch_context", new JSONObject(cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_SURVEY_LAUNCH_CONTEXT)))); responseJson.put("responses", new JSONArray(cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_JSON)))); ContentResolver cr2 = getContentResolver(); Cursor promptsCursor = cr2.query(Responses.buildPromptResponsesUri(responseId), new String [] {PromptResponses.PROMPT_RESPONSE_VALUE, SurveyPrompts.SURVEY_PROMPT_TYPE}, SurveyPrompts.SURVEY_PROMPT_TYPE + "='photo'", null, null); while (promptsCursor.moveToNext()) { photoUUIDs.add(promptsCursor.getString(promptsCursor.getColumnIndex(PromptResponses.PROMPT_RESPONSE_VALUE))); } promptsCursor.close(); } catch (JSONException e) { throw new RuntimeException(e); } responsesJsonArray.put(responseJson); String campaignUrn = cursor.getString(cursor.getColumnIndex(Responses.CAMPAIGN_URN)); String campaignCreationTimestamp = cursor.getString(cursor.getColumnIndex(Campaigns.CAMPAIGN_CREATED)); File [] photos = Response.getResponseImageUploadDir(this).listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String filename) { if (photoUUIDs.contains(filename.split("\\.")[0])) { return true; } return false; } }); OhmageApi.UploadResponse response = mApi.surveyUpload(serverUrl, username, hashedPassword, OhmageApi.CLIENT_NAME, campaignUrn, campaignCreationTimestamp, responsesJsonArray.toString(), photos); int responseStatus = Response.STATUS_UPLOADED; if (response.getResult() == Result.SUCCESS) { NotificationHelper.hideUploadErrorNotification(this); NotificationHelper.hideAuthNotification(this); } else { responseStatus = Response.STATUS_ERROR_OTHER; switch (response.getResult()) { case FAILURE: Log.e(TAG, "Upload failed due to error codes: " + Utilities.stringArrayToString(response.getErrorCodes(), ", ")); uploadErrorOccurred = true; boolean isAuthenticationError = false; boolean isUserDisabled = false; String errorCode = null; for (String code : response.getErrorCodes()) { if (code.charAt(1) == '2') { authErrorOccurred = true; isAuthenticationError = true; if (code.equals("0201")) { isUserDisabled = true; } } if (code.equals("0700") || code.equals("0707") || code.equals("0703") || code.equals("0710")) { errorCode = code; break; } } if (isUserDisabled) { new SharedPreferencesHelper(this).setUserDisabled(true); } if (isAuthenticationError) { responseStatus = Response.STATUS_ERROR_AUTHENTICATION; } else if ("0700".equals(errorCode)) { responseStatus = Response.STATUS_ERROR_CAMPAIGN_NO_EXIST; } else if ("0707".equals(errorCode)) { responseStatus = Response.STATUS_ERROR_INVALID_USER_ROLE; } else if ("0703".equals(errorCode)) { responseStatus = Response.STATUS_ERROR_CAMPAIGN_STOPPED; } else if ("0710".equals(errorCode)) { responseStatus = Response.STATUS_ERROR_CAMPAIGN_OUT_OF_DATE; } else { responseStatus = Response.STATUS_ERROR_OTHER; } break; case INTERNAL_ERROR: uploadErrorOccurred = true; responseStatus = Response.STATUS_ERROR_OTHER; break; case HTTP_ERROR: responseStatus = Response.STATUS_ERROR_HTTP; break; } } ContentValues cv2 = new ContentValues(); cv2.put(Responses.RESPONSE_STATUS, responseStatus); cr.update(Responses.buildResponseUri(responseId), cv2, null, null); cursor.moveToNext(); } cursor.close(); if (isBackground) { if (authErrorOccurred) { NotificationHelper.showAuthNotification(this); } else if (uploadErrorOccurred) { NotificationHelper.showUploadErrorNotification(this); } } } private void uploadMobility(Intent intent) { sendBroadcast(new Intent(UploadService.MOBILITY_UPLOAD_STARTED)); boolean uploadSensorData = true; SharedPreferencesHelper helper = new SharedPreferencesHelper(this); String username = helper.getUsername(); String hashedPassword = helper.getHashedPassword(); long uploadAfterTimestamp = helper.getLastMobilityUploadTimestamp(); if (uploadAfterTimestamp == 0) { uploadAfterTimestamp = helper.getLoginTimestamp(); } Long now = System.currentTimeMillis(); Cursor c = MobilityInterface.getMobilityCursor(this, uploadAfterTimestamp); OhmageApi.UploadResponse response = new OhmageApi.UploadResponse(OhmageApi.Result.SUCCESS, null); if (c != null && c.getCount() > 0) { Log.i(TAG, "There are " + String.valueOf(c.getCount()) + " mobility points to upload."); c.moveToFirst(); int remainingCount = c.getCount(); int limit = 60; while (remainingCount > 0) { if (remainingCount < limit) { limit = remainingCount; } Log.i(TAG, "Attempting to upload a batch with " + String.valueOf(limit) + " mobility points."); JSONArray mobilityJsonArray = new JSONArray(); for (int i = 0; i < limit; i++) { JSONObject mobilityPointJson = new JSONObject(); try { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Long time = Long.parseLong(c.getString(c.getColumnIndex(MobilityInterface.KEY_TIME))); if (i == limit - 1) { uploadAfterTimestamp = time; } mobilityPointJson.put("id", c.getString(c.getColumnIndex(MobilityInterface.KEY_ID))); mobilityPointJson.put("time", time); mobilityPointJson.put("timezone", c.getString(c.getColumnIndex(MobilityInterface.KEY_TIMEZONE))); if (uploadSensorData) { mobilityPointJson.put("subtype", "sensor_data"); JSONObject dataJson = new JSONObject(); dataJson.put("mode", c.getString(c.getColumnIndex(MobilityInterface.KEY_MODE))); try { dataJson.put("speed", Float.parseFloat(c.getString(c.getColumnIndex(MobilityInterface.KEY_SPEED)))); } catch (NumberFormatException e) { dataJson.put("speed", "NaN"); } catch (JSONException e) { dataJson.put("speed", "NaN"); } String accelDataString = c.getString(c.getColumnIndex(MobilityInterface.KEY_ACCELDATA)); if (accelDataString == null || accelDataString.equals("")) { accelDataString = "[]"; } dataJson.put("accel_data", new JSONArray(accelDataString)); String wifiDataString = c.getString(c.getColumnIndex(MobilityInterface.KEY_WIFIDATA)); if (wifiDataString == null || wifiDataString.equals("")) { wifiDataString = "{}"; } dataJson.put("wifi_data", new JSONObject(wifiDataString)); mobilityPointJson.put("data", dataJson); } else { mobilityPointJson.put("subtype", "mode_only"); mobilityPointJson.put("mode", c.getString(c.getColumnIndex(MobilityInterface.KEY_MODE))); } String locationStatus = c.getString(c.getColumnIndex(MobilityInterface.KEY_STATUS)); mobilityPointJson.put("location_status", locationStatus); if (! locationStatus.equals(SurveyGeotagService.LOCATION_UNAVAILABLE)) { JSONObject locationJson = new JSONObject(); try { locationJson.put("latitude", Double.parseDouble(c.getString(c.getColumnIndex(MobilityInterface.KEY_LATITUDE)))); } catch (NumberFormatException e) { locationJson.put("latitude", "NaN"); } catch (JSONException e) { locationJson.put("latitude", "NaN"); } try { locationJson.put("longitude", Double.parseDouble(c.getString(c.getColumnIndex(MobilityInterface.KEY_LONGITUDE)))); } catch (NumberFormatException e) { locationJson.put("longitude", "NaN"); } catch (JSONException e) { locationJson.put("longitude", "NaN"); } locationJson.put("provider", c.getString(c.getColumnIndex(MobilityInterface.KEY_PROVIDER))); try { locationJson.put("accuracy", Float.parseFloat(c.getString(c.getColumnIndex(MobilityInterface.KEY_ACCURACY)))); } catch (NumberFormatException e) { locationJson.put("accuracy", "NaN"); } catch (JSONException e) { locationJson.put("accuracy", "NaN"); } locationJson.put("time", Long.parseLong(c.getString(c.getColumnIndex(MobilityInterface.KEY_LOC_TIMESTAMP)))); locationJson.put("timezone", c.getString(c.getColumnIndex(MobilityInterface.KEY_TIMEZONE))); mobilityPointJson.put("location", locationJson); } } catch (JSONException e) { Log.e(TAG, "error creating mobility json", e); if(isBackground) NotificationHelper.showMobilityErrorNotification(this); throw new RuntimeException(e); } mobilityJsonArray.put(mobilityPointJson); c.moveToNext(); } response = mApi.mobilityUpload(Config.DEFAULT_SERVER_URL, username, hashedPassword, OhmageApi.CLIENT_NAME, mobilityJsonArray.toString()); if (response.getResult().equals(OhmageApi.Result.SUCCESS)) { Log.i(TAG, "Successfully uploaded " + String.valueOf(limit) + " mobility points."); helper.putLastMobilityUploadTimestamp(uploadAfterTimestamp); remainingCount -= limit; Log.i(TAG, "There are " + String.valueOf(remainingCount) + " mobility points remaining to be uploaded."); NotificationHelper.hideMobilityErrorNotification(this); } else { Log.e(TAG, "Failed to upload mobility points. Cancelling current round of mobility uploads."); switch (response.getResult()) { case FAILURE: Log.e(TAG, "Upload failed due to error codes: " + Utilities.stringArrayToString(response.getErrorCodes(), ", ")); boolean isAuthenticationError = false; boolean isUserDisabled = false; for (String code : response.getErrorCodes()) { if (code.charAt(1) == '2') { isAuthenticationError = true; if (code.equals("0201")) { isUserDisabled = true; } } } if (isUserDisabled) { new SharedPreferencesHelper(this).setUserDisabled(true); } if (isBackground) { if (isAuthenticationError) { NotificationHelper.showAuthNotification(this); } else { NotificationHelper.showMobilityErrorNotification(this); } } break; case INTERNAL_ERROR: Log.e(TAG, "Upload failed due to unknown internal error"); if (isBackground) NotificationHelper.showMobilityErrorNotification(this); break; case HTTP_ERROR: Log.e(TAG, "Upload failed due to network error"); break; } break; } } c.close(); } else { Log.i(TAG, "No mobility points to upload."); } sendBroadcast(new Intent(UploadService.MOBILITY_UPLOAD_FINISHED)); } }
true
true
private void uploadSurveyResponses(Intent intent) { String serverUrl = Config.DEFAULT_SERVER_URL; SharedPreferencesHelper helper = new SharedPreferencesHelper(this); String username = helper.getUsername(); String hashedPassword = helper.getHashedPassword(); boolean uploadErrorOccurred = false; boolean authErrorOccurred = false; DbHelper dbHelper = new DbHelper(this); Uri dataUri = intent.getData(); if(!Responses.isResponseUri(dataUri)) { Log.e(TAG, "Upload service can only be called with a response URI"); return; } ContentResolver cr = getContentResolver(); String [] projection = new String [] { Tables.RESPONSES + "." + Responses._ID, Responses.RESPONSE_UUID, Responses.RESPONSE_DATE, Responses.RESPONSE_TIME, Responses.RESPONSE_TIMEZONE, Responses.RESPONSE_LOCATION_STATUS, Responses.RESPONSE_LOCATION_LATITUDE, Responses.RESPONSE_LOCATION_LONGITUDE, Responses.RESPONSE_LOCATION_PROVIDER, Responses.RESPONSE_LOCATION_ACCURACY, Responses.RESPONSE_LOCATION_TIME, Tables.RESPONSES + "." + Responses.SURVEY_ID, Responses.RESPONSE_SURVEY_LAUNCH_CONTEXT, Responses.RESPONSE_JSON, Tables.RESPONSES + "." + Responses.CAMPAIGN_URN, Campaigns.CAMPAIGN_CREATED}; String select = Responses.RESPONSE_STATUS + "!=" + Response.STATUS_DOWNLOADED + " AND " + Responses.RESPONSE_STATUS + "!=" + Response.STATUS_UPLOADED + " AND " + Responses.RESPONSE_STATUS + "!=" + Response.STATUS_WAITING_FOR_LOCATION; Cursor cursor = cr.query(dataUri, projection, select, null, null); // If there is no data we should just return if(cursor == null || !cursor.moveToFirst()) return; ContentValues cv = new ContentValues(); cv.put(Responses.RESPONSE_STATUS, Response.STATUS_QUEUED); cr.update(dataUri, cv, select, null); for (int i = 0; i < cursor.getCount(); i++) { long responseId = cursor.getLong(cursor.getColumnIndex(Responses._ID)); ContentValues values = new ContentValues(); values.put(Responses.RESPONSE_STATUS, Response.STATUS_UPLOADING); cr.update(Responses.buildResponseUri(responseId), values, null, null); // cr.update(Responses.CONTENT_URI, values, Tables.RESPONSES + "." + Responses._ID + "=" + responseId, null); JSONArray responsesJsonArray = new JSONArray(); JSONObject responseJson = new JSONObject(); final ArrayList<String> photoUUIDs = new ArrayList<String>(); try { responseJson.put("survey_key", cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_UUID))); responseJson.put("time", cursor.getLong(cursor.getColumnIndex(Responses.RESPONSE_TIME))); responseJson.put("timezone", cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_TIMEZONE))); String locationStatus = cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_STATUS)); responseJson.put("location_status", locationStatus); if (! locationStatus.equals(SurveyGeotagService.LOCATION_UNAVAILABLE)) { JSONObject locationJson = new JSONObject(); locationJson.put("latitude", cursor.getDouble(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_LATITUDE))); locationJson.put("longitude", cursor.getDouble(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_LONGITUDE))); String provider = cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_PROVIDER)); locationJson.put("provider", provider); Log.i(TAG, "Response uploaded with " + provider + " location"); locationJson.put("accuracy", cursor.getFloat(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_ACCURACY))); locationJson.put("time", cursor.getLong(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_TIME))); locationJson.put("timezone", cursor.getLong(cursor.getColumnIndex(Responses.RESPONSE_TIMEZONE))); responseJson.put("location", locationJson); } else { Log.w(TAG, "Response uploaded without a location"); } responseJson.put("survey_id", cursor.getString(cursor.getColumnIndex(Responses.SURVEY_ID))); responseJson.put("survey_launch_context", new JSONObject(cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_SURVEY_LAUNCH_CONTEXT)))); responseJson.put("responses", new JSONArray(cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_JSON)))); ContentResolver cr2 = getContentResolver(); Cursor promptsCursor = cr2.query(Responses.buildPromptResponsesUri(responseId), new String [] {PromptResponses.PROMPT_RESPONSE_VALUE, SurveyPrompts.SURVEY_PROMPT_TYPE}, SurveyPrompts.SURVEY_PROMPT_TYPE + "='photo'", null, null); while (promptsCursor.moveToNext()) { photoUUIDs.add(promptsCursor.getString(promptsCursor.getColumnIndex(PromptResponses.PROMPT_RESPONSE_VALUE))); } promptsCursor.close(); } catch (JSONException e) { throw new RuntimeException(e); } responsesJsonArray.put(responseJson); String campaignUrn = cursor.getString(cursor.getColumnIndex(Responses.CAMPAIGN_URN)); String campaignCreationTimestamp = cursor.getString(cursor.getColumnIndex(Campaigns.CAMPAIGN_CREATED)); File [] photos = Response.getResponseImageUploadDir(this).listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String filename) { if (photoUUIDs.contains(filename.split("\\.")[0])) { return true; } return false; } }); OhmageApi.UploadResponse response = mApi.surveyUpload(serverUrl, username, hashedPassword, OhmageApi.CLIENT_NAME, campaignUrn, campaignCreationTimestamp, responsesJsonArray.toString(), photos); int responseStatus = Response.STATUS_UPLOADED; if (response.getResult() == Result.SUCCESS) { NotificationHelper.hideUploadErrorNotification(this); NotificationHelper.hideAuthNotification(this); } else { responseStatus = Response.STATUS_ERROR_OTHER; switch (response.getResult()) { case FAILURE: Log.e(TAG, "Upload failed due to error codes: " + Utilities.stringArrayToString(response.getErrorCodes(), ", ")); uploadErrorOccurred = true; boolean isAuthenticationError = false; boolean isUserDisabled = false; String errorCode = null; for (String code : response.getErrorCodes()) { if (code.charAt(1) == '2') { authErrorOccurred = true; isAuthenticationError = true; if (code.equals("0201")) { isUserDisabled = true; } } if (code.equals("0700") || code.equals("0707") || code.equals("0703") || code.equals("0710")) { errorCode = code; break; } } if (isUserDisabled) { new SharedPreferencesHelper(this).setUserDisabled(true); } if (isAuthenticationError) { responseStatus = Response.STATUS_ERROR_AUTHENTICATION; } else if ("0700".equals(errorCode)) { responseStatus = Response.STATUS_ERROR_CAMPAIGN_NO_EXIST; } else if ("0707".equals(errorCode)) { responseStatus = Response.STATUS_ERROR_INVALID_USER_ROLE; } else if ("0703".equals(errorCode)) { responseStatus = Response.STATUS_ERROR_CAMPAIGN_STOPPED; } else if ("0710".equals(errorCode)) { responseStatus = Response.STATUS_ERROR_CAMPAIGN_OUT_OF_DATE; } else { responseStatus = Response.STATUS_ERROR_OTHER; } break; case INTERNAL_ERROR: uploadErrorOccurred = true; responseStatus = Response.STATUS_ERROR_OTHER; break; case HTTP_ERROR: responseStatus = Response.STATUS_ERROR_HTTP; break; } } ContentValues cv2 = new ContentValues(); cv2.put(Responses.RESPONSE_STATUS, responseStatus); cr.update(Responses.buildResponseUri(responseId), cv2, null, null); cursor.moveToNext(); } cursor.close(); if (isBackground) { if (authErrorOccurred) { NotificationHelper.showAuthNotification(this); } else if (uploadErrorOccurred) { NotificationHelper.showUploadErrorNotification(this); } } }
private void uploadSurveyResponses(Intent intent) { String serverUrl = Config.DEFAULT_SERVER_URL; SharedPreferencesHelper helper = new SharedPreferencesHelper(this); String username = helper.getUsername(); String hashedPassword = helper.getHashedPassword(); boolean uploadErrorOccurred = false; boolean authErrorOccurred = false; DbHelper dbHelper = new DbHelper(this); Uri dataUri = intent.getData(); if(!Responses.isResponseUri(dataUri)) { Log.e(TAG, "Upload service can only be called with a response URI"); return; } ContentResolver cr = getContentResolver(); String [] projection = new String [] { Tables.RESPONSES + "." + Responses._ID, Responses.RESPONSE_UUID, Responses.RESPONSE_DATE, Responses.RESPONSE_TIME, Responses.RESPONSE_TIMEZONE, Responses.RESPONSE_LOCATION_STATUS, Responses.RESPONSE_LOCATION_LATITUDE, Responses.RESPONSE_LOCATION_LONGITUDE, Responses.RESPONSE_LOCATION_PROVIDER, Responses.RESPONSE_LOCATION_ACCURACY, Responses.RESPONSE_LOCATION_TIME, Tables.RESPONSES + "." + Responses.SURVEY_ID, Responses.RESPONSE_SURVEY_LAUNCH_CONTEXT, Responses.RESPONSE_JSON, Tables.RESPONSES + "." + Responses.CAMPAIGN_URN, Campaigns.CAMPAIGN_CREATED}; String select = Responses.RESPONSE_STATUS + "!=" + Response.STATUS_DOWNLOADED + " AND " + Responses.RESPONSE_STATUS + "!=" + Response.STATUS_UPLOADED + " AND " + Responses.RESPONSE_STATUS + "!=" + Response.STATUS_WAITING_FOR_LOCATION; Cursor cursor = cr.query(dataUri, projection, select, null, null); // If there is no data we should just return if(cursor == null || !cursor.moveToFirst()) return; ContentValues cv = new ContentValues(); cv.put(Responses.RESPONSE_STATUS, Response.STATUS_QUEUED); cr.update(dataUri, cv, select, null); for (int i = 0; i < cursor.getCount(); i++) { long responseId = cursor.getLong(cursor.getColumnIndex(Responses._ID)); ContentValues values = new ContentValues(); values.put(Responses.RESPONSE_STATUS, Response.STATUS_UPLOADING); cr.update(Responses.buildResponseUri(responseId), values, null, null); // cr.update(Responses.CONTENT_URI, values, Tables.RESPONSES + "." + Responses._ID + "=" + responseId, null); JSONArray responsesJsonArray = new JSONArray(); JSONObject responseJson = new JSONObject(); final ArrayList<String> photoUUIDs = new ArrayList<String>(); try { responseJson.put("survey_key", cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_UUID))); responseJson.put("time", cursor.getLong(cursor.getColumnIndex(Responses.RESPONSE_TIME))); responseJson.put("timezone", cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_TIMEZONE))); String locationStatus = cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_STATUS)); responseJson.put("location_status", locationStatus); if (! locationStatus.equals(SurveyGeotagService.LOCATION_UNAVAILABLE)) { JSONObject locationJson = new JSONObject(); locationJson.put("latitude", cursor.getDouble(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_LATITUDE))); locationJson.put("longitude", cursor.getDouble(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_LONGITUDE))); String provider = cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_PROVIDER)); locationJson.put("provider", provider); Log.i(TAG, "Response uploaded with " + provider + " location"); locationJson.put("accuracy", cursor.getFloat(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_ACCURACY))); locationJson.put("time", cursor.getLong(cursor.getColumnIndex(Responses.RESPONSE_LOCATION_TIME))); locationJson.put("timezone", cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_TIMEZONE))); responseJson.put("location", locationJson); } else { Log.w(TAG, "Response uploaded without a location"); } responseJson.put("survey_id", cursor.getString(cursor.getColumnIndex(Responses.SURVEY_ID))); responseJson.put("survey_launch_context", new JSONObject(cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_SURVEY_LAUNCH_CONTEXT)))); responseJson.put("responses", new JSONArray(cursor.getString(cursor.getColumnIndex(Responses.RESPONSE_JSON)))); ContentResolver cr2 = getContentResolver(); Cursor promptsCursor = cr2.query(Responses.buildPromptResponsesUri(responseId), new String [] {PromptResponses.PROMPT_RESPONSE_VALUE, SurveyPrompts.SURVEY_PROMPT_TYPE}, SurveyPrompts.SURVEY_PROMPT_TYPE + "='photo'", null, null); while (promptsCursor.moveToNext()) { photoUUIDs.add(promptsCursor.getString(promptsCursor.getColumnIndex(PromptResponses.PROMPT_RESPONSE_VALUE))); } promptsCursor.close(); } catch (JSONException e) { throw new RuntimeException(e); } responsesJsonArray.put(responseJson); String campaignUrn = cursor.getString(cursor.getColumnIndex(Responses.CAMPAIGN_URN)); String campaignCreationTimestamp = cursor.getString(cursor.getColumnIndex(Campaigns.CAMPAIGN_CREATED)); File [] photos = Response.getResponseImageUploadDir(this).listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String filename) { if (photoUUIDs.contains(filename.split("\\.")[0])) { return true; } return false; } }); OhmageApi.UploadResponse response = mApi.surveyUpload(serverUrl, username, hashedPassword, OhmageApi.CLIENT_NAME, campaignUrn, campaignCreationTimestamp, responsesJsonArray.toString(), photos); int responseStatus = Response.STATUS_UPLOADED; if (response.getResult() == Result.SUCCESS) { NotificationHelper.hideUploadErrorNotification(this); NotificationHelper.hideAuthNotification(this); } else { responseStatus = Response.STATUS_ERROR_OTHER; switch (response.getResult()) { case FAILURE: Log.e(TAG, "Upload failed due to error codes: " + Utilities.stringArrayToString(response.getErrorCodes(), ", ")); uploadErrorOccurred = true; boolean isAuthenticationError = false; boolean isUserDisabled = false; String errorCode = null; for (String code : response.getErrorCodes()) { if (code.charAt(1) == '2') { authErrorOccurred = true; isAuthenticationError = true; if (code.equals("0201")) { isUserDisabled = true; } } if (code.equals("0700") || code.equals("0707") || code.equals("0703") || code.equals("0710")) { errorCode = code; break; } } if (isUserDisabled) { new SharedPreferencesHelper(this).setUserDisabled(true); } if (isAuthenticationError) { responseStatus = Response.STATUS_ERROR_AUTHENTICATION; } else if ("0700".equals(errorCode)) { responseStatus = Response.STATUS_ERROR_CAMPAIGN_NO_EXIST; } else if ("0707".equals(errorCode)) { responseStatus = Response.STATUS_ERROR_INVALID_USER_ROLE; } else if ("0703".equals(errorCode)) { responseStatus = Response.STATUS_ERROR_CAMPAIGN_STOPPED; } else if ("0710".equals(errorCode)) { responseStatus = Response.STATUS_ERROR_CAMPAIGN_OUT_OF_DATE; } else { responseStatus = Response.STATUS_ERROR_OTHER; } break; case INTERNAL_ERROR: uploadErrorOccurred = true; responseStatus = Response.STATUS_ERROR_OTHER; break; case HTTP_ERROR: responseStatus = Response.STATUS_ERROR_HTTP; break; } } ContentValues cv2 = new ContentValues(); cv2.put(Responses.RESPONSE_STATUS, responseStatus); cr.update(Responses.buildResponseUri(responseId), cv2, null, null); cursor.moveToNext(); } cursor.close(); if (isBackground) { if (authErrorOccurred) { NotificationHelper.showAuthNotification(this); } else if (uploadErrorOccurred) { NotificationHelper.showUploadErrorNotification(this); } } }
diff --git a/drools-planner-core/src/main/java/org/drools/planner/config/constructionheuristic/greedyFit/GreedyFitSolverPhaseConfig.java b/drools-planner-core/src/main/java/org/drools/planner/config/constructionheuristic/greedyFit/GreedyFitSolverPhaseConfig.java index 5f9c0263..0a519b73 100644 --- a/drools-planner-core/src/main/java/org/drools/planner/config/constructionheuristic/greedyFit/GreedyFitSolverPhaseConfig.java +++ b/drools-planner-core/src/main/java/org/drools/planner/config/constructionheuristic/greedyFit/GreedyFitSolverPhaseConfig.java @@ -1,144 +1,145 @@ /* * Copyright 2011 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.drools.planner.config.constructionheuristic.greedyFit; import java.util.ArrayList; import java.util.List; import java.util.Set; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamImplicit; import org.drools.planner.config.EnvironmentMode; import org.drools.planner.config.phase.SolverPhaseConfig; import org.drools.planner.core.constructionheuristic.greedyFit.DefaultGreedyFitSolverPhase; import org.drools.planner.core.constructionheuristic.greedyFit.GreedyFitSolverPhase; import org.drools.planner.core.constructionheuristic.greedyFit.decider.DefaultGreedyDecider; import org.drools.planner.core.constructionheuristic.greedyFit.decider.GreedyDecider; import org.drools.planner.core.constructionheuristic.greedyFit.decider.PickEarlyGreedyFitType; import org.drools.planner.core.constructionheuristic.greedyFit.selector.GreedyPlanningEntitySelector; import org.drools.planner.core.domain.entity.PlanningEntityDescriptor; import org.drools.planner.core.domain.solution.SolutionDescriptor; import org.drools.planner.core.domain.variable.PlanningVariableDescriptor; import org.drools.planner.core.heuristic.selector.entity.PlanningEntitySelector; import org.drools.planner.core.heuristic.selector.variable.PlanningValueSelector; import org.drools.planner.core.heuristic.selector.variable.PlanningValueWalker; import org.drools.planner.core.heuristic.selector.variable.PlanningVariableWalker; import org.drools.planner.core.score.definition.ScoreDefinition; import org.drools.planner.core.termination.Termination; @XStreamAlias("greedyFit") public class GreedyFitSolverPhaseConfig extends SolverPhaseConfig { // Warning: all fields are null (and not defaulted) because they can be inherited // and also because the input config file should match the output config file @XStreamImplicit(itemFieldName = "greedyFitPlanningEntity") protected List<GreedyFitPlanningEntityConfig> greedyFitPlanningEntityConfigList = null; protected PickEarlyGreedyFitType pickEarlyGreedyFitType = null; public List<GreedyFitPlanningEntityConfig> getGreedyFitPlanningEntityConfigList() { return greedyFitPlanningEntityConfigList; } public void setGreedyFitPlanningEntityConfigList(List<GreedyFitPlanningEntityConfig> greedyFitPlanningEntityConfigList) { this.greedyFitPlanningEntityConfigList = greedyFitPlanningEntityConfigList; } public PickEarlyGreedyFitType getPickEarlyGreedyFitType() { return pickEarlyGreedyFitType; } public void setPickEarlyGreedyFitType(PickEarlyGreedyFitType pickEarlyGreedyFitType) { this.pickEarlyGreedyFitType = pickEarlyGreedyFitType; } // ************************************************************************ // Builder methods // ************************************************************************ public GreedyFitSolverPhase buildSolverPhase(EnvironmentMode environmentMode, SolutionDescriptor solutionDescriptor, ScoreDefinition scoreDefinition, Termination solverTermination) { DefaultGreedyFitSolverPhase greedySolverPhase = new DefaultGreedyFitSolverPhase(); configureSolverPhase(greedySolverPhase, environmentMode, scoreDefinition, solverTermination); greedySolverPhase.setGreedyPlanningEntitySelector(buildGreedyPlanningEntitySelector(solutionDescriptor)); greedySolverPhase.setGreedyDecider(buildGreedyDecider(solutionDescriptor, environmentMode)); if (environmentMode == EnvironmentMode.DEBUG || environmentMode == EnvironmentMode.TRACE) { greedySolverPhase.setAssertStepScoreIsUncorrupted(true); } return greedySolverPhase; } private GreedyPlanningEntitySelector buildGreedyPlanningEntitySelector(SolutionDescriptor solutionDescriptor) { GreedyPlanningEntitySelector greedyPlanningEntitySelector = new GreedyPlanningEntitySelector(); List<PlanningEntitySelector> planningEntitySelectorList = new ArrayList<PlanningEntitySelector>(greedyFitPlanningEntityConfigList.size()); for (GreedyFitPlanningEntityConfig greedyFitPlanningEntityConfig : greedyFitPlanningEntityConfigList) { planningEntitySelectorList.add(greedyFitPlanningEntityConfig.buildPlanningEntitySelector(solutionDescriptor)); } greedyPlanningEntitySelector.setPlanningEntitySelectorList(planningEntitySelectorList); return greedyPlanningEntitySelector; } private GreedyDecider buildGreedyDecider(SolutionDescriptor solutionDescriptor, EnvironmentMode environmentMode) { DefaultGreedyDecider greedyDecider = new DefaultGreedyDecider(); PickEarlyGreedyFitType pickEarlyGreedyFitType = (this.pickEarlyGreedyFitType == null) ? PickEarlyGreedyFitType.NEVER : this.pickEarlyGreedyFitType; Set<Class<?>> planningEntityImplementationClassSet = solutionDescriptor.getPlanningEntityImplementationClassSet(); if (planningEntityImplementationClassSet.size() != 1) { // TODO Multiple MUST BE SUPPORTED TOO throw new UnsupportedOperationException("Currently the greedyFit implementation only supports " + "1 planningEntityImplementationClass."); } Class<?> planningEntityImplementationClass = planningEntityImplementationClassSet.iterator().next(); PlanningEntityDescriptor planningEntityDescriptor = solutionDescriptor.getPlanningEntityDescriptor(planningEntityImplementationClass); PlanningVariableWalker planningVariableWalker = new PlanningVariableWalker(planningEntityDescriptor); List<PlanningValueWalker> planningValueWalkerList = new ArrayList<PlanningValueWalker>(); for (PlanningVariableDescriptor planningVariableDescriptor : planningEntityDescriptor.getPlanningVariableDescriptors()) { PlanningValueSelector planningValueSelector = new PlanningValueSelector(planningVariableDescriptor); + // TODO should be configured to do BEST etc. PlanningValueWalker planningValueWalker = new PlanningValueWalker( planningVariableDescriptor, planningValueSelector); planningValueWalkerList.add(planningValueWalker); } planningVariableWalker.setPlanningValueWalkerList(planningValueWalkerList); greedyDecider.setPlanningVariableWalker(planningVariableWalker); greedyDecider.setPickEarlyGreedyFitType(pickEarlyGreedyFitType); if (environmentMode == EnvironmentMode.TRACE) { greedyDecider.setAssertMoveScoreIsUncorrupted(true); } return greedyDecider; } public void inherit(GreedyFitSolverPhaseConfig inheritedConfig) { super.inherit(inheritedConfig); if (greedyFitPlanningEntityConfigList == null) { greedyFitPlanningEntityConfigList = inheritedConfig.getGreedyFitPlanningEntityConfigList(); } else if (inheritedConfig.getGreedyFitPlanningEntityConfigList() != null) { // The inherited greedyFitPlanningEntityConfigList should be before the non-inherited one List<GreedyFitPlanningEntityConfig> mergedList = new ArrayList<GreedyFitPlanningEntityConfig>( inheritedConfig.getGreedyFitPlanningEntityConfigList()); mergedList.addAll(greedyFitPlanningEntityConfigList); greedyFitPlanningEntityConfigList = mergedList; } if (pickEarlyGreedyFitType == null) { pickEarlyGreedyFitType = inheritedConfig.getPickEarlyGreedyFitType(); } } }
true
true
private GreedyDecider buildGreedyDecider(SolutionDescriptor solutionDescriptor, EnvironmentMode environmentMode) { DefaultGreedyDecider greedyDecider = new DefaultGreedyDecider(); PickEarlyGreedyFitType pickEarlyGreedyFitType = (this.pickEarlyGreedyFitType == null) ? PickEarlyGreedyFitType.NEVER : this.pickEarlyGreedyFitType; Set<Class<?>> planningEntityImplementationClassSet = solutionDescriptor.getPlanningEntityImplementationClassSet(); if (planningEntityImplementationClassSet.size() != 1) { // TODO Multiple MUST BE SUPPORTED TOO throw new UnsupportedOperationException("Currently the greedyFit implementation only supports " + "1 planningEntityImplementationClass."); } Class<?> planningEntityImplementationClass = planningEntityImplementationClassSet.iterator().next(); PlanningEntityDescriptor planningEntityDescriptor = solutionDescriptor.getPlanningEntityDescriptor(planningEntityImplementationClass); PlanningVariableWalker planningVariableWalker = new PlanningVariableWalker(planningEntityDescriptor); List<PlanningValueWalker> planningValueWalkerList = new ArrayList<PlanningValueWalker>(); for (PlanningVariableDescriptor planningVariableDescriptor : planningEntityDescriptor.getPlanningVariableDescriptors()) { PlanningValueSelector planningValueSelector = new PlanningValueSelector(planningVariableDescriptor); PlanningValueWalker planningValueWalker = new PlanningValueWalker( planningVariableDescriptor, planningValueSelector); planningValueWalkerList.add(planningValueWalker); } planningVariableWalker.setPlanningValueWalkerList(planningValueWalkerList); greedyDecider.setPlanningVariableWalker(planningVariableWalker); greedyDecider.setPickEarlyGreedyFitType(pickEarlyGreedyFitType); if (environmentMode == EnvironmentMode.TRACE) { greedyDecider.setAssertMoveScoreIsUncorrupted(true); } return greedyDecider; }
private GreedyDecider buildGreedyDecider(SolutionDescriptor solutionDescriptor, EnvironmentMode environmentMode) { DefaultGreedyDecider greedyDecider = new DefaultGreedyDecider(); PickEarlyGreedyFitType pickEarlyGreedyFitType = (this.pickEarlyGreedyFitType == null) ? PickEarlyGreedyFitType.NEVER : this.pickEarlyGreedyFitType; Set<Class<?>> planningEntityImplementationClassSet = solutionDescriptor.getPlanningEntityImplementationClassSet(); if (planningEntityImplementationClassSet.size() != 1) { // TODO Multiple MUST BE SUPPORTED TOO throw new UnsupportedOperationException("Currently the greedyFit implementation only supports " + "1 planningEntityImplementationClass."); } Class<?> planningEntityImplementationClass = planningEntityImplementationClassSet.iterator().next(); PlanningEntityDescriptor planningEntityDescriptor = solutionDescriptor.getPlanningEntityDescriptor(planningEntityImplementationClass); PlanningVariableWalker planningVariableWalker = new PlanningVariableWalker(planningEntityDescriptor); List<PlanningValueWalker> planningValueWalkerList = new ArrayList<PlanningValueWalker>(); for (PlanningVariableDescriptor planningVariableDescriptor : planningEntityDescriptor.getPlanningVariableDescriptors()) { PlanningValueSelector planningValueSelector = new PlanningValueSelector(planningVariableDescriptor); // TODO should be configured to do BEST etc. PlanningValueWalker planningValueWalker = new PlanningValueWalker( planningVariableDescriptor, planningValueSelector); planningValueWalkerList.add(planningValueWalker); } planningVariableWalker.setPlanningValueWalkerList(planningValueWalkerList); greedyDecider.setPlanningVariableWalker(planningVariableWalker); greedyDecider.setPickEarlyGreedyFitType(pickEarlyGreedyFitType); if (environmentMode == EnvironmentMode.TRACE) { greedyDecider.setAssertMoveScoreIsUncorrupted(true); } return greedyDecider; }
diff --git a/jgsf/src/main/java/com/jenjinstudios/message/ExecutablePublicKeyMessage.java b/jgsf/src/main/java/com/jenjinstudios/message/ExecutablePublicKeyMessage.java index e0b55d2f..cc839b57 100644 --- a/jgsf/src/main/java/com/jenjinstudios/message/ExecutablePublicKeyMessage.java +++ b/jgsf/src/main/java/com/jenjinstudios/message/ExecutablePublicKeyMessage.java @@ -1,85 +1,85 @@ package com.jenjinstudios.message; import com.jenjinstudios.io.MessageInputStream; import com.jenjinstudios.net.ClientHandler; import javax.crypto.*; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; import java.util.logging.Level; import java.util.logging.Logger; /** * This class handles processing a PublicKeyMessage from the client. * @author Caleb Brinkman */ public class ExecutablePublicKeyMessage extends ServerExecutableMessage { /** The Logger for this class. */ private static final Logger LOGGER = Logger.getLogger(ExecutablePublicKeyMessage.class.getName()); /** * Construct a new ExecutableMessage. Must be implemented by subclasses. * @param handler The handler using this ExecutableMessage. * @param message The message. */ public ExecutablePublicKeyMessage(ClientHandler handler, Message message) { super(handler, message); } @Override public void runSynced() { } @Override public void runASync() { Message aesMessage = new Message("AESKeyMessage"); byte[] encryptedAESKey = MessageInputStream.NO_KEY; - try // TODO Make sure error is handled gracefully + try { // Generate an AES key. KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(128); byte[] aesKeyBytes = keyGenerator.generateKey().getEncoded(); // Set the output stream and input stream aes key for the client handler. getClientHandler().setAESKey(aesKeyBytes); // Get the public key from the message. byte[] publicKeyBytes = (byte[]) getMessage().getArgument("key"); PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBytes)); // Create a cipher using the public key, and encrypt the AES key. Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); encryptedAESKey = cipher.doFinal(aesKeyBytes); } catch (NoSuchAlgorithmException e) { LOGGER.log(Level.SEVERE, "Unable to create AES key!", e); } catch (InvalidKeySpecException e) { LOGGER.log(Level.SEVERE, "Unable to create public key from received bytes!", e); } catch (NoSuchPaddingException | BadPaddingException e) { LOGGER.log(Level.SEVERE, "Incorrect padding specified in RSA encryption?!?", e); } catch (InvalidKeyException e) { LOGGER.log(Level.SEVERE, "Unable to encrypt RSA, invalid key received!", e); } catch (IllegalBlockSizeException e) { LOGGER.log(Level.SEVERE, "Illegal block size?!?", e); } // Construct the AESKeyMessage aesMessage.setArgument("key", encryptedAESKey); // Send the AESKeyMessage getClientHandler().queueMessage(aesMessage); } }
true
true
public void runASync() { Message aesMessage = new Message("AESKeyMessage"); byte[] encryptedAESKey = MessageInputStream.NO_KEY; try // TODO Make sure error is handled gracefully { // Generate an AES key. KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(128); byte[] aesKeyBytes = keyGenerator.generateKey().getEncoded(); // Set the output stream and input stream aes key for the client handler. getClientHandler().setAESKey(aesKeyBytes); // Get the public key from the message. byte[] publicKeyBytes = (byte[]) getMessage().getArgument("key"); PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBytes)); // Create a cipher using the public key, and encrypt the AES key. Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); encryptedAESKey = cipher.doFinal(aesKeyBytes); } catch (NoSuchAlgorithmException e) { LOGGER.log(Level.SEVERE, "Unable to create AES key!", e); } catch (InvalidKeySpecException e) { LOGGER.log(Level.SEVERE, "Unable to create public key from received bytes!", e); } catch (NoSuchPaddingException | BadPaddingException e) { LOGGER.log(Level.SEVERE, "Incorrect padding specified in RSA encryption?!?", e); } catch (InvalidKeyException e) { LOGGER.log(Level.SEVERE, "Unable to encrypt RSA, invalid key received!", e); } catch (IllegalBlockSizeException e) { LOGGER.log(Level.SEVERE, "Illegal block size?!?", e); } // Construct the AESKeyMessage aesMessage.setArgument("key", encryptedAESKey); // Send the AESKeyMessage getClientHandler().queueMessage(aesMessage); }
public void runASync() { Message aesMessage = new Message("AESKeyMessage"); byte[] encryptedAESKey = MessageInputStream.NO_KEY; try { // Generate an AES key. KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(128); byte[] aesKeyBytes = keyGenerator.generateKey().getEncoded(); // Set the output stream and input stream aes key for the client handler. getClientHandler().setAESKey(aesKeyBytes); // Get the public key from the message. byte[] publicKeyBytes = (byte[]) getMessage().getArgument("key"); PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBytes)); // Create a cipher using the public key, and encrypt the AES key. Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); encryptedAESKey = cipher.doFinal(aesKeyBytes); } catch (NoSuchAlgorithmException e) { LOGGER.log(Level.SEVERE, "Unable to create AES key!", e); } catch (InvalidKeySpecException e) { LOGGER.log(Level.SEVERE, "Unable to create public key from received bytes!", e); } catch (NoSuchPaddingException | BadPaddingException e) { LOGGER.log(Level.SEVERE, "Incorrect padding specified in RSA encryption?!?", e); } catch (InvalidKeyException e) { LOGGER.log(Level.SEVERE, "Unable to encrypt RSA, invalid key received!", e); } catch (IllegalBlockSizeException e) { LOGGER.log(Level.SEVERE, "Illegal block size?!?", e); } // Construct the AESKeyMessage aesMessage.setArgument("key", encryptedAESKey); // Send the AESKeyMessage getClientHandler().queueMessage(aesMessage); }
diff --git a/src/com/example/memopad/MemoList.java b/src/com/example/memopad/MemoList.java index 929b285..d940e7c 100644 --- a/src/com/example/memopad/MemoList.java +++ b/src/com/example/memopad/MemoList.java @@ -1,39 +1,39 @@ package com.example.memopad; import android.app.ListActivity; import android.os.Bundle; import android.view.View; import android.widget.ListView; //added imports import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.widget.SimpleCursorAdapter; import android.content.Intent; public class MemoList extends ListActivity { static final String [] cols = {"title","memo", android.provider.BaseColumns._ID,}; MemoDBHelper memos; //cols is gotten when searching database @Override protected void onListItemClick(ListView l, View v, int position, long id) { // TODO Auto-generated method stub super.onListItemClick(l, v, position, id); } @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.memolist); - showMemos(getMemos()); + showMemos(getMemos());//getMemos() is Undefined. super.onCreate(savedInstanceState); } public MemoList() { // TODO Auto-generated constructor stub } }//class
true
true
protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.memolist); showMemos(getMemos()); super.onCreate(savedInstanceState); }
protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.memolist); showMemos(getMemos());//getMemos() is Undefined. super.onCreate(savedInstanceState); }
diff --git a/SARA/src/sara/AddHighlightServlet.java b/SARA/src/sara/AddHighlightServlet.java index 1fa5a9c..01316eb 100644 --- a/SARA/src/sara/AddHighlightServlet.java +++ b/SARA/src/sara/AddHighlightServlet.java @@ -1,64 +1,64 @@ package sara; import com.google.gson.Gson; import java.io.IOException; import javax.servlet.http.*; import sara.SARADocument; import sara.Highlight; import sara.Selection; import java.util.Arrays; import sara.HighlightService; import com.googlecode.objectify.*; import com.googlecode.objectify.annotation.*; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; public class AddHighlightServlet extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { System.out.println(req.getParameter("nodeID")); if(req.getParameter("nodeID") != null) { //all we actually need is a selection to create a highlight. String document = req.getParameter("document"); System.out.println(document); String comment = "" + req.getParameter("comment"); System.out.println(comment); //String difficulty = "" + req.getParameter("difficulty"); int difficulty = 0; //String usefulness = "" + req.getParameter("usefulness"); String userid = ""; UserService userService = UserServiceFactory.getUserService(); if(req.getUserPrincipal() != null) { System.out.println(req.getUserPrincipal().getName()); userid = req.getUserPrincipal().getName(); } String nodeID = "" + req.getParameter("nodeID"); System.out.println(nodeID); int startOffset = (new Integer(req.getParameter("startOffset"))).intValue(); System.out.println(startOffset); int offsetDelta = (new Integer(req.getParameter("offsetDelta"))).intValue(); int privacy = (new Integer(req.getParameter("privacy"))).intValue(); System.out.println(offsetDelta); //chang Key<SARADocument> dockey = new Key<SARADocument>(SARADocument.class, new Long(document)); - Highlight highlight = new Highlight(dockey, comment, difficulty, 50, user, nodeID, startOffset, offsetDelta, privacy); + Highlight highlight = new Highlight(dockey, comment, difficulty, 50, userid, nodeID, startOffset, offsetDelta, privacy); HighlightService hs = new HighlightService(); //chang hs.addHighlight(highlight); System.out.println(highlight.toJson()); } } }
true
true
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { System.out.println(req.getParameter("nodeID")); if(req.getParameter("nodeID") != null) { //all we actually need is a selection to create a highlight. String document = req.getParameter("document"); System.out.println(document); String comment = "" + req.getParameter("comment"); System.out.println(comment); //String difficulty = "" + req.getParameter("difficulty"); int difficulty = 0; //String usefulness = "" + req.getParameter("usefulness"); String userid = ""; UserService userService = UserServiceFactory.getUserService(); if(req.getUserPrincipal() != null) { System.out.println(req.getUserPrincipal().getName()); userid = req.getUserPrincipal().getName(); } String nodeID = "" + req.getParameter("nodeID"); System.out.println(nodeID); int startOffset = (new Integer(req.getParameter("startOffset"))).intValue(); System.out.println(startOffset); int offsetDelta = (new Integer(req.getParameter("offsetDelta"))).intValue(); int privacy = (new Integer(req.getParameter("privacy"))).intValue(); System.out.println(offsetDelta); //chang Key<SARADocument> dockey = new Key<SARADocument>(SARADocument.class, new Long(document)); Highlight highlight = new Highlight(dockey, comment, difficulty, 50, user, nodeID, startOffset, offsetDelta, privacy); HighlightService hs = new HighlightService(); //chang hs.addHighlight(highlight); System.out.println(highlight.toJson()); } }
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { System.out.println(req.getParameter("nodeID")); if(req.getParameter("nodeID") != null) { //all we actually need is a selection to create a highlight. String document = req.getParameter("document"); System.out.println(document); String comment = "" + req.getParameter("comment"); System.out.println(comment); //String difficulty = "" + req.getParameter("difficulty"); int difficulty = 0; //String usefulness = "" + req.getParameter("usefulness"); String userid = ""; UserService userService = UserServiceFactory.getUserService(); if(req.getUserPrincipal() != null) { System.out.println(req.getUserPrincipal().getName()); userid = req.getUserPrincipal().getName(); } String nodeID = "" + req.getParameter("nodeID"); System.out.println(nodeID); int startOffset = (new Integer(req.getParameter("startOffset"))).intValue(); System.out.println(startOffset); int offsetDelta = (new Integer(req.getParameter("offsetDelta"))).intValue(); int privacy = (new Integer(req.getParameter("privacy"))).intValue(); System.out.println(offsetDelta); //chang Key<SARADocument> dockey = new Key<SARADocument>(SARADocument.class, new Long(document)); Highlight highlight = new Highlight(dockey, comment, difficulty, 50, userid, nodeID, startOffset, offsetDelta, privacy); HighlightService hs = new HighlightService(); //chang hs.addHighlight(highlight); System.out.println(highlight.toJson()); } }
diff --git a/dx/src/com/android/dx/ssa/back/IdenticalBlockCombiner.java b/dx/src/com/android/dx/ssa/back/IdenticalBlockCombiner.java index e9974c0fd..cfc70153e 100644 --- a/dx/src/com/android/dx/ssa/back/IdenticalBlockCombiner.java +++ b/dx/src/com/android/dx/ssa/back/IdenticalBlockCombiner.java @@ -1,182 +1,182 @@ /* * Copyright (C) 2007 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.dx.ssa.back; import com.android.dx.rop.code.BasicBlock; import com.android.dx.rop.code.BasicBlockList; import com.android.dx.rop.code.CstInsn; import com.android.dx.rop.code.Insn; import com.android.dx.rop.code.InsnList; import com.android.dx.rop.code.RegOps; import com.android.dx.rop.code.RopMethod; import com.android.dx.rop.code.SwitchInsn; import com.android.dx.util.IntList; import java.util.BitSet; /** * Searches for basic blocks that all have the same successor and insns * but different predecessors. These blocks are then combined into a single * block and the now-unused blocks are deleted. These identical blocks * frequently are created when catch blocks are edge-split. */ public class IdenticalBlockCombiner { private final RopMethod ropMethod; private final BasicBlockList blocks; private final BasicBlockList newBlocks; /** * Constructs instance. Call {@code process()} to run. * * @param rm {@code non-null;} instance to process */ public IdenticalBlockCombiner(RopMethod rm) { ropMethod = rm; blocks = ropMethod.getBlocks(); newBlocks = blocks.getMutableCopy(); } /** * Runs algorithm. TODO: This is n^2, and could be made linear-ish with * a hash. In particular, hash the contents of each block and only * compare blocks with the same hash. * * @return {@code non-null;} new method that has been processed */ public RopMethod process() { int szBlocks = blocks.size(); // indexed by label BitSet toDelete = new BitSet(blocks.getMaxLabel()); // For each non-deleted block... for (int bindex = 0; bindex < szBlocks; bindex++) { BasicBlock b = blocks.get(bindex); if (toDelete.get(b.getLabel())) { // doomed block continue; } IntList preds = ropMethod.labelToPredecessors(b.getLabel()); // ...look at all of it's predecessors that have only one succ... int szPreds = preds.size(); for (int i = 0; i < szPreds; i++) { int iLabel = preds.get(i); BasicBlock iBlock = blocks.labelToBlock(iLabel); if (toDelete.get(iLabel) - || iBlock.getSuccessors().size() > 1) { + || iBlock.getSuccessors().size() > 1 + || iBlock.getFirstInsn().getOpcode().getOpcode() == + RegOps.MOVE_RESULT) { continue; } IntList toCombine = new IntList(); // ...and see if they can be combined with any other preds... for (int j = i + 1; j < szPreds; j++) { int jLabel = preds.get(j); BasicBlock jBlock = blocks.labelToBlock(jLabel); if (jBlock.getSuccessors().size() == 1 - && iBlock.getFirstInsn().getOpcode().getOpcode() != - RegOps.MOVE_RESULT && compareInsns(iBlock, jBlock)) { toCombine.add(jLabel); toDelete.set(jLabel); } } combineBlocks(iLabel, toCombine); } } for (int i = szBlocks - 1; i >= 0; i--) { if (toDelete.get(newBlocks.get(i).getLabel())) { newBlocks.set(i, null); } } newBlocks.shrinkToFit(); newBlocks.setImmutable(); return new RopMethod(newBlocks, ropMethod.getFirstLabel()); } /** * Helper method to compare the contents of two blocks. * * @param a {@code non-null;} a block to compare * @param b {@code non-null;} another block to compare * @return {@code true} iff the two blocks' instructions are the same */ private static boolean compareInsns(BasicBlock a, BasicBlock b) { return a.getInsns().contentEquals(b.getInsns()); } /** * Combines blocks proven identical into one alpha block, re-writing * all of the successor links that point to the beta blocks to point * to the alpha block instead. * * @param alphaLabel block that will replace all the beta block * @param betaLabels label list of blocks to combine */ private void combineBlocks(int alphaLabel, IntList betaLabels) { int szBetas = betaLabels.size(); for (int i = 0; i < szBetas; i++) { int betaLabel = betaLabels.get(i); BasicBlock bb = blocks.labelToBlock(betaLabel); IntList preds = ropMethod.labelToPredecessors(bb.getLabel()); int szPreds = preds.size(); for (int j = 0; j < szPreds; j++) { BasicBlock predBlock = newBlocks.labelToBlock(preds.get(j)); replaceSucc(predBlock, betaLabel, alphaLabel); } } } /** * Replaces one of a block's successors with a different label. Constructs * an updated BasicBlock instance and places it in {@code newBlocks}. * * @param block block to replace * @param oldLabel label of successor to replace * @param newLabel label of new successor */ private void replaceSucc(BasicBlock block, int oldLabel, int newLabel) { IntList newSuccessors = block.getSuccessors().mutableCopy(); int newPrimarySuccessor; newSuccessors.set(newSuccessors.indexOf(oldLabel), newLabel); newPrimarySuccessor = block.getPrimarySuccessor(); if (newPrimarySuccessor == oldLabel) { newPrimarySuccessor = newLabel; } newSuccessors.setImmutable(); BasicBlock newBB = new BasicBlock(block.getLabel(), block.getInsns(), newSuccessors, newPrimarySuccessor); newBlocks.set(newBlocks.indexOfLabel(block.getLabel()), newBB); } }
false
true
public RopMethod process() { int szBlocks = blocks.size(); // indexed by label BitSet toDelete = new BitSet(blocks.getMaxLabel()); // For each non-deleted block... for (int bindex = 0; bindex < szBlocks; bindex++) { BasicBlock b = blocks.get(bindex); if (toDelete.get(b.getLabel())) { // doomed block continue; } IntList preds = ropMethod.labelToPredecessors(b.getLabel()); // ...look at all of it's predecessors that have only one succ... int szPreds = preds.size(); for (int i = 0; i < szPreds; i++) { int iLabel = preds.get(i); BasicBlock iBlock = blocks.labelToBlock(iLabel); if (toDelete.get(iLabel) || iBlock.getSuccessors().size() > 1) { continue; } IntList toCombine = new IntList(); // ...and see if they can be combined with any other preds... for (int j = i + 1; j < szPreds; j++) { int jLabel = preds.get(j); BasicBlock jBlock = blocks.labelToBlock(jLabel); if (jBlock.getSuccessors().size() == 1 && iBlock.getFirstInsn().getOpcode().getOpcode() != RegOps.MOVE_RESULT && compareInsns(iBlock, jBlock)) { toCombine.add(jLabel); toDelete.set(jLabel); } } combineBlocks(iLabel, toCombine); } } for (int i = szBlocks - 1; i >= 0; i--) { if (toDelete.get(newBlocks.get(i).getLabel())) { newBlocks.set(i, null); } } newBlocks.shrinkToFit(); newBlocks.setImmutable(); return new RopMethod(newBlocks, ropMethod.getFirstLabel()); }
public RopMethod process() { int szBlocks = blocks.size(); // indexed by label BitSet toDelete = new BitSet(blocks.getMaxLabel()); // For each non-deleted block... for (int bindex = 0; bindex < szBlocks; bindex++) { BasicBlock b = blocks.get(bindex); if (toDelete.get(b.getLabel())) { // doomed block continue; } IntList preds = ropMethod.labelToPredecessors(b.getLabel()); // ...look at all of it's predecessors that have only one succ... int szPreds = preds.size(); for (int i = 0; i < szPreds; i++) { int iLabel = preds.get(i); BasicBlock iBlock = blocks.labelToBlock(iLabel); if (toDelete.get(iLabel) || iBlock.getSuccessors().size() > 1 || iBlock.getFirstInsn().getOpcode().getOpcode() == RegOps.MOVE_RESULT) { continue; } IntList toCombine = new IntList(); // ...and see if they can be combined with any other preds... for (int j = i + 1; j < szPreds; j++) { int jLabel = preds.get(j); BasicBlock jBlock = blocks.labelToBlock(jLabel); if (jBlock.getSuccessors().size() == 1 && compareInsns(iBlock, jBlock)) { toCombine.add(jLabel); toDelete.set(jLabel); } } combineBlocks(iLabel, toCombine); } } for (int i = szBlocks - 1; i >= 0; i--) { if (toDelete.get(newBlocks.get(i).getLabel())) { newBlocks.set(i, null); } } newBlocks.shrinkToFit(); newBlocks.setImmutable(); return new RopMethod(newBlocks, ropMethod.getFirstLabel()); }
diff --git a/hibernate/src/main/java/woko/hibernate/HibernateTxInterceptor.java b/hibernate/src/main/java/woko/hibernate/HibernateTxInterceptor.java index 529a7ef6..5c343e56 100644 --- a/hibernate/src/main/java/woko/hibernate/HibernateTxInterceptor.java +++ b/hibernate/src/main/java/woko/hibernate/HibernateTxInterceptor.java @@ -1,67 +1,67 @@ package woko.hibernate; import net.sourceforge.stripes.action.Resolution; import net.sourceforge.stripes.controller.ExecutionContext; import net.sourceforge.stripes.controller.Intercepts; import net.sourceforge.stripes.controller.LifecycleStage; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import woko.Woko; import woko.util.WLogger; @Intercepts({LifecycleStage.RequestInit, LifecycleStage.RequestComplete}) public class HibernateTxInterceptor implements net.sourceforge.stripes.controller.Interceptor { private static final WLogger log = WLogger.getLogger(HibernateTxInterceptor.class); private SessionFactory getSessionFactory(ExecutionContext context) { Woko woko = Woko.getWoko(context.getActionBeanContext().getServletContext()); HibernateStore hs = (HibernateStore)woko.getObjectStore(); return hs.getSessionFactory(); } public Resolution intercept(ExecutionContext context) throws Exception { LifecycleStage stage = context.getLifecycleStage(); if (stage==LifecycleStage.RequestInit) { Transaction tx = getSessionFactory(context).getCurrentSession().beginTransaction(); log.debug("Started transaction : " + tx); } else if (stage.equals(LifecycleStage.RequestComplete)) { Transaction tx = getSessionFactory(context).getCurrentSession().getTransaction(); if (tx==null) { log.debug("No transaction found, nothing to do."); } else { try { log.debug("Commiting transaction " + tx); tx.commit(); } catch(Exception e) { - log.error("Commit error : $e", e); + log.error("Commit error", e); tx.rollback(); throw e; } } } try { return context.proceed(); } catch(Exception e) { log.error("Exception while proceeding with context, rollbacking transaction if any, exception will be rethrown", e); Session session = getSessionFactory(context).getCurrentSession(); if (session!=null) { Transaction tx = session.getTransaction(); if (tx!=null) { try { tx.rollback(); } catch(Exception e2) { log.error("Exception while rollbacking", e2); } } } // re-throw exception throw e; } } }
true
true
public Resolution intercept(ExecutionContext context) throws Exception { LifecycleStage stage = context.getLifecycleStage(); if (stage==LifecycleStage.RequestInit) { Transaction tx = getSessionFactory(context).getCurrentSession().beginTransaction(); log.debug("Started transaction : " + tx); } else if (stage.equals(LifecycleStage.RequestComplete)) { Transaction tx = getSessionFactory(context).getCurrentSession().getTransaction(); if (tx==null) { log.debug("No transaction found, nothing to do."); } else { try { log.debug("Commiting transaction " + tx); tx.commit(); } catch(Exception e) { log.error("Commit error : $e", e); tx.rollback(); throw e; } } } try { return context.proceed(); } catch(Exception e) { log.error("Exception while proceeding with context, rollbacking transaction if any, exception will be rethrown", e); Session session = getSessionFactory(context).getCurrentSession(); if (session!=null) { Transaction tx = session.getTransaction(); if (tx!=null) { try { tx.rollback(); } catch(Exception e2) { log.error("Exception while rollbacking", e2); } } } // re-throw exception throw e; } }
public Resolution intercept(ExecutionContext context) throws Exception { LifecycleStage stage = context.getLifecycleStage(); if (stage==LifecycleStage.RequestInit) { Transaction tx = getSessionFactory(context).getCurrentSession().beginTransaction(); log.debug("Started transaction : " + tx); } else if (stage.equals(LifecycleStage.RequestComplete)) { Transaction tx = getSessionFactory(context).getCurrentSession().getTransaction(); if (tx==null) { log.debug("No transaction found, nothing to do."); } else { try { log.debug("Commiting transaction " + tx); tx.commit(); } catch(Exception e) { log.error("Commit error", e); tx.rollback(); throw e; } } } try { return context.proceed(); } catch(Exception e) { log.error("Exception while proceeding with context, rollbacking transaction if any, exception will be rethrown", e); Session session = getSessionFactory(context).getCurrentSession(); if (session!=null) { Transaction tx = session.getTransaction(); if (tx!=null) { try { tx.rollback(); } catch(Exception e2) { log.error("Exception while rollbacking", e2); } } } // re-throw exception throw e; } }